Annotation of gforth/doc/gforth.ds, revision 1.33
1.1 anton 1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28 crook 3:
1.21 crook 4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28 crook 5: @comment 1. x-ref all ambiguous or implementation-defined features?
6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
7: @comment 3. words in miscellaneous section need a home.
8: @comment 4. search for TODO for other minor and major works required.
9: @comment 5. [rats] change all @var to @i in Forth source so that info
10: @comment file looks decent.
1.29 crook 11: @comment .. would be useful to have a word that identified all deferred words
12: @comment should semantics stuff in intro be moved to another section
13:
1.28 crook 14:
1.1 anton 15: @comment %**start of header (This is for running Texinfo on a region.)
16: @setfilename gforth.info
17: @settitle Gforth Manual
18: @dircategory GNU programming tools
19: @direntry
20: * Gforth: (gforth). A fast interpreter for the Forth language.
21: @end direntry
22: @comment @setchapternewpage odd
1.29 crook 23: @comment TODO this gets left in by HTML converter
1.12 anton 24: @macro progstyle {}
25: Programming style note:
1.3 anton 26: @end macro
1.1 anton 27: @comment %**end of header (This is for running Texinfo on a region.)
28:
1.29 crook 29:
30: @comment ----------------------------------------------------------
31: @comment macros for beautifying glossary entries
32: @comment if these are used, need to strip them out for HTML converter
33: @comment else they get repeated verbatim in HTML output.
34: @comment .. not working yet.
35:
36: @macro GLOSS-START {}
37: @iftex
38: @ninerm
39: @end iftex
40: @end macro
41:
42: @macro GLOSS-END {}
43: @iftex
44: @rm
45: @end iftex
46: @end macro
47:
48: @comment ----------------------------------------------------------
49:
50:
1.10 anton 51: @include version.texi
52:
1.1 anton 53: @ifinfo
1.11 anton 54: This file documents Gforth @value{VERSION}
1.1 anton 55:
1.26 crook 56: Copyright @copyright{} 1995-1999 Free Software Foundation, Inc.
1.1 anton 57:
58: Permission is granted to make and distribute verbatim copies of
59: this manual provided the copyright notice and this permission notice
60: are preserved on all copies.
61:
62: @ignore
63: Permission is granted to process this file through TeX and print the
64: results, provided the printed document carries a copying permission
65: notice identical to this one except for the removal of this paragraph
66: (this paragraph not being relevant to the printed manual).
67:
68: @end ignore
69: Permission is granted to copy and distribute modified versions of this
70: manual under the conditions for verbatim copying, provided also that the
71: sections entitled "Distribution" and "General Public License" are
72: included exactly as in the original, and provided that the entire
73: resulting derived work is distributed under the terms of a permission
74: notice identical to this one.
75:
76: Permission is granted to copy and distribute translations of this manual
77: into another language, under the above conditions for modified versions,
78: except that the sections entitled "Distribution" and "General Public
79: License" may be included in a translation approved by the author instead
80: of in the original English.
81: @end ifinfo
82:
83: @finalout
84: @titlepage
85: @sp 10
86: @center @titlefont{Gforth Manual}
87: @sp 2
1.11 anton 88: @center for version @value{VERSION}
1.1 anton 89: @sp 2
90: @center Anton Ertl
1.6 pazsan 91: @center Bernd Paysan
1.5 anton 92: @center Jens Wilke
1.23 crook 93: @center Neal Crook
1.1 anton 94: @sp 3
1.29 crook 95: @center This manual is permanently under construction and was last updated on 04-May-1999
1.1 anton 96:
97: @comment The following two commands start the copyright page.
98: @page
99: @vskip 0pt plus 1filll
1.29 crook 100: Copyright @copyright{} 1995--1999 Free Software Foundation, Inc.
1.1 anton 101:
102: @comment !! Published by ... or You can get a copy of this manual ...
103:
104: Permission is granted to make and distribute verbatim copies of
105: this manual provided the copyright notice and this permission notice
106: are preserved on all copies.
107:
108: Permission is granted to copy and distribute modified versions of this
109: manual under the conditions for verbatim copying, provided also that the
110: sections entitled "Distribution" and "General Public License" are
111: included exactly as in the original, and provided that the entire
112: resulting derived work is distributed under the terms of a permission
113: notice identical to this one.
114:
115: Permission is granted to copy and distribute translations of this manual
116: into another language, under the above conditions for modified versions,
117: except that the sections entitled "Distribution" and "General Public
118: License" may be included in a translation approved by the author instead
119: of in the original English.
120: @end titlepage
121:
122:
123: @node Top, License, (dir), (dir)
124: @ifinfo
125: Gforth is a free implementation of ANS Forth available on many
1.11 anton 126: personal machines. This manual corresponds to version @value{VERSION}.
1.1 anton 127: @end ifinfo
128:
129: @menu
1.21 crook 130: * License:: The GPL
1.26 crook 131: * Goals:: About the Gforth Project
1.29 crook 132: * Gforth Environment:: Starting (and exiting) Gforth
1.21 crook 133: * Introduction:: An introduction to ANS Forth
1.1 anton 134: * Words:: Forth words available in Gforth
1.24 anton 135: * Error messages:: How to interpret them
1.1 anton 136: * Tools:: Programming tools
137: * ANS conformance:: Implementation-defined options etc.
138: * Model:: The abstract machine of Gforth
139: * Integrating Gforth:: Forth as scripting language for applications
140: * Emacs and Gforth:: The Gforth Mode
141: * Image Files:: @code{.fi} files contain compiled code
142: * Engine:: The inner interpreter and the primitives
1.24 anton 143: * Binding to System Library::
1.13 pazsan 144: * Cross Compiler:: The Cross Compiler
1.1 anton 145: * Bugs:: How to report them
146: * Origin:: Authors and ancestors of Gforth
1.21 crook 147: * Forth-related information:: Books and places to look on the WWW
1.1 anton 148: * Word Index:: An item for each Forth word
149: * Concept Index:: A menu covering many topics
1.12 anton 150:
1.24 anton 151: @detailmenu --- The Detailed Node Listing ---
1.12 anton 152:
1.26 crook 153: Goals of Gforth
154:
155: * Gforth Extensions Sinful?::
156:
1.29 crook 157: Gforth Environment
158:
1.32 anton 159: * Invoking Gforth:: Getting in
160: * Leaving Gforth:: Getting out
161: * Command-line editing::
1.29 crook 162: * Upper and lower case::
1.32 anton 163: * Environment variables:: ..that affect how Gforth starts up
164: * Gforth Files:: What gets installed and where
1.29 crook 165:
1.24 anton 166: An Introduction to ANS Forth
167:
168: * Introducing the Text Interpreter::
169: * Stacks and Postfix notation::
170: * Your first definition::
171: * How does that work?::
172: * Forth is written in Forth::
173: * Review - elements of a Forth system::
1.29 crook 174: * Where to go next::
1.24 anton 175: * Exercises::
176:
1.12 anton 177: Forth Words
178:
179: * Notation::
1.21 crook 180: * Comments::
181: * Boolean Flags::
1.12 anton 182: * Arithmetic::
183: * Stack Manipulation::
184: * Memory::
185: * Control Structures::
186: * Defining Words::
1.21 crook 187: * The Text Interpreter::
1.12 anton 188: * Tokens for Words::
1.21 crook 189: * Word Lists::
190: * Environmental Queries::
1.12 anton 191: * Files::
192: * Blocks::
193: * Other I/O::
194: * Programming Tools::
195: * Assembler and Code Words::
196: * Threading Words::
1.26 crook 197: * Locals::
198: * Structures::
199: * Object-oriented Forth::
1.21 crook 200: * Passing Commands to the OS::
201: * Miscellaneous Words::
1.12 anton 202:
203: Arithmetic
204:
205: * Single precision::
206: * Bitwise operations::
1.21 crook 207: * Double precision:: Double-cell integer arithmetic
208: * Numeric comparison::
1.32 anton 209: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 210: * Floating Point::
211:
212: Stack Manipulation
213:
214: * Data stack::
215: * Floating point stack::
216: * Return stack::
217: * Locals stack::
218: * Stack pointer manipulation::
219:
220: Memory
221:
1.32 anton 222: * Memory model::
223: * Dictionary allocation::
224: * Heap Allocation::
225: * Memory Access::
226: * Address arithmetic::
227: * Memory Blocks::
1.12 anton 228:
229: Control Structures
230:
1.32 anton 231: * Selection:: IF.. ELSE.. ENDIF
232: * Simple Loops:: BEGIN..
233: * Counted Loops:: DO
234: * Arbitrary control structures::
235: * Calls and returns::
1.12 anton 236: * Exception Handling::
237:
238: Defining Words
239:
1.32 anton 240: * Simple Defining Words:: Variables, values and constants
241: * Colon Definitions::
242: * User-defined Defining Words::
243: * Supplying names::
244: * Interpretation and Compilation Semantics::
1.12 anton 245:
1.21 crook 246: The Text Interpreter
247:
1.29 crook 248: * Input Sources::
1.21 crook 249: * Number Conversion::
250: * Interpret/Compile states::
251: * Literals::
252: * Interpreter Directives::
253:
1.26 crook 254: Word Lists
255:
256: * Why use word lists?::
257: * Word list examples::
258:
259: Files
260:
261: * Forth source files::
262: * General files::
263: * Search Paths::
264: * Forth Search Paths::
265: * General Search Paths::
266:
267: Other I/O
268:
1.32 anton 269: * Simple numeric output:: Predefined formats
270: * Formatted numeric output:: Formatted (pictured) output
271: * String Formats:: How Forth stores strings in memory
272: * Displaying characters and strings:: Other stuff
273: * Input:: Input
1.26 crook 274:
275: Programming Tools
276:
277: * Debugging:: Simple and quick.
278: * Assertions:: Making your programs self-checking.
279: * Singlestep Debugger:: Executing your program word by word.
280:
281: Locals
282:
283: * Gforth locals::
284: * ANS Forth locals::
285:
286: Gforth locals
287:
288: * Where are locals visible by name?::
289: * How long do locals live?::
290: * Programming Style::
291: * Implementation::
292:
1.12 anton 293: Structures
294:
295: * Why explicit structure support?::
296: * Structure Usage::
297: * Structure Naming Convention::
298: * Structure Implementation::
299: * Structure Glossary::
300:
301: Object-oriented Forth
302:
1.24 anton 303: * Why object-oriented programming?::
304: * Object-Oriented Terminology::
305: * Objects::
306: * OOF::
307: * Mini-OOF::
1.23 crook 308: * Comparison with other object models::
1.12 anton 309:
1.24 anton 310: The @file{objects.fs} model
1.12 anton 311:
312: * Properties of the Objects model::
313: * Basic Objects Usage::
1.23 crook 314: * The Objects base class::
1.12 anton 315: * Creating objects::
316: * Object-Oriented Programming Style::
317: * Class Binding::
318: * Method conveniences::
319: * Classes and Scoping::
320: * Object Interfaces::
321: * Objects Implementation::
322: * Objects Glossary::
323:
1.24 anton 324: The @file{oof.fs} model
1.12 anton 325:
326: * Properties of the OOF model::
327: * Basic OOF Usage::
1.23 crook 328: * The OOF base class::
1.12 anton 329: * Class Declaration::
330: * Class Implementation::
331:
1.24 anton 332: The @file{mini-oof.fs} model
1.23 crook 333:
334: * Basic Mini-OOF Usage::
335: * Mini-OOF Example::
336: * Mini-OOF Implementation::
337:
1.12 anton 338: Tools
339:
340: * ANS Report:: Report the words used, sorted by wordset.
341:
342: ANS conformance
343:
344: * The Core Words::
345: * The optional Block word set::
346: * The optional Double Number word set::
347: * The optional Exception word set::
348: * The optional Facility word set::
349: * The optional File-Access word set::
350: * The optional Floating-Point word set::
351: * The optional Locals word set::
352: * The optional Memory-Allocation word set::
353: * The optional Programming-Tools word set::
354: * The optional Search-Order word set::
355:
356: The Core Words
357:
358: * core-idef:: Implementation Defined Options
359: * core-ambcond:: Ambiguous Conditions
360: * core-other:: Other System Documentation
361:
362: The optional Block word set
363:
364: * block-idef:: Implementation Defined Options
365: * block-ambcond:: Ambiguous Conditions
366: * block-other:: Other System Documentation
367:
368: The optional Double Number word set
369:
370: * double-ambcond:: Ambiguous Conditions
371:
372: The optional Exception word set
373:
374: * exception-idef:: Implementation Defined Options
375:
376: The optional Facility word set
377:
378: * facility-idef:: Implementation Defined Options
379: * facility-ambcond:: Ambiguous Conditions
380:
381: The optional File-Access word set
382:
383: * file-idef:: Implementation Defined Options
384: * file-ambcond:: Ambiguous Conditions
385:
386: The optional Floating-Point word set
387:
388: * floating-idef:: Implementation Defined Options
389: * floating-ambcond:: Ambiguous Conditions
390:
391: The optional Locals word set
392:
393: * locals-idef:: Implementation Defined Options
394: * locals-ambcond:: Ambiguous Conditions
395:
396: The optional Memory-Allocation word set
397:
398: * memory-idef:: Implementation Defined Options
399:
400: The optional Programming-Tools word set
401:
402: * programming-idef:: Implementation Defined Options
403: * programming-ambcond:: Ambiguous Conditions
404:
405: The optional Search-Order word set
406:
407: * search-idef:: Implementation Defined Options
408: * search-ambcond:: Ambiguous Conditions
409:
410: Image Files
411:
1.24 anton 412: * Image Licensing Issues:: Distribution terms for images.
413: * Image File Background:: Why have image files?
1.32 anton 414: * Non-Relocatable Image Files:: don't always work.
1.24 anton 415: * Data-Relocatable Image Files:: are better.
1.32 anton 416: * Fully Relocatable Image Files:: better yet.
1.24 anton 417: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 418: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 419: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 420:
421: Fully Relocatable Image Files
422:
1.27 crook 423: * gforthmi:: The normal way
1.12 anton 424: * cross.fs:: The hard way
425:
426: Engine
427:
428: * Portability::
429: * Threading::
430: * Primitives::
431: * Performance::
432:
433: Threading
434:
435: * Scheduling::
436: * Direct or Indirect Threaded?::
437: * DOES>::
438:
439: Primitives
440:
441: * Automatic Generation::
442: * TOS Optimization::
443: * Produced code::
1.13 pazsan 444:
445: Cross Compiler
446:
447: * Using the Cross Compiler::
448: * How the Cross Compiler Works::
449:
1.24 anton 450: Other Forth-related information
1.21 crook 451:
452: * Internet resources::
453: * Books::
454: * The Forth Interest Group::
455: * Conferences::
456:
1.24 anton 457: @end detailmenu
1.1 anton 458: @end menu
459:
1.26 crook 460: @node License, Goals, Top, Top
1.1 anton 461: @unnumbered GNU GENERAL PUBLIC LICENSE
462: @center Version 2, June 1991
463:
464: @display
465: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
466: 675 Mass Ave, Cambridge, MA 02139, USA
467:
468: Everyone is permitted to copy and distribute verbatim copies
469: of this license document, but changing it is not allowed.
470: @end display
471:
472: @unnumberedsec Preamble
473:
474: The licenses for most software are designed to take away your
475: freedom to share and change it. By contrast, the GNU General Public
476: License is intended to guarantee your freedom to share and change free
477: software---to make sure the software is free for all its users. This
478: General Public License applies to most of the Free Software
479: Foundation's software and to any other program whose authors commit to
480: using it. (Some other Free Software Foundation software is covered by
481: the GNU Library General Public License instead.) You can apply it to
482: your programs, too.
483:
484: When we speak of free software, we are referring to freedom, not
485: price. Our General Public Licenses are designed to make sure that you
486: have the freedom to distribute copies of free software (and charge for
487: this service if you wish), that you receive source code or can get it
488: if you want it, that you can change the software or use pieces of it
489: in new free programs; and that you know you can do these things.
490:
491: To protect your rights, we need to make restrictions that forbid
492: anyone to deny you these rights or to ask you to surrender the rights.
493: These restrictions translate to certain responsibilities for you if you
494: distribute copies of the software, or if you modify it.
495:
496: For example, if you distribute copies of such a program, whether
497: gratis or for a fee, you must give the recipients all the rights that
498: you have. You must make sure that they, too, receive or can get the
499: source code. And you must show them these terms so they know their
500: rights.
501:
502: We protect your rights with two steps: (1) copyright the software, and
503: (2) offer you this license which gives you legal permission to copy,
504: distribute and/or modify the software.
505:
506: Also, for each author's protection and ours, we want to make certain
507: that everyone understands that there is no warranty for this free
508: software. If the software is modified by someone else and passed on, we
509: want its recipients to know that what they have is not the original, so
510: that any problems introduced by others will not reflect on the original
511: authors' reputations.
512:
513: Finally, any free program is threatened constantly by software
514: patents. We wish to avoid the danger that redistributors of a free
515: program will individually obtain patent licenses, in effect making the
516: program proprietary. To prevent this, we have made it clear that any
517: patent must be licensed for everyone's free use or not licensed at all.
518:
519: The precise terms and conditions for copying, distribution and
520: modification follow.
521:
522: @iftex
523: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
524: @end iftex
525: @ifinfo
526: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
527: @end ifinfo
528:
529: @enumerate 0
530: @item
531: This License applies to any program or other work which contains
532: a notice placed by the copyright holder saying it may be distributed
533: under the terms of this General Public License. The ``Program'', below,
534: refers to any such program or work, and a ``work based on the Program''
535: means either the Program or any derivative work under copyright law:
536: that is to say, a work containing the Program or a portion of it,
537: either verbatim or with modifications and/or translated into another
538: language. (Hereinafter, translation is included without limitation in
539: the term ``modification''.) Each licensee is addressed as ``you''.
540:
541: Activities other than copying, distribution and modification are not
542: covered by this License; they are outside its scope. The act of
543: running the Program is not restricted, and the output from the Program
544: is covered only if its contents constitute a work based on the
545: Program (independent of having been made by running the Program).
546: Whether that is true depends on what the Program does.
547:
548: @item
549: You may copy and distribute verbatim copies of the Program's
550: source code as you receive it, in any medium, provided that you
551: conspicuously and appropriately publish on each copy an appropriate
552: copyright notice and disclaimer of warranty; keep intact all the
553: notices that refer to this License and to the absence of any warranty;
554: and give any other recipients of the Program a copy of this License
555: along with the Program.
556:
557: You may charge a fee for the physical act of transferring a copy, and
558: you may at your option offer warranty protection in exchange for a fee.
559:
560: @item
561: You may modify your copy or copies of the Program or any portion
562: of it, thus forming a work based on the Program, and copy and
563: distribute such modifications or work under the terms of Section 1
564: above, provided that you also meet all of these conditions:
565:
566: @enumerate a
567: @item
568: You must cause the modified files to carry prominent notices
569: stating that you changed the files and the date of any change.
570:
571: @item
572: You must cause any work that you distribute or publish, that in
573: whole or in part contains or is derived from the Program or any
574: part thereof, to be licensed as a whole at no charge to all third
575: parties under the terms of this License.
576:
577: @item
578: If the modified program normally reads commands interactively
579: when run, you must cause it, when started running for such
580: interactive use in the most ordinary way, to print or display an
581: announcement including an appropriate copyright notice and a
582: notice that there is no warranty (or else, saying that you provide
583: a warranty) and that users may redistribute the program under
584: these conditions, and telling the user how to view a copy of this
585: License. (Exception: if the Program itself is interactive but
586: does not normally print such an announcement, your work based on
587: the Program is not required to print an announcement.)
588: @end enumerate
589:
590: These requirements apply to the modified work as a whole. If
591: identifiable sections of that work are not derived from the Program,
592: and can be reasonably considered independent and separate works in
593: themselves, then this License, and its terms, do not apply to those
594: sections when you distribute them as separate works. But when you
595: distribute the same sections as part of a whole which is a work based
596: on the Program, the distribution of the whole must be on the terms of
597: this License, whose permissions for other licensees extend to the
598: entire whole, and thus to each and every part regardless of who wrote it.
599:
600: Thus, it is not the intent of this section to claim rights or contest
601: your rights to work written entirely by you; rather, the intent is to
602: exercise the right to control the distribution of derivative or
603: collective works based on the Program.
604:
605: In addition, mere aggregation of another work not based on the Program
606: with the Program (or with a work based on the Program) on a volume of
607: a storage or distribution medium does not bring the other work under
608: the scope of this License.
609:
610: @item
611: You may copy and distribute the Program (or a work based on it,
612: under Section 2) in object code or executable form under the terms of
613: Sections 1 and 2 above provided that you also do one of the following:
614:
615: @enumerate a
616: @item
617: Accompany it with the complete corresponding machine-readable
618: source code, which must be distributed under the terms of Sections
619: 1 and 2 above on a medium customarily used for software interchange; or,
620:
621: @item
622: Accompany it with a written offer, valid for at least three
623: years, to give any third party, for a charge no more than your
624: cost of physically performing source distribution, a complete
625: machine-readable copy of the corresponding source code, to be
626: distributed under the terms of Sections 1 and 2 above on a medium
627: customarily used for software interchange; or,
628:
629: @item
630: Accompany it with the information you received as to the offer
631: to distribute corresponding source code. (This alternative is
632: allowed only for noncommercial distribution and only if you
633: received the program in object code or executable form with such
634: an offer, in accord with Subsection b above.)
635: @end enumerate
636:
637: The source code for a work means the preferred form of the work for
638: making modifications to it. For an executable work, complete source
639: code means all the source code for all modules it contains, plus any
640: associated interface definition files, plus the scripts used to
641: control compilation and installation of the executable. However, as a
642: special exception, the source code distributed need not include
643: anything that is normally distributed (in either source or binary
644: form) with the major components (compiler, kernel, and so on) of the
645: operating system on which the executable runs, unless that component
646: itself accompanies the executable.
647:
648: If distribution of executable or object code is made by offering
649: access to copy from a designated place, then offering equivalent
650: access to copy the source code from the same place counts as
651: distribution of the source code, even though third parties are not
652: compelled to copy the source along with the object code.
653:
654: @item
655: You may not copy, modify, sublicense, or distribute the Program
656: except as expressly provided under this License. Any attempt
657: otherwise to copy, modify, sublicense or distribute the Program is
658: void, and will automatically terminate your rights under this License.
659: However, parties who have received copies, or rights, from you under
660: this License will not have their licenses terminated so long as such
661: parties remain in full compliance.
662:
663: @item
664: You are not required to accept this License, since you have not
665: signed it. However, nothing else grants you permission to modify or
666: distribute the Program or its derivative works. These actions are
667: prohibited by law if you do not accept this License. Therefore, by
668: modifying or distributing the Program (or any work based on the
669: Program), you indicate your acceptance of this License to do so, and
670: all its terms and conditions for copying, distributing or modifying
671: the Program or works based on it.
672:
673: @item
674: Each time you redistribute the Program (or any work based on the
675: Program), the recipient automatically receives a license from the
676: original licensor to copy, distribute or modify the Program subject to
677: these terms and conditions. You may not impose any further
678: restrictions on the recipients' exercise of the rights granted herein.
679: You are not responsible for enforcing compliance by third parties to
680: this License.
681:
682: @item
683: If, as a consequence of a court judgment or allegation of patent
684: infringement or for any other reason (not limited to patent issues),
685: conditions are imposed on you (whether by court order, agreement or
686: otherwise) that contradict the conditions of this License, they do not
687: excuse you from the conditions of this License. If you cannot
688: distribute so as to satisfy simultaneously your obligations under this
689: License and any other pertinent obligations, then as a consequence you
690: may not distribute the Program at all. For example, if a patent
691: license would not permit royalty-free redistribution of the Program by
692: all those who receive copies directly or indirectly through you, then
693: the only way you could satisfy both it and this License would be to
694: refrain entirely from distribution of the Program.
695:
696: If any portion of this section is held invalid or unenforceable under
697: any particular circumstance, the balance of the section is intended to
698: apply and the section as a whole is intended to apply in other
699: circumstances.
700:
701: It is not the purpose of this section to induce you to infringe any
702: patents or other property right claims or to contest validity of any
703: such claims; this section has the sole purpose of protecting the
704: integrity of the free software distribution system, which is
705: implemented by public license practices. Many people have made
706: generous contributions to the wide range of software distributed
707: through that system in reliance on consistent application of that
708: system; it is up to the author/donor to decide if he or she is willing
709: to distribute software through any other system and a licensee cannot
710: impose that choice.
711:
712: This section is intended to make thoroughly clear what is believed to
713: be a consequence of the rest of this License.
714:
715: @item
716: If the distribution and/or use of the Program is restricted in
717: certain countries either by patents or by copyrighted interfaces, the
718: original copyright holder who places the Program under this License
719: may add an explicit geographical distribution limitation excluding
720: those countries, so that distribution is permitted only in or among
721: countries not thus excluded. In such case, this License incorporates
722: the limitation as if written in the body of this License.
723:
724: @item
725: The Free Software Foundation may publish revised and/or new versions
726: of the General Public License from time to time. Such new versions will
727: be similar in spirit to the present version, but may differ in detail to
728: address new problems or concerns.
729:
730: Each version is given a distinguishing version number. If the Program
731: specifies a version number of this License which applies to it and ``any
732: later version'', you have the option of following the terms and conditions
733: either of that version or of any later version published by the Free
734: Software Foundation. If the Program does not specify a version number of
735: this License, you may choose any version ever published by the Free Software
736: Foundation.
737:
738: @item
739: If you wish to incorporate parts of the Program into other free
740: programs whose distribution conditions are different, write to the author
741: to ask for permission. For software which is copyrighted by the Free
742: Software Foundation, write to the Free Software Foundation; we sometimes
743: make exceptions for this. Our decision will be guided by the two goals
744: of preserving the free status of all derivatives of our free software and
745: of promoting the sharing and reuse of software generally.
746:
747: @iftex
748: @heading NO WARRANTY
749: @end iftex
750: @ifinfo
751: @center NO WARRANTY
752: @end ifinfo
753:
754: @item
755: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
756: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
757: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
758: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
759: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
760: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
761: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
762: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
763: REPAIR OR CORRECTION.
764:
765: @item
766: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
767: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
768: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
769: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
770: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
771: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
772: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
773: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
774: POSSIBILITY OF SUCH DAMAGES.
775: @end enumerate
776:
777: @iftex
778: @heading END OF TERMS AND CONDITIONS
779: @end iftex
780: @ifinfo
781: @center END OF TERMS AND CONDITIONS
782: @end ifinfo
783:
784: @page
785: @unnumberedsec How to Apply These Terms to Your New Programs
786:
787: If you develop a new program, and you want it to be of the greatest
788: possible use to the public, the best way to achieve this is to make it
789: free software which everyone can redistribute and change under these terms.
790:
791: To do so, attach the following notices to the program. It is safest
792: to attach them to the start of each source file to most effectively
793: convey the exclusion of warranty; and each file should have at least
794: the ``copyright'' line and a pointer to where the full notice is found.
795:
796: @smallexample
797: @var{one line to give the program's name and a brief idea of what it does.}
798: Copyright (C) 19@var{yy} @var{name of author}
799:
800: This program is free software; you can redistribute it and/or modify
801: it under the terms of the GNU General Public License as published by
802: the Free Software Foundation; either version 2 of the License, or
803: (at your option) any later version.
804:
805: This program is distributed in the hope that it will be useful,
806: but WITHOUT ANY WARRANTY; without even the implied warranty of
807: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
808: GNU General Public License for more details.
809:
810: You should have received a copy of the GNU General Public License
811: along with this program; if not, write to the Free Software
812: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
813: @end smallexample
814:
815: Also add information on how to contact you by electronic and paper mail.
816:
817: If the program is interactive, make it output a short notice like this
818: when it starts in an interactive mode:
819:
820: @smallexample
821: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
822: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
823: type `show w'.
824: This is free software, and you are welcome to redistribute it
825: under certain conditions; type `show c' for details.
826: @end smallexample
827:
828: The hypothetical commands @samp{show w} and @samp{show c} should show
829: the appropriate parts of the General Public License. Of course, the
830: commands you use may be called something other than @samp{show w} and
831: @samp{show c}; they could even be mouse-clicks or menu items---whatever
832: suits your program.
833:
834: You should also get your employer (if you work as a programmer) or your
835: school, if any, to sign a ``copyright disclaimer'' for the program, if
836: necessary. Here is a sample; alter the names:
837:
838: @smallexample
839: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
840: `Gnomovision' (which makes passes at compilers) written by James Hacker.
841:
842: @var{signature of Ty Coon}, 1 April 1989
843: Ty Coon, President of Vice
844: @end smallexample
845:
846: This General Public License does not permit incorporating your program into
847: proprietary programs. If your program is a subroutine library, you may
848: consider it more useful to permit linking proprietary applications with the
849: library. If this is what you want to do, use the GNU Library General
850: Public License instead of this License.
851:
852: @iftex
853: @unnumbered Preface
854: @cindex Preface
1.21 crook 855: This manual documents Gforth. Some introductory material is provided for
856: readers who are unfamiliar with Forth or who are migrating to Gforth
857: from other Forth compilers. However, this manual is primarily a
858: reference manual.
1.1 anton 859: @end iftex
860:
1.28 crook 861: @comment TODO much more blurb here.
1.26 crook 862:
863: @c ******************************************************************
1.29 crook 864: @node Goals, Gforth Environment, License, Top
1.26 crook 865: @comment node-name, next, previous, up
866: @chapter Goals of Gforth
867: @cindex goals of the Gforth project
868: The goal of the Gforth Project is to develop a standard model for
869: ANS Forth. This can be split into several subgoals:
870:
871: @itemize @bullet
872: @item
873: Gforth should conform to the ANS Forth Standard.
874: @item
875: It should be a model, i.e. it should define all the
876: implementation-dependent things.
877: @item
878: It should become standard, i.e. widely accepted and used. This goal
879: is the most difficult one.
880: @end itemize
881:
882: To achieve these goals Gforth should be
883: @itemize @bullet
884: @item
885: Similar to previous models (fig-Forth, F83)
886: @item
887: Powerful. It should provide for all the things that are considered
888: necessary today and even some that are not yet considered necessary.
889: @item
890: Efficient. It should not get the reputation of being exceptionally
891: slow.
892: @item
893: Free.
894: @item
895: Available on many machines/easy to port.
896: @end itemize
897:
898: Have we achieved these goals? Gforth conforms to the ANS Forth
899: standard. It may be considered a model, but we have not yet documented
900: which parts of the model are stable and which parts we are likely to
901: change. It certainly has not yet become a de facto standard, but it
902: appears to be quite popular. It has some similarities to and some
903: differences from previous models. It has some powerful features, but not
904: yet everything that we envisioned. We certainly have achieved our
905: execution speed goals (@pxref{Performance}). It is free and available
906: on many machines.
907:
908: @menu
909: * Gforth Extensions Sinful?::
910: @end menu
911:
912: @node Gforth Extensions Sinful?, , Goals, Goals
913: @comment node-name, next, previous, up
914: @section Is it a Sin to use Gforth Extensions?
915: @cindex Gforth extensions
916:
917: If you've been paying attention, you will have realised that there is an
918: ANS (American National Standard) for Forth. As you read through the rest
1.29 crook 919: of this manual, you will see documentation for @i{Standard} words, and
920: documentation for some appealing Gforth @i{extensions}. You might ask
921: yourself the question: @i{``Given that there is a standard, would I be
1.26 crook 922: committing a sin to use (non-Standard) Gforth extensions?''}
923:
924: The answer to that question is somewhat pragmatic and somewhat
925: philosophical. Consider these points:
926:
927: @itemize @bullet
928: @item
929: A number of the Gforth extensions can be implemented in ANS Forth using
930: files provided in the @file{compat/} directory. These are mentioned in
931: the text in passing.
932: @item
933: Forth has a rich historical precedent for programmers taking advantage
934: of implementation-dependent features of their tools (for example,
935: relying on a knowledge of the dictionary structure). Sometimes these
936: techniques are necessary to extract every last bit of performance from
937: the hardware, sometimes they are just a programming shorthand.
938: @item
939: The best way to break the rules is to know what the rules are. To learn
940: the rules, there is no substitute for studying the text of the Standard
941: itself. In particular, Appendix A of the Standard (@var{Rationale})
942: provides a valuable insight into the thought processes of the technical
943: committee.
944: @item
945: The best reason to break a rule is because you have to; because it's
946: more productive to do that, because it makes your code run fast enough
947: or because you can see no Standard way to achieve what you want to
948: achieve.
949: @end itemize
950:
951: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
952: analyse your program and determine what non-Standard definitions it
953: relies upon.
954:
1.29 crook 955:
1.26 crook 956: @c ******************************************************************
1.29 crook 957: @node Gforth Environment, Introduction, Goals, Top
958: @chapter Gforth Environment
959: @cindex Gforth environment
1.21 crook 960:
1.29 crook 961: Note: ultimately, the gforth man page will be auto-generated from the
962: material in this chapter.
1.21 crook 963:
964: @menu
1.29 crook 965: * Invoking Gforth:: Getting in
966: * Leaving Gforth:: Getting out
967: * Command-line editing::
968: * Upper and lower case::
969: * Environment variables:: ..that affect how Gforth starts up
970: * Gforth Files:: What gets installed and where
1.21 crook 971: @end menu
972:
1.30 anton 973: @xref{Image Files} for related information about the creation of images.
1.29 crook 974:
1.21 crook 975: @comment ----------------------------------------------
1.29 crook 976: @node Invoking Gforth, Leaving Gforth, ,Gforth Environment
977: @section Invoking Gforth
978: @cindex invoking Gforth
979: @cindex running Gforth
980: @cindex command-line options
981: @cindex options on the command line
982: @cindex flags on the command line
1.21 crook 983:
1.30 anton 984: Gforth is made up of two parts; an executable ``engine'' (named
985: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
986: will usually just say @code{gforth} -- this automatically loads the
987: default image file @file{gforth.fi}. In many other cases the default
988: Gforth image will be invoked like this:
1.21 crook 989: @example
1.30 anton 990: gforth [file | -e forth-code] ...
1.21 crook 991: @end example
1.29 crook 992: @noindent
993: This interprets the contents of the files and the Forth code in the order they
994: are given.
1.21 crook 995:
1.30 anton 996: In addition to the @file{gforth} engine, there is also an engine called
997: @file{gforth-fast}, which is faster, but gives less informative error
998: messages (@pxref{Error messages}).
999:
1.29 crook 1000: In general, the command line looks like this:
1.21 crook 1001:
1002: @example
1.30 anton 1003: gforth[-fast] [engine options] [image options]
1.21 crook 1004: @end example
1005:
1.30 anton 1006: The engine options must come before the rest of the command
1.29 crook 1007: line. They are:
1.26 crook 1008:
1.29 crook 1009: @table @code
1010: @cindex -i, command-line option
1011: @cindex --image-file, command-line option
1012: @item --image-file @i{file}
1013: @itemx -i @i{file}
1014: Loads the Forth image @i{file} instead of the default
1015: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 1016:
1.29 crook 1017: @cindex --path, command-line option
1018: @cindex -p, command-line option
1019: @item --path @i{path}
1020: @itemx -p @i{path}
1021: Uses @i{path} for searching the image file and Forth source code files
1022: instead of the default in the environment variable @code{GFORTHPATH} or
1023: the path specified at installation time (e.g.,
1024: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
1025: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 1026:
1.29 crook 1027: @cindex --dictionary-size, command-line option
1028: @cindex -m, command-line option
1029: @cindex @i{size} parameters for command-line options
1030: @cindex size of the dictionary and the stacks
1031: @item --dictionary-size @i{size}
1032: @itemx -m @i{size}
1033: Allocate @i{size} space for the Forth dictionary space instead of
1034: using the default specified in the image (typically 256K). The
1035: @i{size} specification for this and subsequent options consists of
1036: an integer and a unit (e.g.,
1037: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
1038: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
1039: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
1040: @code{e} is used.
1.21 crook 1041:
1.29 crook 1042: @cindex --data-stack-size, command-line option
1043: @cindex -d, command-line option
1044: @item --data-stack-size @i{size}
1045: @itemx -d @i{size}
1046: Allocate @i{size} space for the data stack instead of using the
1047: default specified in the image (typically 16K).
1.21 crook 1048:
1.29 crook 1049: @cindex --return-stack-size, command-line option
1050: @cindex -r, command-line option
1051: @item --return-stack-size @i{size}
1052: @itemx -r @i{size}
1053: Allocate @i{size} space for the return stack instead of using the
1054: default specified in the image (typically 15K).
1.21 crook 1055:
1.29 crook 1056: @cindex --fp-stack-size, command-line option
1057: @cindex -f, command-line option
1058: @item --fp-stack-size @i{size}
1059: @itemx -f @i{size}
1060: Allocate @i{size} space for the floating point stack instead of
1061: using the default specified in the image (typically 15.5K). In this case
1062: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 1063:
1.29 crook 1064: @cindex --locals-stack-size, command-line option
1065: @cindex -l, command-line option
1066: @item --locals-stack-size @i{size}
1067: @itemx -l @i{size}
1068: Allocate @i{size} space for the locals stack instead of using the
1069: default specified in the image (typically 14.5K).
1.21 crook 1070:
1.29 crook 1071: @cindex -h, command-line option
1072: @cindex --help, command-line option
1073: @item --help
1074: @itemx -h
1075: Print a message about the command-line options
1.21 crook 1076:
1.29 crook 1077: @cindex -v, command-line option
1078: @cindex --version, command-line option
1079: @item --version
1080: @itemx -v
1081: Print version and exit
1.21 crook 1082:
1.29 crook 1083: @cindex --debug, command-line option
1084: @item --debug
1085: Print some information useful for debugging on startup.
1.21 crook 1086:
1.29 crook 1087: @cindex --offset-image, command-line option
1088: @item --offset-image
1089: Start the dictionary at a slightly different position than would be used
1090: otherwise (useful for creating data-relocatable images,
1091: @pxref{Data-Relocatable Image Files}).
1.21 crook 1092:
1.29 crook 1093: @cindex --no-offset-im, command-line option
1094: @item --no-offset-im
1095: Start the dictionary at the normal position.
1.21 crook 1096:
1.29 crook 1097: @cindex --clear-dictionary, command-line option
1098: @item --clear-dictionary
1099: Initialize all bytes in the dictionary to 0 before loading the image
1100: (@pxref{Data-Relocatable Image Files}).
1101:
1102: @cindex --die-on-signal, command-line-option
1103: @item --die-on-signal
1104: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
1105: or the segmentation violation SIGSEGV) by translating it into a Forth
1106: @code{THROW}. With this option, Gforth exits if it receives such a
1107: signal. This option is useful when the engine and/or the image might be
1108: severely broken (such that it causes another signal before recovering
1109: from the first); this option avoids endless loops in such cases.
1110: @end table
1111:
1112: @cindex loading files at startup
1113: @cindex executing code on startup
1114: @cindex batch processing with Gforth
1115: As explained above, the image-specific command-line arguments for the
1116: default image @file{gforth.fi} consist of a sequence of filenames and
1117: @code{-e @var{forth-code}} options that are interpreted in the sequence
1118: in which they are given. The @code{-e @var{forth-code}} or
1119: @code{--evaluate @var{forth-code}} option evaluates the Forth
1120: code. This option takes only one argument; if you want to evaluate more
1121: Forth words, you have to quote them or use @code{-e} several times. To exit
1122: after processing the command line (instead of entering interactive mode)
1123: append @code{-e bye} to the command line.
1124:
1125: @cindex versions, invoking other versions of Gforth
1126: If you have several versions of Gforth installed, @code{gforth} will
1127: invoke the version that was installed last. @code{gforth-@i{version}}
1128: invokes a specific version. You may want to use the option
1129: @code{--path}, if your environment contains the variable
1130: @code{GFORTHPATH}.
1131:
1132: Not yet implemented:
1133: On startup the system first executes the system initialization file
1134: (unless the option @code{--no-init-file} is given; note that the system
1135: resulting from using this option may not be ANS Forth conformant). Then
1136: the user initialization file @file{.gforth.fs} is executed, unless the
1137: option @code{--no-rc} is given; this file is first searched in @file{.},
1138: then in @file{~}, then in the normal path (see above).
1.21 crook 1139:
1140:
1141:
1.29 crook 1142: @comment ----------------------------------------------
1143: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
1144: @section Leaving Gforth
1145: @cindex Gforth - leaving
1146: @cindex leaving Gforth
1.21 crook 1147:
1.30 anton 1148: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
1149: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
1150: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1151: data are discarded. @xref{Image Files} for ways of saving the state of
1152: the system before leaving Gforth.
1.21 crook 1153:
1.29 crook 1154: doc-bye
1.21 crook 1155:
1.29 crook 1156: @comment ----------------------------------------------
1157: @node Command-line editing, Upper and lower case,Leaving Gforth,Gforth Environment
1158: @section Command-line editing
1159: @cindex command-line editing
1.21 crook 1160:
1.29 crook 1161: Gforth maintains a history file that records every line that you type to
1162: the text interpreter. This file is preserved between sessions, and is
1163: used to provide a command-line recall facility; if you type ctrl-P
1164: repeatedly you can recall successively older commands from this (or
1165: previous) session(s). The full list of command-line editing facilities is:
1.21 crook 1166:
1.30 anton 1167: @comment use @table? - anton
1.21 crook 1168: @itemize @bullet
1169: @item
1.30 anton 1170: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
1.29 crook 1171: commands from the history buffer.
1172: @item
1.30 anton 1173: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
1.29 crook 1174: from the history buffer.
1175: @item
1.30 anton 1176: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
1.29 crook 1177: @item
1.30 anton 1178: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
1.29 crook 1179: @item
1.30 anton 1180: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
1.29 crook 1181: closing up the line.
1182: @item
1.30 anton 1183: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
1.29 crook 1184: @item
1.30 anton 1185: @kbd{Ctrl-a} to move the cursor to the start of the line.
1.21 crook 1186: @item
1.30 anton 1187: @kbd{Ctrl-e} to move the cursor to the end of the line.
1.21 crook 1188: @item
1.30 anton 1189: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
1.29 crook 1190: line.
1.21 crook 1191: @item
1.30 anton 1192: @key{TAB} to step through all possible full-word completions of the word
1.29 crook 1193: currently being typed.
1.21 crook 1194: @item
1.30 anton 1195: @kbd{Ctrl-d} at the start of the line to terminate Gforth (gracefully,
1196: using @code{bye}).
1.21 crook 1197: @end itemize
1198:
1.29 crook 1199: When editing, displayable characters are inserted to the left of the
1200: cursor position; the line is always in ``insert'' (as opposed to
1201: ``overstrike'') mode.
1202:
1203: @cindex history file
1204: @cindex @file{.gforth-history}
1205: On Unix systems, the history file is @file{~/.gforth-history} by
1206: default@footnote{i.e. it is stored in the user's home directory.}. You
1207: can find out the name and location of your history file using:
1208:
1209: @example
1210: history-file type \ Unix-class systems
1.21 crook 1211:
1.29 crook 1212: history-file type \ Other systems
1213: history-dir type
1.21 crook 1214: @end example
1215:
1.29 crook 1216: If you enter long definitions by hand, you can use a text editor to
1217: paste them out of the history file into a Forth source file for reuse at
1218: a later time.
1219:
1220: Gforth never trims the size of the history file, so you should do this
1221: periodically, if necessary.
1222:
1223: @comment this is all defined in history.fs
1224:
1225:
1226:
1227: @comment ----------------------------------------------
1228: @node Upper and lower case, Environment variables,Command-line editing,Gforth Environment
1229: @section Upper and lower case
1230: @cindex case-sensitivity
1231: @cindex upper and lower case
1232:
1233: Gforth is case-insensitive, so you can enter definitions and invoke
1234: Standard words using upper, lower or mixed case (however,
1235: @pxref{core-idef, Implementation-defined options, Implementation-defined
1236: options}).
1237:
1.30 anton 1238: ANS Forth only @i{requires} implementations to recognise Standard words
1239: when they are typed entirely in upper case. Therefore, a Standard
1240: program must use upper case for all Standard words. You can use whatever
1241: case you like for words that you define, but in a standard program you
1242: have to use the words in the same case that you defined them.
1243:
1244: Gforth supports case sensitivity through @code{table}s (case-sensitive
1245: wordlists, @pxref{Word Lists}).
1246:
1247: Two people have asked how to convert Gforth to case sensitivity; while
1248: we think this is a bad idea, you can change all wordlists into tables
1249: like this:
1.29 crook 1250:
1.30 anton 1251: @example
1252: ' table-find forth-wordlist wordlist-map @ !
1253: @end example
1254:
1255: Note that you now have to type the predefined words in the same case
1256: that we defined them, which are varying. You may want to convert them
1257: to your favourite case before doing this operation (I won't explain how,
1258: because if you are even contemplating to do this, you'd better have
1259: enough knowledge of Forth systems to know this already).
1.29 crook 1260:
1261: @comment ----------------------------------------------
1262: @node Environment variables, Gforth Files, Upper and lower case,Gforth Environment
1263: @section Environment variables
1264: @cindex environment variables
1.21 crook 1265:
1.29 crook 1266: Gforth uses these environment variables:
1.21 crook 1267:
1.29 crook 1268: @itemize @bullet
1269: @item
1270: @cindex GFORTHHIST - environment variable
1271: GFORTHHIST - (Unix systems only) specifies the directory in which to
1272: open/create the history file, @file{.gforth-history}. Default:
1273: @code{$HOME}.
1.21 crook 1274:
1.29 crook 1275: @item
1276: @cindex GFORTHPATH - environment variable
1277: GFORTHPATH - specifies the path used when searching for the gforth image file and
1278: for Forth source-code files.
1.21 crook 1279:
1.29 crook 1280: @item
1281: @cindex GFORTH - environment variable
1282: GFORTH - used by @file{gforthmi} @xref{gforthmi}.
1.26 crook 1283:
1.29 crook 1284: @item
1285: @cindex GFORTHD - environment variable
1286: GFORTHD - used by @file{gforthmi} @xref{gforthmi}.
1.21 crook 1287:
1.29 crook 1288: @item
1289: @cindex TMP, TEMP - environment variable
1290: TMP, TEMP - (non-Unix systems only) used as a potential location for the
1291: history file.
1292: @end itemize
1.21 crook 1293:
1.29 crook 1294: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1295: @comment mentioning these.
1.21 crook 1296:
1.29 crook 1297: All the Gforth environment variables default to sensible values if they
1298: are not set.
1.21 crook 1299:
1300:
1.29 crook 1301: @comment ----------------------------------------------
1302: @node Gforth Files, ,Environment variables,Gforth Environment
1303: @section Gforth files
1304: @cindex Gforth files
1.21 crook 1305:
1.30 anton 1306: When you Gforth on a Unix system in the default places, it installs
1307: files in these locations:
1.21 crook 1308:
1.26 crook 1309: @itemize @bullet
1310: @item
1.29 crook 1311: @file{/usr/local/bin/gforth}
1312: @item
1313: @file{/usr/local/bin/gforthmi}
1314: @item
1315: @file{/usr/local/man/man1/gforth.1} - man page.
1316: @item
1317: @file{/usr/local/info} - the Info version of this manual.
1318: @item
1.30 anton 1319: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1.29 crook 1320: @item
1321: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1.26 crook 1322: @item
1.30 anton 1323: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1.26 crook 1324: @item
1.30 anton 1325: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1.26 crook 1326: @end itemize
1.21 crook 1327:
1.30 anton 1328: You can select different places for installation by using
1329: @code{configure} options (listed with @code{configure --help}).
1.21 crook 1330:
1.29 crook 1331: @c ******************************************************************
1332: @node Introduction, Words, Gforth Environment, Top
1333: @comment node-name, next, previous, up
1334: @chapter An Introduction to ANS Forth
1335: @cindex Forth - an introduction
1.21 crook 1336:
1.29 crook 1337: The primary purpose of this manual is to document Gforth. However, since
1338: Forth is not a widely-known language and there is a lack of up-to-date
1339: teaching material, it seems worthwhile to provide some introductory
1340: material. @xref{Forth-related information} for other sources of Forth-related
1341: information.
1.21 crook 1342:
1.29 crook 1343: The examples in this section should work on any ANS Forth; the
1344: output shown was produced using Gforth. Each example attempts to
1345: reproduce the exact output that Gforth produces. If you try out the
1346: examples (and you should), what you should type is shown @kbd{like this}
1347: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 1348: that, where the example shows @key{RET} it means that you should
1.29 crook 1349: press the ``carriage return'' key. Unfortunately, some output formats for
1350: this manual cannot show the difference between @kbd{this} and
1351: @code{this} which will make trying out the examples harder (but not
1352: impossible).
1.21 crook 1353:
1.29 crook 1354: Forth is an unusual language. It provides an interactive development
1355: environment which includes both an interpreter and compiler. Forth
1356: programming style encourages you to break a problem down into many
1357: @cindex factoring
1358: small fragments (@dfn{factoring}), and then to develop and test each
1359: fragment interactively. Forth advocates assert that breaking the
1360: edit-compile-test cycle used by conventional programming languages can
1361: lead to great productivity improvements.
1.21 crook 1362:
1.29 crook 1363: @menu
1364: * Introducing the Text Interpreter::
1365: * Stacks and Postfix notation::
1366: * Your first definition::
1367: * How does that work?::
1368: * Forth is written in Forth::
1369: * Review - elements of a Forth system::
1370: * Where to go next::
1371: * Exercises::
1372: @end menu
1.21 crook 1373:
1.29 crook 1374: @comment ----------------------------------------------
1375: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
1376: @section Introducing the Text Interpreter
1377: @cindex text interpreter
1378: @cindex outer interpreter
1.21 crook 1379:
1.30 anton 1380: @c IMO this is too detailed and the pace is too slow for
1381: @c an introduction. If you know German, take a look at
1382: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
1383: @c to see how I do it - anton
1384:
1.29 crook 1385: When you invoke the Forth image, you will see a startup banner printed
1386: and nothing else (if you have Gforth installed on your system, try
1.30 anton 1387: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 1388: its command line interpreter, which is called the @dfn{Text Interpreter}
1389: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.30 anton 1390: about the text interpreter as you read through this chapter, but
1391: @pxref{The Text Interpreter} for more detail).
1.21 crook 1392:
1.29 crook 1393: Although it's not obvious, Forth is actually waiting for your
1.30 anton 1394: input. Type a number and press the @key{RET} key:
1.21 crook 1395:
1.26 crook 1396: @example
1.30 anton 1397: @kbd{45@key{RET}} ok
1.26 crook 1398: @end example
1.21 crook 1399:
1.29 crook 1400: Rather than give you a prompt to invite you to input something, the text
1401: interpreter prints a status message @i{after} it has processed a line
1402: of input. The status message in this case (``@code{ ok}'' followed by
1403: carriage-return) indicates that the text interpreter was able to process
1404: all of your input successfully. Now type something illegal:
1405:
1406: @example
1.30 anton 1407: @kbd{qwer341@key{RET}}
1.29 crook 1408: :1: Undefined word
1409: qwer341
1410: ^^^^^^^
1411: $400D2BA8 Bounce
1412: $400DBDA8 no.extensions
1413: @end example
1.23 crook 1414:
1.29 crook 1415: The exact text, other than the ``Undefined word'' may differ slightly on
1416: your system, but the effect is the same; when the text interpreter
1417: detects an error, it discards any remaining text on a line, resets
1.30 anton 1418: certain internal state and prints an error message. @xref{Error
1419: messages} for a detailed description of error messages.
1.23 crook 1420:
1.29 crook 1421: The text interpreter waits for you to press carriage-return, and then
1422: processes your input line. Starting at the beginning of the line, it
1423: breaks the line into groups of characters separated by spaces. For each
1424: group of characters in turn, it makes two attempts to do something:
1.23 crook 1425:
1.29 crook 1426: @itemize @bullet
1427: @item
1428: It tries to treat it as a command. It does this by searching a @dfn{name
1429: dictionary}. If the group of characters matches an entry in the name
1430: dictionary, the name dictionary provides the text interpreter with
1431: information that allows the text interpreter perform some actions. In
1432: Forth jargon, we say that the group
1433: @cindex word
1434: @cindex definition
1435: @cindex execution token
1436: @cindex xt
1437: of characters names a @dfn{word}, that the dictionary search returns an
1438: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
1439: word, and that the text interpreter executes the xt. Often, the terms
1440: @dfn{word} and @dfn{definition} are used interchangeably.
1441: @item
1442: If the text interpreter fails to find a match in the name dictionary, it
1443: tries to treat the group of characters as a number in the current number
1444: base (when you start up Forth, the current number base is base 10). If
1445: the group of characters legitimately represents a number, the text
1446: interpreter pushes the number onto a stack (we'll learn more about that
1447: in the next section).
1448: @end itemize
1.23 crook 1449:
1.29 crook 1450: If the text interpreter is unable to do either of these things with any
1451: group of characters, it discards the group of characters and the rest of
1452: the line, then prints an error message. If the text interpreter reaches
1453: the end of the line without error, it prints the status message ``@code{ ok}''
1454: followed by carriage-return.
1.21 crook 1455:
1.29 crook 1456: This is the simplest command we can give to the text interpreter:
1.23 crook 1457:
1458: @example
1.30 anton 1459: @key{RET} ok
1.23 crook 1460: @end example
1.21 crook 1461:
1.29 crook 1462: The text interpreter did everything we asked it to do (nothing) without
1463: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
1464: command:
1.21 crook 1465:
1.23 crook 1466: @example
1.30 anton 1467: @kbd{12 dup fred dup@key{RET}}
1.29 crook 1468: :1: Undefined word
1469: 12 dup fred dup
1470: ^^^^
1471: $400D2BA8 Bounce
1472: $400DBDA8 no.extensions
1.23 crook 1473: @end example
1.21 crook 1474:
1.29 crook 1475: When you press the carriage-return key, the text interpreter starts to
1476: work its way along the line:
1.21 crook 1477:
1.29 crook 1478: @itemize @bullet
1479: @item
1480: When it gets to the space after the @code{2}, it takes the group of
1481: characters @code{12} and looks them up in the name
1482: dictionary@footnote{We can't tell if it found them or not, but assume
1483: for now that it did not}. There is no match for this group of characters
1484: in the name dictionary, so it tries to treat them as a number. It is
1485: able to do this successfully, so it puts the number, 12, ``on the stack''
1486: (whatever that means).
1487: @item
1488: The text interpreter resumes scanning the line and gets the next group
1489: of characters, @code{dup}. It looks it up in the name dictionary and
1490: (you'll have to take my word for this) finds it, and executes the word
1491: @code{dup} (whatever that means).
1492: @item
1493: Once again, the text interpreter resumes scanning the line and gets the
1494: group of characters @code{fred}. It looks them up in the name
1495: dictionary, but can't find them. It tries to treat them as a number, but
1496: they don't represent any legal number.
1497: @end itemize
1.21 crook 1498:
1.29 crook 1499: At this point, the text interpreter gives up and prints an error
1500: message. The error message shows exactly how far the text interpreter
1501: got in processing the line. In particular, it shows that the text
1502: interpreter made no attempt to do anything with the final character
1503: group, @code{dup}, even though we have good reason to believe that the
1504: text interpreter would have no problem looking that word up and
1505: executing it a second time.
1.21 crook 1506:
1507:
1.29 crook 1508: @comment ----------------------------------------------
1509: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
1510: @section Stacks, postfix notation and parameter passing
1511: @cindex text interpreter
1512: @cindex outer interpreter
1.21 crook 1513:
1.29 crook 1514: In procedural programming languages (like C and Pascal), the
1515: building-block of programs is the @dfn{function} or @dfn{procedure}. These
1516: functions or procedures are called with @dfn{explicit parameters}. For
1517: example, in C we might write:
1.21 crook 1518:
1.23 crook 1519: @example
1.29 crook 1520: total = total + new_volume(length,height,depth);
1.23 crook 1521: @end example
1.21 crook 1522:
1.23 crook 1523: @noindent
1.29 crook 1524: where new_volume is a function-call to another piece of code, and total,
1525: length, height and depth are all variables. length, height and depth are
1526: parameters to the function-call.
1.21 crook 1527:
1.29 crook 1528: In Forth, the equivalent of the function or procedure is the
1529: @dfn{definition} and parameters are implicitly passed between
1530: definitions using a shared stack that is visible to the
1531: programmer. Although Forth does support variables, the existence of the
1532: stack means that they are used far less often than in most other
1533: programming languages. When the text interpreter encounters a number, it
1534: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 1535: actual number is implementation-dependent ...) and the particular stack
1.29 crook 1536: used for any operation is implied unambiguously by the operation being
1537: performed. The stack used for all integer operations is called the @dfn{data
1538: stack} and, since this is the stack used most commonly, references to
1539: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 1540:
1.29 crook 1541: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 1542:
1.23 crook 1543: @example
1.30 anton 1544: @kbd{1 2 3@key{RET}} ok
1.23 crook 1545: @end example
1.21 crook 1546:
1.29 crook 1547: Then this instructs the text interpreter to placed three numbers on the
1548: (data) stack. An analogy for the behaviour of the stack is to take a
1549: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
1550: the table. The 3 was the last card onto the pile (``last-in'') and if
1551: you take a card off the pile then, unless you're prepared to fiddle a
1552: bit, the card that you take off will be the 3 (``first-out''). The
1553: number that will be first-out of the stack is called the @dfn{top of
1554: stack}, which
1555: @cindex TOS definition
1556: is often abbreviated to @dfn{TOS}.
1.21 crook 1557:
1.29 crook 1558: To understand how parameters are passed in Forth, consider the
1559: behaviour of the definition @code{+} (pronounced ``plus''). You will not
1560: be surprised to learn that this definition performs addition. More
1561: precisely, it adds two number together and produces a result. Where does
1562: it get the two numbers from? It takes the top two numbers off the
1563: stack. Where does it place the result? On the stack. You can act-out the
1564: behaviour of @code{+} with your playing cards like this:
1.21 crook 1565:
1566: @itemize @bullet
1567: @item
1.29 crook 1568: Pick up two cards from the stack on the table
1.21 crook 1569: @item
1.29 crook 1570: Stare at them intently and ask yourself ``what @i{is} the sum of these two
1571: numbers''
1.21 crook 1572: @item
1.29 crook 1573: Decide that the answer is 5
1.21 crook 1574: @item
1.29 crook 1575: Shuffle the two cards back into the pack and find a 5
1.21 crook 1576: @item
1.29 crook 1577: Put a 5 on the remaining ace that's on the table.
1.21 crook 1578: @end itemize
1579:
1.29 crook 1580: If you don't have a pack of cards handy but you do have Forth running,
1581: you can use the definition @code{.s} to show the current state of the stack,
1582: without affecting the stack. Type:
1.21 crook 1583:
1584: @example
1.30 anton 1585: @kbd{clearstack 1 2 3@key{RET}} ok
1586: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 1587: @end example
1588:
1.29 crook 1589: The text interpreter looks up the word @code{clearstack} and executes
1590: it; it tidies up the stack and removes any entries that may have been
1591: left on it by earlier examples. The text interpreter pushes each of the
1592: three numbers in turn onto the stack. Finally, the text interpreter
1593: looks up the word @code{.s} and executes it. The effect of executing
1594: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
1595: followed by a list of all the items on the stack; the item on the far
1596: right-hand side is the TOS.
1.21 crook 1597:
1.29 crook 1598: You can now type:
1.21 crook 1599:
1.29 crook 1600: @example
1.30 anton 1601: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 1602: @end example
1.21 crook 1603:
1.29 crook 1604: @noindent
1605: which is correct; there are now 2 items on the stack and the result of
1606: the addition is 5.
1.23 crook 1607:
1.29 crook 1608: If you're playing with cards, try doing a second addition: pick up the
1609: two cards, work out that their sum is 6, shuffle them into the pack,
1610: look for a 6 and place that on the table. You now have just one item on
1611: the stack. What happens if you try to do a third addition? Pick up the
1612: first card, pick up the second card -- ah! There is no second card. This
1613: is called a @dfn{stack underflow} and consitutes an error. If you try to
1614: do the same thing with Forth it will report an error (probably a Stack
1615: Underflow or an Invalid Memory Address error).
1.23 crook 1616:
1.29 crook 1617: The opposite situation to a stack underflow is a @dfn{stack overflow},
1618: which simply accepts that there is a finite amount of storage space
1619: reserved for the stack. To stretch the playing card analogy, if you had
1620: enough packs of cards and you piled the cards up on the table, you would
1621: eventually be unable to add another card; you'd hit the ceiling. Gforth
1622: allows you to set the maximum size of the stacks. In general, the only
1623: time that you will get a stack overflow is because a definition has a
1624: bug in it and is generating data on the stack uncontrollably.
1.23 crook 1625:
1.29 crook 1626: There's one final use for the playing card analogy. If you model your
1627: stack using a pack of playing cards, the maximum number of items on
1628: your stack will be 52 (I assume you didn't use the Joker). The maximum
1629: @i{value} of any item on the stack is 13 (the King). In fact, the only
1630: possible numbers are positive integer numbers 1 through 13; you can't
1631: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
1632: think about some of the cards, you can accommodate different
1633: numbers. For example, you could think of the Jack as representing 0,
1634: the Queen as representing -1 and the King as representing -2. Your
1635: *range* remains unchanged (you can still only represent a total of 13
1636: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 1637:
1.29 crook 1638: In that analogy, the limit was the amount of information that a single
1639: stack entry could hold, and Forth has a similar limit. In Forth, the
1640: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
1641: implementation dependent and affects the maximum value that a stack
1642: entry can hold. A Standard Forth provides a cell size of at least
1643: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 1644:
1.29 crook 1645: Forth does not do any type checking for you, so you are free to
1646: manipulate and combine stack items in any way you wish. A convenient way
1647: of treating stack items is as 2's complement signed integers, and that
1648: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 1649:
1.29 crook 1650: @example
1.30 anton 1651: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 1652: @end example
1.21 crook 1653:
1.29 crook 1654: If you use numbers and definitions like @code{+} in order to turn Forth
1655: into a great big pocket calculator, you will realise that it's rather
1656: different from a normal calculator. Rather than typing 2 + 3 = you had
1657: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
1658: result). The terminology used to describe this difference is to say that
1659: your calculator uses @dfn{Infix Notation} (parameters and operators are
1660: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
1661: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 1662:
1.29 crook 1663: Whilst postfix notation might look confusing to begin with, it has
1664: several important advantages:
1.21 crook 1665:
1.23 crook 1666: @itemize @bullet
1667: @item
1.29 crook 1668: it is unambiguous
1.23 crook 1669: @item
1.29 crook 1670: it is more concise
1.23 crook 1671: @item
1.29 crook 1672: it fits naturally with a stack-based system
1.23 crook 1673: @end itemize
1.21 crook 1674:
1.29 crook 1675: To examine these claims in more detail, consider these sums:
1.21 crook 1676:
1.29 crook 1677: @example
1678: 6 + 5 * 4 =
1679: 4 * 5 + 6 =
1680: @end example
1.21 crook 1681:
1.29 crook 1682: If you're just learning maths or your maths is very rusty, you will
1683: probably come up with the answer 44 for the first and 26 for the
1684: second. If you are a bit of a whizz at maths you will remember the
1685: @i{convention} that multiplication takes precendence over addition, and
1686: you'd come up with the answer 26 both times. To explain the answer 26
1687: to someone who got the answer 44, you'd probably rewrite the first sum
1688: like this:
1.21 crook 1689:
1.29 crook 1690: @example
1691: 6 + (5 * 4) =
1692: @end example
1.21 crook 1693:
1.29 crook 1694: If what you really wanted was to perform the addition before the
1695: multiplication, you would have to use parentheses to force it.
1.21 crook 1696:
1.29 crook 1697: If you did the first two sums on a pocket calculator you would probably
1698: get the right answers, unless you were very cautious and entered them using
1699: these keystroke sequences:
1.21 crook 1700:
1.29 crook 1701: 6 + 5 = * 4 =
1702: 4 * 5 = + 6 =
1.21 crook 1703:
1.29 crook 1704: Postfix notation is unambiguous because the order that the operators
1705: are applied is always explicit; that also means that parentheses are
1706: never required. The operators are @i{active} (the act of quoting the
1707: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 1708:
1.29 crook 1709: The sum 6 + 5 * 4 can be written (in postfix notation) in two
1710: equivalent ways:
1.26 crook 1711:
1712: @example
1.29 crook 1713: 6 5 4 * + or:
1714: 5 4 * 6 +
1.26 crook 1715: @end example
1.23 crook 1716:
1.29 crook 1717: An important thing that you should notice about this notation is that
1718: the @i{order} of the numbers does not change; if you want to subtract
1719: 2 from 10 you type @code{10 2 -}.
1.1 anton 1720:
1.29 crook 1721: The reason that Forth uses postfix notation is very simple to explain: it
1722: makes the implementation extremely simple, and it follows naturally from
1723: using the stack as a mechanism for passing parameters. Another way of
1724: thinking about this is to realise that all Forth definitions are
1725: @i{active}; they execute as they are encountered by the text
1726: interpreter. The result of this is that the syntax of Forth is trivially
1727: simple.
1.1 anton 1728:
1729:
1730:
1.29 crook 1731: @comment ----------------------------------------------
1732: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
1733: @section Your first Forth definition
1734: @cindex first definition
1.1 anton 1735:
1.29 crook 1736: Until now, the examples we've seen have been trivial; we've just been
1737: using Forth as a bigger-than-pocket calculator. Also, each calculation
1738: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
1739: again@footnote{That's not quite true. If you press the up-arrow key on
1740: your keyboard you should be able to scroll back to any earlier command,
1741: edit it and re-enter it.} In this section we'll see how to add new
1742: words to Forth's vocabulary.
1.1 anton 1743:
1.29 crook 1744: The easiest way to create a new word is to use a @dfn{colon
1745: definition}. We'll define a few and try them out before worrying too
1746: much about how they work. Try typing in these examples; be careful to
1747: copy the spaces accurately:
1.1 anton 1748:
1.29 crook 1749: @example
1750: : add-two 2 + . ;
1751: : greet ." Hello and welcome" ;
1752: : demo 5 add-two ;
1753: @end example
1.1 anton 1754:
1.29 crook 1755: @noindent
1756: Now try them out:
1.1 anton 1757:
1.29 crook 1758: @example
1.30 anton 1759: @kbd{greet@key{RET}} Hello and welcome ok
1760: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
1761: @kbd{4 add-two@key{RET}} 6 ok
1762: @kbd{demo@key{RET}} 7 ok
1763: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 1764: @end example
1.1 anton 1765:
1.29 crook 1766: The first new thing that we've introduced here is the pair of words
1767: @code{:} and @code{;}. These are used to start and terminate a new
1768: definition, respectively. The first word after the @code{:} is the name
1769: for the new definition.
1.1 anton 1770:
1.29 crook 1771: As you can see from the examples, a definition is built up of words that
1772: have already been defined; Forth makes no distinction between
1773: definitions that existed when you started the system up, and those that
1774: you define yourself.
1.1 anton 1775:
1.29 crook 1776: The examples also introduce the words @code{.} (dot), @code{."}
1777: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
1778: the stack and displays it. It's like @code{.s} except that it only
1779: displays the top item of the stack and it is destructive; after it has
1780: executed, the number is no longer on the stack. There is always one
1781: space printed after the number, and no spaces before it. Dot-quote
1782: defines a string (a sequence of characters) that will be printed when
1783: the word is executed. The string can contain any printable characters
1784: except @code{"}. A @code{"} has a special function; it is not a Forth
1785: word but it acts as a delimiter (the way that delimiters work is
1786: described in the next section). Finally, @code{dup} duplicates the value
1787: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 1788:
1.29 crook 1789: We already know that the text interpreter searches through the
1790: dictionary to locate names. If you've followed the examples earlier, you
1791: will already have a definition called @code{add-two}. Lets try modifying
1792: it by typing in a new definition:
1.1 anton 1793:
1.29 crook 1794: @example
1.30 anton 1795: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 1796: @end example
1.5 anton 1797:
1.29 crook 1798: Forth recognised that we were defining a word that already exists, and
1799: printed a message to warn us of that fact. Let's try out the new
1800: definition:
1.5 anton 1801:
1.29 crook 1802: @example
1.30 anton 1803: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 1804: @end example
1.1 anton 1805:
1.29 crook 1806: @noindent
1807: All that we've actually done here, though, is to create a new
1808: definition, with a particular name. The fact that there was already a
1809: definition with the same name did not make any difference to the way
1810: that the new definition was created (except that Forth printed a warning
1811: message). The old definition of add-two still exists (try @code{demo}
1812: again to see that this is true). Any new definition will use the new
1813: definition of @code{add-two}, but old definitions continue to use the
1814: version that already existed at the time that they were @code{compiled}.
1.1 anton 1815:
1.29 crook 1816: Before you go on to the next section, try defining and redefining some
1817: words of your own.
1.1 anton 1818:
1.29 crook 1819: @comment ----------------------------------------------
1820: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
1821: @section How does that work?
1822: @cindex parsing words
1.1 anton 1823:
1.30 anton 1824: @c That's pretty deep (IMO way too deep) for an introduction. - anton
1825:
1826: @c Is it a good idea to talk about the interpretation semantics of a
1827: @c number? We don't have an xt to go along with it. - anton
1828:
1829: @c Now that I have eliminated execution semantics, I wonder if it would not
1830: @c be better to keep them (or add run-time semantics), to make it easier to
1831: @c explain what compilation semantics usually does. - anton
1832:
1.29 crook 1833: Now we're going to take another look at the definition of @code{add-two}
1834: from the previous section. From our knowledge of the way that the text
1835: interpreter works, we would have expected this result when we tried to
1836: define @code{add-two}:
1.21 crook 1837:
1.29 crook 1838: @example
1.30 anton 1839: @kbd{: add-two 2 + . " ;@key{RET}}
1.29 crook 1840: ^^^^^^^
1841: Error: Undefined word
1842: @end example
1.28 crook 1843:
1.29 crook 1844: The reason that this didn't happen is bound up in the way that @code{:}
1845: works. The word @code{:} does two special things. The first special
1846: thing that it does prevents the text interpreter from ever seeing the
1847: characters @code{add-two}. The text interpreter uses a variable called
1848: @cindex modifying >IN
1849: @code{>IN} (pronounced ''to-in'') to keep track of where it is in the
1850: input line. When it encounters the word @code{:} it behaves in exactly
1851: the same way as it does for any other word; it looks it up in the name
1852: dictionary, finds its xt and executes it. When @code{:} executes, it
1853: looks at the input buffer, finds the word @code{add-two} and advances the
1854: value of @code{>IN} to point past it. It then does some other stuff
1855: associated with creating the new definition (including creating an entry
1856: for @code{add-two} in the name dictionary). When the execution of @code{:}
1857: completes, control returns to the text interpreter, which is oblivious
1858: to the fact that it has been tricked into ignoring part of the input
1859: line.
1.21 crook 1860:
1.29 crook 1861: @cindex parsing words
1862: Words like @code{:} -- words that advance the value of @code{>IN} and so
1863: prevent the text interpreter from acting on the whole of the input line
1864: -- are called @dfn{parsing words}.
1.21 crook 1865:
1.29 crook 1866: @cindex @code{state} - effect on the text interpreter
1867: @cindex text interpreter - effect of state
1868: The second special thing that @code{:} does is change the value of a
1869: variable called @code{state}, which affects the way that the text
1870: interpreter behaves. When Gforth starts up, @code{state} has the value
1871: 0, and the text interpreter is said to be @dfn{interpreting}. During a
1872: colon definition (started with @code{:}), @code{state} is set to -1 and
1873: the text interpreter is said to be @dfn{compiling}. The word @code{;}
1874: ends the definition -- one of the things that it does is to change the
1875: value of @code{state} back to 0.
1.21 crook 1876:
1.29 crook 1877: We have already seen how the text interpreter behaves when it is
1878: interpreting; it looks for each character sequence in the dictionary,
1879: finds its xt and executes it, or it converts it to a number and pushes
1880: it onto the stack, or it fails to do either and generates an error.
1.21 crook 1881:
1.29 crook 1882: When the text interpreter is compiling, its behaviour is slightly
1883: different; it still looks for each character sequence in the dictionary
1.30 anton 1884: and finds it, or converts it to a number, or fails to do either and
1885: generates an error. But instead of the execution token of a word it
1886: finds and executes the compilation token. For most words executing the
1887: compilation token results in laying down (@dfn{compiling}) the execution
1888: token, i.e., some magic to make that xt or number get executed or pushed
1889: at a later time; at the time that @code{add-two} is
1890: @dfn{executed}. Therefore, when you execute @code{add-two} its
1891: @dfn{run-time effect} is exactly the same as if you had typed @code{2 +
1892: .} outside of a definition, and pressed carriage-return.
1.28 crook 1893:
1.30 anton 1894: In Forth, every word or number can be described in terms of two
1.29 crook 1895: properties:
1.28 crook 1896:
1897: @itemize @bullet
1898: @item
1.30 anton 1899: Its @dfn{interpretation semantics}, represented by the execution token.
1.28 crook 1900: @item
1.30 anton 1901: Its @dfn{compilation semantics}, represented by the compilation token.
1.29 crook 1902: @end itemize
1903:
1.30 anton 1904: The value of @code{state} determines whether the text interpreter will
1905: use the compilation or interpretation semantics of a word or number that
1906: it encounters.
1.29 crook 1907:
1908: @itemize @bullet
1.28 crook 1909: @item
1.29 crook 1910: @cindex interpretation semantics
1911: When the text interpreter encounters a word or number in @dfn{interpret}
1912: state, it performs the @dfn{interpretation semantics} of the word or
1913: number.
1.28 crook 1914: @item
1.29 crook 1915: @cindex compilation semantics
1916: When the text interpreter encounters a word or number in @dfn{compile}
1917: state, it performs the @dfn{compilation semantics} of the word or
1918: number.
1919: @end itemize
1920:
1921: @noindent
1922: Numbers are always treated in a fixed way:
1923:
1924: @itemize @bullet
1.28 crook 1925: @item
1.30 anton 1926: When the number is @dfn{interpreted}, its behaviour is to push the number onto the stack.
1.28 crook 1927: @item
1.30 anton 1928: When the number is @dfn{compiled}, a piece of code is appended to the
1929: current definition that pushes the number when it runs. (In other words,
1930: the compilation semantics of a number are to postpone its interpretation
1931: semantics until the run-time of the definition that it is being compiled
1932: into.)
1.29 crook 1933: @end itemize
1934:
1935: The behaviour of a word is not so regular, but most have @i{default
1.30 anton 1936: compilation semantics} which means that they behave like this:
1.29 crook 1937:
1938: @itemize @bullet
1.28 crook 1939: @item
1.30 anton 1940: The @dfn{interpretation semantics} of the word are to do something useful.
1941: @item
1.29 crook 1942: The @dfn{compilation semantics} of the word are to append its
1.30 anton 1943: @dfn{interpretation semantics} to the current definition (so that its
1944: run-time behaviour is to do something useful).
1.28 crook 1945: @end itemize
1946:
1.30 anton 1947: @cindex immediate words
1.29 crook 1948: The actual behaviour of any particular word depends upon the way in
1949: which it was defined. When the text interpreter finds the word in the
1950: name dictionary, it not only retrieves the xt for the word, it also
1951: retrieves some flags: the @dfn{compile-only} flag and the @dfn{immediate
1952: flag}. The compile-only flag indicates that the word has no
1.30 anton 1953: interpretation semantics (the run-time behaviour for the default
1954: compilation semantics is not affected by this flag, however); any
1955: attempt to interpret a word that has the compile-only flag set will
1956: generate an error (for example, @code{IF} has no interpretation
1957: semantics). The immediate flag changes the compilation semantics of the
1958: word; if it is set, the compilation semantics are equal to the
1959: interpretation semantics (again ignoring the compile-only flag). it. In
1960: other words, these so-called @dfn{immediate} words behave like this:
1.29 crook 1961:
1962: @itemize @bullet
1963: @item
1.30 anton 1964: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 1965: @item
1.30 anton 1966: The @dfn{compilation semantics} of the word are to do something useful
1967: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 1968: @end itemize
1.28 crook 1969:
1.29 crook 1970: This example shows the difference between an immediate and a
1971: non-immediate word:
1.28 crook 1972:
1.29 crook 1973: @example
1974: : show-state state @@ . ;
1975: : show-state-now show-state ; immediate
1976: : word1 show-state ;
1977: : word2 show-state-now ;
1.28 crook 1978: @end example
1.23 crook 1979:
1.29 crook 1980: The word @code{immediate} after the definition of @code{show-state-now}
1981: makes that word an immediate word. These definitions introduce a new
1982: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
1983: variable, and leaves it on the stack. Therefore, the behaviour of
1984: @code{show-state} is to print a number that represents the current value
1985: of @code{state}.
1.28 crook 1986:
1.29 crook 1987: When you execute @code{word1}, it prints the number 0, indicating that
1988: the system is interpreting. When the text interpreter compiled the
1989: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 1990: compilation semantics are to append its interpretation semantics to the
1.29 crook 1991: current definition. When you execute @code{word1}, it performs the
1.30 anton 1992: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 1993: (and therefore @code{show-state}) are executed, the system is
1994: interpreting.
1.28 crook 1995:
1.30 anton 1996: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 1997: you should have seen the number -1 printed, followed by ``@code{
1998: ok}''. When the text interpreter compiled the definition of
1999: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 2000: whose compilation semantics are therefore to perform its interpretation
1.29 crook 2001: semantics. It is executed straight away (even before the text
2002: interpreter has moved on to process another group of characters; the
2003: @code{;} in this example). The effect of executing it are to display the
2004: value of @code{state} @i{at the time that the definition of}
2005: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
2006: system is compiling at this time. If you execute @code{word2} it does
2007: nothing at all.
1.28 crook 2008:
1.29 crook 2009: @cindex @code{."}, how it works
2010: Before leaving the subject of immediate words, consider the behaviour of
2011: @code{."} in the definition of @code{greet}, in the previous
2012: section. This word is both a parsing word and an immediate word. Notice
2013: that there is a space between @code{."} and the start of the text
2014: @code{Hello and welcome}, but that there is no space between the last
2015: letter of @code{welcome} and the @code{"} character. The reason for this
2016: is that @code{."} is a Forth word; it must have a space after it so that
2017: the text interpreter can identify it. The @code{"} is not a Forth word;
2018: it is a @dfn{delimiter}. The examples earlier show that, when the string
2019: is displayed, there is neither a space before the @code{H} nor after the
2020: @code{e}. Since @code{."} is an immediate word, it executes at the time
2021: that @code{greet} is defined. When it executes, its behaviour is to
2022: search forward in the input line looking for the delimiter. When it
2023: finds the delimiter, it updates @code{>IN} to point past the
2024: delimiter. It also compiles some magic code into the definition of
2025: @code{greet}; the xt of a run-time routine that prints a text string. It
2026: compiles the string @code{Hello and welcome} into memory so that it is
2027: available to be printed later. When the text interpreter gains control,
2028: the next word it finds in the input stream is @code{;} and so it
2029: terminates the definition of @code{greet}.
1.28 crook 2030:
2031:
2032: @comment ----------------------------------------------
1.29 crook 2033: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
2034: @section Forth is written in Forth
2035: @cindex structure of Forth programs
2036:
2037: When you start up a Forth compiler, a large number of definitions
2038: already exist. In Forth, you develop a new application using bottom-up
2039: programming techniques to create new definitions that are defined in
2040: terms of existing definitions. As you create each definition you can
2041: test and debug it interactively.
2042:
2043: If you have tried out the examples in this section, you will probably
2044: have typed them in by hand; when you leave Gforth, your definitions will
2045: be lost. You can avoid this by using a text editor to enter Forth source
2046: code into a file, and then loading code from the file using
2047: @code{include} (@xref{Forth source files}). A Forth source file is
2048: processed by the text interpreter, just as though you had typed it in by
2049: hand@footnote{Actually, there are some subtle differences -- see
2050: @ref{The Text Interpreter}.}.
2051:
2052: Gforth also supports the traditional Forth alternative to using text
2053: files for program entry (@xref{Blocks}).
1.28 crook 2054:
1.29 crook 2055: In common with many, if not most, Forth compilers, most of Gforth is
2056: actually written in Forth. All of the @file{.fs} files in the
2057: installation directory@footnote{For example,
1.30 anton 2058: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 2059: study to see examples of Forth programming.
1.28 crook 2060:
1.29 crook 2061: Gforth maintains a history file that records every line that you type to
2062: the text interpreter. This file is preserved between sessions, and is
2063: used to provide a command-line recall facility. If you enter long
2064: definitions by hand, you can use a text editor to paste them out of the
2065: history file into a Forth source file for reuse at a later time
2066: (@pxref{Command-line editing} for more information).
1.28 crook 2067:
2068:
2069: @comment ----------------------------------------------
1.29 crook 2070: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
2071: @section Review - elements of a Forth system
2072: @cindex elements of a Forth system
1.28 crook 2073:
1.29 crook 2074: To summarise this chapter:
1.28 crook 2075:
2076: @itemize @bullet
2077: @item
1.29 crook 2078: Forth programs use @dfn{factoring} to break a problem down into small
2079: fragments called @dfn{words} or @dfn{definitions}.
2080: @item
2081: Forth program development is an interactive process.
2082: @item
2083: The main command loop that accepts input, and controls both
2084: interpretation and compilation, is called the @dfn{text interpreter}
2085: (also known as the @dfn{outer interpreter}).
2086: @item
2087: Forth has a very simple syntax, consisting of words and numbers
2088: separated by spaces or carriage-return characters. Any additional syntax
2089: is imposed by @dfn{parsing words}.
2090: @item
2091: Forth uses a stack to pass parameters between words. As a result, it
2092: uses postfix notation.
2093: @item
2094: To use a word that has previously been defined, the text interpreter
2095: searches for the word in the @dfn{name dictionary}.
2096: @item
1.30 anton 2097: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 2098: @item
1.29 crook 2099: The text interpreter uses the value of @code{state} to select between
2100: the use of the @dfn{interpretation semantics} and the @dfn{compilation
2101: semantics} of a word that it encounters.
1.28 crook 2102: @item
1.30 anton 2103: The relationship between the @dfn{interpretation semantics} and
2104: @dfn{compilation semantics} for a word
1.29 crook 2105: depend upon the way in which the word was defined (for example, whether
2106: it is an @dfn{immediate} word).
1.28 crook 2107: @item
1.29 crook 2108: Forth definitions can be implemented in Forth (called @dfn{high-level
2109: definitions}) or in some other way (usually a lower-level language and
2110: as a result often called @dfn{low-level definitions}, @dfn{code
2111: definitions} or @dfn{primitives}).
1.28 crook 2112: @item
1.29 crook 2113: Many Forth systems are implemented mainly in Forth.
1.28 crook 2114: @end itemize
2115:
2116:
1.29 crook 2117: @comment ----------------------------------------------
2118: @node Where to go next,Exercises,Review - elements of a Forth system, Introduction
2119: @section Where To Go Next
2120: @cindex where to go next
1.28 crook 2121:
1.29 crook 2122: Amazing as it may seem, if you have read (and understood) this far, you
2123: know almost all the fundamentals about the inner workings of a Forth
2124: system. You certainly know enough to be able to read and understand the
2125: rest of this manual and the ANS Forth document, to learn more about the
2126: facilities that Forth in general and Gforth in particular provide. Even
2127: scarier, you know almost enough to implement your own Forth system.
1.30 anton 2128: However, that's not a good idea just yet... better to try writing some
1.29 crook 2129: programs in Gforth.
1.28 crook 2130:
1.29 crook 2131: Forth has such a rich vocabulary that it can be hard to know where to
2132: start in learning it. This section suggests a few sets of words that are
2133: enough to write small but useful programs. Use the word index in this
2134: document to learn more about each word, then try it out and try to write
2135: small definitions using it. Start by experimenting with these words:
1.28 crook 2136:
2137: @itemize @bullet
2138: @item
1.29 crook 2139: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
2140: @item
2141: Comparison: @code{MIN MAX =}
2142: @item
2143: Logic: @code{AND OR XOR NOT}
2144: @item
2145: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 2146: @item
1.29 crook 2147: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 2148: @item
1.29 crook 2149: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 2150: @item
1.29 crook 2151: Defining words: @code{: ; CREATE}
1.28 crook 2152: @item
1.29 crook 2153: Memory allocation words: @code{ALLOT ,}
1.28 crook 2154: @item
1.29 crook 2155: Tools: @code{SEE WORDS .S MARKER}
2156: @end itemize
2157:
2158: When you have mastered those, go on to:
2159:
2160: @itemize @bullet
1.28 crook 2161: @item
1.29 crook 2162: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 2163: @item
1.29 crook 2164: Memory access: @code{@@ !}
1.28 crook 2165: @end itemize
1.23 crook 2166:
1.29 crook 2167: When you have mastered these, there's nothing for it but to read through
2168: the whole of this manual and find out what you've missed.
2169:
2170: @comment ----------------------------------------------
2171: @node Exercises, ,Where to go next, Introduction
2172: @section Exercises
2173: @cindex exercises
2174:
2175: TODO: provide a set of programming excercises linked into the stuff done
2176: already and into other sections of the manual. Provide solutions to all
2177: the exercises in a .fs file in the distribution.
2178:
2179: @c Get some inspiration from Starting Forth and Kelly&Spies.
2180:
2181: @c excercises:
2182: @c 1. take inches and convert to feet and inches.
2183: @c 2. take temperature and convert from fahrenheight to celcius;
2184: @c may need to care about symmetric vs floored??
2185: @c 3. take input line and do character substitution
2186: @c to encipher or decipher
2187: @c 4. as above but work on a file for in and out
2188: @c 5. take input line and convert to pig-latin
2189: @c
2190: @c thing of sets of things to exercise then come up with
2191: @c problems that need those things.
2192:
2193:
1.26 crook 2194: @c ******************************************************************
1.29 crook 2195: @node Words, Error messages, Introduction, Top
1.1 anton 2196: @chapter Forth Words
1.26 crook 2197: @cindex words
1.1 anton 2198:
2199: @menu
2200: * Notation::
1.21 crook 2201: * Comments::
2202: * Boolean Flags::
1.1 anton 2203: * Arithmetic::
2204: * Stack Manipulation::
1.5 anton 2205: * Memory::
1.1 anton 2206: * Control Structures::
2207: * Defining Words::
1.21 crook 2208: * The Text Interpreter::
1.12 anton 2209: * Tokens for Words::
1.21 crook 2210: * Word Lists::
2211: * Environmental Queries::
1.12 anton 2212: * Files::
2213: * Blocks::
2214: * Other I/O::
2215: * Programming Tools::
2216: * Assembler and Code Words::
2217: * Threading Words::
1.26 crook 2218: * Locals::
2219: * Structures::
2220: * Object-oriented Forth::
1.21 crook 2221: * Passing Commands to the OS::
2222: * Miscellaneous Words::
1.1 anton 2223: @end menu
2224:
1.21 crook 2225: @node Notation, Comments, Words, Words
1.1 anton 2226: @section Notation
2227: @cindex notation of glossary entries
2228: @cindex format of glossary entries
2229: @cindex glossary notation format
2230: @cindex word glossary entry format
2231:
2232: The Forth words are described in this section in the glossary notation
2233: that has become a de-facto standard for Forth texts, i.e.,
2234:
2235: @format
1.29 crook 2236: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 2237: @end format
1.29 crook 2238: @i{Description}
1.1 anton 2239:
2240: @table @var
2241: @item word
1.28 crook 2242: The name of the word.
1.1 anton 2243:
2244: @item Stack effect
2245: @cindex stack effect
1.29 crook 2246: The stack effect is written in the notation @code{@i{before} --
2247: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 2248: stack entries before and after the execution of the word. The rest of
2249: the stack is not touched by the word. The top of stack is rightmost,
2250: i.e., a stack sequence is written as it is typed in. Note that Gforth
2251: uses a separate floating point stack, but a unified stack
1.29 crook 2252: notation. Also, return stack effects are not shown in @i{stack
2253: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 2254: the type and/or the function of the item. See below for a discussion of
2255: the types.
2256:
2257: All words have two stack effects: A compile-time stack effect and a
2258: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 2259: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 2260: this standard behaviour, or the word does other unusual things at
2261: compile time, both stack effects are shown; otherwise only the run-time
2262: stack effect is shown.
2263:
2264: @cindex pronounciation of words
2265: @item pronunciation
2266: How the word is pronounced.
2267:
2268: @cindex wordset
2269: @item wordset
1.21 crook 2270: The ANS Forth standard is divided into several word sets. A standard
2271: system need not support all of them. Therefore, in theory, the fewer
2272: word sets your program uses the more portable it will be. However, we
2273: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 2274: all word sets. Words that are not defined in ANS Forth have
1.21 crook 2275: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 2276: describes words that will work in future releases of Gforth;
2277: @code{gforth-internal} words are more volatile. Environmental query
2278: strings are also displayed like words; you can recognize them by the
1.21 crook 2279: @code{environment} in the word set field.
1.1 anton 2280:
2281: @item Description
2282: A description of the behaviour of the word.
2283: @end table
2284:
2285: @cindex types of stack items
2286: @cindex stack item types
2287: The type of a stack item is specified by the character(s) the name
2288: starts with:
2289:
2290: @table @code
2291: @item f
2292: @cindex @code{f}, stack item type
2293: Boolean flags, i.e. @code{false} or @code{true}.
2294: @item c
2295: @cindex @code{c}, stack item type
2296: Char
2297: @item w
2298: @cindex @code{w}, stack item type
2299: Cell, can contain an integer or an address
2300: @item n
2301: @cindex @code{n}, stack item type
2302: signed integer
2303: @item u
2304: @cindex @code{u}, stack item type
2305: unsigned integer
2306: @item d
2307: @cindex @code{d}, stack item type
2308: double sized signed integer
2309: @item ud
2310: @cindex @code{ud}, stack item type
2311: double sized unsigned integer
2312: @item r
2313: @cindex @code{r}, stack item type
2314: Float (on the FP stack)
1.21 crook 2315: @item a-
1.1 anton 2316: @cindex @code{a_}, stack item type
2317: Cell-aligned address
1.21 crook 2318: @item c-
1.1 anton 2319: @cindex @code{c_}, stack item type
2320: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 2321: @item f-
1.1 anton 2322: @cindex @code{f_}, stack item type
2323: Float-aligned address
1.21 crook 2324: @item df-
1.1 anton 2325: @cindex @code{df_}, stack item type
2326: Address aligned for IEEE double precision float
1.21 crook 2327: @item sf-
1.1 anton 2328: @cindex @code{sf_}, stack item type
2329: Address aligned for IEEE single precision float
2330: @item xt
2331: @cindex @code{xt}, stack item type
2332: Execution token, same size as Cell
2333: @item wid
2334: @cindex @code{wid}, stack item type
1.21 crook 2335: Word list ID, same size as Cell
1.1 anton 2336: @item f83name
2337: @cindex @code{f83name}, stack item type
2338: Pointer to a name structure
2339: @item "
2340: @cindex @code{"}, stack item type
1.12 anton 2341: string in the input stream (not on the stack). The terminating character
2342: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 2343: quotes.
2344: @end table
2345:
1.21 crook 2346: @node Comments, Boolean Flags, Notation, Words
2347: @section Comments
1.26 crook 2348: @cindex comments
1.21 crook 2349:
1.29 crook 2350: Forth supports two styles of comment; the traditional @i{in-line} comment,
2351: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 2352:
1.23 crook 2353: doc-(
1.21 crook 2354: doc-\
1.23 crook 2355: doc-\G
1.21 crook 2356:
2357: @node Boolean Flags, Arithmetic, Comments, Words
2358: @section Boolean Flags
1.26 crook 2359: @cindex Boolean flags
1.21 crook 2360:
2361: A Boolean flag is cell-sized. A cell with all bits clear represents the
2362: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 2363: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 2364: a cell that has @i{any} bit set as @code{true}.
1.21 crook 2365:
2366: doc-true
2367: doc-false
1.29 crook 2368: doc-on
2369: doc-off
1.21 crook 2370:
2371: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 2372: @section Arithmetic
2373: @cindex arithmetic words
2374:
2375: @cindex division with potentially negative operands
2376: Forth arithmetic is not checked, i.e., you will not hear about integer
2377: overflow on addition or multiplication, you may hear about division by
2378: zero if you are lucky. The operator is written after the operands, but
2379: the operands are still in the original order. I.e., the infix @code{2-1}
2380: corresponds to @code{2 1 -}. Forth offers a variety of division
2381: operators. If you perform division with potentially negative operands,
2382: you do not want to use @code{/} or @code{/mod} with its undefined
2383: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
2384: former, @pxref{Mixed precision}).
1.26 crook 2385: @comment TODO discuss the different division forms and the std approach
1.1 anton 2386:
2387: @menu
2388: * Single precision::
2389: * Bitwise operations::
1.21 crook 2390: * Double precision:: Double-cell integer arithmetic
2391: * Numeric comparison::
1.29 crook 2392: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 2393: * Floating Point::
2394: @end menu
2395:
2396: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
2397: @subsection Single precision
2398: @cindex single precision arithmetic words
2399:
1.21 crook 2400: By default, numbers in Forth are single-precision integers that are 1
1.26 crook 2401: cell in size. They can be signed or unsigned, depending upon how you
1.21 crook 2402: treat them. @xref{Number Conversion} for the rules used by the text
2403: interpreter for recognising single-precision integers.
2404:
1.1 anton 2405: doc-+
1.21 crook 2406: doc-1+
1.1 anton 2407: doc--
1.21 crook 2408: doc-1-
1.1 anton 2409: doc-*
2410: doc-/
2411: doc-mod
2412: doc-/mod
2413: doc-negate
2414: doc-abs
2415: doc-min
2416: doc-max
1.21 crook 2417: doc-d>s
1.27 crook 2418: doc-floored
1.1 anton 2419:
1.21 crook 2420: @node Bitwise operations, Double precision, Single precision, Arithmetic
1.1 anton 2421: @subsection Bitwise operations
2422: @cindex bitwise operation words
2423:
2424: doc-and
2425: doc-or
2426: doc-xor
2427: doc-invert
1.21 crook 2428: doc-lshift
2429: doc-rshift
1.1 anton 2430: doc-2*
1.21 crook 2431: doc-d2*
1.1 anton 2432: doc-2/
1.21 crook 2433: doc-d2/
2434:
2435: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
2436: @subsection Double precision
2437: @cindex double precision arithmetic words
2438:
2439: @xref{Number Conversion} for the rules used by the text interpreter for
2440: recognising double-precision integers.
2441:
2442: A double precision number is represented by a cell pair, with the most
1.31 anton 2443: significant cell at the TOS. It is trivial to convert an unsigned
1.26 crook 2444: single to an (unsigned) double; simply push a @code{0} onto the
2445: TOS. Since numbers are represented by Gforth using 2's complement
2446: arithmetic, converting a signed single to a (signed) double requires
1.31 anton 2447: sign-extension across the most significant cell. This can be achieved
1.26 crook 2448: using @code{s>d}. The moral of the story is that you cannot convert a
2449: number without knowing whether it represents an unsigned or a
2450: signed number.
1.21 crook 2451:
2452: doc-s>d
2453: doc-d+
2454: doc-d-
2455: doc-dnegate
2456: doc-dabs
2457: doc-dmin
2458: doc-dmax
2459:
2460: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
2461: @subsection Numeric comparison
2462: @cindex numeric comparison words
2463:
1.28 crook 2464: doc-<
2465: doc-<=
2466: doc-<>
2467: doc-=
2468: doc->
2469: doc->=
2470:
1.21 crook 2471: doc-0<
1.23 crook 2472: doc-0<=
1.21 crook 2473: doc-0<>
2474: doc-0=
1.23 crook 2475: doc-0>
2476: doc-0>=
1.28 crook 2477:
2478: doc-u<
2479: doc-u<=
1.31 anton 2480: @c TODO why u<> and u= ... they are the same as <> and =
2481: @c commented them out because they are unnecessary
2482: @c doc-u<>
2483: @c doc-u=
1.28 crook 2484: doc-u>
2485: doc-u>=
2486:
2487: doc-within
2488:
2489: doc-d<
2490: doc-d<=
2491: doc-d<>
2492: doc-d=
2493: doc-d>
2494: doc-d>=
1.23 crook 2495:
1.21 crook 2496: doc-d0<
1.23 crook 2497: doc-d0<=
2498: doc-d0<>
1.21 crook 2499: doc-d0=
1.23 crook 2500: doc-d0>
2501: doc-d0>=
2502:
1.21 crook 2503: doc-du<
1.28 crook 2504: doc-du<=
1.31 anton 2505: @c doc-du<>
2506: @c doc-du=
1.28 crook 2507: doc-du>
2508: doc-du>=
1.1 anton 2509:
1.21 crook 2510: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 2511: @subsection Mixed precision
2512: @cindex mixed precision arithmetic words
2513:
2514: doc-m+
2515: doc-*/
2516: doc-*/mod
2517: doc-m*
2518: doc-um*
2519: doc-m*/
2520: doc-um/mod
2521: doc-fm/mod
2522: doc-sm/rem
2523:
1.21 crook 2524: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 2525: @subsection Floating Point
2526: @cindex floating point arithmetic words
2527:
1.21 crook 2528: @xref{Number Conversion} for the rules used by the text interpreter for
2529: recognising floating-point numbers.
1.1 anton 2530:
1.32 anton 2531: Gforth has a separate floating point
1.26 crook 2532: stack, but the documentation uses the unified notation.
1.1 anton 2533:
2534: @cindex floating-point arithmetic, pitfalls
2535: Floating point numbers have a number of unpleasant surprises for the
2536: unwary (e.g., floating point addition is not associative) and even a few
2537: for the wary. You should not use them unless you know what you are doing
2538: or you don't care that the results you get are totally bogus. If you
2539: want to learn about the problems of floating point numbers (and how to
2540: avoid them), you might start with @cite{David Goldberg, What Every
2541: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
1.17 anton 2542: Computing Surveys 23(1):5@minus{}48, March 1991}
2543: (@url{http://www.validgh.com/goldberg/paper.ps}).
1.1 anton 2544:
1.21 crook 2545: doc-d>f
2546: doc-f>d
1.1 anton 2547: doc-f+
2548: doc-f-
2549: doc-f*
2550: doc-f/
2551: doc-fnegate
2552: doc-fabs
2553: doc-fmax
2554: doc-fmin
2555: doc-floor
2556: doc-fround
2557: doc-f**
2558: doc-fsqrt
2559: doc-fexp
2560: doc-fexpm1
2561: doc-fln
2562: doc-flnp1
2563: doc-flog
2564: doc-falog
1.32 anton 2565: doc-f2*
2566: doc-f2/
2567: doc-1/f
2568: doc-precision
2569: doc-set-precision
2570:
2571: @cindex angles in trigonometric operations
2572: @cindex trigonometric operations
2573: Angles in floating point operations are given in radians (a full circle
2574: has 2 pi radians).
2575:
1.1 anton 2576: doc-fsin
2577: doc-fcos
2578: doc-fsincos
2579: doc-ftan
2580: doc-fasin
2581: doc-facos
2582: doc-fatan
2583: doc-fatan2
2584: doc-fsinh
2585: doc-fcosh
2586: doc-ftanh
2587: doc-fasinh
2588: doc-facosh
2589: doc-fatanh
1.21 crook 2590: doc-pi
1.28 crook 2591:
1.32 anton 2592: @cindex equality of floats
2593: @cindex floating-point comparisons
1.31 anton 2594: One particular problem with floating-point arithmetic is that comparison
2595: for equality often fails when you would expect it to succeed. For this
2596: reason approximate equality is often preferred (but you still have to
2597: know what you are doing). The comparison words are:
2598:
2599: doc-f~rel
2600: doc-f~abs
2601: doc-f=
2602: doc-f~
2603: doc-f<>
2604:
2605: doc-f<
2606: doc-f<=
2607: doc-f>
2608: doc-f>=
2609:
1.21 crook 2610: doc-f0<
1.28 crook 2611: doc-f0<=
2612: doc-f0<>
1.21 crook 2613: doc-f0=
1.28 crook 2614: doc-f0>
2615: doc-f0>=
2616:
1.1 anton 2617:
2618: @node Stack Manipulation, Memory, Arithmetic, Words
2619: @section Stack Manipulation
2620: @cindex stack manipulation words
2621:
2622: @cindex floating-point stack in the standard
1.21 crook 2623: Gforth maintains a number of separate stacks:
2624:
1.29 crook 2625: @cindex data stack
2626: @cindex parameter stack
1.21 crook 2627: @itemize @bullet
2628: @item
1.29 crook 2629: A data stack (also known as the @dfn{parameter stack}) -- for
2630: characters, cells, addresses, and double cells.
1.21 crook 2631:
1.29 crook 2632: @cindex floating-point stack
1.21 crook 2633: @item
2634: A floating point stack -- for floating point numbers.
2635:
1.29 crook 2636: @cindex return stack
1.21 crook 2637: @item
2638: A return stack -- for storing the return addresses of colon
1.32 anton 2639: definitions and other (non-FP) data.
1.21 crook 2640:
1.29 crook 2641: @cindex locals stack
1.21 crook 2642: @item
2643: A locals stack for storing local variables.
2644: @end itemize
2645:
1.1 anton 2646: @menu
2647: * Data stack::
2648: * Floating point stack::
2649: * Return stack::
2650: * Locals stack::
2651: * Stack pointer manipulation::
2652: @end menu
2653:
2654: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
2655: @subsection Data stack
2656: @cindex data stack manipulation words
2657: @cindex stack manipulations words, data stack
2658:
2659: doc-drop
2660: doc-nip
2661: doc-dup
2662: doc-over
2663: doc-tuck
2664: doc-swap
1.21 crook 2665: doc-pick
1.1 anton 2666: doc-rot
2667: doc--rot
2668: doc-?dup
2669: doc-roll
2670: doc-2drop
2671: doc-2nip
2672: doc-2dup
2673: doc-2over
2674: doc-2tuck
2675: doc-2swap
2676: doc-2rot
2677:
2678: @node Floating point stack, Return stack, Data stack, Stack Manipulation
2679: @subsection Floating point stack
2680: @cindex floating-point stack manipulation words
2681: @cindex stack manipulation words, floating-point stack
2682:
1.32 anton 2683: Whilst every sane Forth has a separate floating-point stack, it is not
2684: strictly required; an ANS Forth system could theoretically keep
2685: floating-point numbers on the data stack. As an additional difficulty,
2686: you don't know how many cells a floating-point number takes. It is
2687: reportedly possible to write words in a way that they work also for a
2688: unified stack model, but we do not recommend trying it. Instead, just
2689: say that your program has an environmental dependency on a separate
2690: floating-point stack.
2691:
2692: doc-floating-stack
2693:
1.1 anton 2694: doc-fdrop
2695: doc-fnip
2696: doc-fdup
2697: doc-fover
2698: doc-ftuck
2699: doc-fswap
1.21 crook 2700: doc-fpick
1.1 anton 2701: doc-frot
2702:
2703: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
2704: @subsection Return stack
2705: @cindex return stack manipulation words
2706: @cindex stack manipulation words, return stack
2707:
1.32 anton 2708: @cindex return stack and locals
2709: @cindex locals and return stack
2710: A Forth system is allowed to keep local variables on the
2711: return stack. This is reasonable, as local variables usually eliminate
2712: the need to use the return stack explicitly. So, if you want to produce
2713: a standard compliant program and you are using local variables in a
2714: word, forget about return stack manipulations in that word (refer to the
2715: standard document for the exact rules).
2716:
1.1 anton 2717: doc->r
2718: doc-r>
2719: doc-r@
2720: doc-rdrop
2721: doc-2>r
2722: doc-2r>
2723: doc-2r@
2724: doc-2rdrop
2725:
2726: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
2727: @subsection Locals stack
2728:
1.26 crook 2729: @comment TODO
1.21 crook 2730:
1.1 anton 2731: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
2732: @subsection Stack pointer manipulation
2733: @cindex stack pointer manipulation words
2734:
1.21 crook 2735: doc-sp0
1.1 anton 2736: doc-sp@
2737: doc-sp!
1.21 crook 2738: doc-fp0
1.1 anton 2739: doc-fp@
2740: doc-fp!
1.21 crook 2741: doc-rp0
1.1 anton 2742: doc-rp@
2743: doc-rp!
1.21 crook 2744: doc-lp0
1.1 anton 2745: doc-lp@
2746: doc-lp!
2747:
2748: @node Memory, Control Structures, Stack Manipulation, Words
2749: @section Memory
1.26 crook 2750: @cindex memory words
1.1 anton 2751:
1.32 anton 2752: @menu
2753: * Memory model::
2754: * Dictionary allocation::
2755: * Heap Allocation::
2756: * Memory Access::
2757: * Address arithmetic::
2758: * Memory Blocks::
2759: @end menu
2760:
2761: @node Memory model, Dictionary allocation, Memory, Memory
2762: @subsection ANS Forth and Gforth memory models
2763:
2764: @c The ANS Forth description is a mess (e.g., is the heap part of
2765: @c the dictionary?), so let's not stick to closely with it.
2766:
2767: ANS Forth considers a Forth system as consisting of several memories, of
2768: which only @dfn{data space} is managed and accessible with the memory
2769: words. Memory not necessarily in data space includes the stacks, the
2770: code (called code space) and the headers (called name space). In Gforth
2771: everything is in data space, but the code for the primitives is usually
2772: read-only.
2773:
2774: Data space is divided into a number of areas: The (data space portion of
2775: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
2776: refer to the search data structure embodied in word lists and headers,
2777: because it is used for looking up names, just as you would in a
2778: conventional dictionary.}, the heap, and a number of system-allocated
2779: buffers.
2780:
2781: In ANS Forth data space is also divided into contiguous regions. You
2782: can only use address arithmetic within a contiguous region, not between
2783: them. Usually each allocation gives you one contiguous region, but the
1.33 ! anton 2784: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 2785: allocation}).
2786:
2787: Gforth provides one big address space, and address arithmetic can be
2788: performed between any addresses. However, in the dictionary headers or
2789: code are interleaved with data, so almost the only contiguous data space
2790: regions there are those described by ANS Forth as contiguous; but you
2791: can be sure that the dictionary is allocated towards increasing
2792: addresses even between contiguous regions. The memory order of
2793: allocations in the heap is platform-dependent (and possibly different
2794: from one run to the next).
2795:
2796: @subsubsection ANS Forth dictionary details
2797:
2798: @c !! I have deleted some of the stuff this section refers to - anton
1.27 crook 2799:
1.32 anton 2800: This section is just informative, you can skip it if you are in a hurry.
1.27 crook 2801:
1.29 crook 2802: When you create a colon definition, the text interpreter compiles the
1.32 anton 2803: code for the definition into the code space and compiles the name
2804: of the definition into the header space, together with other
1.27 crook 2805: information about the definition (such as its execution token).
2806:
2807: When you create a variable, the execution of @code{variable} will
1.32 anton 2808: compile some code, assign one cell in data space, and compile the name
2809: of the variable into the header space.
1.27 crook 2810:
2811: @cindex memory regions - relationship between them
2812: ANS Forth does not specify the relationship between the three memory
2813: regions, and specifies that a Standard program must not access code or
2814: data space directly -- it may only access data space directly. In
2815: addition, the Standard defines what relationships you may and may not
2816: rely on when allocating regions in data space. These constraints are
2817: simply a reflection of the many diverse techniques that are used to
2818: implement Forth systems; understanding and following the requirements of
2819: the Standard allows you to write portable programs -- programs that run
2820: in the same way on any of these diverse systems. Another way of looking
2821: at this is to say that ANS Forth was designed to permit compliant Forth
2822: systems to be implemented in many diverse ways.
2823:
2824: @cindex memory regions - how they are assigned
1.29 crook 2825: Here are some examples of ways in which name, code and data spaces
2826: might be assigned in different Forth implementations:
1.27 crook 2827:
2828: @itemize @bullet
2829: @item
2830: For a Forth system that runs from RAM under a general-purpose operating
2831: system, it can be convenient to interleave name, code and data spaces in
2832: a single contiguous memory region. This organisation can be
2833: memory-efficient (for example, because the relationship between the name
1.32 anton 2834: dictionary entry and the associated code space entry can be
1.27 crook 2835: implicit, rather than requiring an explicit memory pointer to reference
1.32 anton 2836: from the header space and the code space). This is the
1.27 crook 2837: organisation used by Gforth, as this example@footnote{The addresses
2838: in the example have been truncated to fit it onto the page, and the
2839: addresses and data shown will not match the output from your system} shows:
2840: @example
2841: hex
2842: variable fred 123456 fred !
2843: variable jim abcd jim !
2844: : foo + / - ;
2845: ' fred 10 - 50 dump
2846: ..80: 5C 46 0E 40 84 66 72 65 - 64 20 20 20 20 20 20 20 \F.@.fred
2847: ..90: D0 9B 04 08 00 00 00 00 - 56 34 12 00 80 46 0E 40 ........V4...F.@
2848: ..A0: 83 6A 69 6D 20 20 20 20 - D0 9B 04 08 00 00 00 00 .jim ........
2849: ..B0: CD AB 00 00 9C 46 0E 40 - 83 66 6F 6F 20 20 20 20 .....F.@.foo
2850: ..C0: 80 9B 04 08 00 00 00 00 - E4 2E 05 08 0C 2F 05 08 ............./..
2851: @end example
2852:
2853: @item
2854: For a high-performance system running on a modern RISC processor with a
2855: modified Harvard architecture (one that has a unified main memory but
2856: separate instruction and data caches), it is desirable to separate
2857: processor instructions from processor data. This encourages a high cache
1.32 anton 2858: density and therefore a high cache hit rate. The Forth code space
1.27 crook 2859: is not necessarily made up entirely of processor instructions; its
2860: nature is dependent upon the Forth implementation.
2861:
2862: @item
2863: A Forth compiler that runs on a segmented 8086 processor could be
2864: designed to interleave the name, code and data spaces within a single
2865: 64Kbyte segment. A more common implementation choice is to use a
2866: separate 64Kbyte segment for each region, which provides more memory
2867: overall but provides an address map in which only the data space is
2868: accessible.
2869:
2870: @item
2871: Microprocessors exist that run Forth (or many of the primitives required
2872: to implement the Forth virtual machine efficiently) directly. On these
2873: processors, the relationship between name, code and data spaces may be
1.32 anton 2874: imposed as a side-effect of the architecture of the processor.
1.27 crook 2875:
2876: @item
2877: A Forth compiler that executes from ROM on an embedded system needs its
2878: data space separated from the name and code spaces so that the data
2879: space can be mapped to a RAM area.
2880:
2881: @item
2882: A Forth compiler that runs on an embedded system may have a requirement
2883: for a small memory footprint. On such a system it can be useful to
1.32 anton 2884: separate the header space from the data and code spaces; once the
2885: application has been compiled, the header space is no longer
1.27 crook 2886: required@footnote{more strictly speaking, most applications can be
1.32 anton 2887: designed so that this is the case}. The header space can be deleted
1.29 crook 2888: entirely, or could be stored in memory on a remote @i{host} system for
1.27 crook 2889: debug and development purposes. In the latter case, the compiler running
1.29 crook 2890: on the @i{target} system could implement a protocol across a
1.32 anton 2891: communication link that would allow it to interrogate the header space.
1.27 crook 2892: @end itemize
2893:
1.1 anton 2894:
1.32 anton 2895: @node Dictionary allocation, Heap Allocation, Memory model, Memory
2896: @subsection Dictionary allocation
1.27 crook 2897: @cindex reserving data space
2898: @cindex data space - reserving some
2899:
1.32 anton 2900: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
2901: you want to deallocate X, you also deallocate everything
2902: allocated after X.
2903:
2904: The allocations using the words below are contiguous and grow the region
2905: towards increasing addresses. Other words that allocate dictionary
2906: memory of any kind (i.e., defining words including @code{:noname}) end
2907: the contiguous region and start a new one.
2908:
2909: In ANS Forth only @code{create}d words are guaranteed to produce an
2910: address that is the start of the following contiguous region. In
2911: particular, the cell allocated by @code{variable} is not guaranteed to
2912: be contiguous with following @code{allot}ed memory.
2913:
2914: You can deallocate memory by using @code{allot} with a negative argument
2915: (with some restrictions, see @code{allot}). For larger deallocations use
2916: @code{marker}.
1.27 crook 2917:
1.29 crook 2918:
1.27 crook 2919: doc-here
2920: doc-unused
2921: doc-allot
2922: doc-c,
1.29 crook 2923: doc-f,
1.27 crook 2924: doc-,
2925: doc-2,
1.29 crook 2926: @cindex user space
2927: doc-udp
2928: doc-uallot
1.27 crook 2929:
1.32 anton 2930: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
2931: course you should allocate memory in an aligned way, too. I.e., before
2932: allocating allocating a cell, @code{here} must be cell-aligned, etc.
2933: The words below align @code{here} if it is not already. Basically it is
2934: only already aligned for a type, if the last allocation was a multiple
2935: of the size of this type and if @code{here} was aligned for this type
2936: before.
2937:
2938: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
2939: ANS Forth (@code{maxalign}ed in Gforth).
2940:
2941: doc-align
2942: doc-falign
2943: doc-sfalign
2944: doc-dfalign
2945: doc-maxalign
2946: doc-cfalign
2947:
2948:
2949: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
2950: @subsection Heap allocation
2951: @cindex heap allocation
2952: @cindex dynamic allocation of memory
2953: @cindex memory-allocation word set
2954:
2955: Heap allocation supports deallocation of allocated memory in any
2956: order. Dictionary allocation is not affected by it (i.e., it does not
2957: end a contiguous region). In Gforth, these words are implemented using
2958: the standard C library calls malloc(), free() and resize().
2959:
2960: doc-allocate
2961: doc-free
2962: doc-resize
2963:
1.27 crook 2964:
1.32 anton 2965: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 2966: @subsection Memory Access
2967: @cindex memory access words
2968:
2969: doc-@
2970: doc-!
2971: doc-+!
2972: doc-c@
2973: doc-c!
2974: doc-2@
2975: doc-2!
2976: doc-f@
2977: doc-f!
2978: doc-sf@
2979: doc-sf!
2980: doc-df@
2981: doc-df!
2982:
1.32 anton 2983: @node Address arithmetic, Memory Blocks, Memory Access, Memory
2984: @subsection Address arithmetic
1.1 anton 2985: @cindex address arithmetic words
2986:
1.32 anton 2987: Address arithmetic is the foundation on which data structures like
2988: arrays, records (@pxref{Structures}) and objects (@pxref{Object-oriented
2989: Forth}) are built.
2990:
1.1 anton 2991: ANS Forth does not specify the sizes of the data types. Instead, it
2992: offers a number of words for computing sizes and doing address
1.29 crook 2993: arithmetic. Address arithmetic is performed in terms of address units
2994: (aus); on most systems the address unit is one byte. Note that a
2995: character may have more than one au, so @code{chars} is no noop (on
2996: systems where it is a noop, it compiles to nothing).
1.1 anton 2997:
2998: @cindex alignment of addresses for types
2999: ANS Forth also defines words for aligning addresses for specific
3000: types. Many computers require that accesses to specific data types
3001: must only occur at specific addresses; e.g., that cells may only be
3002: accessed at addresses divisible by 4. Even if a machine allows unaligned
3003: accesses, it can usually perform aligned accesses faster.
3004:
3005: For the performance-conscious: alignment operations are usually only
3006: necessary during the definition of a data structure, not during the
3007: (more frequent) accesses to it.
3008:
3009: ANS Forth defines no words for character-aligning addresses. This is not
3010: an oversight, but reflects the fact that addresses that are not
3011: char-aligned have no use in the standard and therefore will not be
3012: created.
3013:
3014: @cindex @code{CREATE} and alignment
1.29 crook 3015: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 3016: are cell-aligned; in addition, Gforth guarantees that these addresses
3017: are aligned for all purposes.
3018:
1.26 crook 3019: Note that the ANS Forth word @code{char} has nothing to do with address
3020: arithmetic.
1.1 anton 3021:
3022: doc-chars
3023: doc-char+
3024: doc-cells
3025: doc-cell+
3026: doc-cell
3027: doc-aligned
3028: doc-floats
3029: doc-float+
3030: doc-float
3031: doc-faligned
3032: doc-sfloats
3033: doc-sfloat+
3034: doc-sfaligned
3035: doc-dfloats
3036: doc-dfloat+
3037: doc-dfaligned
3038: doc-maxaligned
3039: doc-cfaligned
3040: doc-address-unit-bits
3041:
1.32 anton 3042: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 3043: @subsection Memory Blocks
3044: @cindex memory block words
1.27 crook 3045: @cindex character strings - moving and copying
3046:
3047: Memory blocks often represent character strings; @xref{String Formats}
3048: for ways of storing character strings in memory. @xref{Displaying
3049: characters and strings} for other string-processing words.
1.1 anton 3050:
1.32 anton 3051: Some of these words work on address units. Others work on character
3052: units (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
3053: address. Choose the correct operation depending upon your data type.
1.21 crook 3054:
3055: When copying characters between overlapping memory regions, choose
3056: carefully between @code{cmove} and @code{cmove>}.
3057:
1.29 crook 3058: You can only use any of these words @i{portably} to access data space.
1.21 crook 3059:
1.27 crook 3060: @comment TODO - think the naming of the arguments is wrong for move
1.29 crook 3061: @comment well, really it seems to be the Standard that's wrong; it
3062: @comment describes MOVE as a word that requires a CELL-aligned source
3063: @comment and destination address but a xtranfer count that need not
3064: @comment be a multiple of CELL.
1.1 anton 3065: doc-move
3066: doc-erase
3067: doc-cmove
3068: doc-cmove>
3069: doc-fill
3070: doc-blank
1.21 crook 3071: doc-compare
3072: doc-search
1.27 crook 3073: doc--trailing
3074: doc-/string
3075:
3076: @comment TODO examples
3077:
1.1 anton 3078:
1.26 crook 3079: @node Control Structures, Defining Words, Memory, Words
1.1 anton 3080: @section Control Structures
3081: @cindex control structures
3082:
1.33 ! anton 3083: Control structures in Forth cannot be used interpretively, only in a
! 3084: colon definition@footnote{To be precise, they have no interpretation
! 3085: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
! 3086: not like this limitation, but have not seen a satisfying way around it
! 3087: yet, although many schemes have been proposed.
1.1 anton 3088:
3089: @menu
1.33 ! anton 3090: * Selection:: IF ... ELSE ... ENDIF
! 3091: * Simple Loops:: BEGIN ...
1.29 crook 3092: * Counted Loops:: DO
3093: * Arbitrary control structures::
3094: * Calls and returns::
1.1 anton 3095: * Exception Handling::
3096: @end menu
3097:
3098: @node Selection, Simple Loops, Control Structures, Control Structures
3099: @subsection Selection
3100: @cindex selection control structures
3101: @cindex control structures for selection
3102:
1.33 ! anton 3103: @c what's the purpose of all these @i? Maybe we should define a macro
! 3104: @c so we can produce logical markup. - anton
! 3105:
1.1 anton 3106: @cindex @code{IF} control structure
3107: @example
1.29 crook 3108: @i{flag}
1.1 anton 3109: IF
1.29 crook 3110: @i{code}
1.1 anton 3111: ENDIF
3112: @end example
1.21 crook 3113: @noindent
1.33 ! anton 3114:
! 3115: @var{code} is executed if @var{flag} is non-zero (that's truth as far as
! 3116: @code{IF} etc. are concerned).
! 3117:
1.1 anton 3118: @example
1.29 crook 3119: @i{flag}
1.1 anton 3120: IF
1.29 crook 3121: @i{code1}
1.1 anton 3122: ELSE
1.29 crook 3123: @i{code2}
1.1 anton 3124: ENDIF
3125: @end example
3126:
1.33 ! anton 3127: If @var{flag} is true, perform @var{code1}, otherwise @var{code2}.
! 3128:
1.1 anton 3129: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
3130: standard, and @code{ENDIF} is not, although it is quite popular. We
3131: recommend using @code{ENDIF}, because it is less confusing for people
3132: who also know other languages (and is not prone to reinforcing negative
3133: prejudices against Forth in these people). Adding @code{ENDIF} to a
3134: system that only supplies @code{THEN} is simple:
3135: @example
1.21 crook 3136: : ENDIF POSTPONE THEN ; immediate
1.1 anton 3137: @end example
3138:
3139: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
3140: (adv.)} has the following meanings:
3141: @quotation
3142: ... 2b: following next after in order ... 3d: as a necessary consequence
3143: (if you were there, then you saw them).
3144: @end quotation
3145: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
3146: and many other programming languages has the meaning 3d.]
3147:
1.21 crook 3148: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 3149: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 3150: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 3151: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
3152: @file{compat/control.fs}.
3153:
3154: @cindex @code{CASE} control structure
3155: @example
1.29 crook 3156: @i{n}
1.1 anton 3157: CASE
1.29 crook 3158: @i{n1} OF @i{code1} ENDOF
3159: @i{n2} OF @i{code2} ENDOF
1.1 anton 3160: @dots{}
3161: ENDCASE
3162: @end example
3163:
1.29 crook 3164: Executes the first @i{codei}, where the @i{ni} is equal to
3165: @i{n}. A default case can be added by simply writing the code after
3166: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
1.1 anton 3167: but must not consume it.
3168:
3169: @node Simple Loops, Counted Loops, Selection, Control Structures
3170: @subsection Simple Loops
3171: @cindex simple loops
3172: @cindex loops without count
3173:
3174: @cindex @code{WHILE} loop
3175: @example
3176: BEGIN
1.29 crook 3177: @i{code1}
3178: @i{flag}
1.1 anton 3179: WHILE
1.29 crook 3180: @i{code2}
1.1 anton 3181: REPEAT
3182: @end example
3183:
1.29 crook 3184: @i{code1} is executed and @i{flag} is computed. If it is true,
3185: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 3186: false, execution continues after the @code{REPEAT}.
3187:
3188: @cindex @code{UNTIL} loop
3189: @example
3190: BEGIN
1.29 crook 3191: @i{code}
3192: @i{flag}
1.1 anton 3193: UNTIL
3194: @end example
3195:
1.29 crook 3196: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 3197:
3198: @cindex endless loop
3199: @cindex loops, endless
3200: @example
3201: BEGIN
1.29 crook 3202: @i{code}
1.1 anton 3203: AGAIN
3204: @end example
3205:
3206: This is an endless loop.
3207:
3208: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
3209: @subsection Counted Loops
3210: @cindex counted loops
3211: @cindex loops, counted
3212: @cindex @code{DO} loops
3213:
3214: The basic counted loop is:
3215: @example
1.29 crook 3216: @i{limit} @i{start}
1.1 anton 3217: ?DO
1.29 crook 3218: @i{body}
1.1 anton 3219: LOOP
3220: @end example
3221:
1.29 crook 3222: This performs one iteration for every integer, starting from @i{start}
3223: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 3224: accessed with @code{i}. For example, the loop:
1.1 anton 3225: @example
3226: 10 0 ?DO
3227: i .
3228: LOOP
3229: @end example
1.21 crook 3230: @noindent
3231: prints @code{0 1 2 3 4 5 6 7 8 9}
3232:
1.1 anton 3233: The index of the innermost loop can be accessed with @code{i}, the index
3234: of the next loop with @code{j}, and the index of the third loop with
3235: @code{k}.
3236:
3237: doc-i
3238: doc-j
3239: doc-k
3240:
3241: The loop control data are kept on the return stack, so there are some
1.21 crook 3242: restrictions on mixing return stack accesses and counted loop words. In
3243: particuler, if you put values on the return stack outside the loop, you
3244: cannot read them inside the loop@footnote{well, not in a way that is
3245: portable.}. If you put values on the return stack within a loop, you
3246: have to remove them before the end of the loop and before accessing the
3247: index of the loop.
1.1 anton 3248:
3249: There are several variations on the counted loop:
3250:
1.21 crook 3251: @itemize @bullet
3252: @item
3253: @code{LEAVE} leaves the innermost counted loop immediately; execution
3254: continues after the associated @code{LOOP} or @code{NEXT}. For example:
3255:
3256: @example
3257: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
3258: @end example
3259: prints @code{0 1 2 3}
3260:
1.1 anton 3261:
1.21 crook 3262: @item
3263: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
3264: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
3265: return stack so @code{EXIT} can get to its return address. For example:
3266:
3267: @example
3268: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
3269: @end example
3270: prints @code{0 1 2 3}
3271:
3272:
3273: @item
1.29 crook 3274: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 3275: (and @code{LOOP} iterates until they become equal by wrap-around
3276: arithmetic). This behaviour is usually not what you want. Therefore,
3277: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 3278: @code{?DO}), which do not enter the loop if @i{start} is greater than
3279: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 3280: unsigned loop parameters.
3281:
1.21 crook 3282: @item
3283: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
3284: the loop, independent of the loop parameters. Do not use @code{DO}, even
3285: if you know that the loop is entered in any case. Such knowledge tends
3286: to become invalid during maintenance of a program, and then the
3287: @code{DO} will make trouble.
3288:
3289: @item
1.29 crook 3290: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
3291: index by @i{n} instead of by 1. The loop is terminated when the border
3292: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 3293:
1.21 crook 3294: @example
3295: 4 0 +DO i . 2 +LOOP
3296: @end example
3297: @noindent
3298: prints @code{0 2}
3299:
3300: @example
3301: 4 1 +DO i . 2 +LOOP
3302: @end example
3303: @noindent
3304: prints @code{1 3}
1.1 anton 3305:
3306:
3307: @cindex negative increment for counted loops
3308: @cindex counted loops with negative increment
1.29 crook 3309: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 3310:
1.21 crook 3311: @example
3312: -1 0 ?DO i . -1 +LOOP
3313: @end example
3314: @noindent
3315: prints @code{0 -1}
1.1 anton 3316:
1.21 crook 3317: @example
3318: 0 0 ?DO i . -1 +LOOP
3319: @end example
3320: prints nothing.
1.1 anton 3321:
1.29 crook 3322: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
3323: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
3324: index by @i{u} each iteration. The loop is terminated when the border
3325: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 3326: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
3327:
1.21 crook 3328: @example
3329: -2 0 -DO i . 1 -LOOP
3330: @end example
3331: @noindent
3332: prints @code{0 -1}
1.1 anton 3333:
1.21 crook 3334: @example
3335: -1 0 -DO i . 1 -LOOP
3336: @end example
3337: @noindent
3338: prints @code{0}
3339:
3340: @example
3341: 0 0 -DO i . 1 -LOOP
3342: @end example
3343: @noindent
3344: prints nothing.
1.1 anton 3345:
1.21 crook 3346: @end itemize
1.1 anton 3347:
3348: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 3349: @code{-LOOP} are not defined in ANS Forth. However, an implementation
3350: for these words that uses only standard words is provided in
3351: @file{compat/loops.fs}.
1.1 anton 3352:
3353:
3354: @cindex @code{FOR} loops
1.26 crook 3355: Another counted loop is:
1.1 anton 3356: @example
1.29 crook 3357: @i{n}
1.1 anton 3358: FOR
1.29 crook 3359: @i{body}
1.1 anton 3360: NEXT
3361: @end example
3362: This is the preferred loop of native code compiler writers who are too
1.26 crook 3363: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 3364: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
3365: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 3366: Forth systems may behave differently, even if they support @code{FOR}
3367: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 3368:
3369: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
3370: @subsection Arbitrary control structures
3371: @cindex control structures, user-defined
3372:
3373: @cindex control-flow stack
3374: ANS Forth permits and supports using control structures in a non-nested
3375: way. Information about incomplete control structures is stored on the
3376: control-flow stack. This stack may be implemented on the Forth data
3377: stack, and this is what we have done in Gforth.
3378:
3379: @cindex @code{orig}, control-flow stack item
3380: @cindex @code{dest}, control-flow stack item
3381: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
3382: entry represents a backward branch target. A few words are the basis for
3383: building any control structure possible (except control structures that
3384: need storage, like calls, coroutines, and backtracking).
3385:
3386: doc-if
3387: doc-ahead
3388: doc-then
3389: doc-begin
3390: doc-until
3391: doc-again
3392: doc-cs-pick
3393: doc-cs-roll
3394:
1.21 crook 3395: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
3396: manipulate the control-flow stack in a portable way. Without them, you
3397: would need to know how many stack items are occupied by a control-flow
3398: entry (many systems use one cell. In Gforth they currently take three,
3399: but this may change in the future).
3400:
1.1 anton 3401: Some standard control structure words are built from these words:
3402:
3403: doc-else
3404: doc-while
3405: doc-repeat
3406:
3407: Gforth adds some more control-structure words:
3408:
3409: doc-endif
3410: doc-?dup-if
3411: doc-?dup-0=-if
3412:
3413: Counted loop words constitute a separate group of words:
3414:
3415: doc-?do
3416: doc-+do
3417: doc-u+do
3418: doc--do
3419: doc-u-do
3420: doc-do
3421: doc-for
3422: doc-loop
3423: doc-+loop
3424: doc--loop
3425: doc-next
3426: doc-leave
3427: doc-?leave
3428: doc-unloop
3429: doc-done
3430:
1.21 crook 3431: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
3432: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 3433: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
3434: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
3435: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
3436: resolved (by using one of the loop-ending words or @code{DONE}).
3437:
1.26 crook 3438: Another group of control structure words are:
1.1 anton 3439:
3440: doc-case
3441: doc-endcase
3442: doc-of
3443: doc-endof
3444:
1.21 crook 3445: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
3446: @code{CS-ROLL}.
1.1 anton 3447:
3448: @subsubsection Programming Style
3449:
3450: In order to ensure readability we recommend that you do not create
3451: arbitrary control structures directly, but define new control structure
3452: words for the control structure you want and use these words in your
1.26 crook 3453: program. For example, instead of writing:
1.1 anton 3454:
3455: @example
1.26 crook 3456: BEGIN
1.1 anton 3457: ...
1.26 crook 3458: IF [ 1 CS-ROLL ]
1.1 anton 3459: ...
1.26 crook 3460: AGAIN THEN
1.1 anton 3461: @end example
3462:
1.21 crook 3463: @noindent
1.1 anton 3464: we recommend defining control structure words, e.g.,
3465:
3466: @example
1.26 crook 3467: : WHILE ( DEST -- ORIG DEST )
3468: POSTPONE IF
3469: 1 CS-ROLL ; immediate
3470:
3471: : REPEAT ( orig dest -- )
3472: POSTPONE AGAIN
3473: POSTPONE THEN ; immediate
1.1 anton 3474: @end example
3475:
1.21 crook 3476: @noindent
1.1 anton 3477: and then using these to create the control structure:
3478:
3479: @example
1.26 crook 3480: BEGIN
1.1 anton 3481: ...
1.26 crook 3482: WHILE
1.1 anton 3483: ...
1.26 crook 3484: REPEAT
1.1 anton 3485: @end example
3486:
3487: That's much easier to read, isn't it? Of course, @code{REPEAT} and
3488: @code{WHILE} are predefined, so in this example it would not be
3489: necessary to define them.
3490:
3491: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
3492: @subsection Calls and returns
3493: @cindex calling a definition
3494: @cindex returning from a definition
3495:
1.3 anton 3496: @cindex recursive definitions
3497: A definition can be called simply be writing the name of the definition
1.26 crook 3498: to be called. Normally a definition is invisible during its own
1.3 anton 3499: definition. If you want to write a directly recursive definition, you
1.26 crook 3500: can use @code{recursive} to make the current definition visible, or
3501: @code{recurse} to call the current definition directly.
1.3 anton 3502:
3503: doc-recursive
3504: doc-recurse
3505:
1.21 crook 3506: @comment TODO add example of the two recursion methods
1.12 anton 3507: @quotation
3508: @progstyle
3509: I prefer using @code{recursive} to @code{recurse}, because calling the
3510: definition by name is more descriptive (if the name is well-chosen) than
3511: the somewhat cryptic @code{recurse}. E.g., in a quicksort
3512: implementation, it is much better to read (and think) ``now sort the
3513: partitions'' than to read ``now do a recursive call''.
3514: @end quotation
1.3 anton 3515:
1.29 crook 3516: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 3517:
3518: @example
1.28 crook 3519: Defer foo
1.3 anton 3520:
3521: : bar ( ... -- ... )
3522: ... foo ... ;
3523:
3524: :noname ( ... -- ... )
3525: ... bar ... ;
3526: IS foo
3527: @end example
3528:
1.33 ! anton 3529: Deferred words are discussed in more detail in @ref{Simple
! 3530: Defining Words}.
! 3531:
1.26 crook 3532: The current definition returns control to the calling definition when
1.33 ! anton 3533: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 3534:
3535: doc-exit
3536: doc-;s
3537:
3538: @node Exception Handling, , Calls and returns, Control Structures
3539: @subsection Exception Handling
1.26 crook 3540: @cindex exceptions
1.1 anton 3541:
1.26 crook 3542: If your program detects a fatal error condition, the simplest action
3543: that it can take is to @code{quit}. This resets the return stack and
3544: restarts the text interpreter, but does not print any error message.
1.21 crook 3545:
1.26 crook 3546: The next stage in severity is to execute @code{abort}, which has the
3547: same effect as @code{quit}, with the addition that it resets the data
3548: stack.
1.1 anton 3549:
1.26 crook 3550: A slightly more sophisticated approach is use use @code{abort"}, which
3551: compiles a string to be used as an error message and does a conditional
3552: @code{abort} at run-time. For example:
1.1 anton 3553:
1.26 crook 3554: @example
1.30 anton 3555: @kbd{: checker abort" That flag was true" ." A false flag" ;@key{RET}} ok
3556: @kbd{0 checker@key{RET}} A false flag ok
3557: @kbd{1 checker@key{RET}}
1.26 crook 3558: :1: That flag was true
3559: 1 checker
3560: ^^^^^^^
3561: $400D1648 throw
3562: $400E4660
3563: @end example
1.1 anton 3564:
1.26 crook 3565: These simple techniques allow a program to react to a fatal error
3566: condition, but they are not exactly user-friendly. The ANS Forth
3567: Exception word set provides the pair of words @code{throw} and
3568: @code{catch}, which can be used to provide sophisticated error-handling.
1.1 anton 3569:
1.26 crook 3570: @code{catch} has a similar behaviour to @code{execute}, in that it takes
1.29 crook 3571: an @i{xt} as a parameter and starts execution of the xt. However,
1.26 crook 3572: before passing control to the xt, @code{catch} pushes an
1.29 crook 3573: @dfn{exception frame} onto the @dfn{exception stack}. This exception
1.26 crook 3574: frame is used to restore the system to a known state if a detected error
3575: occurs during the execution of the xt. A typical way to use @code{catch}
3576: would be:
1.1 anton 3577:
1.26 crook 3578: @example
3579: ... ['] foo catch IF ...
3580: @end example
1.1 anton 3581:
1.33 ! anton 3582: @c TOS is undefined. - anton
1.26 crook 3583: Whilst @code{foo} executes, it can call other words to any level of
3584: nesting, as usual. If @code{foo} (and all the words that it calls)
1.33 ! anton 3585: execute successfully, control will ultimately pass to the word following
! 3586: the @code{catch}, and there will be a 0 at TOS. However, if any word
! 3587: detects an error, it can terminate the execution of @code{foo} by
! 3588: pushing a non-zero error code onto the stack and then performing a
! 3589: @code{throw}. The execution of @code{throw} will pass control to the
! 3590: word following the @code{catch}, but this time the TOS will hold the
! 3591: error code. Therefore, the @code{IF} in the example can be used to
! 3592: determine whether @code{foo} executed successfully.
1.1 anton 3593:
1.26 crook 3594: This simple example shows how you can use @code{throw} and @code{catch}
3595: to ``take over'' exception handling from the system:
1.1 anton 3596: @example
1.26 crook 3597: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
1.1 anton 3598: @end example
3599:
1.26 crook 3600: The next example is more sophisticated and shows a multi-level
3601: @code{throw} and @code{catch}. To understand this example, start at the
3602: definition of @code{top-level} and work backwards:
3603:
1.1 anton 3604: @example
1.26 crook 3605: : lowest-level ( -- c )
3606: key dup 27 = if
3607: 1 throw \ ESCAPE key pressed
3608: else
3609: ." lowest-level successfull" CR
3610: then
3611: ;
3612:
3613: : lower-level ( -- c )
3614: lowest-level
3615: \ at this level consider a CTRL-U to be a fatal error
3616: dup 21 = if \ CTRL-U
3617: 2 throw
3618: else
3619: ." lower-level successfull" CR
3620: then
3621: ;
3622:
3623: : low-level ( -- c )
3624: ['] lower-level catch
3625: ?dup if
3626: \ error occurred - do we recognise it?
3627: dup 1 = if
3628: \ ESCAPE key pressed.. pretend it was an E
3629: [char] E
3630: else throw \ propogate the error upwards
3631: then
3632: then
3633: ." low-level successfull" CR
3634: ;
3635:
3636: : top-level ( -- )
3637: CR ['] low-level catch \ CATCH is used like EXECUTE
3638: ?dup if \ error occurred..
3639: ." Error " . ." occurred - contact your supplier"
3640: else
3641: ." The '" emit ." ' key was pressed" CR
3642: then
3643: ;
1.1 anton 3644: @end example
3645:
1.26 crook 3646: The ANS Forth document assigns @code{throw} codes thus:
1.1 anton 3647:
1.26 crook 3648: @itemize @bullet
3649: @item
3650: codes in the range -1 -- -255 are reserved to be assigned by the
3651: Standard. Assignments for codes in the range -1 -- -58 are currently
3652: documented in the Standard. In particular, @code{-1 throw} is equivalent
3653: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
3654: @item
3655: codes in the range -256 -- -4095 are reserved to be assigned by the system.
3656: @item
3657: all other codes may be assigned by programs.
3658: @end itemize
1.1 anton 3659:
1.26 crook 3660: Gforth provides the word @code{exception} as a mechanism for assigning
3661: system throw codes to applications. This allows multiple applications to
3662: co-exist in memory without any clash of @code{throw} codes. A definition
3663: of @code{exception} in ANS Forth is provided in
3664: @file{compat/exception.fs}.
1.1 anton 3665:
1.26 crook 3666: doc-quit
3667: doc-abort
3668: doc-abort"
1.1 anton 3669:
1.26 crook 3670: doc-catch
1.29 crook 3671: doc-throw
3672: doc---exception-exception
3673:
3674:
3675: @c -------------------------------------------------------------
3676: @node Defining Words, The Text Interpreter, Control Structures, Words
3677: @section Defining Words
3678: @cindex defining words
3679:
3680: @menu
3681: * Simple Defining Words:: Variables, values and constants
3682: * Colon Definitions::
3683: * User-defined Defining Words::
3684: * Supplying names::
3685: * Interpretation and Compilation Semantics::
3686: @end menu
3687:
3688: @node Simple Defining Words, Colon Definitions, Defining Words, Defining Words
3689: @subsection Simple Defining Words
3690: @cindex simple defining words
3691: @cindex defining words, simple
3692:
1.33 ! anton 3693: @c split this section?
! 3694:
1.29 crook 3695: Defining words are used to create new entries in the dictionary. The
3696: simplest defining word is @code{CREATE}. @code{CREATE} is used like
3697: this:
3698:
3699: @example
3700: CREATE new-word1
3701: @end example
3702:
3703: @code{CREATE} is a parsing word that generates a dictionary entry for
3704: @code{new-word1}. When @code{new-word1} is executed, all that it does is
3705: leave an address on the stack. The address represents the value of
3706: the data space pointer (@code{HERE}) at the time that @code{new-word1}
3707: was defined. Therefore, @code{CREATE} is a way of associating a name
3708: with the address of a region of memory.
3709:
3710: By extending this example to reserve some memory in data space, we end
3711: up with a @i{variable}. Here are two different ways to do it:
3712:
3713: @example
3714: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
3715: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
3716: @end example
3717:
3718: The variable can be examined and modified using @code{@@} (``fetch'') and
3719: @code{!} (``store'') like this:
3720:
3721: @example
3722: new-word2 @@ . \ get address, fetch from it and display
3723: 1234 new-word2 ! \ new value, get address, store to it
3724: @end example
3725:
3726: As a final refinement, the whole code sequence can be wrapped up in a
3727: defining word (pre-empting the subject of the next section), making it
3728: easier to create new variables:
3729:
3730: @example
1.33 ! anton 3731: : myvariable ( "name" -- a-addr ) CREATE 0 , ;
1.29 crook 3732:
3733: myvariable foo
3734: myvariable joe
3735:
3736: 45 3 * foo ! \ set foo to 135
3737: 1234 joe ! \ set joe to 1234
3738: 3 joe +! \ increment joe by 3.. to 1237
3739: @end example
3740:
3741: Not surprisingly, there is no need to define @code{myvariable}, since
3742: Forth already has a definition @code{Variable}. It behaves in exactly
1.33 ! anton 3743: the same way as @code{myvariable}. Forth also provides @code{2Variable}
! 3744: and @code{fvariable} for double and floating-point variables,
! 3745: respectively.
1.29 crook 3746:
3747: @cindex arrays
3748: A similar mechanism can be used to create arrays. For example, an
3749: 80-character text input buffer:
3750:
3751: @example
3752: CREATE text-buf 80 chars allot
3753:
3754: text-buf 0 chars c@@ \ the 1st character (offset 0)
3755: text-buf 3 chars c@@ \ the 4th character (offset 3)
3756: @end example
3757:
3758: You can build arbitrarily complex data structures by allocating
3759: appropriate areas of memory. @xref{Structures} for further discussions
3760: of this, and to learn about some Gforth tools that make it easier.
3761:
3762: @cindex user variables
3763: @cindex user space
3764: The defining word @code{User} behaves in the same way as @code{Variable}.
3765: The difference is that it reserves space in @i{user (data) space} rather
3766: than normal data space. In a Forth system that has a multi-tasker, each
3767: task has its own set of user variables.
3768:
3769: @comment TODO is that stuff about user variables strictly correct? Is it
3770: @comment just terminal tasks that have user variables?
3771: @comment should document tasker.fs (with some examples) elsewhere
3772: @comment in this manual, then expand on user space and user variables.
3773:
3774: After @code{CREATE} and @code{Variable}s, the next defining word to
3775: consider is @code{Constant}. @code{Constant} allows you to declare a
3776: fixed value and refer to it by name. For example:
3777:
3778: @example
3779: 12 Constant INCHES-PER-FOOT
3780: 3E+08 fconstant SPEED-O-LIGHT
3781: @end example
3782:
3783: A @code{Variable} can be both read and written, so its run-time
3784: behaviour is to supply an address through which its current value can be
3785: manipulated. In contrast, the value of a @code{Constant} cannot be
3786: changed once it has been declared@footnote{Well, often it can be -- but
3787: not in a Standard, portable way. It's safer to use a @code{Value} (read
3788: on).} so it's not necessary to supply the address -- it is more
3789: efficient to return the value of the constant directly. That's exactly
3790: what happens; the run-time effect of a constant is to put its value on
3791: the top of the stack (@ref{User-defined Defining Words} describes one
3792: way of implementing @code{Constant}).
3793:
3794: Gforth also provides @code{2Constant} and @code{fconstant} for defining
3795: double and floating-point constants, respectively.
3796:
3797: Constants in Forth behave differently from their equivalents in other
3798: programming languages. In other languages, a constant (such as an EQU in
3799: assembler or a #define in C) only exists at compile-time; in the
3800: executable program the constant has been translated into an absolute
3801: number and, unless you are using a symbolic debugger, it's impossible to
3802: know what abstract thing that number represents. In Forth a constant has
1.32 anton 3803: an entry in the header space and remains there after the code that
1.29 crook 3804: uses it has been defined. In fact, it must remain in the dictionary
3805: since it has run-time duties to perform. For example:
3806:
3807: @example
3808: 12 Constant INCHES-PER-FOOT
3809: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
3810: @end example
3811:
1.33 ! anton 3812: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.29 crook 3813: @cindex in-lining of constants
3814: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
3815: associated with the constant @code{INCHES-PER-FOOT}. If you use
3816: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
3817: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
3818: attempt to optimise constants by in-lining them where they are used. You
3819: can force Gforth to in-line a constant like this:
3820:
3821: @example
3822: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
3823: @end example
3824:
3825: If you use @code{see} to decompile @i{this} version of
3826: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.33 ! anton 3827: longer present. @xref{Interpret/Compile states} and @ref{Literals} on
! 3828: how this works.
1.29 crook 3829:
3830: In-lining constants in this way might improve execution time
3831: fractionally, and can ensure that a constant is now only referenced at
3832: compile-time. However, the definition of the constant still remains in
3833: the dictionary. Some Forth compilers provide a mechanism for controlling
3834: a second dictionary for holding transient words such that this second
3835: dictionary can be deleted later in order to recover memory
3836: space. However, there is no standard way of doing this.
3837:
3838: One aspect of constants and variables that can sometimes be confusing is
3839: that they have different stack effects; one returns its value whilst the
3840: other returns the address of its value. The defining word @code{Value}
3841: provides an alternative to @code{Variable}, and has the same stack
3842: effect as a constant. A @code{Value} needs an additional word, @code{TO}
3843: to allow its value to be changed. Here are some examples:
3844:
3845: @example
3846: 12 Value APPLES \ a Value is initialised when it is declared.. like a
3847: \ constant but unlike a variable
3848: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
3849: APPLES \ puts 34 on the top of the stack.
3850: @end example
3851:
3852: The defining word @code{Defer} allows you to define a word by name
3853: without defining its behaviour; the definition of its behaviour is
3854: deferred. Here are two situation where this can be useful:
3855:
3856: @itemize @bullet
3857: @item
3858: Where you want to allow the behaviour of a word to be altered later, and
3859: for all precompiled references to the word to change when its behaviour
3860: is changed.
3861: @item
3862: For mutual recursion; @xref{Calls and returns}.
3863: @end itemize
3864:
3865: In the following example, @code{foo} always invokes the version of
3866: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
3867: always invokes the version that prints ``@code{Hello}''. There is no way
3868: of getting @code{foo} to use the later version without re-ordering the
3869: source code and recompilng it.
3870:
3871: @example
3872: : greet ." Good morning" ;
3873: : foo ... greet ... ;
3874: : greet ." Hello" ;
3875: : bar ... greet ... ;
3876: @end example
3877:
3878: This problem can be solved by defining @code{greet} as a @code{Defer}red
3879: word. The behaviour of a @code{Defer}red word can be defined and
3880: redefined at any time by using @code{IS} to associate the xt of a
3881: previously-defined word with it. The previous example becomes:
3882:
3883: @example
3884: Defer greet
3885: : foo ... greet ... ;
3886: : bar ... greet ... ;
3887: : greet1 ." Good morning" ;
3888: : greet2 ." Hello" ;
3889: ' greet2 IS greet \ make greet behave like greet2
3890: @end example
3891:
3892: A deferred word can only inherit default semantics from the xt (because
3893: that is all that an xt can represent -- @pxref{Tokens for Words} for
3894: more discussion of this). However, the semantics of the deferred word
3895: itself can be modified at the time that it is defined. For example:
3896:
3897: @example
3898: : bar .... ; compile-only
3899: Defer fred immediate
3900: Defer jim
3901:
3902: ' bar IS jim \ jim has default semantics
3903: ' bar IS fred \ fred is immediate
3904: @end example
1.1 anton 3905:
1.29 crook 3906: The defining word @code{Alias} allows you to define a word by name that
3907: has the same behaviour as some other word. Here are two situation where
3908: this can be useful:
1.1 anton 3909:
1.29 crook 3910: @itemize @bullet
3911: @item
3912: When you want access to a word's definition from a different word list
3913: (for an example of this, see the definition of the @code{Root} word list
3914: in the Gforth source).
3915: @item
3916: When you want to create a synonym; a definition that can be known by
3917: either of two names (for example, @code{THEN} and @code{ENDIF} are
3918: aliases).
3919: @end itemize
1.1 anton 3920:
1.29 crook 3921: The word whose behaviour the alias is to inherit is represented by an
3922: xt. Therefore, the alias can only inherits default semantics from its
3923: ancestor. The semantics of the alias itself can be modified at the time
3924: that it is defined. For example:
1.1 anton 3925:
1.29 crook 3926: @example
3927: : foo ... ; immediate
1.1 anton 3928:
1.29 crook 3929: ' foo Alias bar \ bar is not an immediate word
3930: ' foo Alias fooby immediate \ fooby is an immediate word
3931: @end example
1.26 crook 3932:
1.29 crook 3933: Words that are aliases have the same xt. Their semantics can differ
3934: because the rules about a word's semantics are stored in the name
3935: dictionary, and the aliases each have their own dictionary entry. It
3936: follows that words that are aliases have different name tokens and may
3937: have the same or different compilation tokens. Once again, see
3938: @ref{Tokens for Words} for more discussions of this.
1.27 crook 3939:
1.33 ! anton 3940: @c distribute this to the appropriate paragraphs? - anton
1.29 crook 3941: doc-create
1.26 crook 3942: doc-variable
3943: doc-2variable
3944: doc-fvariable
3945: doc-user
1.29 crook 3946: doc-constant
3947: doc-2constant
3948: doc-fconstant
1.26 crook 3949: doc-value
3950: doc-to
3951: doc-defer
3952: doc-is
1.29 crook 3953: doc-alias
3954: @comment TODO document these: what's defers <is> [is]
3955: doc-what's
1.28 crook 3956: doc-defers
1.26 crook 3957:
3958: Definitions in ANS Forth for @code{defer}, @code{<is>} and
3959: @code{[is]} are provided in @file{compat/defer.fs}.
1.29 crook 3960:
1.1 anton 3961:
1.26 crook 3962: @node Colon Definitions, User-defined Defining Words, Simple Defining Words, Defining Words
3963: @subsection Colon Definitions
3964: @cindex colon definitions
1.1 anton 3965:
1.26 crook 3966: @example
3967: : name ( ... -- ... )
3968: word1 word2 word3 ;
3969: @end example
1.1 anton 3970:
1.29 crook 3971: @noindent
3972: Creates a word called @code{name} that, upon execution, executes
1.26 crook 3973: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.1 anton 3974:
1.29 crook 3975: The explanation above is somewhat superficial. @xref{Your first
3976: definition} for simple examples of colon definitions, then
3977: @xref{Interpretation and Compilation Semantics} for an in-depth
3978: discussion of some of the issues involved.
1.26 crook 3979:
3980: doc-:
3981: doc-;
1.1 anton 3982:
1.26 crook 3983: @node User-defined Defining Words, Supplying names, Colon Definitions, Defining Words
3984: @subsection User-defined Defining Words
3985: @cindex user-defined defining words
3986: @cindex defining words, user-defined
1.1 anton 3987:
1.29 crook 3988: You can create a new defining word by wrapping defining-time code around
3989: an existing defining word and putting the sequence in a colon
3990: definition. For example, suppose that you have a word @code{stats} that
3991: gathers statistics about colon definitions given the @i{xt} of the
3992: definition, and you want every colon definition in your application to
3993: make a call to @code{stats}. You can define and use a new version of
3994: @code{:} like this:
3995:
3996: @example
3997: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
3998: ... ; \ other code
3999:
4000: : my: : lastxt postpone literal ['] stats compile, ;
4001:
4002: my: foo + - ;
4003: @end example
4004:
4005: When @code{foo} is defined using @code{my:} these steps occur:
4006:
4007: @itemize @bullet
4008: @item
4009: @code{my:} is executed.
4010: @item
4011: The @code{:} within the definition (the one between @code{my:} and
4012: @code{lastxt}) is executed, and does just what it always does; it parses
4013: the input stream for a name, builds a dictionary header for the name
4014: @code{foo} and switches @code{state} from interpret to compile.
4015: @item
4016: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
4017: being defined -- @code{foo} -- onto the stack.
4018: @item
4019: The code that was produced by @code{postpone literal} is executed; this
4020: causes the value on the stack to be compiled as a literal in the code
4021: area of @code{foo}.
4022: @item
4023: The code @code{['] stats} compiles a literal into the definition of
4024: @code{my:}. When @code{compile,} is executed, that literal -- the
4025: execution token for @code{stats} -- is layed down in the code area of
4026: @code{foo} , following the literal@footnote{Strictly speaking, the
4027: mechanism that @code{compile,} uses to convert an @i{xt} into something
4028: in the code area is implementation-dependent. A threaded implementation
4029: might spit out the execution token directly whilst another
4030: implementation might spit out a native code sequence.}.
4031: @item
4032: At this point, the execution of @code{my:} is complete, and control
4033: returns to the text interpreter. The text interpreter is in compile
4034: state, so subsequent text @code{+ -} is compiled into the definition of
4035: @code{foo} and the @code{;} terminates the definition as always.
4036: @end itemize
4037:
4038: You can use @code{see} to decompile a word that was defined using
4039: @code{my:} and see how it is different from a normal @code{:}
4040: definition. For example:
4041:
4042: @example
4043: : bar + - ; \ like foo but using : rather than my:
4044: see bar
4045: : bar
4046: + - ;
4047: see foo
4048: : foo
4049: 107645672 stats + - ;
4050:
4051: \ use ' stats . to show that 107645672 is the xt for stats
4052: @end example
4053:
4054:
1.33 ! anton 4055: @c a deferred word is not neccessary for these examples. - anton
1.29 crook 4056: Rather than edit your application's source code to change every @code{:}
4057: to a @code{my:}, use a deferred word:
4058:
4059: @example
4060: : real: : ; \ retain access to the original
4061: defer : \ redefine as a deferred word
4062: ' my: IS : \ use special version of :
4063: \
4064: \ load application here
4065: \
4066: ' real: IS : \ go back to the original
4067: @end example
4068:
4069: You can use techniques like this to make new defining words in terms of
4070: @i{any} existing defining word.
1.1 anton 4071:
4072:
1.29 crook 4073: @cindex defining defining words
1.26 crook 4074: @cindex @code{CREATE} ... @code{DOES>}
4075: If you want the words defined with your defining words to behave
4076: differently from words defined with standard defining words, you can
4077: write your defining word like this:
1.1 anton 4078:
4079: @example
1.26 crook 4080: : def-word ( "name" -- )
1.29 crook 4081: CREATE @i{code1}
1.26 crook 4082: DOES> ( ... -- ... )
1.29 crook 4083: @i{code2} ;
1.26 crook 4084:
4085: def-word name
1.1 anton 4086: @end example
4087:
1.29 crook 4088: @cindex child words
4089: This fragment defines a @dfn{defining word} @code{def-word} and then
4090: executes it. When @code{def-word} executes, it @code{CREATE}s a new
4091: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
4092: is not executed at this time. The word @code{name} is sometimes called a
4093: @dfn{child} of @code{def-word}.
4094:
4095: When you execute @code{name}, the address of the body of @code{name} is
4096: put on the data stack and @i{code2} is executed (the address of the body
4097: of @code{name} is the address @code{HERE} returns immediately after the
4098: @code{CREATE}).
4099:
4100: @cindex atavism in child words
1.33 ! anton 4101: You can use @code{def-word} to define a set of child words that behave
1.29 crook 4102: differently, though atavistically; they all have a common run-time
4103: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
4104: builds a data area in the body of the child word. The structure of the
4105: data is common to all children of @code{def-word}, but the data values
4106: are specific -- and private -- to each child word. When a child word is
4107: executed, the address of its private data area is passed as a parameter
4108: on TOS to be used and manipulated@footnote{It is legitimate both to read
4109: and write to this data area.} by @i{code2}.
4110:
4111: The two fragments of code that make up the defining words act (are
4112: executed) at two completely separate times:
1.1 anton 4113:
1.29 crook 4114: @itemize @bullet
4115: @item
4116: At @i{define time}, the defining word executes @i{code1} to generate a
4117: child word
4118: @item
4119: At @i{child execution time}, when a child word is invoked, @i{code2}
4120: is executed, using parameters (data) that are private and specific to
4121: the child word.
4122: @end itemize
4123:
4124: @c NAC I think this is a really bad example, because it diminishes
4125: @c rather than emphasising the fact that some important stuff happens
4126: @c at define time, and other important stuff happens at child-invocation
4127: @c time, and that those two times are potentially very different.
1.33 ! anton 4128:
! 4129: @c Well, IMO CREATE-DOES> is usually presented with much ado, making
! 4130: @c people think that it's hard to understand, and making those people who
! 4131: @c understand it easily think that it's hyped. I prefer presenting it in a
! 4132: @c diminished way and only emphasize the special issues later. - anton
! 4133:
! 4134: In other words, if you make the following definitions:
! 4135: @example
! 4136: : def-word1 ( "name" -- )
! 4137: CREATE @i{code1} ;
! 4138:
! 4139: : action1 ( ... -- ... )
! 4140: @i{code2} ;
! 4141:
! 4142: def-word1 name1
! 4143: @end example
! 4144:
! 4145: Using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 4146:
1.29 crook 4147: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 4148:
1.1 anton 4149: @example
1.29 crook 4150: : CONSTANT ( w "name" -- )
4151: CREATE ,
1.26 crook 4152: DOES> ( -- w )
4153: @@ ;
1.1 anton 4154: @end example
4155:
1.29 crook 4156: @comment There is a beautiful description of how this works and what
4157: @comment it does in the Forthwrite 100th edition.. as well as an elegant
4158: @comment commentary on the Counting Fruits problem.
4159:
4160: When you create a constant with @code{5 CONSTANT five}, a set of
4161: define-time actions take place; first a new word @code{five} is created,
4162: then the value 5 is laid down in the body of @code{five} with
4163: @code{,}. When @code{five} is invoked, the address of the body is put on
4164: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
4165: no code of its own; it simply contains a data field and a pointer to the
4166: code that follows @code{DOES>} in its defining word. That makes words
4167: created in this way very compact.
4168:
4169: The final example in this section is intended to remind you that space
4170: reserved in @code{CREATE}d words is @i{data} space and therefore can be
4171: both read and written by a Standard program@footnote{Exercise: use this
4172: example as a starting point for your own implementation of @code{Value}
4173: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
4174: @code{[']}.}:
4175:
4176: @example
4177: : foo ( "name" -- )
4178: CREATE -1 ,
4179: DOES> ( -- )
1.33 ! anton 4180: @@ . ;
1.29 crook 4181:
4182: foo first-word
4183: foo second-word
4184:
4185: 123 ' first-word >BODY !
4186: @end example
4187:
4188: If @code{first-word} had been a @code{CREATE}d word, we could simply
4189: have executed it to get the address of its data field. However, since it
4190: was defined to have @code{DOES>} actions, its execution semantics are to
4191: perform those @code{DOES>} actions. To get the address of its data field
4192: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
4193: translate the xt into the address of the data field. When you execute
4194: @code{first-word}, it will display @code{123}. When you execute
4195: @code{second-word} it will display @code{-1}.
1.26 crook 4196:
4197: @cindex stack effect of @code{DOES>}-parts
4198: @cindex @code{DOES>}-parts, stack effect
1.29 crook 4199: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 4200: the stack effect of the defined words, not the stack effect of the
4201: following code (the following code expects the address of the body on
4202: the top of stack, which is not reflected in the stack comment). This is
4203: the convention that I use and recommend (it clashes a bit with using
4204: locals declarations for stack effect specification, though).
1.1 anton 4205:
1.26 crook 4206: @subsubsection Applications of @code{CREATE..DOES>}
4207: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 4208:
1.26 crook 4209: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 4210:
1.26 crook 4211: @cindex factoring similar colon definitions
4212: When you see a sequence of code occurring several times, and you can
4213: identify a meaning, you will factor it out as a colon definition. When
4214: you see similar colon definitions, you can factor them using
4215: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
4216: that look very similar:
1.1 anton 4217: @example
1.26 crook 4218: : ori, ( reg-target reg-source n -- )
4219: 0 asm-reg-reg-imm ;
4220: : andi, ( reg-target reg-source n -- )
4221: 1 asm-reg-reg-imm ;
1.1 anton 4222: @end example
4223:
1.26 crook 4224: @noindent
4225: This could be factored with:
4226: @example
4227: : reg-reg-imm ( op-code -- )
4228: CREATE ,
4229: DOES> ( reg-target reg-source n -- )
4230: @@ asm-reg-reg-imm ;
4231:
4232: 0 reg-reg-imm ori,
4233: 1 reg-reg-imm andi,
4234: @end example
1.1 anton 4235:
1.26 crook 4236: @cindex currying
4237: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
4238: supply a part of the parameters for a word (known as @dfn{currying} in
4239: the functional language community). E.g., @code{+} needs two
4240: parameters. Creating versions of @code{+} with one parameter fixed can
4241: be done like this:
1.1 anton 4242: @example
1.26 crook 4243: : curry+ ( n1 -- )
4244: CREATE ,
4245: DOES> ( n2 -- n1+n2 )
4246: @@ + ;
4247:
4248: 3 curry+ 3+
4249: -2 curry+ 2-
1.1 anton 4250: @end example
4251:
1.26 crook 4252: @subsubsection The gory details of @code{CREATE..DOES>}
4253: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 4254:
1.26 crook 4255: doc-does>
1.1 anton 4256:
1.26 crook 4257: @cindex @code{DOES>} in a separate definition
4258: This means that you need not use @code{CREATE} and @code{DOES>} in the
4259: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 4260: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 4261: @example
4262: : does1
4263: DOES> ( ... -- ... )
4264: ... ;
1.1 anton 4265:
1.26 crook 4266: : does2
4267: DOES> ( ... -- ... )
4268: ... ;
1.1 anton 4269:
1.26 crook 4270: : def-word ( ... -- ... )
4271: create ...
4272: IF
4273: does1
4274: ELSE
4275: does2
4276: ENDIF ;
4277: @end example
1.1 anton 4278:
1.26 crook 4279: In this example, the selection of whether to use @code{does1} or
4280: @code{does2} is made at compile-time; at the time that the child word is
1.29 crook 4281: @code{CREATE}d.
1.1 anton 4282:
1.26 crook 4283: @cindex @code{DOES>} in interpretation state
4284: In a standard program you can apply a @code{DOES>}-part only if the last
4285: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
4286: will override the behaviour of the last word defined in any case. In a
4287: standard program, you can use @code{DOES>} only in a colon
4288: definition. In Gforth, you can also use it in interpretation state, in a
4289: kind of one-shot mode; for example:
1.1 anton 4290: @example
1.26 crook 4291: CREATE name ( ... -- ... )
1.29 crook 4292: @i{initialization}
1.26 crook 4293: DOES>
1.29 crook 4294: @i{code} ;
1.1 anton 4295: @end example
4296:
1.26 crook 4297: @noindent
4298: is equivalent to the standard:
1.1 anton 4299: @example
1.26 crook 4300: :noname
4301: DOES>
1.29 crook 4302: @i{code} ;
1.26 crook 4303: CREATE name EXECUTE ( ... -- ... )
1.29 crook 4304: @i{initialization}
1.1 anton 4305: @end example
4306:
1.26 crook 4307: You can get the address of the body of a word with:
4308:
4309: doc->body
1.1 anton 4310:
1.26 crook 4311: @node Supplying names, Interpretation and Compilation Semantics, User-defined Defining Words, Defining Words
1.29 crook 4312: @subsection Supplying the name of a defined word
1.26 crook 4313: @cindex names for defined words
4314: @cindex defining words, name parameter
1.1 anton 4315:
1.26 crook 4316: @cindex defining words, name given in a string
1.29 crook 4317: By default, a defining word takes the name for the defined word from the
1.26 crook 4318: input stream. Sometimes you want to supply the name from a string. You
4319: can do this with:
1.1 anton 4320:
1.26 crook 4321: doc-nextname
1.1 anton 4322:
1.26 crook 4323: For example:
1.1 anton 4324:
1.26 crook 4325: @example
4326: s" foo" nextname create
4327: @end example
4328: @noindent
4329: is equivalent to:
4330: @example
4331: create foo
4332: @end example
1.1 anton 4333:
1.26 crook 4334: @cindex defining words without name
1.29 crook 4335: Sometimes you want to define an @dfn{anonymous word}; a word without a
1.26 crook 4336: name. You can do this with:
1.1 anton 4337:
1.26 crook 4338: doc-:noname
1.1 anton 4339:
1.26 crook 4340: This leaves the execution token for the word on the stack after the
4341: closing @code{;}. Here's an example in which a deferred word is
4342: initialised with an @code{xt} from an anonymous colon definition:
4343: @example
4344: Defer deferred
4345: :noname ( ... -- ... )
4346: ... ;
4347: IS deferred
4348: @end example
1.1 anton 4349:
1.29 crook 4350: @noindent
1.26 crook 4351: Gforth provides an alternative way of doing this, using two separate
4352: words:
1.1 anton 4353:
1.26 crook 4354: doc-noname
4355: @cindex execution token of last defined word
4356: doc-lastxt
1.1 anton 4357:
1.29 crook 4358: @noindent
1.26 crook 4359: The previous example can be rewritten using @code{noname} and
4360: @code{lastxt}:
1.1 anton 4361:
1.26 crook 4362: @example
4363: Defer deferred
4364: noname : ( ... -- ... )
4365: ... ;
4366: lastxt IS deferred
4367: @end example
1.1 anton 4368:
1.29 crook 4369: @noindent
1.33 ! anton 4370: @code{noname} and @code{nextname} work with any defining word, not just
! 4371: @code{:}.
! 4372:
1.26 crook 4373: @code{lastxt} also works when the last word was not defined as
1.29 crook 4374: @code{noname}. It also has the useful property that is is valid as soon
4375: as the header for a definition has been build. Thus:
4376:
4377: @example
4378: lastxt . : foo [ lastxt . ] ; ' foo .
4379: @end example
4380:
4381: @noindent
4382: prints 3 numbers; the last two are the same.
1.1 anton 4383:
4384:
1.26 crook 4385: @node Interpretation and Compilation Semantics, , Supplying names, Defining Words
4386: @subsection Interpretation and Compilation Semantics
4387: @cindex semantics, interpretation and compilation
1.1 anton 4388:
1.26 crook 4389: @cindex interpretation semantics
4390: The @dfn{interpretation semantics} of a word are what the text
4391: interpreter does when it encounters the word in interpret state. It also
4392: appears in some other contexts, e.g., the execution token returned by
1.29 crook 4393: @code{' @i{word}} identifies the interpretation semantics of
4394: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
4395: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 4396:
1.26 crook 4397: @cindex compilation semantics
4398: The @dfn{compilation semantics} of a word are what the text interpreter
4399: does when it encounters the word in compile state. It also appears in
1.29 crook 4400: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
1.26 crook 4401: standard terminology, ``appends to the current definition''.} the
1.29 crook 4402: compilation semantics of @i{word}.
1.1 anton 4403:
1.26 crook 4404: @cindex execution semantics
4405: The standard also talks about @dfn{execution semantics}. They are used
4406: only for defining the interpretation and compilation semantics of many
4407: words. By default, the interpretation semantics of a word are to
4408: @code{execute} its execution semantics, and the compilation semantics of
4409: a word are to @code{compile,} its execution semantics.@footnote{In
4410: standard terminology: The default interpretation semantics are its
4411: execution semantics; the default compilation semantics are to append its
4412: execution semantics to the execution semantics of the current
4413: definition.}
4414:
4415: @comment TODO expand, make it co-operate with new sections on text interpreter.
4416:
4417: @cindex immediate words
4418: @cindex compile-only words
4419: You can change the semantics of the most-recently defined word:
4420:
4421: doc-immediate
4422: doc-compile-only
4423: doc-restrict
4424:
4425: Note that ticking (@code{'}) a compile-only word gives an error
4426: (``Interpreting a compile-only word'').
1.1 anton 4427:
1.26 crook 4428: Gforth also allows you to define words with arbitrary combinations of
4429: interpretation and compilation semantics.
1.1 anton 4430:
1.26 crook 4431: doc-interpret/compile:
1.1 anton 4432:
1.26 crook 4433: This feature was introduced for implementing @code{TO} and @code{S"}. I
4434: recommend that you do not define such words, as cute as they may be:
4435: they make it hard to get at both parts of the word in some contexts.
4436: E.g., assume you want to get an execution token for the compilation
4437: part. Instead, define two words, one that embodies the interpretation
4438: part, and one that embodies the compilation part. Once you have done
4439: that, you can define a combined word with @code{interpret/compile:} for
4440: the convenience of your users.
1.1 anton 4441:
1.26 crook 4442: You might try to use this feature to provide an optimizing
4443: implementation of the default compilation semantics of a word. For
4444: example, by defining:
1.1 anton 4445: @example
1.26 crook 4446: :noname
4447: foo bar ;
4448: :noname
4449: POSTPONE foo POSTPONE bar ;
1.29 crook 4450: interpret/compile: opti-foobar
1.1 anton 4451: @end example
1.26 crook 4452:
1.23 crook 4453: @noindent
1.26 crook 4454: as an optimizing version of:
4455:
1.1 anton 4456: @example
1.26 crook 4457: : foobar
4458: foo bar ;
1.1 anton 4459: @end example
4460:
1.26 crook 4461: Unfortunately, this does not work correctly with @code{[compile]},
4462: because @code{[compile]} assumes that the compilation semantics of all
4463: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 4464: opti-foobar} would compile compilation semantics, whereas
4465: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 4466:
1.26 crook 4467: @cindex state-smart words (are a bad idea)
1.29 crook 4468: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 4469: by @code{interpret/compile:} (words are state-smart if they check
4470: @code{STATE} during execution). E.g., they would try to code
4471: @code{foobar} like this:
1.1 anton 4472:
1.26 crook 4473: @example
4474: : foobar
4475: STATE @@
4476: IF ( compilation state )
4477: POSTPONE foo POSTPONE bar
4478: ELSE
4479: foo bar
4480: ENDIF ; immediate
4481: @end example
1.1 anton 4482:
1.26 crook 4483: Although this works if @code{foobar} is only processed by the text
4484: interpreter, it does not work in other contexts (like @code{'} or
4485: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
4486: for a state-smart word, not for the interpretation semantics of the
4487: original @code{foobar}; when you execute this execution token (directly
4488: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
4489: state, the result will not be what you expected (i.e., it will not
4490: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
4491: write them@footnote{For a more detailed discussion of this topic, see
4492: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
4493: Ertl; presented at EuroForth '98 and available from
1.33 ! anton 4494: @url{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz}}!
1.1 anton 4495:
1.26 crook 4496: @cindex defining words with arbitrary semantics combinations
4497: It is also possible to write defining words that define words with
4498: arbitrary combinations of interpretation and compilation semantics. In
4499: general, they look like this:
1.1 anton 4500:
1.26 crook 4501: @example
4502: : def-word
4503: create-interpret/compile
1.29 crook 4504: @i{code1}
1.26 crook 4505: interpretation>
1.29 crook 4506: @i{code2}
1.26 crook 4507: <interpretation
4508: compilation>
1.29 crook 4509: @i{code3}
1.26 crook 4510: <compilation ;
4511: @end example
1.1 anton 4512:
1.29 crook 4513: For a @i{word} defined with @code{def-word}, the interpretation
4514: semantics are to push the address of the body of @i{word} and perform
4515: @i{code2}, and the compilation semantics are to push the address of
4516: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 4517: can also be defined like this (except that the defined constants don't
4518: behave correctly when @code{[compile]}d):
1.1 anton 4519:
1.26 crook 4520: @example
4521: : constant ( n "name" -- )
4522: create-interpret/compile
4523: ,
4524: interpretation> ( -- n )
4525: @@
4526: <interpretation
4527: compilation> ( compilation. -- ; run-time. -- n )
4528: @@ postpone literal
4529: <compilation ;
4530: @end example
1.1 anton 4531:
1.26 crook 4532: doc-create-interpret/compile
4533: doc-interpretation>
4534: doc-<interpretation
4535: doc-compilation>
4536: doc-<compilation
1.1 anton 4537:
1.29 crook 4538: Words defined with @code{interpret/compile:} and
1.26 crook 4539: @code{create-interpret/compile} have an extended header structure that
4540: differs from other words; however, unless you try to access them with
4541: plain address arithmetic, you should not notice this. Words for
4542: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 4543: @code{'} @i{word} @code{>body} also gives you the body of a word created
4544: with @code{create-interpret/compile}.
1.1 anton 4545:
1.27 crook 4546: doc-postpone
1.29 crook 4547: @comment TODO -- expand glossary text for POSTPONE
1.27 crook 4548:
1.26 crook 4549: @c ----------------------------------------------------------
4550: @node The Text Interpreter, Tokens for Words, Defining Words, Words
4551: @section The Text Interpreter
4552: @cindex interpreter - outer
4553: @cindex text interpreter
4554: @cindex outer interpreter
1.1 anton 4555:
1.29 crook 4556: The text interpreter@footnote{This is an expanded version of the
4557: material in @ref{Introducing the Text Interpreter}.} is an endless loop
4558: that processes input from the current input device. A popular
4559: implementation technique for Forth is to implement a @dfn{forth virtual
4560: machine} using a loop called the @dfn{inner interpreter}. Because of
4561: this naming, the text interpreter is also known as the @dfn{outer
1.27 crook 4562: interpreter}.
4563:
1.29 crook 4564: @cindex interpret state
4565: @cindex compile state
4566: The text interpreter operates in one of two states: @dfn{interpret
4567: state} and @dfn{compile state}. The current state is defined by the
4568: aptly-named variable, @code{state}.
4569:
4570: This section starts by describing how the text interpreter behaves when
4571: it is in interpret state, processing input from the user input device --
4572: the keyboard. This is the mode that a Forth system is in after it starts
4573: up.
4574:
4575: @cindex input buffer
4576: @cindex terminal input buffer
4577: The text interpreter works from an area of memory called the @dfn{input
4578: buffer}@footnote{When the text interpreter is processing input from the
4579: keyboard, this area of memory is called the @dfn{terminal input buffer}
4580: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
4581: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 4582: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 4583: leading spaces (called @dfn{delimiters}) then parses a string (a
4584: sequence of non-space characters) until it reaches either a space
4585: character or the end of the buffer. Having parsed a string, it makes two
4586: attempts to process it:
1.27 crook 4587:
1.29 crook 4588: @cindex dictionary
1.27 crook 4589: @itemize @bullet
4590: @item
1.29 crook 4591: It looks for the string in a @dfn{dictionary} of definitions. If the
4592: string is found, the string names a @dfn{definition} (also known as a
4593: @dfn{word}) and the dictionary search returns information that allows
4594: the text interpreter to perform the word's @dfn{interpretation
4595: semantics}. In most cases, this simply means that the word will be
4596: executed.
1.27 crook 4597: @item
4598: If the string is not found in the dictionary, the text interpreter
1.29 crook 4599: attempts to treat it as a number, using the rules described in
4600: @ref{Number Conversion}. If the string represents a legal number in the
4601: current radix, the number is pushed onto a parameter stack (the data
4602: stack for integers, the floating-point stack for floating-point
4603: numbers).
4604: @end itemize
4605:
4606: If both attempts fail, or if the word is found in the dictionary but has
4607: no interpretation semantics@footnote{This happens if the word was
4608: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
4609: remainder of the input buffer, issues an error message and waits for
4610: more input. If one of the attempts succeeds, the text interpreter
4611: repeats the parsing process until the whole of the input buffer has been
4612: processed, at which point it prints the status message ``@code{ ok}''
4613: and waits for more input.
4614:
4615: @cindex parse area
4616: The text interpreter keeps track of its position in the input buffer by
4617: updating a variable called @code{>IN} (pronounced ``to-in''). The value
4618: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
4619: of the input buffer. The region from offset @code{>IN @@} to the end of
4620: the input buffer is called the @dfn{parse area}@footnote{In other words,
4621: the text interpreter processes the contents of the input buffer by
4622: parsing strings from the parse area until the parse area is empty.}.
4623: This example shows how @code{>IN} changes as the text interpreter parses
4624: the input buffer:
4625:
4626: @example
4627: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
4628: CR ." ->" TYPE ." <-" ; IMMEDIATE
4629:
4630: 1 2 3 remaining + remaining .
4631:
4632: : foo 1 2 3 remaining SWAP remaining ;
4633: @end example
4634:
4635: @noindent
4636: The result is:
4637:
4638: @example
4639: ->+ remaining .<-
4640: ->.<-5 ok
4641:
4642: ->SWAP remaining ;-<
4643: ->;<- ok
4644: @end example
4645:
4646: @cindex parsing words
4647: The value of @code{>IN} can also be modified by a word in the input
4648: buffer that is executed by the text interpreter. This means that a word
4649: can ``trick'' the text interpreter into either skipping a section of the
4650: input buffer@footnote{This is how parsing words work.} or into parsing a
4651: section twice. For example:
1.27 crook 4652:
1.29 crook 4653: @example
4654: : lat ." <<lat>>" ;
4655: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
4656: @end example
4657:
4658: @noindent
4659: When @code{flat} is executed, this output is produced@footnote{Exercise
4660: for the reader: what would happen if the @code{3} were replaced with
4661: @code{4}?}:
4662:
4663: @example
4664: <<flat>><<lat>>
4665: @end example
4666:
4667: @noindent
4668: Two important notes about the behaviour of the text interpreter:
1.27 crook 4669:
4670: @itemize @bullet
4671: @item
4672: It processes each input string to completion before parsing additional
1.29 crook 4673: characters from the input buffer.
4674: @item
4675: It treats the input buffer as a read-only region (and so must your code).
4676: @end itemize
4677:
4678: @noindent
4679: When the text interpreter is in compile state, its behaviour changes in
4680: these ways:
4681:
4682: @itemize @bullet
4683: @item
4684: If a parsed string is found in the dictionary, the text interpreter will
4685: perform the word's @dfn{compilation semantics}. In most cases, this
4686: simply means that the execution semantics of the word will be appended
4687: to the current definition.
1.27 crook 4688: @item
1.29 crook 4689: When a number is encountered, it is compiled into the current definition
4690: (as a literal) rather than being pushed onto a parameter stack.
4691: @item
4692: If an error occurs, @code{state} is modified to put the text interpreter
4693: back into interpret state.
4694: @item
4695: Each time a line is entered from the keyboard, Gforth prints
4696: ``@code{ compiled}'' rather than `` @code{ok}''.
4697: @end itemize
4698:
4699: @cindex text interpreter - input sources
4700: When the text interpreter is using an input device other than the
4701: keyboard, its behaviour changes in these ways:
4702:
4703: @itemize @bullet
4704: @item
4705: When the parse area is empty, the text interpreter attempts to refill
4706: the input buffer from the input source. When the input source is
4707: exhausted, the input source is set back to the user input device.
4708: @item
4709: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
4710: time the parse area is emptied.
4711: @item
4712: If an error occurs, the input source is set back to the user input
4713: device.
1.27 crook 4714: @end itemize
1.21 crook 4715:
1.29 crook 4716: @ref{Input Sources} describes this in more detail.
4717:
1.26 crook 4718: doc->in
1.27 crook 4719: doc-source
4720:
1.26 crook 4721: doc-tib
4722: doc-#tib
1.1 anton 4723:
1.26 crook 4724: @menu
1.29 crook 4725: * Input Sources::
1.26 crook 4726: * Number Conversion::
4727: * Interpret/Compile states::
4728: * Literals::
4729: * Interpreter Directives::
4730: @end menu
1.1 anton 4731:
1.29 crook 4732: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
4733: @subsection Input Sources
4734: @cindex input sources
4735: @cindex text interpreter - input sources
4736:
4737: By default, the text interpreter accepts input from the user input
4738: device (the keyboard) when Forth starts up. The text interpreter can
4739: process input from any of these sources:
4740:
4741: @itemize @bullet
4742: @item
4743: The user input device -- the keyboard.
4744: @item
4745: A file, using the words described in @ref{Forth source files}.
4746: @item
4747: A block, using the words described in @ref{Blocks}.
4748: @item
4749: A text string, using @code{evaluate}.
4750: @end itemize
4751:
4752: A program can identify the current input device from the values of
4753: @code{source-id} and @code{blk}.
4754:
4755: doc-source-id
4756: doc-blk
4757:
4758: doc-save-input
4759: doc-restore-input
4760:
4761: doc-evaluate
1.1 anton 4762:
1.29 crook 4763:
4764: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 4765: @subsection Number Conversion
4766: @cindex number conversion
4767: @cindex double-cell numbers, input format
4768: @cindex input format for double-cell numbers
4769: @cindex single-cell numbers, input format
4770: @cindex input format for single-cell numbers
4771: @cindex floating-point numbers, input format
4772: @cindex input format for floating-point numbers
1.1 anton 4773:
1.29 crook 4774: This section describes the rules that the text interpreter uses when it
4775: tries to convert a string into a number.
1.1 anton 4776:
1.26 crook 4777: Let <digit> represent any character that is a legal digit in the current
1.29 crook 4778: number base@footnote{For example, 0-9 when the number base is decimal or
4779: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 4780:
1.26 crook 4781: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 4782:
1.29 crook 4783: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
4784: in the braces (@i{a} or @i{b} or neither).
1.1 anton 4785:
1.26 crook 4786: Let * represent any number of instances of the previous character
4787: (including none).
1.1 anton 4788:
1.26 crook 4789: Let any other character represent itself.
1.1 anton 4790:
1.29 crook 4791: @noindent
1.26 crook 4792: Now, the conversion rules are:
1.21 crook 4793:
1.26 crook 4794: @itemize @bullet
4795: @item
4796: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 4797: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 4798: @item
4799: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 4800: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 4801: arithmetic. Examples are -45 -5681 -0
4802: @item
4803: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 4804: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
4805: (all three of these represent the same number).
1.26 crook 4806: @item
4807: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 4808: double-precision (double-cell-sized) negative integer, and is
1.26 crook 4809: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 4810: -34.65 (all three of these represent the same number).
1.26 crook 4811: @item
1.29 crook 4812: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
4813: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.26 crook 4814: number. Examples are 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 4815: number) +12.E-4
1.26 crook 4816: @end itemize
1.1 anton 4817:
1.26 crook 4818: By default, the number base used for integer number conversion is given
1.29 crook 4819: by the contents of the variable @code{BASE}. Base 10 (decimal) is
1.26 crook 4820: always used for floating-point number conversion.
1.1 anton 4821:
1.29 crook 4822: doc-dpl
1.26 crook 4823: doc-base
4824: doc-hex
4825: doc-decimal
1.1 anton 4826:
1.26 crook 4827: @cindex '-prefix for character strings
4828: @cindex &-prefix for decimal numbers
4829: @cindex %-prefix for binary numbers
4830: @cindex $-prefix for hexadecimal numbers
1.29 crook 4831: Gforth allows you to override the value of @code{BASE} by using a
4832: prefix@footnote{Some Forth implementations provide a similar scheme by
4833: implementing @code{$} etc. as parsing words that process the subsequent
4834: number in the input stream and push it onto the stack. For example, see
4835: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
4836: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
4837: is required between the prefix and the number.} before the first digit
4838: of an (integer) number. Four prefixes are supported:
1.1 anton 4839:
1.26 crook 4840: @itemize @bullet
4841: @item
4842: @code{&} -- decimal number
4843: @item
4844: @code{%} -- binary number
4845: @item
4846: @code{$} -- hexadecimal number
4847: @item
4848: @code{'} -- base 256 number
4849: @end itemize
1.1 anton 4850:
1.26 crook 4851: Here are some examples, with the equivalent decimal number shown after
4852: in braces:
1.1 anton 4853:
1.26 crook 4854: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
4855: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
4856: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
4857: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 4858:
1.26 crook 4859: @cindex number conversion - traps for the unwary
1.29 crook 4860: @noindent
1.26 crook 4861: Number conversion has a number of traps for the unwary:
1.1 anton 4862:
1.26 crook 4863: @itemize @bullet
4864: @item
4865: You cannot determine the current number base using the code sequence
4866: @code{BASE @@ .} -- the number base is always 10 in the current number
4867: base. Instead, use something like @code{BASE @@ DECIMAL DUP . BASE !}
4868: @item
4869: If the number base is set to a value greater than 14 (for example,
4870: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
4871: it to be intepreted as either a single-precision integer or a
4872: floating-point number (Gforth treats it as an integer). The ambiguity
4873: can be resolved by explicitly stating the sign of the mantissa and/or
4874: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
4875: ambiguity arises; either representation will be treated as a
4876: floating-point number.
4877: @item
1.29 crook 4878: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 4879: It is used to specify file types.
4880: @item
4881: ANS Forth requires the @code{.} of a double-precision number to
4882: be the final character in the string. Allowing the @code{.} to be
4883: anywhere after the first digit is a Gforth extension.
4884: @item
4885: The number conversion process does not check for overflow.
4886: @item
4887: In Gforth, number conversion to floating-point numbers always use base
4888: 10, irrespective of the value of @code{BASE}. In ANS Forth,
4889: conversion to floating-point numbers whilst the value of
4890: @code{BASE} is not 10 is an ambiguous condition.
4891: @end itemize
1.1 anton 4892:
1.29 crook 4893: @ref{Input} describes words that you can use to read numbers into your
4894: programs.
1.1 anton 4895:
1.26 crook 4896: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
4897: @subsection Interpret/Compile states
4898: @cindex Interpret/Compile states
1.1 anton 4899:
1.29 crook 4900: A standard program is not permitted to change @code{state}
4901: explicitly. However, it can change @code{state} implicitly, using the
4902: words @code{[} and @code{]}. When @code{[} is executed it switches
4903: @code{state} to interpret state, and therefore the text interpreter
4904: starts interpreting. When @code{]} is executed it switches @code{state}
4905: to compile state and therefore the text interpreter starts
4906: compiling. The most common usage for these words is to compile literals,
4907: as shown in @ref{Literals}. However, they give you the freedom to switch
4908: modes at will. Here is an example of building a jump-table of execution
4909: tokens:
4910:
4911: @example
4912: : AA ." this is A" ;
4913: : BB ." this is B" ;
4914: : CC ." this is C" ;
4915:
4916: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
4917: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
4918: cells table + @ execute ;
4919: @end example
4920:
4921: @noindent
4922: Now @code{0 go} will display ``@code{this is A}''. The table can be
4923: built far more neatly@footnote{The source code is neater.. what is
4924: compiled in memory in each case is identical.} like this:
4925:
4926: @example
4927: create table ] aa bb cc [
4928: @end example
4929:
4930: The problem with this code is that it is not portable; it will only work
4931: on systems where code space and data space co-incide. The reason is that
4932: both tables @i{compile} execution tokens -- into code space. The
4933: Standard only allows data space to be assigned for a @code{CREATE}d
4934: word. In addition, the Standard only allows @code{@@} to access data
4935: space, whilst this example is using it to access code space. The only
4936: portable, Standard way to build this table is to build it in data space,
4937: like this:
4938:
4939: @example
4940: create table ' aa , ' bb , ' cc ,
4941: @end example
4942:
4943: @noindent
4944: A similar technique can be used to build a table of constants:
4945:
4946: @example
4947: create primes 1 , 3 , 5 , 7 , 11 ,
4948: @end example
1.1 anton 4949:
1.26 crook 4950: doc-state
4951: doc-[
4952: doc-]
1.1 anton 4953:
1.26 crook 4954: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
4955: @subsection Literals
4956: @cindex Literals
1.21 crook 4957:
1.29 crook 4958: Often, you want to use a number within a colon definition. When you do
4959: this, the text interpreter automatically compiles the number as a
4960: @i{literal}. A literal is a number whose run-time effect is to be pushed
4961: onto the stack. If you had to do some maths to generate the number, you
4962: might write it like this:
4963:
4964: @example
4965: : HOUR-TO-SEC ( n1 -- n2 )
4966: 60 * \ to minutes
4967: 60 * ; \ to seconds
4968: @end example
4969:
4970: It is very clear what this definition is doing, but it's inefficient
4971: since it is performing 2 multiples at run-time. An alternative would be
4972: to write:
4973:
4974: @example
4975: : HOUR-TO-SEC ( n1 -- n2 )
4976: 3600 * ; \ to seconds
4977: @end example
4978:
4979: Which does the same thing, and has the advantage of using a single
4980: multiply. Ideally, we'd like the efficiency of the second with the
4981: readability of the first.
4982:
4983: @code{Literal} allows us to achieve that. It takes a number from the
4984: stack and lays it down in the current definition just as though the
4985: number had been typed directly into the definition. Our first attempt
4986: might look like this:
4987:
4988: @example
4989: 60 \ mins per hour
4990: 60 * \ seconds per minute
4991: : HOUR-TO-SEC ( n1 -- n2 )
4992: Literal * ; \ to seconds
4993: @end example
4994:
4995: But this produces the error message @code{unstructured}. What happened?
4996: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
4997: @i{colon-sys} is implementation-defined. In other words, once we start a
4998: colon definition we can't portably access anything that was on the stack
4999: before the definition began@footnote{@cite{Two Problems in ANS Forth},
5000: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
5001: some situations where you might want to access stack items above
5002: colon-sys, and provides a solution to the problem.}. The correct way of
5003: solving this problem in this instance is to use @code{[ ]} like this:
5004:
5005: @example
5006: : HOUR-TO-SEC ( n1 -- n2 )
5007: [ 60 \ minutes per hour
5008: 60 * ] \ seconds per minute
5009: LITERAL * ; \ to seconds
5010: @end example
1.23 crook 5011:
1.26 crook 5012: doc-literal
5013: doc-]L
5014: doc-2literal
5015: doc-fliteral
1.1 anton 5016:
1.29 crook 5017: @node Interpreter Directives, , Literals, The Text Interpreter
1.26 crook 5018: @subsection Interpreter Directives
5019: @cindex interpreter directives
1.1 anton 5020:
1.29 crook 5021: These words are usually used in interpret state; typically to control
5022: which parts of a source file are processed by the text
1.26 crook 5023: interpreter. There are only a few ANS Forth Standard words, but Gforth
5024: supplements these with a rich set of immediate control structure words
5025: to compensate for the fact that the non-immediate versions can only be
1.29 crook 5026: used in compile state (@pxref{Control Structures}). Typical usages:
5027:
5028: @example
5029: FALSE Constant ASSEMBLER
5030: .
5031: .
5032: ASSEMBLER [IF]
5033: : ASSEMBLER-FEATURE
5034: ...
5035: ;
5036: [ENDIF]
5037: .
5038: .
5039: : SEE
5040: ... \ general-purpose SEE code
5041: [ ASSEMBLER [IF] ]
5042: ... \ assembler-specific SEE code
5043: [ [ENDIF] ]
5044: ;
5045: @end example
1.1 anton 5046:
1.26 crook 5047: doc-[IF]
5048: doc-[ELSE]
5049: doc-[THEN]
5050: doc-[ENDIF]
1.1 anton 5051:
1.26 crook 5052: doc-[IFDEF]
5053: doc-[IFUNDEF]
1.1 anton 5054:
1.26 crook 5055: doc-[?DO]
5056: doc-[DO]
5057: doc-[FOR]
5058: doc-[LOOP]
5059: doc-[+LOOP]
5060: doc-[NEXT]
1.1 anton 5061:
1.26 crook 5062: doc-[BEGIN]
5063: doc-[UNTIL]
5064: doc-[AGAIN]
5065: doc-[WHILE]
5066: doc-[REPEAT]
1.1 anton 5067:
1.27 crook 5068:
5069:
1.26 crook 5070: @c -------------------------------------------------------------
5071: @node Tokens for Words, Word Lists, The Text Interpreter, Words
5072: @section Tokens for Words
5073: @cindex tokens for words
1.1 anton 5074:
1.28 crook 5075: This section describes the creation and use of tokens that represent
1.29 crook 5076: words.
5077:
1.32 anton 5078: Named words have information stored in their header space entries to
1.29 crook 5079: indicate any non-default semantics (@pxref{Interpretation and
5080: Compilation Semantics}). The semantics can be modified, using
5081: @code{immediate} and/or @code{compile-only}, at the time that the words
1.32 anton 5082: are defined. Unnamed words have (by definition) no header space
1.29 crook 5083: entry, and therefore must have default semantics.
1.21 crook 5084:
1.26 crook 5085: Named words have interpretation and compilation semantics. Unnamed words
5086: just have execution semantics.
1.21 crook 5087:
1.29 crook 5088: @cindex xt
5089: @cindex execution token
5090: The execution semantics of an unnamed word are represented by an
5091: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
5092: the execution token of the last word defined can be produced with
5093: @code{lastxt}.
5094:
5095: The interpretation semantics of a named word are also represented by an
5096: execution token. You can produce the execution token using @code{'} or
5097: @code{[']}. A simple example shows the difference between the two:
1.21 crook 5098:
1.29 crook 5099: @example
5100: : greet ( -- ) ." Hello" ;
5101: : foo ( -- xt ) ['] greet ; \ ['] parses greet at compile-time
5102: : bar ( -- ) ' EXECUTE ; \ ' parses at run-time
1.1 anton 5103:
1.29 crook 5104: \ the next four lines all do the same thing
5105: foo EXECUTE
5106: greet
5107: ' greet EXECUTE
5108: boo greet
5109: @end example
1.1 anton 5110:
1.29 crook 5111: An execution token occupies one cell.
1.26 crook 5112: @cindex code field address
5113: @cindex CFA
1.29 crook 5114: In Gforth, the abstract data type @i{execution token} is implemented
1.26 crook 5115: as a code field address (CFA).
5116: @comment TODO note that the standard does not say what it represents..
5117: @comment and you cannot necessarily compile it in all Forths (eg native
5118: @comment compilers?).
1.1 anton 5119:
1.29 crook 5120: For literals, use @code{'} in interpreted code and @code{[']} in
5121: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
5122: unusually by complaining about compile-only words. To get the execution
5123: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
5124: or @code{[COMP'] @i{name} DROP}.
1.1 anton 5125:
1.26 crook 5126: @cindex compilation token
1.29 crook 5127: The compilation semantics of a named word are represented by a
5128: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
5129: @i{xt} is an execution token. The compilation semantics represented by
5130: the compilation token can be performed with @code{execute}, which
5131: consumes the whole compilation token, with an additional stack effect
5132: determined by the represented compilation semantics.
5133:
5134: At present, the @i{w} part of a compilation token is an execution token,
5135: and the @i{xt} part represents either @code{execute} or
5136: @code{compile,}@footnote{Depending upon the compilation semantics of the
5137: word. If the word has default compilation semantics, the @i{xt} will
5138: represent @code{compile,}. If the word is @code{immediate}, the @i{xt}
5139: will represent @code{execute}.}. However, don't rely on that knowledge,
5140: unless necessary; future versions of Gforth may introduce unusual
5141: compilation tokens (e.g., a compilation token that represents the
5142: compilation semantics of a literal).
1.1 anton 5143:
1.26 crook 5144: You can compile the compilation semantics with @code{postpone,}. I.e.,
1.29 crook 5145: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
5146: @i{word}}.
1.21 crook 5147:
1.26 crook 5148: @cindex name token
5149: @cindex name field address
5150: @cindex NFA
1.29 crook 5151: Named words are also represented by the @dfn{name token}, (@i{nt}). In
5152: Gforth, the abstract data type @emph{name token} is implemented as a
5153: name field address (NFA).
5154:
5155: doc-execute
5156: doc-compile,
5157: doc-[']
5158: doc-'
5159: doc-[comp']
5160: doc-comp'
5161: doc-postpone,
1.1 anton 5162:
1.26 crook 5163: doc-find-name
5164: doc-name>int
5165: doc-name?int
5166: doc-name>comp
5167: doc-name>string
1.1 anton 5168:
1.26 crook 5169: @c -------------------------------------------------------------
5170: @node Word Lists, Environmental Queries, Tokens for Words, Words
5171: @section Word Lists
5172: @cindex word lists
1.32 anton 5173: @cindex header space
1.1 anton 5174:
1.26 crook 5175: @cindex wid
5176: All definitions other than those created by @code{:noname} have an entry
1.32 anton 5177: in the header space. The header space is fragmented into a number
1.29 crook 5178: of parts, called @dfn{word lists}. A word list is identified by a
5179: cell-sized word list identifier (@i{wid}) in much the same way as a
1.26 crook 5180: file is identified by a file handle. The numerical value of the wid has
5181: no (portable) meaning, and might change from session to session.
1.1 anton 5182:
1.26 crook 5183: @cindex compilation word list
5184: At any one time, a single word list is defined as the word list to which
1.29 crook 5185: all new definitions will be added -- this is called the @dfn{compilation
1.26 crook 5186: word list}. When Gforth is started, the compilation word list is the
5187: word list called @code{FORTH-WORDLIST}.
1.1 anton 5188:
1.26 crook 5189: @cindex search order stack
1.29 crook 5190: Forth maintains a stack of word lists, representing the @dfn{search
1.32 anton 5191: order}. When the header space is searched (for example, when
1.26 crook 5192: attempting to find a word's execution token during compilation), only
5193: those word lists that are currently in the search order are
5194: searched. The most recently-defined word in the word list at the top of
5195: the word list stack is searched first, and the search proceeds until
5196: either the word is located or the oldest definition in the word list at
5197: the bottom of the stack is reached. Definitions of the word may exist in
5198: more than one word lists; the search order determines which version will
5199: be found.
1.1 anton 5200:
1.29 crook 5201: The ANS Forth ``Search order'' word set is intended to provide a set of
5202: low-level tools that allow various different schemes to be
1.26 crook 5203: implemented. Gforth provides @code{vocabulary}, a traditional Forth
5204: word. @file{compat/vocabulary.fs} provides an implementation in ANS
5205: Standard Forth.
1.1 anton 5206:
1.27 crook 5207: @comment TODO: locals section refers to here, saying that every word list (aka
5208: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.1 anton 5209:
1.27 crook 5210: @comment the thisone- prefix is used to pick out the true definition of a
5211: @comment word from the source files, rather than some alias.
1.26 crook 5212: doc-forth-wordlist
5213: doc-definitions
5214: doc-get-current
5215: doc-set-current
5216: doc-get-order
1.27 crook 5217: doc---thisone-set-order
1.26 crook 5218: doc-wordlist
1.30 anton 5219: doc-table
1.26 crook 5220: doc-also
1.27 crook 5221: doc---thisone-forth
1.26 crook 5222: doc-only
1.27 crook 5223: doc---thisone-order
1.26 crook 5224: doc-previous
1.15 anton 5225:
1.26 crook 5226: doc-find
5227: doc-search-wordlist
1.15 anton 5228:
1.26 crook 5229: doc-words
5230: doc-vlist
1.1 anton 5231:
1.26 crook 5232: doc-mappedwordlist
5233: doc-root
5234: doc-vocabulary
5235: doc-seal
5236: doc-vocs
5237: doc-current
5238: doc-context
1.1 anton 5239:
1.26 crook 5240: @menu
5241: * Why use word lists?::
5242: * Word list examples::
5243: @end menu
5244:
5245: @node Why use word lists?, Word list examples, Word Lists, Word Lists
5246: @subsection Why use word lists?
5247: @cindex word lists - why use them?
5248:
1.29 crook 5249: Here are some reasons for using multiple word lists:
1.26 crook 5250:
5251: @itemize @bullet
5252: @item
1.32 anton 5253: To improve compilation speed by reducing the number of header space
1.26 crook 5254: entries that must be searched. This is achieved by creating a new
5255: word list that contains all of the definitions that are used in the
5256: definition of a Forth system but which would not usually be used by
5257: programs running on that system. That word list would be on the search
5258: list when the Forth system was compiled but would be removed from the
5259: search list for normal operation. This can be a useful technique for
5260: low-performance systems (for example, 8-bit processors in embedded
5261: systems) but is unlikely to be necessary in high-performance desktop
5262: systems.
5263: @item
5264: To prevent a set of words from being used outside the context in which
5265: they are valid. Two classic examples of this are an integrated editor
5266: (all of the edit commands are defined in a separate word list; the
5267: search order is set to the editor word list when the editor is invoked;
5268: the old search order is restored when the editor is terminated) and an
5269: integrated assembler (the op-codes for the machine are defined in a
5270: separate word list which is used when a @code{CODE} word is defined).
5271: @item
5272: To prevent a name-space clash between multiple definitions with the same
5273: name. For example, when building a cross-compiler you might have a word
5274: @code{IF} that generates conditional code for your target system. By
5275: placing this definition in a different word list you can control whether
5276: the host system's @code{IF} or the target system's @code{IF} get used in
5277: any particular context by controlling the order of the word lists on the
5278: search order stack.
5279: @end itemize
1.1 anton 5280:
1.26 crook 5281: @node Word list examples, ,Why use word lists?, Word Lists
5282: @subsection Word list examples
5283: @cindex word lists - examples
1.1 anton 5284:
1.26 crook 5285: Here is an example of creating and using a new wordlist using ANS
5286: Forth Standard words:
1.1 anton 5287:
5288: @example
1.26 crook 5289: wordlist constant my-new-words-wordlist
5290: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
1.21 crook 5291:
1.26 crook 5292: \ add it to the search order
5293: also my-new-words
1.21 crook 5294:
1.26 crook 5295: \ alternatively, add it to the search order and make it
5296: \ the compilation word list
5297: also my-new-words definitions
5298: \ type "order" to see the problem
1.21 crook 5299: @end example
5300:
1.26 crook 5301: The problem with this example is that @code{order} has no way to
5302: associate the name @code{my-new-words} with the wid of the word list (in
5303: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
5304: that has no associated name). There is no Standard way of associating a
5305: name with a wid.
5306:
5307: In Gforth, this example can be re-coded using @code{vocabulary}, which
5308: associates a name with a wid:
1.21 crook 5309:
1.26 crook 5310: @example
5311: vocabulary my-new-words
1.21 crook 5312:
1.26 crook 5313: \ add it to the search order
5314: my-new-words
1.21 crook 5315:
1.26 crook 5316: \ alternatively, add it to the search order and make it
5317: \ the compilation word list
5318: my-new-words definitions
5319: \ type "order" to see that the problem is solved
5320: @end example
1.23 crook 5321:
1.26 crook 5322: @c -------------------------------------------------------------
5323: @node Environmental Queries, Files, Word Lists, Words
5324: @section Environmental Queries
5325: @cindex environmental queries
1.21 crook 5326:
1.26 crook 5327: ANS Forth introduced the idea of ``environmental queries'' as a way
5328: for a program running on a system to determine certain characteristics of the system.
5329: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 5330:
1.32 anton 5331: The Standard requires that the header space used for environmental queries
5332: be distinct from the header space used for definitions.
1.21 crook 5333:
1.26 crook 5334: Typically, environmental queries are supported by creating a set of
1.29 crook 5335: definitions in a word list that is @i{only} used during environmental
1.26 crook 5336: queries; that is what Gforth does. There is no Standard way of adding
5337: definitions to the set of recognised environmental queries, but any
5338: implementation that supports the loading of optional word sets must have
5339: some mechanism for doing this (after loading the word set, the
5340: associated environmental query string must return @code{true}). In
5341: Gforth, the word list used to honour environmental queries can be
5342: manipulated just like any other word list.
1.21 crook 5343:
1.26 crook 5344: doc-environment?
5345: doc-environment-wordlist
1.21 crook 5346:
1.26 crook 5347: doc-gforth
5348: doc-os-class
1.21 crook 5349:
1.26 crook 5350: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
5351: returning two items on the stack, querying it using @code{environment?}
5352: will return an additional item; the @code{true} flag that shows that the
5353: string was recognised.
1.21 crook 5354:
1.26 crook 5355: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 5356:
1.26 crook 5357: Here are some examples of using environmental queries:
1.21 crook 5358:
1.26 crook 5359: @example
5360: s" address-unit-bits" environment? 0=
5361: [IF]
5362: cr .( environmental attribute address-units-bits unknown... ) cr
5363: [THEN]
1.21 crook 5364:
1.26 crook 5365: s" block" environment? [IF] DROP include block.fs [THEN]
1.21 crook 5366:
1.26 crook 5367: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
1.21 crook 5368:
1.26 crook 5369: s" gforth" environment? [IF] .( Gforth version ) TYPE
5370: [ELSE] .( Not Gforth..) [THEN]
5371: @end example
1.21 crook 5372:
5373:
1.26 crook 5374: Here is an example of adding a definition to the environment word list:
1.21 crook 5375:
1.26 crook 5376: @example
5377: get-current environment-wordlist set-current
5378: true constant block
5379: true constant block-ext
5380: set-current
5381: @end example
1.21 crook 5382:
1.26 crook 5383: You can see what definitions are in the environment word list like this:
1.21 crook 5384:
1.26 crook 5385: @example
5386: get-order 1+ environment-wordlist swap set-order words previous
5387: @end example
1.21 crook 5388:
5389:
1.26 crook 5390: @c -------------------------------------------------------------
5391: @node Files, Blocks, Environmental Queries, Words
5392: @section Files
1.28 crook 5393: @cindex files
5394: @cindex I/O - file-handling
1.21 crook 5395:
1.26 crook 5396: Gforth provides facilities for accessing files that are stored in the
5397: host operating system's file-system. Files that are processed by Gforth
5398: can be divided into two categories:
1.21 crook 5399:
1.23 crook 5400: @itemize @bullet
5401: @item
1.29 crook 5402: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 5403: @item
1.29 crook 5404: Files that are processed by some other program (@dfn{general files}).
1.26 crook 5405: @end itemize
5406:
5407: @menu
5408: * Forth source files::
5409: * General files::
5410: * Search Paths::
5411: * Forth Search Paths::
5412: * General Search Paths::
5413: @end menu
5414:
1.21 crook 5415:
1.26 crook 5416: @c -------------------------------------------------------------
5417: @node Forth source files, General files, Files, Files
5418: @subsection Forth source files
5419: @cindex including files
5420: @cindex Forth source files
1.21 crook 5421:
1.26 crook 5422: The simplest way to interpret the contents of a file is to use one of
5423: these two formats:
1.21 crook 5424:
1.26 crook 5425: @example
5426: include mysource.fs
5427: s" mysource.fs" included
5428: @end example
1.21 crook 5429:
1.26 crook 5430: Sometimes you want to include a file only if it is not included already
5431: (by, say, another source file). In that case, you can use one of these
5432: fomats:
1.21 crook 5433:
1.26 crook 5434: @example
5435: require mysource.fs
5436: needs mysource.fs
5437: s" mysource.fs" required
5438: @end example
1.21 crook 5439:
1.26 crook 5440: @cindex stack effect of included files
5441: @cindex including files, stack effect
5442: I recommend that you write your source files such that interpreting them
5443: does not change the stack. This allows using these files with
5444: @code{required} and friends without complications. For example:
1.21 crook 5445:
1.26 crook 5446: @example
5447: 1 require foo.fs drop
5448: @end example
1.21 crook 5449:
1.26 crook 5450: doc-include-file
5451: doc-included
1.28 crook 5452: doc-included?
1.26 crook 5453: doc-include
5454: doc-required
5455: doc-require
5456: doc-needs
1.28 crook 5457: doc-init-included-files
1.21 crook 5458:
1.26 crook 5459: A definition in ANS Forth for @code{required} is provided in
5460: @file{compat/required.fs}.
1.21 crook 5461:
1.26 crook 5462: @c -------------------------------------------------------------
5463: @node General files, Search Paths, Forth source files, Files
5464: @subsection General files
5465: @cindex general files
5466: @cindex file-handling
1.21 crook 5467:
1.26 crook 5468: Files are opened/created by name and type. The following types are
5469: recognised:
1.1 anton 5470:
1.26 crook 5471: doc-r/o
5472: doc-r/w
5473: doc-w/o
5474: doc-bin
1.1 anton 5475:
1.26 crook 5476: When a file is opened/created, it returns a file identifier,
1.29 crook 5477: @i{wfileid} that is used for all other file commands. All file
5478: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 5479: successful operation and an implementation-defined non-zero value in the
5480: case of an error.
1.21 crook 5481:
1.26 crook 5482: doc-open-file
5483: doc-create-file
1.21 crook 5484:
1.26 crook 5485: doc-close-file
5486: doc-delete-file
5487: doc-rename-file
5488: doc-read-file
5489: doc-read-line
5490: doc-write-file
5491: doc-write-line
5492: doc-emit-file
5493: doc-flush-file
1.21 crook 5494:
1.26 crook 5495: doc-file-status
5496: doc-file-position
5497: doc-reposition-file
5498: doc-file-size
5499: doc-resize-file
1.21 crook 5500:
1.26 crook 5501: @c ---------------------------------------------------------
5502: @node Search Paths, Forth Search Paths, General files, Files
5503: @subsection Search Paths
5504: @cindex path for @code{included}
5505: @cindex file search path
5506: @cindex @code{include} search path
5507: @cindex search path for files
1.21 crook 5508:
1.26 crook 5509: If you specify an absolute filename (i.e., a filename starting with
5510: @file{/} or @file{~}, or with @file{:} in the second position (as in
5511: @samp{C:...})) for @code{included} and friends, that file is included
5512: just as you would expect.
1.21 crook 5513:
1.26 crook 5514: For relative filenames, Gforth uses a search path similar to Forth's
5515: search order (@pxref{Word Lists}). It tries to find the given filename
5516: in the directories present in the path, and includes the first one it
5517: finds. There are separate search paths for Forth source files and
5518: general files.
1.21 crook 5519:
1.26 crook 5520: If the search path contains the directory @file{.} (as it should), this
5521: refers to the directory that the present file was @code{included}
5522: from. This allows files to include other files relative to their own
5523: position (irrespective of the current working directory or the absolute
5524: position). This feature is essential for libraries consisting of
5525: several files, where a file may include other files from the library.
5526: It corresponds to @code{#include "..."} in C. If the current input
5527: source is not a file, @file{.} refers to the directory of the innermost
5528: file being included, or, if there is no file being included, to the
5529: current working directory.
1.21 crook 5530:
1.26 crook 5531: Use @file{~+} to refer to the current working directory (as in the
5532: @code{bash}).
1.1 anton 5533:
1.26 crook 5534: If the filename starts with @file{./}, the search path is not searched
5535: (just as with absolute filenames), and the @file{.} has the same meaning
5536: as described above.
1.1 anton 5537:
1.26 crook 5538: @c ---------------------------------------------------------
5539: @node Forth Search Paths, General Search Paths, Search Paths, Files
5540: @subsubsection Forth Search Paths
1.28 crook 5541: @cindex search path control - Forth
1.5 anton 5542:
1.26 crook 5543: The search path is initialized when you start Gforth (@pxref{Invoking
5544: Gforth}). You can display it and change it using these words:
1.5 anton 5545:
1.26 crook 5546: doc-.fpath
5547: doc-fpath+
5548: doc-fpath=
5549: doc-open-fpath-file
1.5 anton 5550:
1.26 crook 5551: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 5552:
1.26 crook 5553: @example
5554: fpath= /usr/lib/forth/|./
5555: require timer.fs
5556: @end example
1.5 anton 5557:
1.26 crook 5558: @c ---------------------------------------------------------
5559: @node General Search Paths, , Forth Search Paths, Files
5560: @subsubsection General Search Paths
5561: @cindex search path control - for user applications
1.5 anton 5562:
1.26 crook 5563: Your application may need to search files in several directories, like
5564: @code{included} does. To facilitate this, Gforth allows you to define
5565: and use your own search paths, by providing generic equivalents of the
5566: Forth search path words:
1.5 anton 5567:
1.26 crook 5568: doc-.path
5569: doc-path+
5570: doc-path=
5571: doc-open-path-file
1.5 anton 5572:
1.26 crook 5573: Here's an example of creating a search path:
1.5 anton 5574:
1.26 crook 5575: @example
5576: \ Make a buffer for the path:
5577: create mypath 100 chars , \ maximum length (is checked)
5578: 0 , \ real len
5579: 100 chars allot \ space for path
5580: @end example
1.5 anton 5581:
1.26 crook 5582: @c -------------------------------------------------------------
5583: @node Blocks, Other I/O, Files, Words
5584: @section Blocks
1.28 crook 5585: @cindex I/O - blocks
5586: @cindex blocks
5587:
5588: When you run Gforth on a modern desk-top computer, it runs under the
5589: control of an operating system which provides certain services. One of
5590: these services is @var{file services}, which allows Forth source code
5591: and data to be stored in files and read into Gforth (@pxref{Files}).
5592:
5593: Traditionally, Forth has been an important programming language on
5594: systems where it has interfaced directly to the underlying hardware with
5595: no intervening operating system. Forth provides a mechanism, called
1.29 crook 5596: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 5597:
5598: A block is a 1024-byte data area, which can be used to hold data or
5599: Forth source code. No structure is imposed on the contents of the
5600: block. A block is identified by its number; blocks are numbered
5601: contiguously from 1 to an implementation-defined maximum.
5602:
5603: A typical system that used blocks but no operating system might use a
5604: single floppy-disk drive for mass storage, with the disks formatted to
5605: provide 256-byte sectors. Blocks would be implemented by assigning the
5606: first four sectors of the disk to block 1, the second four sectors to
5607: block 2 and so on, up to the limit of the capacity of the disk. The disk
5608: would not contain any file system information, just the set of blocks.
5609:
1.29 crook 5610: @cindex blocks file
1.28 crook 5611: On systems that do provide file services, blocks are typically
1.29 crook 5612: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 5613: file}. The size of the blocks file will be an exact multiple of 1024
5614: bytes, corresponding to the number of blocks it contains. This is the
5615: mechanism that Gforth uses.
5616:
1.29 crook 5617: @cindex @file{blocks.fb}
1.28 crook 5618: Only 1 blocks file can be open at a time. If you use block words without
5619: having specified a blocks file, Gforth defaults to the blocks file
5620: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
5621: locate a blocks file (@pxref{Forth Search Paths}).
5622:
1.29 crook 5623: @cindex block buffers
1.28 crook 5624: When you read and write blocks under program control, Gforth uses a
1.29 crook 5625: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 5626: not used when you use @code{load} to interpret the contents of a block.
5627:
5628: The behaviour of the block buffers is directly analagous to that of a
5629: cache. Each block buffer has three states:
5630:
5631: @itemize @bullet
5632: @item
5633: Unassigned
5634: @item
5635: Assigned-clean
5636: @item
5637: Assigned-dirty
5638: @end itemize
5639:
1.29 crook 5640: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 5641: block, the block (specified by its block number) must be assigned to a
5642: block buffer.
5643:
5644: The assignment of a block to a block buffer is performed by @code{block}
5645: or @code{buffer}. Use @code{block} when you wish to modify the existing
5646: contents of a block. Use @code{buffer} when you don't care about the
5647: existing contents of the block@footnote{The ANS Forth definition of
5648: @code{block} is intended not to cause disk I/O; if the data associated
5649: with the particular block is already stored in a block buffer due to an
5650: earlier @code{block} command, @code{buffer} will return that block
5651: buffer and the existing contents of the block will be
5652: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 5653: block buffer for the block.}.
1.28 crook 5654:
5655: Once a block has been assigned to a block buffer, the block buffer state
1.29 crook 5656: becomes @i{assigned-clean}. Data can now be manipulated within the
1.28 crook 5657: block buffer.
5658:
5659: When the contents of a block buffer is changed it is necessary,
5660: @i{before calling} @code{block} @i{or} @code{buffer} @i{again}, to
5661: either abandon the changes (by doing nothing) or commit the changes,
5662: using @code{update}. Using @code{update} does not change the blocks
1.29 crook 5663: file; it simply changes a block buffer's state to @i{assigned-dirty}.
1.28 crook 5664:
1.29 crook 5665: The word @code{flush} causes all @i{assigned-dirty} blocks to be
1.28 crook 5666: written back to the blocks file on disk. Leaving Gforth using @code{bye}
5667: also causes a @code{flush} to be performed.
5668:
1.29 crook 5669: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 5670: algorithm to assign a block buffer to a block. That means that any
5671: particular block can only be assigned to one specific block buffer,
1.29 crook 5672: called (for the particular operation) the @i{victim buffer}. If the
5673: victim buffer is @i{unassigned} or @i{assigned-clean} it can be
5674: allocated to the new block immediately. If it is @i{assigned-dirty}
1.28 crook 5675: its current contents must be written out to disk before it can be
5676: allocated to the new block.
5677:
5678: Although no structure is imposed on the contents of a block, it is
5679: traditional to display the contents as 16 lines each of 64 characters. A
5680: block provides a single, continuous stream of input (for example, it
5681: acts as a single parse area) -- there are no end-of-line characters
5682: within a block, and no end-of-file character at the end of a
5683: block. There are two consequences of this:
1.26 crook 5684:
1.28 crook 5685: @itemize @bullet
5686: @item
5687: The last character of one line wraps straight into the first character
5688: of the following line
5689: @item
5690: The word @code{\} -- comment to end of line -- requires special
5691: treatment; in the context of a block it causes all characters until the
5692: end of the current 64-character ``line'' to be ignored.
5693: @end itemize
5694:
5695: In Gforth, when you use @code{block} with a non-existent block number,
5696: the current block file will be extended to the appropriate size and the
5697: block buffer will be initialised with spaces.
5698:
1.29 crook 5699: Gforth doesn't encourage the use of blocks; the mechanism is only
5700: provided for backward compatibility -- ANS Forth requires blocks to be
5701: available when files are.
1.28 crook 5702:
5703: Common techniques that are used when working with blocks include:
5704:
5705: @itemize @bullet
5706: @item
5707: A screen editor that allows you to edit blocks without leaving the Forth
5708: environment.
5709: @item
5710: Shadow screens; where every code block has an associated block
5711: containing comments (for example: code in odd block numbers, comments in
5712: even block numbers). Typically, the block editor provides a convenient
5713: mechanism to toggle between code and comments.
5714: @item
5715: Load blocks; a single block (typically block 1) contains a number of
5716: @code{thru} commands which @code{load} the whole of the application.
5717: @item
5718: Chaining blocks; a block terminates with a @code{-->} so that a whole
5719: application can be @code{load}ed by @code{load}ing a single block.
5720: @end itemize
1.26 crook 5721:
1.29 crook 5722: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
5723: integrated into a Forth programming environment.
1.26 crook 5724:
5725: @comment TODO what about errors on open-blocks?
5726: doc-open-blocks
5727: doc-use
5728: doc-get-block-fid
5729: doc-block-position
1.28 crook 5730:
5731: doc-scr
5732: doc-list
5733:
5734: doc---block-block
5735: doc-buffer
5736:
1.26 crook 5737: doc-update
1.28 crook 5738: doc-updated?
1.26 crook 5739: doc-save-buffers
5740: doc-empty-buffers
5741: doc-empty-buffer
5742: doc-flush
1.28 crook 5743:
1.26 crook 5744: doc-load
5745: doc-thru
5746: doc-+load
5747: doc-+thru
5748: doc---block--->
5749: doc-block-included
5750:
5751: @c -------------------------------------------------------------
5752: @node Other I/O, Programming Tools, Blocks, Words
5753: @section Other I/O
1.28 crook 5754: @cindex I/O - keyboard and display
1.26 crook 5755:
5756: @menu
5757: * Simple numeric output:: Predefined formats
5758: * Formatted numeric output:: Formatted (pictured) output
5759: * String Formats:: How Forth stores strings in memory
5760: * Displaying characters and strings:: Other stuff
5761: * Input:: Input
5762: @end menu
5763:
5764: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
5765: @subsection Simple numeric output
1.28 crook 5766: @cindex numeric output - simple/free-format
1.5 anton 5767:
1.26 crook 5768: The simplest output functions are those that display numbers from the
5769: data or floating-point stacks. Floating-point output is always displayed
5770: using base 10. Numbers displayed from the data stack use the value stored
5771: in @code{base}.
1.5 anton 5772:
1.26 crook 5773: doc-.
5774: doc-dec.
5775: doc-hex.
5776: doc-u.
5777: doc-.r
5778: doc-u.r
5779: doc-d.
5780: doc-ud.
5781: doc-d.r
5782: doc-ud.r
5783: doc-f.
5784: doc-fe.
5785: doc-fs.
1.5 anton 5786:
1.26 crook 5787: Examples of printing the number 1234.5678E23 in the different floating-point output
5788: formats are shown below:
1.5 anton 5789:
5790: @example
1.26 crook 5791: f. 123456779999999000000000000.
5792: fe. 123.456779999999E24
5793: fs. 1.23456779999999E26
1.5 anton 5794: @end example
5795:
5796:
1.26 crook 5797: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
5798: @subsection Formatted numeric output
1.28 crook 5799: @cindex formatted numeric output
1.26 crook 5800: @cindex pictured numeric output
1.28 crook 5801: @cindex numeric output - formatted
1.26 crook 5802:
1.29 crook 5803: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 5804: output} for formatted printing of integers. In this technique, digits
5805: are extracted from the number (using the current output radix defined by
5806: @code{base}), converted to ASCII codes and appended to a string that is
5807: built in a scratch-pad area of memory (@pxref{core-idef,
5808: Implementation-defined options, Implementation-defined
5809: options}). Arbitrary characters can be appended to the string during the
5810: extraction process. The completed string is specified by an address
5811: and length and can be manipulated (@code{TYPE}ed, copied, modified)
5812: under program control.
1.5 anton 5813:
1.26 crook 5814: All of the words described in the previous section for simple numeric
5815: output are implemented in Gforth using pictured numeric output.
1.5 anton 5816:
1.26 crook 5817: Three important things to remember about Pictured Numeric Output:
1.5 anton 5818:
1.26 crook 5819: @itemize @bullet
5820: @item
1.28 crook 5821: It always operates on double-precision numbers; to display a
5822: single-precision number, convert it first (@pxref{Double precision} for
5823: ways of doing this).
1.26 crook 5824: @item
1.28 crook 5825: It always treats the double-precision number as though it were
5826: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 5827: @item
5828: The string is built up from right to left; least significant digit first.
5829: @end itemize
1.5 anton 5830:
1.26 crook 5831: doc-<#
5832: doc-#
5833: doc-#s
5834: doc-hold
5835: doc-sign
5836: doc-#>
1.5 anton 5837:
1.26 crook 5838: doc-represent
1.5 anton 5839:
1.26 crook 5840: Here are some examples of using pictured numeric output:
1.5 anton 5841:
5842: @example
1.26 crook 5843: : my-u. ( u -- )
5844: \ Simplest use of pns.. behaves like Standard u.
5845: 0 \ convert to unsigned double
5846: <# \ start conversion
5847: #s \ convert all digits
5848: #> \ complete conversion
5849: TYPE SPACE ; \ display, with trailing space
1.5 anton 5850:
1.26 crook 5851: : cents-only ( u -- )
5852: 0 \ convert to unsigned double
5853: <# \ start conversion
5854: # # \ convert two least-significant digits
5855: #> \ complete conversion, discard other digits
5856: TYPE SPACE ; \ display, with trailing space
1.5 anton 5857:
1.26 crook 5858: : dollars-and-cents ( u -- )
5859: 0 \ convert to unsigned double
5860: <# \ start conversion
5861: # # \ convert two least-significant digits
5862: [char] . hold \ insert decimal point
5863: #s \ convert remaining digits
5864: [char] $ hold \ append currency symbol
5865: #> \ complete conversion
5866: TYPE SPACE ; \ display, with trailing space
1.5 anton 5867:
1.26 crook 5868: : my-. ( n -- )
5869: \ handling negatives.. behaves like Standard .
5870: s>d \ convert to signed double
5871: swap over dabs \ leave sign byte followed by unsigned double
5872: <# \ start conversion
5873: #s \ convert all digits
5874: rot sign \ get at sign byte, append "-" if needed
5875: #> \ complete conversion
5876: TYPE SPACE ; \ display, with trailing space
1.5 anton 5877:
1.26 crook 5878: : account. ( n -- )
5879: \ accountants don't like minus signs, they use braces
5880: \ for negative numbers
5881: s>d \ convert to signed double
5882: swap over dabs \ leave sign byte followed by unsigned double
5883: <# \ start conversion
5884: 2 pick \ get copy of sign byte
5885: 0< IF [char] ) hold THEN \ right-most character of output
5886: #s \ convert all digits
5887: rot \ get at sign byte
5888: 0< IF [char] ( hold THEN
5889: #> \ complete conversion
5890: TYPE SPACE ; \ display, with trailing space
1.5 anton 5891: @end example
5892:
1.26 crook 5893: Here are some examples of using these words:
1.5 anton 5894:
5895: @example
1.26 crook 5896: 1 my-u. 1
5897: hex -1 my-u. decimal FFFFFFFF
5898: 1 cents-only 01
5899: 1234 cents-only 34
5900: 2 dollars-and-cents $0.02
5901: 1234 dollars-and-cents $12.34
5902: 123 my-. 123
5903: -123 my. -123
5904: 123 account. 123
5905: -456 account. (456)
1.5 anton 5906: @end example
5907:
5908:
1.26 crook 5909: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
5910: @subsection String Formats
1.27 crook 5911: @cindex strings - see character strings
5912: @cindex character strings - formats
1.28 crook 5913: @cindex I/O - see character strings
1.26 crook 5914:
1.27 crook 5915: Forth commonly uses two different methods for representing character
5916: strings:
1.26 crook 5917:
5918: @itemize @bullet
5919: @item
5920: @cindex address of counted string
1.29 crook 5921: As a @dfn{counted string}, represented by a @i{c-addr}. The char
5922: addressed by @i{c-addr} contains a character-count, @i{n}, of the
5923: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 5924: memory.
5925: @item
1.29 crook 5926: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
5927: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 5928: first byte of the string.
5929: @end itemize
5930:
5931: ANS Forth encourages the use of the second format when representing
5932: strings on the stack, whilst conceeding that the counted string format
5933: remains useful as a way of storing strings in memory.
5934:
5935: doc-count
5936:
5937: @xref{Memory Blocks} for words that move, copy and search
5938: for strings. @xref{Displaying characters and strings,} for words that
5939: display characters and strings.
5940:
5941:
5942: @node Displaying characters and strings, Input, String Formats, Other I/O
5943: @subsection Displaying characters and strings
1.27 crook 5944: @cindex characters - compiling and displaying
5945: @cindex character strings - compiling and displaying
1.26 crook 5946:
5947: This section starts with a glossary of Forth words and ends with a set
5948: of examples.
5949:
5950: doc-bl
5951: doc-space
5952: doc-spaces
5953: doc-emit
5954: doc-toupper
5955: doc-."
5956: doc-.(
5957: doc-type
5958: doc-cr
1.27 crook 5959: @cindex cursor control
1.26 crook 5960: doc-at-xy
5961: doc-page
5962: doc-s"
5963: doc-c"
5964: doc-char
5965: doc-[char]
5966: doc-sliteral
5967:
5968: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 5969:
5970: @example
1.26 crook 5971: .( text-1)
5972: : my-word
5973: ." text-2" cr
5974: .( text-3)
5975: ;
5976:
5977: ." text-4"
5978:
5979: : my-char
5980: [char] ALPHABET emit
5981: char emit
5982: ;
1.5 anton 5983: @end example
5984:
1.26 crook 5985: When you load this code into Gforth, the following output is generated:
1.5 anton 5986:
1.26 crook 5987: @example
1.30 anton 5988: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 5989: @end example
1.5 anton 5990:
1.26 crook 5991: @itemize @bullet
5992: @item
5993: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
5994: is an immediate word; it behaves in the same way whether it is used inside
5995: or outside a colon definition.
5996: @item
5997: Message @code{text-4} is displayed because of Gforth's added interpretation
5998: semantics for @code{."}.
5999: @item
1.29 crook 6000: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 6001: performs the compilation semantics for @code{."} within the definition of
6002: @code{my-word}.
6003: @end itemize
1.5 anton 6004:
1.26 crook 6005: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 6006:
1.26 crook 6007: @example
1.30 anton 6008: @kbd{my-word @key{RET}} text-2
1.26 crook 6009: ok
1.30 anton 6010: @kbd{my-char fred @key{RET}} Af ok
6011: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 6012: @end example
1.5 anton 6013:
6014: @itemize @bullet
6015: @item
1.26 crook 6016: Message @code{text-2} is displayed because of the run-time behaviour of
6017: @code{."}.
6018: @item
6019: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
6020: on the stack at run-time. @code{emit} always displays the character
6021: when @code{my-char} is executed.
6022: @item
6023: @code{char} parses a string at run-time and the second @code{emit} displays
6024: the first character of the string.
1.5 anton 6025: @item
1.26 crook 6026: If you type @code{see my-char} you can see that @code{[char]} discarded
6027: the text ``LPHABET'' and only compiled the display code for ``A'' into the
6028: definition of @code{my-char}.
1.5 anton 6029: @end itemize
6030:
6031:
6032:
1.26 crook 6033: @node Input, , Displaying characters and strings, Other I/O
6034: @subsection Input
6035: @cindex input
1.28 crook 6036: @cindex I/O - see input
6037: @cindex parsing a string
1.5 anton 6038:
1.27 crook 6039: @xref{String Formats} for ways of storing character strings in memory.
1.5 anton 6040:
1.27 crook 6041: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 6042: @comment then index them
1.27 crook 6043:
6044: doc-key
6045: doc-key?
1.26 crook 6046: doc->number
6047: doc->float
6048: doc-accept
1.27 crook 6049: doc-pad
6050: doc-parse
6051: doc-word
6052: doc-sword
6053: doc-refill
6054: @comment obsolescent words..
6055: doc-convert
1.26 crook 6056: doc-query
6057: doc-expect
1.27 crook 6058: doc-span
1.5 anton 6059:
6060:
6061: @c -------------------------------------------------------------
1.26 crook 6062: @node Programming Tools, Assembler and Code Words, Other I/O, Words
6063: @section Programming Tools
6064: @cindex programming tools
1.12 anton 6065:
6066: @menu
1.26 crook 6067: * Debugging:: Simple and quick.
6068: * Assertions:: Making your programs self-checking.
6069: * Singlestep Debugger:: Executing your program word by word.
1.5 anton 6070: @end menu
6071:
1.26 crook 6072: @node Debugging, Assertions, Programming Tools, Programming Tools
6073: @subsection Debugging
6074: @cindex debugging
1.5 anton 6075:
1.26 crook 6076: Languages with a slow edit/compile/link/test development loop tend to
6077: require sophisticated tracing/stepping debuggers to facilate
6078: productive debugging.
1.5 anton 6079:
1.26 crook 6080: A much better (faster) way in fast-compiling languages is to add
6081: printing code at well-selected places, let the program run, look at
6082: the output, see where things went wrong, add more printing code, etc.,
6083: until the bug is found.
1.5 anton 6084:
1.26 crook 6085: The simple debugging aids provided in @file{debugs.fs}
6086: are meant to support this style of debugging. In addition, there are
6087: words for non-destructively inspecting the stack and memory:
1.5 anton 6088:
1.26 crook 6089: doc-.s
6090: doc-f.s
1.5 anton 6091:
1.29 crook 6092: There is a word @code{.r} but it does @i{not} display the return
1.26 crook 6093: stack! It is used for formatted numeric output.
1.5 anton 6094:
1.26 crook 6095: doc-depth
6096: doc-fdepth
6097: doc-clearstack
6098: doc-?
6099: doc-dump
1.5 anton 6100:
1.26 crook 6101: The word @code{~~} prints debugging information (by default the source
6102: location and the stack contents). It is easy to insert. If you use Emacs
6103: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
6104: query-replace them with nothing). The deferred words
6105: @code{printdebugdata} and @code{printdebugline} control the output of
6106: @code{~~}. The default source location output format works well with
6107: Emacs' compilation mode, so you can step through the program at the
6108: source level using @kbd{C-x `} (the advantage over a stepping debugger
6109: is that you can step in any direction and you know where the crash has
6110: happened or where the strange data has occurred).
1.5 anton 6111:
1.26 crook 6112: The default actions of @code{~~} clobber the contents of the pictured
6113: numeric output string, so you should not use @code{~~}, e.g., between
6114: @code{<#} and @code{#>}.
1.5 anton 6115:
1.26 crook 6116: doc-~~
6117: doc-printdebugdata
6118: doc-printdebugline
1.5 anton 6119:
1.26 crook 6120: doc-see
6121: doc-marker
1.5 anton 6122:
1.26 crook 6123: Here's an example of using @code{marker} at the start of a source file
6124: that you are debugging; it ensures that you only ever have one copy of
6125: the file's definitions compiled at any time:
1.5 anton 6126:
1.26 crook 6127: @example
6128: [IFDEF] my-code
6129: my-code
6130: [ENDIF]
1.5 anton 6131:
1.26 crook 6132: marker my-code
1.28 crook 6133: init-included-files
1.5 anton 6134:
1.26 crook 6135: \ .. definitions start here
6136: \ .
6137: \ .
6138: \ end
6139: @end example
1.5 anton 6140:
6141:
6142:
1.26 crook 6143: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
6144: @subsection Assertions
6145: @cindex assertions
1.5 anton 6146:
1.26 crook 6147: It is a good idea to make your programs self-checking, especially if you
6148: make an assumption that may become invalid during maintenance (for
6149: example, that a certain field of a data structure is never zero). Gforth
1.29 crook 6150: supports @dfn{assertions} for this purpose. They are used like this:
1.23 crook 6151:
1.26 crook 6152: @example
1.29 crook 6153: assert( @i{flag} )
1.26 crook 6154: @end example
1.23 crook 6155:
1.26 crook 6156: The code between @code{assert(} and @code{)} should compute a flag, that
6157: should be true if everything is alright and false otherwise. It should
6158: not change anything else on the stack. The overall stack effect of the
6159: assertion is @code{( -- )}. E.g.
1.23 crook 6160:
1.26 crook 6161: @example
6162: assert( 1 1 + 2 = ) \ what we learn in school
6163: assert( dup 0<> ) \ assert that the top of stack is not zero
6164: assert( false ) \ this code should not be reached
6165: @end example
1.23 crook 6166:
1.26 crook 6167: The need for assertions is different at different times. During
6168: debugging, we want more checking, in production we sometimes care more
6169: for speed. Therefore, assertions can be turned off, i.e., the assertion
6170: becomes a comment. Depending on the importance of an assertion and the
6171: time it takes to check it, you may want to turn off some assertions and
6172: keep others turned on. Gforth provides several levels of assertions for
6173: this purpose:
1.23 crook 6174:
1.26 crook 6175: doc-assert0(
6176: doc-assert1(
6177: doc-assert2(
6178: doc-assert3(
6179: doc-assert(
6180: doc-)
1.23 crook 6181:
1.26 crook 6182: The variable @code{assert-level} specifies the highest assertions that
6183: are turned on. I.e., at the default @code{assert-level} of one,
6184: @code{assert0(} and @code{assert1(} assertions perform checking, while
6185: @code{assert2(} and @code{assert3(} assertions are treated as comments.
6186:
6187: The value of @code{assert-level} is evaluated at compile-time, not at
6188: run-time. Therefore you cannot turn assertions on or off at run-time;
6189: you have to set the @code{assert-level} appropriately before compiling a
6190: piece of code. You can compile different pieces of code at different
6191: @code{assert-level}s (e.g., a trusted library at level 1 and
6192: newly-written code at level 3).
1.23 crook 6193:
1.26 crook 6194: doc-assert-level
1.23 crook 6195:
1.26 crook 6196: If an assertion fails, a message compatible with Emacs' compilation mode
6197: is produced and the execution is aborted (currently with @code{ABORT"}.
6198: If there is interest, we will introduce a special throw code. But if you
6199: intend to @code{catch} a specific condition, using @code{throw} is
6200: probably more appropriate than an assertion).
1.23 crook 6201:
1.26 crook 6202: Definitions in ANS Forth for these assertion words are provided
6203: in @file{compat/assert.fs}.
1.23 crook 6204:
6205:
1.26 crook 6206: @node Singlestep Debugger, , Assertions, Programming Tools
6207: @subsection Singlestep Debugger
6208: @cindex singlestep Debugger
6209: @cindex debugging Singlestep
6210: @cindex @code{dbg}
6211: @cindex @code{BREAK:}
6212: @cindex @code{BREAK"}
1.23 crook 6213:
1.26 crook 6214: When you create a new word there's often the need to check whether it
6215: behaves correctly or not. You can do this by typing @code{dbg
6216: badword}. A debug session might look like this:
1.23 crook 6217:
1.26 crook 6218: @example
6219: : badword 0 DO i . LOOP ; ok
6220: 2 dbg badword
6221: : badword
6222: Scanning code...
1.23 crook 6223:
1.26 crook 6224: Nesting debugger ready!
1.23 crook 6225:
1.26 crook 6226: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
6227: 400D4740 8049F68 DO -> [ 0 ]
6228: 400D4744 804A0C8 i -> [ 1 ] 00000
6229: 400D4748 400C5E60 . -> 0 [ 0 ]
6230: 400D474C 8049D0C LOOP -> [ 0 ]
6231: 400D4744 804A0C8 i -> [ 1 ] 00001
6232: 400D4748 400C5E60 . -> 1 [ 0 ]
6233: 400D474C 8049D0C LOOP -> [ 0 ]
6234: 400D4758 804B384 ; -> ok
6235: @end example
1.23 crook 6236:
1.26 crook 6237: Each line displayed is one step. You always have to hit return to
6238: execute the next word that is displayed. If you don't want to execute
6239: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
6240: an overview what keys are available:
1.23 crook 6241:
1.26 crook 6242: @table @i
1.23 crook 6243:
1.30 anton 6244: @item @key{RET}
1.26 crook 6245: Next; Execute the next word.
1.23 crook 6246:
1.26 crook 6247: @item n
6248: Nest; Single step through next word.
1.5 anton 6249:
1.26 crook 6250: @item u
6251: Unnest; Stop debugging and execute rest of word. If we got to this word
6252: with nest, continue debugging with the calling word.
1.5 anton 6253:
1.26 crook 6254: @item d
6255: Done; Stop debugging and execute rest.
1.5 anton 6256:
1.26 crook 6257: @item s
6258: Stop; Abort immediately.
1.5 anton 6259:
1.26 crook 6260: @end table
1.5 anton 6261:
1.26 crook 6262: Debugging large application with this mechanism is very difficult, because
6263: you have to nest very deeply into the program before the interesting part
6264: begins. This takes a lot of time.
1.5 anton 6265:
1.26 crook 6266: To do it more directly put a @code{BREAK:} command into your source code.
6267: When program execution reaches @code{BREAK:} the single step debugger is
6268: invoked and you have all the features described above.
1.23 crook 6269:
1.26 crook 6270: If you have more than one part to debug it is useful to know where the
6271: program has stopped at the moment. You can do this by the
6272: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
6273: string is typed out when the ``breakpoint'' is reached.
6274:
6275: doc-dbg
6276: doc-BREAK:
6277: doc-BREAK"
6278:
6279:
6280: @c -------------------------------------------------------------
6281: @node Assembler and Code Words, Threading Words, Programming Tools, Words
6282: @section Assembler and Code Words
6283: @cindex assembler
6284: @cindex code words
1.5 anton 6285:
1.26 crook 6286: Gforth provides some words for defining primitives (words written in
1.29 crook 6287: machine code), and for defining the machine-code equivalent of
1.26 crook 6288: @code{DOES>}-based defining words. However, the machine-independent
6289: nature of Gforth poses a few problems: First of all, Gforth runs on
6290: several architectures, so it can provide no standard assembler. What's
6291: worse is that the register allocation not only depends on the processor,
6292: but also on the @code{gcc} version and options used.
1.5 anton 6293:
1.29 crook 6294: The words that Gforth offers encapsulate some system dependences (e.g.,
6295: the header structure), so a system-independent assembler may be used in
1.26 crook 6296: Gforth. If you do not have an assembler, you can compile machine code
1.29 crook 6297: directly with @code{,} and @code{c,}@footnote{This isn't portable,
6298: because these words emit stuff in @i{data} space; it works because
6299: Gforth has unified code/data spaces. Assembler isn't likely to be
6300: portable anyway.}.
1.5 anton 6301:
1.26 crook 6302: doc-assembler
6303: doc-code
6304: doc-end-code
6305: doc-;code
6306: doc-flush-icache
1.5 anton 6307:
1.26 crook 6308: If @code{flush-icache} does not work correctly, @code{code} words
6309: etc. will not work (reliably), either.
1.5 anton 6310:
1.29 crook 6311: The typical usage of these @code{code} words can be shown most easily by
6312: analogy to the equivalent high-level defining words:
6313:
6314: @example
6315: : foo code foo
6316: <high-level Forth words> <assembler>
6317: ; end-code
6318:
6319: : bar : bar
6320: <high-level Forth words> <high-level Forth words>
6321: CREATE CREATE
6322: <high-level Forth words> <high-level Forth words>
6323: DOES> ;code
6324: <high-level Forth words> <assembler>
6325: ; end-code
6326: @end example
6327:
1.26 crook 6328: @code{flush-icache} is always present. The other words are rarely used
6329: and reside in @code{code.fs}, which is usually not loaded. You can load
6330: it with @code{require code.fs}.
1.5 anton 6331:
1.26 crook 6332: @cindex registers of the inner interpreter
6333: In the assembly code you will want to refer to the inner interpreter's
6334: registers (e.g., the data stack pointer) and you may want to use other
6335: registers for temporary storage. Unfortunately, the register allocation
6336: is installation-dependent.
1.5 anton 6337:
1.26 crook 6338: The easiest solution is to use explicit register declarations
6339: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
6340: GNU C Manual}) for all of the inner interpreter's registers: You have to
6341: compile Gforth with @code{-DFORCE_REG} (configure option
6342: @code{--enable-force-reg}) and the appropriate declarations must be
6343: present in the @code{machine.h} file (see @code{mips.h} for an example;
6344: you can find a full list of all declarable register symbols with
6345: @code{grep register engine.c}). If you give explicit registers to all
6346: variables that are declared at the beginning of @code{engine()}, you
6347: should be able to use the other caller-saved registers for temporary
6348: storage. Alternatively, you can use the @code{gcc} option
6349: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
6350: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
6351: (however, this restriction on register allocation may slow Gforth
6352: significantly).
1.5 anton 6353:
1.26 crook 6354: If this solution is not viable (e.g., because @code{gcc} does not allow
6355: you to explicitly declare all the registers you need), you have to find
6356: out by looking at the code where the inner interpreter's registers
6357: reside and which registers can be used for temporary storage. You can
6358: get an assembly listing of the engine's code with @code{make engine.s}.
1.5 anton 6359:
1.26 crook 6360: In any case, it is good practice to abstract your assembly code from the
6361: actual register allocation. E.g., if the data stack pointer resides in
6362: register @code{$17}, create an alias for this register called @code{sp},
6363: and use that in your assembly code.
1.5 anton 6364:
1.26 crook 6365: @cindex code words, portable
6366: Another option for implementing normal and defining words efficiently
6367: is to add the desired functionality to the source of Gforth. For normal
6368: words you just have to edit @file{primitives} (@pxref{Automatic
6369: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
6370: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
6371: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5 anton 6372:
6373:
1.26 crook 6374: @c -------------------------------------------------------------
6375: @node Threading Words, Locals, Assembler and Code Words, Words
6376: @section Threading Words
6377: @cindex threading words
1.5 anton 6378:
1.26 crook 6379: @cindex code address
6380: These words provide access to code addresses and other threading stuff
6381: in Gforth (and, possibly, other interpretive Forths). It more or less
6382: abstracts away the differences between direct and indirect threading
6383: (and, for direct threading, the machine dependences). However, at
6384: present this wordset is still incomplete. It is also pretty low-level;
6385: some day it will hopefully be made unnecessary by an internals wordset
6386: that abstracts implementation details away completely.
1.5 anton 6387:
1.26 crook 6388: doc-threading-method
6389: doc->code-address
6390: doc->does-code
6391: doc-code-address!
6392: doc-does-code!
6393: doc-does-handler!
6394: doc-/does-handler
1.5 anton 6395:
1.26 crook 6396: The code addresses produced by various defining words are produced by
6397: the following words:
1.5 anton 6398:
1.26 crook 6399: doc-docol:
6400: doc-docon:
6401: doc-dovar:
6402: doc-douser:
6403: doc-dodefer:
6404: doc-dofield:
1.5 anton 6405:
1.26 crook 6406: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
6407: with @code{>does-code}. If the word was defined in that way, the value
6408: returned is non-zero and identifies the @code{DOES>} used by the
6409: defining word.
6410: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5 anton 6411:
1.26 crook 6412: @c -------------------------------------------------------------
6413: @node Locals, Structures, Threading Words, Words
6414: @section Locals
6415: @cindex locals
1.5 anton 6416:
1.26 crook 6417: Local variables can make Forth programming more enjoyable and Forth
6418: programs easier to read. Unfortunately, the locals of ANS Forth are
6419: laden with restrictions. Therefore, we provide not only the ANS Forth
6420: locals wordset, but also our own, more powerful locals wordset (we
6421: implemented the ANS Forth locals wordset through our locals wordset).
1.5 anton 6422:
1.26 crook 6423: The ideas in this section have also been published in the paper
6424: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
6425: at EuroForth '94; it is available at
6426: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
1.5 anton 6427:
1.26 crook 6428: @menu
6429: * Gforth locals::
6430: * ANS Forth locals::
6431: @end menu
1.5 anton 6432:
1.26 crook 6433: @node Gforth locals, ANS Forth locals, Locals, Locals
6434: @subsection Gforth locals
6435: @cindex Gforth locals
6436: @cindex locals, Gforth style
1.5 anton 6437:
1.26 crook 6438: Locals can be defined with
1.5 anton 6439:
6440: @example
1.26 crook 6441: @{ local1 local2 ... -- comment @}
6442: @end example
6443: or
6444: @example
6445: @{ local1 local2 ... @}
1.5 anton 6446: @end example
6447:
1.26 crook 6448: E.g.,
1.5 anton 6449: @example
1.26 crook 6450: : max @{ n1 n2 -- n3 @}
6451: n1 n2 > if
6452: n1
6453: else
6454: n2
6455: endif ;
1.5 anton 6456: @end example
6457:
1.26 crook 6458: The similarity of locals definitions with stack comments is intended. A
6459: locals definition often replaces the stack comment of a word. The order
6460: of the locals corresponds to the order in a stack comment and everything
6461: after the @code{--} is really a comment.
1.5 anton 6462:
1.26 crook 6463: This similarity has one disadvantage: It is too easy to confuse locals
6464: declarations with stack comments, causing bugs and making them hard to
6465: find. However, this problem can be avoided by appropriate coding
6466: conventions: Do not use both notations in the same program. If you do,
6467: they should be distinguished using additional means, e.g. by position.
6468:
6469: @cindex types of locals
6470: @cindex locals types
6471: The name of the local may be preceded by a type specifier, e.g.,
6472: @code{F:} for a floating point value:
6473:
6474: @example
6475: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
6476: \ complex multiplication
6477: Ar Br f* Ai Bi f* f-
6478: Ar Bi f* Ai Br f* f+ ;
6479: @end example
6480:
6481: @cindex flavours of locals
6482: @cindex locals flavours
6483: @cindex value-flavoured locals
6484: @cindex variable-flavoured locals
6485: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
6486: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
6487: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
6488: with @code{W:}, @code{D:} etc.) produces its value and can be changed
6489: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
6490: produces its address (which becomes invalid when the variable's scope is
6491: left). E.g., the standard word @code{emit} can be defined in terms of
6492: @code{type} like this:
1.5 anton 6493:
6494: @example
1.26 crook 6495: : emit @{ C^ char* -- @}
6496: char* 1 type ;
1.5 anton 6497: @end example
6498:
1.26 crook 6499: @cindex default type of locals
6500: @cindex locals, default type
6501: A local without type specifier is a @code{W:} local. Both flavours of
6502: locals are initialized with values from the data or FP stack.
1.5 anton 6503:
1.26 crook 6504: Currently there is no way to define locals with user-defined data
6505: structures, but we are working on it.
1.5 anton 6506:
1.26 crook 6507: Gforth allows defining locals everywhere in a colon definition. This
6508: poses the following questions:
1.5 anton 6509:
1.26 crook 6510: @menu
6511: * Where are locals visible by name?::
6512: * How long do locals live?::
6513: * Programming Style::
6514: * Implementation::
6515: @end menu
1.5 anton 6516:
1.26 crook 6517: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
6518: @subsubsection Where are locals visible by name?
6519: @cindex locals visibility
6520: @cindex visibility of locals
6521: @cindex scope of locals
1.5 anton 6522:
1.26 crook 6523: Basically, the answer is that locals are visible where you would expect
6524: it in block-structured languages, and sometimes a little longer. If you
6525: want to restrict the scope of a local, enclose its definition in
6526: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 6527:
1.26 crook 6528: doc-scope
6529: doc-endscope
1.5 anton 6530:
1.26 crook 6531: These words behave like control structure words, so you can use them
6532: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
6533: arbitrary ways.
1.5 anton 6534:
1.26 crook 6535: If you want a more exact answer to the visibility question, here's the
6536: basic principle: A local is visible in all places that can only be
6537: reached through the definition of the local@footnote{In compiler
6538: construction terminology, all places dominated by the definition of the
6539: local.}. In other words, it is not visible in places that can be reached
6540: without going through the definition of the local. E.g., locals defined
6541: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
6542: defined in @code{BEGIN}...@code{UNTIL} are visible after the
6543: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5 anton 6544:
1.26 crook 6545: The reasoning behind this solution is: We want to have the locals
6546: visible as long as it is meaningful. The user can always make the
6547: visibility shorter by using explicit scoping. In a place that can
6548: only be reached through the definition of a local, the meaning of a
6549: local name is clear. In other places it is not: How is the local
6550: initialized at the control flow path that does not contain the
6551: definition? Which local is meant, if the same name is defined twice in
6552: two independent control flow paths?
1.5 anton 6553:
1.26 crook 6554: This should be enough detail for nearly all users, so you can skip the
6555: rest of this section. If you really must know all the gory details and
6556: options, read on.
1.5 anton 6557:
1.26 crook 6558: In order to implement this rule, the compiler has to know which places
6559: are unreachable. It knows this automatically after @code{AHEAD},
6560: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
6561: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
6562: compiler that the control flow never reaches that place. If
6563: @code{UNREACHABLE} is not used where it could, the only consequence is
6564: that the visibility of some locals is more limited than the rule above
6565: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
6566: lie to the compiler), buggy code will be produced.
1.5 anton 6567:
1.26 crook 6568: doc-unreachable
1.5 anton 6569:
1.26 crook 6570: Another problem with this rule is that at @code{BEGIN}, the compiler
6571: does not know which locals will be visible on the incoming
6572: back-edge. All problems discussed in the following are due to this
6573: ignorance of the compiler (we discuss the problems using @code{BEGIN}
6574: loops as examples; the discussion also applies to @code{?DO} and other
6575: loops). Perhaps the most insidious example is:
1.5 anton 6576: @example
1.26 crook 6577: AHEAD
6578: BEGIN
6579: x
6580: [ 1 CS-ROLL ] THEN
6581: @{ x @}
6582: ...
6583: UNTIL
6584: @end example
1.5 anton 6585:
1.26 crook 6586: This should be legal according to the visibility rule. The use of
6587: @code{x} can only be reached through the definition; but that appears
6588: textually below the use.
1.5 anton 6589:
1.26 crook 6590: From this example it is clear that the visibility rules cannot be fully
6591: implemented without major headaches. Our implementation treats common
6592: cases as advertised and the exceptions are treated in a safe way: The
6593: compiler makes a reasonable guess about the locals visible after a
6594: @code{BEGIN}; if it is too pessimistic, the
6595: user will get a spurious error about the local not being defined; if the
6596: compiler is too optimistic, it will notice this later and issue a
6597: warning. In the case above the compiler would complain about @code{x}
6598: being undefined at its use. You can see from the obscure examples in
6599: this section that it takes quite unusual control structures to get the
6600: compiler into trouble, and even then it will often do fine.
1.5 anton 6601:
1.26 crook 6602: If the @code{BEGIN} is reachable from above, the most optimistic guess
6603: is that all locals visible before the @code{BEGIN} will also be
6604: visible after the @code{BEGIN}. This guess is valid for all loops that
6605: are entered only through the @code{BEGIN}, in particular, for normal
6606: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
6607: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
6608: compiler. When the branch to the @code{BEGIN} is finally generated by
6609: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
6610: warns the user if it was too optimistic:
6611: @example
6612: IF
6613: @{ x @}
6614: BEGIN
6615: \ x ?
6616: [ 1 cs-roll ] THEN
6617: ...
6618: UNTIL
1.5 anton 6619: @end example
6620:
1.26 crook 6621: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
6622: optimistically assumes that it lives until the @code{THEN}. It notices
6623: this difference when it compiles the @code{UNTIL} and issues a
6624: warning. The user can avoid the warning, and make sure that @code{x}
6625: is not used in the wrong area by using explicit scoping:
6626: @example
6627: IF
6628: SCOPE
6629: @{ x @}
6630: ENDSCOPE
6631: BEGIN
6632: [ 1 cs-roll ] THEN
6633: ...
6634: UNTIL
6635: @end example
1.5 anton 6636:
1.26 crook 6637: Since the guess is optimistic, there will be no spurious error messages
6638: about undefined locals.
1.5 anton 6639:
1.26 crook 6640: If the @code{BEGIN} is not reachable from above (e.g., after
6641: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
6642: optimistic guess, as the locals visible after the @code{BEGIN} may be
6643: defined later. Therefore, the compiler assumes that no locals are
6644: visible after the @code{BEGIN}. However, the user can use
6645: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
6646: visible at the BEGIN as at the point where the top control-flow stack
6647: item was created.
1.5 anton 6648:
1.26 crook 6649: doc-assume-live
1.5 anton 6650:
1.26 crook 6651: E.g.,
1.5 anton 6652: @example
1.26 crook 6653: @{ x @}
6654: AHEAD
6655: ASSUME-LIVE
6656: BEGIN
6657: x
6658: [ 1 CS-ROLL ] THEN
6659: ...
6660: UNTIL
1.5 anton 6661: @end example
6662:
1.26 crook 6663: Other cases where the locals are defined before the @code{BEGIN} can be
6664: handled by inserting an appropriate @code{CS-ROLL} before the
6665: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
6666: behind the @code{ASSUME-LIVE}).
1.5 anton 6667:
1.26 crook 6668: Cases where locals are defined after the @code{BEGIN} (but should be
6669: visible immediately after the @code{BEGIN}) can only be handled by
6670: rearranging the loop. E.g., the ``most insidious'' example above can be
6671: arranged into:
1.5 anton 6672: @example
1.26 crook 6673: BEGIN
6674: @{ x @}
6675: ... 0=
6676: WHILE
6677: x
6678: REPEAT
1.5 anton 6679: @end example
6680:
1.26 crook 6681: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
6682: @subsubsection How long do locals live?
6683: @cindex locals lifetime
6684: @cindex lifetime of locals
1.5 anton 6685:
1.26 crook 6686: The right answer for the lifetime question would be: A local lives at
6687: least as long as it can be accessed. For a value-flavoured local this
6688: means: until the end of its visibility. However, a variable-flavoured
6689: local could be accessed through its address far beyond its visibility
6690: scope. Ultimately, this would mean that such locals would have to be
6691: garbage collected. Since this entails un-Forth-like implementation
6692: complexities, I adopted the same cowardly solution as some other
6693: languages (e.g., C): The local lives only as long as it is visible;
6694: afterwards its address is invalid (and programs that access it
6695: afterwards are erroneous).
1.5 anton 6696:
1.26 crook 6697: @node Programming Style, Implementation, How long do locals live?, Gforth locals
6698: @subsubsection Programming Style
6699: @cindex locals programming style
6700: @cindex programming style, locals
1.5 anton 6701:
1.26 crook 6702: The freedom to define locals anywhere has the potential to change
6703: programming styles dramatically. In particular, the need to use the
6704: return stack for intermediate storage vanishes. Moreover, all stack
6705: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
6706: determined arguments) can be eliminated: If the stack items are in the
6707: wrong order, just write a locals definition for all of them; then
6708: write the items in the order you want.
1.5 anton 6709:
1.26 crook 6710: This seems a little far-fetched and eliminating stack manipulations is
6711: unlikely to become a conscious programming objective. Still, the number
6712: of stack manipulations will be reduced dramatically if local variables
6713: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
6714: a traditional implementation of @code{max}).
1.5 anton 6715:
1.26 crook 6716: This shows one potential benefit of locals: making Forth programs more
6717: readable. Of course, this benefit will only be realized if the
6718: programmers continue to honour the principle of factoring instead of
6719: using the added latitude to make the words longer.
1.5 anton 6720:
1.26 crook 6721: @cindex single-assignment style for locals
6722: Using @code{TO} can and should be avoided. Without @code{TO},
6723: every value-flavoured local has only a single assignment and many
6724: advantages of functional languages apply to Forth. I.e., programs are
6725: easier to analyse, to optimize and to read: It is clear from the
6726: definition what the local stands for, it does not turn into something
6727: different later.
1.5 anton 6728:
1.26 crook 6729: E.g., a definition using @code{TO} might look like this:
1.5 anton 6730: @example
1.26 crook 6731: : strcmp @{ addr1 u1 addr2 u2 -- n @}
6732: u1 u2 min 0
6733: ?do
6734: addr1 c@@ addr2 c@@ -
6735: ?dup-if
6736: unloop exit
6737: then
6738: addr1 char+ TO addr1
6739: addr2 char+ TO addr2
6740: loop
6741: u1 u2 - ;
1.5 anton 6742: @end example
1.26 crook 6743: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
6744: every loop iteration. @code{strcmp} is a typical example of the
6745: readability problems of using @code{TO}. When you start reading
6746: @code{strcmp}, you think that @code{addr1} refers to the start of the
6747: string. Only near the end of the loop you realize that it is something
6748: else.
1.5 anton 6749:
1.26 crook 6750: This can be avoided by defining two locals at the start of the loop that
6751: are initialized with the right value for the current iteration.
1.5 anton 6752: @example
1.26 crook 6753: : strcmp @{ addr1 u1 addr2 u2 -- n @}
6754: addr1 addr2
6755: u1 u2 min 0
6756: ?do @{ s1 s2 @}
6757: s1 c@@ s2 c@@ -
6758: ?dup-if
6759: unloop exit
6760: then
6761: s1 char+ s2 char+
6762: loop
6763: 2drop
6764: u1 u2 - ;
1.5 anton 6765: @end example
1.26 crook 6766: Here it is clear from the start that @code{s1} has a different value
6767: in every loop iteration.
1.5 anton 6768:
1.26 crook 6769: @node Implementation, , Programming Style, Gforth locals
6770: @subsubsection Implementation
6771: @cindex locals implementation
6772: @cindex implementation of locals
1.5 anton 6773:
1.26 crook 6774: @cindex locals stack
6775: Gforth uses an extra locals stack. The most compelling reason for
6776: this is that the return stack is not float-aligned; using an extra stack
6777: also eliminates the problems and restrictions of using the return stack
6778: as locals stack. Like the other stacks, the locals stack grows toward
6779: lower addresses. A few primitives allow an efficient implementation:
1.5 anton 6780:
1.26 crook 6781: doc-@local#
6782: doc-f@local#
6783: doc-laddr#
6784: doc-lp+!#
6785: doc-lp!
6786: doc->l
6787: doc-f>l
1.5 anton 6788:
1.26 crook 6789: In addition to these primitives, some specializations of these
6790: primitives for commonly occurring inline arguments are provided for
6791: efficiency reasons, e.g., @code{@@local0} as specialization of
6792: @code{@@local#} for the inline argument 0. The following compiling words
6793: compile the right specialized version, or the general version, as
6794: appropriate:
1.6 pazsan 6795:
1.26 crook 6796: doc-compile-@local
6797: doc-compile-f@local
6798: doc-compile-lp+!
1.12 anton 6799:
1.26 crook 6800: Combinations of conditional branches and @code{lp+!#} like
6801: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
6802: is taken) are provided for efficiency and correctness in loops.
1.6 pazsan 6803:
1.26 crook 6804: A special area in the dictionary space is reserved for keeping the
6805: local variable names. @code{@{} switches the dictionary pointer to this
6806: area and @code{@}} switches it back and generates the locals
6807: initializing code. @code{W:} etc.@ are normal defining words. This
6808: special area is cleared at the start of every colon definition.
1.6 pazsan 6809:
1.26 crook 6810: @cindex word list for defining locals
6811: A special feature of Gforth's dictionary is used to implement the
6812: definition of locals without type specifiers: every word list (aka
6813: vocabulary) has its own methods for searching
6814: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
6815: with a special search method: When it is searched for a word, it
6816: actually creates that word using @code{W:}. @code{@{} changes the search
6817: order to first search the word list containing @code{@}}, @code{W:} etc.,
6818: and then the word list for defining locals without type specifiers.
1.12 anton 6819:
1.26 crook 6820: The lifetime rules support a stack discipline within a colon
6821: definition: The lifetime of a local is either nested with other locals
6822: lifetimes or it does not overlap them.
1.6 pazsan 6823:
1.26 crook 6824: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
6825: pointer manipulation is generated. Between control structure words
6826: locals definitions can push locals onto the locals stack. @code{AGAIN}
6827: is the simplest of the other three control flow words. It has to
6828: restore the locals stack depth of the corresponding @code{BEGIN}
6829: before branching. The code looks like this:
6830: @format
6831: @code{lp+!#} current-locals-size @minus{} dest-locals-size
6832: @code{branch} <begin>
6833: @end format
1.6 pazsan 6834:
1.26 crook 6835: @code{UNTIL} is a little more complicated: If it branches back, it
6836: must adjust the stack just like @code{AGAIN}. But if it falls through,
6837: the locals stack must not be changed. The compiler generates the
6838: following code:
6839: @format
6840: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
6841: @end format
6842: The locals stack pointer is only adjusted if the branch is taken.
1.6 pazsan 6843:
1.26 crook 6844: @code{THEN} can produce somewhat inefficient code:
6845: @format
6846: @code{lp+!#} current-locals-size @minus{} orig-locals-size
6847: <orig target>:
6848: @code{lp+!#} orig-locals-size @minus{} new-locals-size
6849: @end format
6850: The second @code{lp+!#} adjusts the locals stack pointer from the
1.29 crook 6851: level at the @i{orig} point to the level after the @code{THEN}. The
1.26 crook 6852: first @code{lp+!#} adjusts the locals stack pointer from the current
6853: level to the level at the orig point, so the complete effect is an
6854: adjustment from the current level to the right level after the
6855: @code{THEN}.
1.6 pazsan 6856:
1.26 crook 6857: @cindex locals information on the control-flow stack
6858: @cindex control-flow stack items, locals information
6859: In a conventional Forth implementation a dest control-flow stack entry
6860: is just the target address and an orig entry is just the address to be
6861: patched. Our locals implementation adds a word list to every orig or dest
6862: item. It is the list of locals visible (or assumed visible) at the point
6863: described by the entry. Our implementation also adds a tag to identify
6864: the kind of entry, in particular to differentiate between live and dead
6865: (reachable and unreachable) orig entries.
1.6 pazsan 6866:
1.26 crook 6867: A few unusual operations have to be performed on locals word lists:
1.6 pazsan 6868:
1.26 crook 6869: doc-common-list
6870: doc-sub-list?
6871: doc-list-size
1.6 pazsan 6872:
1.26 crook 6873: Several features of our locals word list implementation make these
6874: operations easy to implement: The locals word lists are organised as
6875: linked lists; the tails of these lists are shared, if the lists
6876: contain some of the same locals; and the address of a name is greater
6877: than the address of the names behind it in the list.
1.6 pazsan 6878:
1.26 crook 6879: Another important implementation detail is the variable
6880: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
6881: determine if they can be reached directly or only through the branch
6882: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
6883: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
6884: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6 pazsan 6885:
1.26 crook 6886: Counted loops are similar to other loops in most respects, but
6887: @code{LEAVE} requires special attention: It performs basically the same
6888: service as @code{AHEAD}, but it does not create a control-flow stack
6889: entry. Therefore the information has to be stored elsewhere;
6890: traditionally, the information was stored in the target fields of the
6891: branches created by the @code{LEAVE}s, by organizing these fields into a
6892: linked list. Unfortunately, this clever trick does not provide enough
6893: space for storing our extended control flow information. Therefore, we
6894: introduce another stack, the leave stack. It contains the control-flow
6895: stack entries for all unresolved @code{LEAVE}s.
1.6 pazsan 6896:
1.26 crook 6897: Local names are kept until the end of the colon definition, even if
6898: they are no longer visible in any control-flow path. In a few cases
6899: this may lead to increased space needs for the locals name area, but
6900: usually less than reclaiming this space would cost in code size.
1.6 pazsan 6901:
6902:
1.26 crook 6903: @node ANS Forth locals, , Gforth locals, Locals
6904: @subsection ANS Forth locals
6905: @cindex locals, ANS Forth style
1.6 pazsan 6906:
1.26 crook 6907: The ANS Forth locals wordset does not define a syntax for locals, but
6908: words that make it possible to define various syntaxes. One of the
6909: possible syntaxes is a subset of the syntax we used in the Gforth locals
6910: wordset, i.e.:
1.6 pazsan 6911:
6912: @example
1.26 crook 6913: @{ local1 local2 ... -- comment @}
1.6 pazsan 6914: @end example
1.23 crook 6915: @noindent
1.26 crook 6916: or
1.6 pazsan 6917: @example
1.26 crook 6918: @{ local1 local2 ... @}
1.6 pazsan 6919: @end example
6920:
1.26 crook 6921: The order of the locals corresponds to the order in a stack comment. The
6922: restrictions are:
1.6 pazsan 6923:
6924: @itemize @bullet
6925: @item
1.26 crook 6926: Locals can only be cell-sized values (no type specifiers are allowed).
1.6 pazsan 6927: @item
1.26 crook 6928: Locals can be defined only outside control structures.
1.6 pazsan 6929: @item
1.26 crook 6930: Locals can interfere with explicit usage of the return stack. For the
6931: exact (and long) rules, see the standard. If you don't use return stack
6932: accessing words in a definition using locals, you will be all right. The
6933: purpose of this rule is to make locals implementation on the return
6934: stack easier.
1.6 pazsan 6935: @item
1.26 crook 6936: The whole definition must be in one line.
6937: @end itemize
1.6 pazsan 6938:
1.26 crook 6939: Locals defined in this way behave like @code{VALUE}s (@xref{Simple
6940: Defining Words}). I.e., they are initialized from the stack. Using their
6941: name produces their value. Their value can be changed using @code{TO}.
1.6 pazsan 6942:
1.26 crook 6943: Since this syntax is supported by Gforth directly, you need not do
6944: anything to use it. If you want to port a program using this syntax to
6945: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
6946: syntax on the other system.
1.6 pazsan 6947:
1.26 crook 6948: Note that a syntax shown in the standard, section A.13 looks
6949: similar, but is quite different in having the order of locals
6950: reversed. Beware!
1.6 pazsan 6951:
1.26 crook 6952: The ANS Forth locals wordset itself consists of a word:
1.6 pazsan 6953:
1.26 crook 6954: doc-(local)
1.6 pazsan 6955:
1.26 crook 6956: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
6957: awful that we strongly recommend not to use it. We have implemented this
6958: syntax to make porting to Gforth easy, but do not document it here. The
6959: problem with this syntax is that the locals are defined in an order
6960: reversed with respect to the standard stack comment notation, making
6961: programs harder to read, and easier to misread and miswrite. The only
6962: merit of this syntax is that it is easy to implement using the ANS Forth
6963: locals wordset.
1.7 pazsan 6964:
6965:
1.26 crook 6966: @c ----------------------------------------------------------
6967: @node Structures, Object-oriented Forth, Locals, Words
6968: @section Structures
6969: @cindex structures
6970: @cindex records
1.7 pazsan 6971:
1.26 crook 6972: This section presents the structure package that comes with Gforth. A
6973: version of the package implemented in ANS Forth is available in
6974: @file{compat/struct.fs}. This package was inspired by a posting on
6975: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
6976: possibly John Hayes). A version of this section has been published in
6977: ???. Marcel Hendrix provided helpful comments.
1.7 pazsan 6978:
1.26 crook 6979: @menu
6980: * Why explicit structure support?::
6981: * Structure Usage::
6982: * Structure Naming Convention::
6983: * Structure Implementation::
6984: * Structure Glossary::
6985: @end menu
1.7 pazsan 6986:
1.26 crook 6987: @node Why explicit structure support?, Structure Usage, Structures, Structures
6988: @subsection Why explicit structure support?
1.7 pazsan 6989:
1.26 crook 6990: @cindex address arithmetic for structures
6991: @cindex structures using address arithmetic
6992: If we want to use a structure containing several fields, we could simply
6993: reserve memory for it, and access the fields using address arithmetic
1.32 anton 6994: (@pxref{Address arithmetic}). As an example, consider a structure with
1.26 crook 6995: the following fields
1.7 pazsan 6996:
1.26 crook 6997: @table @code
6998: @item a
6999: is a float
7000: @item b
7001: is a cell
7002: @item c
7003: is a float
7004: @end table
1.7 pazsan 7005:
1.26 crook 7006: Given the (float-aligned) base address of the structure we get the
7007: address of the field
1.13 pazsan 7008:
1.26 crook 7009: @table @code
7010: @item a
7011: without doing anything further.
7012: @item b
7013: with @code{float+}
7014: @item c
7015: with @code{float+ cell+ faligned}
7016: @end table
1.13 pazsan 7017:
1.26 crook 7018: It is easy to see that this can become quite tiring.
1.13 pazsan 7019:
1.26 crook 7020: Moreover, it is not very readable, because seeing a
7021: @code{cell+} tells us neither which kind of structure is
7022: accessed nor what field is accessed; we have to somehow infer the kind
7023: of structure, and then look up in the documentation, which field of
7024: that structure corresponds to that offset.
1.13 pazsan 7025:
1.26 crook 7026: Finally, this kind of address arithmetic also causes maintenance
7027: troubles: If you add or delete a field somewhere in the middle of the
7028: structure, you have to find and change all computations for the fields
7029: afterwards.
1.13 pazsan 7030:
1.26 crook 7031: So, instead of using @code{cell+} and friends directly, how
7032: about storing the offsets in constants:
1.13 pazsan 7033:
7034: @example
1.26 crook 7035: 0 constant a-offset
7036: 0 float+ constant b-offset
7037: 0 float+ cell+ faligned c-offset
1.13 pazsan 7038: @end example
7039:
1.26 crook 7040: Now we can get the address of field @code{x} with @code{x-offset
7041: +}. This is much better in all respects. Of course, you still
7042: have to change all later offset definitions if you add a field. You can
7043: fix this by declaring the offsets in the following way:
1.13 pazsan 7044:
7045: @example
1.26 crook 7046: 0 constant a-offset
7047: a-offset float+ constant b-offset
7048: b-offset cell+ faligned constant c-offset
1.13 pazsan 7049: @end example
7050:
1.26 crook 7051: Since we always use the offsets with @code{+}, we could use a defining
7052: word @code{cfield} that includes the @code{+} in the action of the
7053: defined word:
1.8 pazsan 7054:
7055: @example
1.26 crook 7056: : cfield ( n "name" -- )
7057: create ,
7058: does> ( name execution: addr1 -- addr2 )
7059: @@ + ;
1.13 pazsan 7060:
1.26 crook 7061: 0 cfield a
7062: 0 a float+ cfield b
7063: 0 b cell+ faligned cfield c
1.13 pazsan 7064: @end example
7065:
1.26 crook 7066: Instead of @code{x-offset +}, we now simply write @code{x}.
7067:
7068: The structure field words now can be used quite nicely. However,
7069: their definition is still a bit cumbersome: We have to repeat the
7070: name, the information about size and alignment is distributed before
7071: and after the field definitions etc. The structure package presented
7072: here addresses these problems.
7073:
7074: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
7075: @subsection Structure Usage
7076: @cindex structure usage
1.13 pazsan 7077:
1.26 crook 7078: @cindex @code{field} usage
7079: @cindex @code{struct} usage
7080: @cindex @code{end-struct} usage
7081: You can define a structure for a (data-less) linked list with:
1.13 pazsan 7082: @example
1.26 crook 7083: struct
7084: cell% field list-next
7085: end-struct list%
1.13 pazsan 7086: @end example
7087:
1.26 crook 7088: With the address of the list node on the stack, you can compute the
7089: address of the field that contains the address of the next node with
7090: @code{list-next}. E.g., you can determine the length of a list
7091: with:
1.13 pazsan 7092:
7093: @example
1.26 crook 7094: : list-length ( list -- n )
7095: \ "list" is a pointer to the first element of a linked list
7096: \ "n" is the length of the list
7097: 0 BEGIN ( list1 n1 )
7098: over
7099: WHILE ( list1 n1 )
7100: 1+ swap list-next @@ swap
7101: REPEAT
7102: nip ;
1.13 pazsan 7103: @end example
7104:
1.26 crook 7105: You can reserve memory for a list node in the dictionary with
7106: @code{list% %allot}, which leaves the address of the list node on the
7107: stack. For the equivalent allocation on the heap you can use @code{list%
7108: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
7109: use @code{list% %allocate}). You can get the the size of a list
7110: node with @code{list% %size} and its alignment with @code{list%
7111: %alignment}.
1.13 pazsan 7112:
1.26 crook 7113: Note that in ANS Forth the body of a @code{create}d word is
7114: @code{aligned} but not necessarily @code{faligned};
7115: therefore, if you do a:
1.13 pazsan 7116: @example
1.26 crook 7117: create @emph{name} foo% %allot
1.8 pazsan 7118: @end example
7119:
1.26 crook 7120: @noindent
7121: then the memory alloted for @code{foo%} is
7122: guaranteed to start at the body of @code{@emph{name}} only if
7123: @code{foo%} contains only character, cell and double fields.
1.20 pazsan 7124:
1.26 crook 7125: @cindex strcutures containing structures
7126: You can include a structure @code{foo%} as a field of
7127: another structure, like this:
1.20 pazsan 7128: @example
1.26 crook 7129: struct
7130: ...
7131: foo% field ...
7132: ...
7133: end-struct ...
1.20 pazsan 7134: @end example
7135:
1.26 crook 7136: @cindex structure extension
7137: @cindex extended records
7138: Instead of starting with an empty structure, you can extend an
7139: existing structure. E.g., a plain linked list without data, as defined
7140: above, is hardly useful; You can extend it to a linked list of integers,
7141: like this:@footnote{This feature is also known as @emph{extended
7142: records}. It is the main innovation in the Oberon language; in other
7143: words, adding this feature to Modula-2 led Wirth to create a new
7144: language, write a new compiler etc. Adding this feature to Forth just
7145: required a few lines of code.}
1.20 pazsan 7146:
7147: @example
1.26 crook 7148: list%
7149: cell% field intlist-int
7150: end-struct intlist%
1.20 pazsan 7151: @end example
7152:
1.26 crook 7153: @code{intlist%} is a structure with two fields:
7154: @code{list-next} and @code{intlist-int}.
1.20 pazsan 7155:
1.26 crook 7156: @cindex structures containing arrays
7157: You can specify an array type containing @emph{n} elements of
7158: type @code{foo%} like this:
1.20 pazsan 7159:
7160: @example
1.26 crook 7161: foo% @emph{n} *
1.20 pazsan 7162: @end example
7163:
1.26 crook 7164: You can use this array type in any place where you can use a normal
7165: type, e.g., when defining a @code{field}, or with
7166: @code{%allot}.
1.20 pazsan 7167:
1.26 crook 7168: @cindex first field optimization
7169: The first field is at the base address of a structure and the word
7170: for this field (e.g., @code{list-next}) actually does not change
7171: the address on the stack. You may be tempted to leave it away in the
7172: interest of run-time and space efficiency. This is not necessary,
7173: because the structure package optimizes this case and compiling such
7174: words does not generate any code. So, in the interest of readability
7175: and maintainability you should include the word for the field when
7176: accessing the field.
1.20 pazsan 7177:
1.26 crook 7178: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
7179: @subsection Structure Naming Convention
7180: @cindex structure naming convention
1.20 pazsan 7181:
1.26 crook 7182: The field names that come to (my) mind are often quite generic, and,
7183: if used, would cause frequent name clashes. E.g., many structures
7184: probably contain a @code{counter} field. The structure names
7185: that come to (my) mind are often also the logical choice for the names
7186: of words that create such a structure.
1.20 pazsan 7187:
1.26 crook 7188: Therefore, I have adopted the following naming conventions:
1.20 pazsan 7189:
1.26 crook 7190: @itemize @bullet
7191: @cindex field naming convention
7192: @item
7193: The names of fields are of the form
7194: @code{@emph{struct}-@emph{field}}, where
7195: @code{@emph{struct}} is the basic name of the structure, and
7196: @code{@emph{field}} is the basic name of the field. You can
7197: think of field words as converting the (address of the)
7198: structure into the (address of the) field.
1.20 pazsan 7199:
1.26 crook 7200: @cindex structure naming convention
7201: @item
7202: The names of structures are of the form
7203: @code{@emph{struct}%}, where
7204: @code{@emph{struct}} is the basic name of the structure.
7205: @end itemize
1.20 pazsan 7206:
1.26 crook 7207: This naming convention does not work that well for fields of extended
7208: structures; e.g., the integer list structure has a field
7209: @code{intlist-int}, but has @code{list-next}, not
7210: @code{intlist-next}.
1.20 pazsan 7211:
1.26 crook 7212: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
7213: @subsection Structure Implementation
7214: @cindex structure implementation
7215: @cindex implementation of structures
1.20 pazsan 7216:
1.26 crook 7217: The central idea in the implementation is to pass the data about the
7218: structure being built on the stack, not in some global
7219: variable. Everything else falls into place naturally once this design
7220: decision is made.
1.20 pazsan 7221:
1.26 crook 7222: The type description on the stack is of the form @emph{align
7223: size}. Keeping the size on the top-of-stack makes dealing with arrays
7224: very simple.
1.20 pazsan 7225:
1.26 crook 7226: @code{field} is a defining word that uses @code{Create}
7227: and @code{DOES>}. The body of the field contains the offset
7228: of the field, and the normal @code{DOES>} action is simply:
1.20 pazsan 7229:
7230: @example
1.26 crook 7231: @ +
1.20 pazsan 7232: @end example
7233:
1.23 crook 7234: @noindent
1.26 crook 7235: i.e., add the offset to the address, giving the stack effect
1.29 crook 7236: @i{addr1 -- addr2} for a field.
1.20 pazsan 7237:
1.26 crook 7238: @cindex first field optimization, implementation
7239: This simple structure is slightly complicated by the optimization
7240: for fields with offset 0, which requires a different
7241: @code{DOES>}-part (because we cannot rely on there being
7242: something on the stack if such a field is invoked during
7243: compilation). Therefore, we put the different @code{DOES>}-parts
7244: in separate words, and decide which one to invoke based on the
7245: offset. For a zero offset, the field is basically a noop; it is
7246: immediate, and therefore no code is generated when it is compiled.
1.20 pazsan 7247:
1.26 crook 7248: @node Structure Glossary, , Structure Implementation, Structures
7249: @subsection Structure Glossary
7250: @cindex structure glossary
1.20 pazsan 7251:
1.26 crook 7252: doc-%align
7253: doc-%alignment
7254: doc-%alloc
7255: doc-%allocate
7256: doc-%allot
7257: doc-cell%
7258: doc-char%
7259: doc-dfloat%
7260: doc-double%
7261: doc-end-struct
7262: doc-field
7263: doc-float%
7264: doc-naligned
7265: doc-sfloat%
7266: doc-%size
7267: doc-struct
1.23 crook 7268:
1.26 crook 7269: @c -------------------------------------------------------------
7270: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
7271: @section Object-oriented Forth
1.20 pazsan 7272:
1.26 crook 7273: Gforth comes with three packages for object-oriented programming:
7274: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
7275: is preloaded, so you have to @code{include} them before use. The most
7276: important differences between these packages (and others) are discussed
7277: in @ref{Comparison with other object models}. All packages are written
7278: in ANS Forth and can be used with any other ANS Forth.
1.20 pazsan 7279:
1.26 crook 7280: @menu
7281: * Why object-oriented programming?::
7282: * Object-Oriented Terminology::
7283: * Objects::
7284: * OOF::
7285: * Mini-OOF::
7286: * Comparison with other object models::
7287: @end menu
1.20 pazsan 7288:
1.23 crook 7289:
1.26 crook 7290: @node Why object-oriented programming?, Object-Oriented Terminology, , Object-oriented Forth
7291: @subsubsection Why object-oriented programming?
7292: @cindex object-oriented programming motivation
7293: @cindex motivation for object-oriented programming
1.23 crook 7294:
1.26 crook 7295: Often we have to deal with several data structures (@emph{objects}),
7296: that have to be treated similarly in some respects, but differently in
7297: others. Graphical objects are the textbook example: circles, triangles,
7298: dinosaurs, icons, and others, and we may want to add more during program
7299: development. We want to apply some operations to any graphical object,
7300: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
7301: has to do something different for every kind of object.
7302: @comment TODO add some other operations eg perimeter, area
7303: @comment and tie in to concrete examples later..
1.23 crook 7304:
1.26 crook 7305: We could implement @code{draw} as a big @code{CASE}
7306: control structure that executes the appropriate code depending on the
7307: kind of object to be drawn. This would be not be very elegant, and,
7308: moreover, we would have to change @code{draw} every time we add
7309: a new kind of graphical object (say, a spaceship).
1.23 crook 7310:
1.26 crook 7311: What we would rather do is: When defining spaceships, we would tell
7312: the system: ``Here's how you @code{draw} a spaceship; you figure
7313: out the rest''.
1.23 crook 7314:
1.26 crook 7315: This is the problem that all systems solve that (rightfully) call
7316: themselves object-oriented; the object-oriented packages presented here
7317: solve this problem (and not much else).
7318: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23 crook 7319:
1.26 crook 7320: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
7321: @subsubsection Object-Oriented Terminology
7322: @cindex object-oriented terminology
7323: @cindex terminology for object-oriented programming
1.23 crook 7324:
1.26 crook 7325: This section is mainly for reference, so you don't have to understand
7326: all of it right away. The terminology is mainly Smalltalk-inspired. In
7327: short:
1.23 crook 7328:
1.26 crook 7329: @table @emph
7330: @cindex class
7331: @item class
7332: a data structure definition with some extras.
1.23 crook 7333:
1.26 crook 7334: @cindex object
7335: @item object
7336: an instance of the data structure described by the class definition.
1.23 crook 7337:
1.26 crook 7338: @cindex instance variables
7339: @item instance variables
7340: fields of the data structure.
1.23 crook 7341:
1.26 crook 7342: @cindex selector
7343: @cindex method selector
7344: @cindex virtual function
7345: @item selector
7346: (or @emph{method selector}) a word (e.g.,
7347: @code{draw}) that performs an operation on a variety of data
7348: structures (classes). A selector describes @emph{what} operation to
7349: perform. In C++ terminology: a (pure) virtual function.
1.23 crook 7350:
1.26 crook 7351: @cindex method
7352: @item method
7353: the concrete definition that performs the operation
7354: described by the selector for a specific class. A method specifies
7355: @emph{how} the operation is performed for a specific class.
1.23 crook 7356:
1.26 crook 7357: @cindex selector invocation
7358: @cindex message send
7359: @cindex invoking a selector
7360: @item selector invocation
7361: a call of a selector. One argument of the call (the TOS (top-of-stack))
7362: is used for determining which method is used. In Smalltalk terminology:
7363: a message (consisting of the selector and the other arguments) is sent
7364: to the object.
1.1 anton 7365:
1.26 crook 7366: @cindex receiving object
7367: @item receiving object
7368: the object used for determining the method executed by a selector
7369: invocation. In the @file{objects.fs} model, it is the object that is on
7370: the TOS when the selector is invoked. (@emph{Receiving} comes from
7371: the Smalltalk @emph{message} terminology.)
1.1 anton 7372:
1.26 crook 7373: @cindex child class
7374: @cindex parent class
7375: @cindex inheritance
7376: @item child class
7377: a class that has (@emph{inherits}) all properties (instance variables,
7378: selectors, methods) from a @emph{parent class}. In Smalltalk
7379: terminology: The subclass inherits from the superclass. In C++
7380: terminology: The derived class inherits from the base class.
1.1 anton 7381:
1.26 crook 7382: @end table
1.21 crook 7383:
1.26 crook 7384: @c If you wonder about the message sending terminology, it comes from
7385: @c a time when each object had it's own task and objects communicated via
7386: @c message passing; eventually the Smalltalk developers realized that
7387: @c they can do most things through simple (indirect) calls. They kept the
7388: @c terminology.
1.1 anton 7389:
7390:
1.26 crook 7391: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
7392: @subsection The @file{objects.fs} model
7393: @cindex objects
7394: @cindex object-oriented programming
1.1 anton 7395:
1.26 crook 7396: @cindex @file{objects.fs}
7397: @cindex @file{oof.fs}
1.1 anton 7398:
1.26 crook 7399: 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}).
7400: @c McKewan's and Zsoter's packages
1.1 anton 7401:
1.26 crook 7402: This section assumes that you have read @ref{Structures}.
1.1 anton 7403:
1.26 crook 7404: The techniques on which this model is based have been used to implement
7405: the parser generator, Gray, and have also been used in Gforth for
7406: implementing the various flavours of word lists (hashed or not,
7407: case-sensitive or not, special-purpose word lists for locals etc.).
1.1 anton 7408:
7409:
1.26 crook 7410: @menu
7411: * Properties of the Objects model::
7412: * Basic Objects Usage::
7413: * The Objects base class::
7414: * Creating objects::
7415: * Object-Oriented Programming Style::
7416: * Class Binding::
7417: * Method conveniences::
7418: * Classes and Scoping::
7419: * Object Interfaces::
7420: * Objects Implementation::
7421: * Objects Glossary::
7422: @end menu
1.1 anton 7423:
1.26 crook 7424: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
7425: and Bernd Paysan helped me with the related works section.
1.1 anton 7426:
1.26 crook 7427: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
7428: @subsubsection Properties of the @file{objects.fs} model
7429: @cindex @file{objects.fs} properties
1.1 anton 7430:
1.26 crook 7431: @itemize @bullet
7432: @item
7433: It is straightforward to pass objects on the stack. Passing
7434: selectors on the stack is a little less convenient, but possible.
1.1 anton 7435:
1.26 crook 7436: @item
7437: Objects are just data structures in memory, and are referenced by their
7438: address. You can create words for objects with normal defining words
7439: like @code{constant}. Likewise, there is no difference between instance
7440: variables that contain objects and those that contain other data.
1.1 anton 7441:
1.26 crook 7442: @item
7443: Late binding is efficient and easy to use.
1.21 crook 7444:
1.26 crook 7445: @item
7446: It avoids parsing, and thus avoids problems with state-smartness
7447: and reduced extensibility; for convenience there are a few parsing
7448: words, but they have non-parsing counterparts. There are also a few
7449: defining words that parse. This is hard to avoid, because all standard
7450: defining words parse (except @code{:noname}); however, such
7451: words are not as bad as many other parsing words, because they are not
7452: state-smart.
1.21 crook 7453:
1.26 crook 7454: @item
7455: It does not try to incorporate everything. It does a few things and does
7456: them well (IMO). In particular, this model was not designed to support
7457: information hiding (although it has features that may help); you can use
7458: a separate package for achieving this.
1.21 crook 7459:
1.26 crook 7460: @item
7461: It is layered; you don't have to learn and use all features to use this
7462: model. Only a few features are necessary (@xref{Basic Objects Usage},
7463: @xref{The Objects base class}, @xref{Creating objects}.), the others
7464: are optional and independent of each other.
1.21 crook 7465:
1.26 crook 7466: @item
7467: An implementation in ANS Forth is available.
1.21 crook 7468:
1.26 crook 7469: @end itemize
1.21 crook 7470:
7471:
1.26 crook 7472: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
7473: @subsubsection Basic @file{objects.fs} Usage
7474: @cindex basic objects usage
7475: @cindex objects, basic usage
1.21 crook 7476:
1.26 crook 7477: You can define a class for graphical objects like this:
1.21 crook 7478:
1.26 crook 7479: @cindex @code{class} usage
7480: @cindex @code{end-class} usage
7481: @cindex @code{selector} usage
7482: @example
7483: object class \ "object" is the parent class
7484: selector draw ( x y graphical -- )
7485: end-class graphical
7486: @end example
1.21 crook 7487:
1.26 crook 7488: This code defines a class @code{graphical} with an
7489: operation @code{draw}. We can perform the operation
7490: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 7491:
1.26 crook 7492: @example
7493: 100 100 t-rex draw
7494: @end example
1.21 crook 7495:
1.26 crook 7496: @noindent
7497: where @code{t-rex} is a word (say, a constant) that produces a
7498: graphical object.
1.21 crook 7499:
1.29 crook 7500: @comment TODO add a 2nd operation eg perimeter.. and use for
1.26 crook 7501: @comment a concrete example
1.21 crook 7502:
1.26 crook 7503: @cindex abstract class
7504: How do we create a graphical object? With the present definitions,
7505: we cannot create a useful graphical object. The class
7506: @code{graphical} describes graphical objects in general, but not
7507: any concrete graphical object type (C++ users would call it an
7508: @emph{abstract class}); e.g., there is no method for the selector
7509: @code{draw} in the class @code{graphical}.
1.21 crook 7510:
1.26 crook 7511: For concrete graphical objects, we define child classes of the
7512: class @code{graphical}, e.g.:
1.21 crook 7513:
1.26 crook 7514: @cindex @code{overrides} usage
7515: @cindex @code{field} usage in class definition
7516: @example
7517: graphical class \ "graphical" is the parent class
7518: cell% field circle-radius
1.21 crook 7519:
1.26 crook 7520: :noname ( x y circle -- )
7521: circle-radius @@ draw-circle ;
7522: overrides draw
1.21 crook 7523:
1.26 crook 7524: :noname ( n-radius circle -- )
7525: circle-radius ! ;
7526: overrides construct
1.21 crook 7527:
1.26 crook 7528: end-class circle
1.21 crook 7529: @end example
7530:
1.26 crook 7531: Here we define a class @code{circle} as a child of @code{graphical},
7532: with field @code{circle-radius} (which behaves just like a field
7533: (@pxref{Structures}); it defines (using @code{overrides}) new methods
7534: for the selectors @code{draw} and @code{construct} (@code{construct} is
7535: defined in @code{object}, the parent class of @code{graphical}).
1.21 crook 7536:
1.26 crook 7537: Now we can create a circle on the heap (i.e.,
7538: @code{allocate}d memory) with:
1.21 crook 7539:
1.26 crook 7540: @cindex @code{heap-new} usage
1.21 crook 7541: @example
1.26 crook 7542: 50 circle heap-new constant my-circle
7543: @end example
1.21 crook 7544:
1.26 crook 7545: @noindent
7546: @code{heap-new} invokes @code{construct}, thus
7547: initializing the field @code{circle-radius} with 50. We can draw
7548: this new circle at (100,100) with:
1.21 crook 7549:
1.26 crook 7550: @example
7551: 100 100 my-circle draw
1.21 crook 7552: @end example
7553:
1.26 crook 7554: @cindex selector invocation, restrictions
7555: @cindex class definition, restrictions
7556: Note: You can only invoke a selector if the object on the TOS
7557: (the receiving object) belongs to the class where the selector was
7558: defined or one of its descendents; e.g., you can invoke
7559: @code{draw} only for objects belonging to @code{graphical}
7560: or its descendents (e.g., @code{circle}). Immediately before
7561: @code{end-class}, the search order has to be the same as
7562: immediately after @code{class}.
1.21 crook 7563:
1.26 crook 7564: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
7565: @subsubsection The @file{object.fs} base class
7566: @cindex @code{object} class
1.21 crook 7567:
1.26 crook 7568: When you define a class, you have to specify a parent class. So how do
7569: you start defining classes? There is one class available from the start:
7570: @code{object}. It is ancestor for all classes and so is the
7571: only class that has no parent. It has two selectors: @code{construct}
7572: and @code{print}.
1.21 crook 7573:
1.26 crook 7574: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
7575: @subsubsection Creating objects
7576: @cindex creating objects
7577: @cindex object creation
7578: @cindex object allocation options
1.21 crook 7579:
1.26 crook 7580: @cindex @code{heap-new} discussion
7581: @cindex @code{dict-new} discussion
7582: @cindex @code{construct} discussion
7583: You can create and initialize an object of a class on the heap with
7584: @code{heap-new} ( ... class -- object ) and in the dictionary
7585: (allocation with @code{allot}) with @code{dict-new} (
7586: ... class -- object ). Both words invoke @code{construct}, which
7587: consumes the stack items indicated by "..." above.
1.21 crook 7588:
1.26 crook 7589: @cindex @code{init-object} discussion
7590: @cindex @code{class-inst-size} discussion
7591: If you want to allocate memory for an object yourself, you can get its
7592: alignment and size with @code{class-inst-size 2@@} ( class --
7593: align size ). Once you have memory for an object, you can initialize
7594: it with @code{init-object} ( ... class object -- );
7595: @code{construct} does only a part of the necessary work.
1.21 crook 7596:
1.26 crook 7597: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
7598: @subsubsection Object-Oriented Programming Style
7599: @cindex object-oriented programming style
1.21 crook 7600:
1.26 crook 7601: This section is not exhaustive.
1.1 anton 7602:
1.26 crook 7603: @cindex stack effects of selectors
7604: @cindex selectors and stack effects
7605: In general, it is a good idea to ensure that all methods for the
7606: same selector have the same stack effect: when you invoke a selector,
7607: you often have no idea which method will be invoked, so, unless all
7608: methods have the same stack effect, you will not know the stack effect
7609: of the selector invocation.
1.21 crook 7610:
1.26 crook 7611: One exception to this rule is methods for the selector
7612: @code{construct}. We know which method is invoked, because we
7613: specify the class to be constructed at the same place. Actually, I
7614: defined @code{construct} as a selector only to give the users a
7615: convenient way to specify initialization. The way it is used, a
7616: mechanism different from selector invocation would be more natural
7617: (but probably would take more code and more space to explain).
1.21 crook 7618:
1.26 crook 7619: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
7620: @subsubsection Class Binding
7621: @cindex class binding
7622: @cindex early binding
1.21 crook 7623:
1.26 crook 7624: @cindex late binding
7625: Normal selector invocations determine the method at run-time depending
7626: on the class of the receiving object. This run-time selection is called
1.29 crook 7627: @i{late binding}.
1.21 crook 7628:
1.26 crook 7629: Sometimes it's preferable to invoke a different method. For example,
7630: you might want to use the simple method for @code{print}ing
7631: @code{object}s instead of the possibly long-winded @code{print} method
7632: of the receiver class. You can achieve this by replacing the invocation
7633: of @code{print} with:
1.21 crook 7634:
1.26 crook 7635: @cindex @code{[bind]} usage
7636: @example
7637: [bind] object print
1.21 crook 7638: @end example
7639:
1.26 crook 7640: @noindent
7641: in compiled code or:
1.21 crook 7642:
1.26 crook 7643: @cindex @code{bind} usage
1.21 crook 7644: @example
1.26 crook 7645: bind object print
1.21 crook 7646: @end example
7647:
1.26 crook 7648: @cindex class binding, alternative to
7649: @noindent
7650: in interpreted code. Alternatively, you can define the method with a
7651: name (e.g., @code{print-object}), and then invoke it through the
7652: name. Class binding is just a (often more convenient) way to achieve
7653: the same effect; it avoids name clutter and allows you to invoke
7654: methods directly without naming them first.
7655:
7656: @cindex superclass binding
7657: @cindex parent class binding
7658: A frequent use of class binding is this: When we define a method
7659: for a selector, we often want the method to do what the selector does
7660: in the parent class, and a little more. There is a special word for
7661: this purpose: @code{[parent]}; @code{[parent]
7662: @emph{selector}} is equivalent to @code{[bind] @emph{parent
7663: selector}}, where @code{@emph{parent}} is the parent
7664: class of the current class. E.g., a method definition might look like:
1.21 crook 7665:
1.26 crook 7666: @cindex @code{[parent]} usage
1.21 crook 7667: @example
1.26 crook 7668: :noname
7669: dup [parent] foo \ do parent's foo on the receiving object
7670: ... \ do some more
7671: ; overrides foo
1.21 crook 7672: @end example
7673:
1.26 crook 7674: @cindex class binding as optimization
7675: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
7676: March 1997), Andrew McKewan presents class binding as an optimization
7677: technique. I recommend not using it for this purpose unless you are in
7678: an emergency. Late binding is pretty fast with this model anyway, so the
7679: benefit of using class binding is small; the cost of using class binding
7680: where it is not appropriate is reduced maintainability.
1.21 crook 7681:
1.26 crook 7682: While we are at programming style questions: You should bind
7683: selectors only to ancestor classes of the receiving object. E.g., say,
7684: you know that the receiving object is of class @code{foo} or its
7685: descendents; then you should bind only to @code{foo} and its
7686: ancestors.
1.21 crook 7687:
1.26 crook 7688: @node Method conveniences, Classes and Scoping, Class Binding, Objects
7689: @subsubsection Method conveniences
7690: @cindex method conveniences
1.1 anton 7691:
1.26 crook 7692: In a method you usually access the receiving object pretty often. If
7693: you define the method as a plain colon definition (e.g., with
7694: @code{:noname}), you may have to do a lot of stack
7695: gymnastics. To avoid this, you can define the method with @code{m:
7696: ... ;m}. E.g., you could define the method for
7697: @code{draw}ing a @code{circle} with
1.20 pazsan 7698:
1.26 crook 7699: @cindex @code{this} usage
7700: @cindex @code{m:} usage
7701: @cindex @code{;m} usage
7702: @example
7703: m: ( x y circle -- )
7704: ( x y ) this circle-radius @@ draw-circle ;m
7705: @end example
1.20 pazsan 7706:
1.26 crook 7707: @cindex @code{exit} in @code{m: ... ;m}
7708: @cindex @code{exitm} discussion
7709: @cindex @code{catch} in @code{m: ... ;m}
7710: When this method is executed, the receiver object is removed from the
7711: stack; you can access it with @code{this} (admittedly, in this
7712: example the use of @code{m: ... ;m} offers no advantage). Note
7713: that I specify the stack effect for the whole method (i.e. including
7714: the receiver object), not just for the code between @code{m:}
7715: and @code{;m}. You cannot use @code{exit} in
7716: @code{m:...;m}; instead, use
7717: @code{exitm}.@footnote{Moreover, for any word that calls
7718: @code{catch} and was defined before loading
7719: @code{objects.fs}, you have to redefine it like I redefined
7720: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20 pazsan 7721:
1.26 crook 7722: @cindex @code{inst-var} usage
7723: You will frequently use sequences of the form @code{this
7724: @emph{field}} (in the example above: @code{this
7725: circle-radius}). If you use the field only in this way, you can
7726: define it with @code{inst-var} and eliminate the
7727: @code{this} before the field name. E.g., the @code{circle}
7728: class above could also be defined with:
1.20 pazsan 7729:
1.26 crook 7730: @example
7731: graphical class
7732: cell% inst-var radius
1.20 pazsan 7733:
1.26 crook 7734: m: ( x y circle -- )
7735: radius @@ draw-circle ;m
7736: overrides draw
1.20 pazsan 7737:
1.26 crook 7738: m: ( n-radius circle -- )
7739: radius ! ;m
7740: overrides construct
1.12 anton 7741:
1.26 crook 7742: end-class circle
7743: @end example
1.12 anton 7744:
1.26 crook 7745: @code{radius} can only be used in @code{circle} and its
7746: descendent classes and inside @code{m:...;m}.
1.12 anton 7747:
1.26 crook 7748: @cindex @code{inst-value} usage
7749: You can also define fields with @code{inst-value}, which is
7750: to @code{inst-var} what @code{value} is to
7751: @code{variable}. You can change the value of such a field with
7752: @code{[to-inst]}. E.g., we could also define the class
7753: @code{circle} like this:
1.12 anton 7754:
1.26 crook 7755: @example
7756: graphical class
7757: inst-value radius
1.12 anton 7758:
1.26 crook 7759: m: ( x y circle -- )
7760: radius draw-circle ;m
7761: overrides draw
1.12 anton 7762:
1.26 crook 7763: m: ( n-radius circle -- )
7764: [to-inst] radius ;m
7765: overrides construct
1.21 crook 7766:
1.26 crook 7767: end-class circle
1.12 anton 7768: @end example
7769:
7770:
1.26 crook 7771: @node Classes and Scoping, Object Interfaces, Method conveniences, Objects
7772: @subsubsection Classes and Scoping
7773: @cindex classes and scoping
7774: @cindex scoping and classes
1.12 anton 7775:
1.26 crook 7776: Inheritance is frequent, unlike structure extension. This exacerbates
7777: the problem with the field name convention (@pxref{Structure Naming
7778: Convention}): One always has to remember in which class the field was
7779: originally defined; changing a part of the class structure would require
7780: changes for renaming in otherwise unaffected code.
1.12 anton 7781:
1.26 crook 7782: @cindex @code{inst-var} visibility
7783: @cindex @code{inst-value} visibility
7784: To solve this problem, I added a scoping mechanism (which was not in my
7785: original charter): A field defined with @code{inst-var} (or
7786: @code{inst-value}) is visible only in the class where it is defined and in
7787: the descendent classes of this class. Using such fields only makes
7788: sense in @code{m:}-defined methods in these classes anyway.
1.12 anton 7789:
1.26 crook 7790: This scoping mechanism allows us to use the unadorned field name,
7791: because name clashes with unrelated words become much less likely.
1.12 anton 7792:
1.26 crook 7793: @cindex @code{protected} discussion
7794: @cindex @code{private} discussion
7795: Once we have this mechanism, we can also use it for controlling the
7796: visibility of other words: All words defined after
7797: @code{protected} are visible only in the current class and its
7798: descendents. @code{public} restores the compilation
7799: (i.e. @code{current}) word list that was in effect before. If you
7800: have several @code{protected}s without an intervening
7801: @code{public} or @code{set-current}, @code{public}
7802: will restore the compilation word list in effect before the first of
7803: these @code{protected}s.
1.12 anton 7804:
1.26 crook 7805: @node Object Interfaces, Objects Implementation, Classes and Scoping, Objects
7806: @subsubsection Object Interfaces
7807: @cindex object interfaces
7808: @cindex interfaces for objects
1.12 anton 7809:
1.26 crook 7810: In this model you can only call selectors defined in the class of the
7811: receiving objects or in one of its ancestors. If you call a selector
7812: with a receiving object that is not in one of these classes, the
7813: result is undefined; if you are lucky, the program crashes
7814: immediately.
1.12 anton 7815:
1.26 crook 7816: @cindex selectors common to hardly-related classes
7817: Now consider the case when you want to have a selector (or several)
7818: available in two classes: You would have to add the selector to a
7819: common ancestor class, in the worst case to @code{object}. You
7820: may not want to do this, e.g., because someone else is responsible for
7821: this ancestor class.
1.12 anton 7822:
1.26 crook 7823: The solution for this problem is interfaces. An interface is a
7824: collection of selectors. If a class implements an interface, the
7825: selectors become available to the class and its descendents. A class
7826: can implement an unlimited number of interfaces. For the problem
7827: discussed above, we would define an interface for the selector(s), and
7828: both classes would implement the interface.
1.12 anton 7829:
1.26 crook 7830: As an example, consider an interface @code{storage} for
7831: writing objects to disk and getting them back, and a class
7832: @code{foo} that implements it. The code would look like this:
1.12 anton 7833:
1.26 crook 7834: @cindex @code{interface} usage
7835: @cindex @code{end-interface} usage
7836: @cindex @code{implementation} usage
7837: @example
7838: interface
7839: selector write ( file object -- )
7840: selector read1 ( file object -- )
7841: end-interface storage
1.12 anton 7842:
1.26 crook 7843: bar class
7844: storage implementation
1.12 anton 7845:
1.26 crook 7846: ... overrides write
7847: ... overrides read
7848: ...
7849: end-class foo
1.12 anton 7850: @end example
7851:
1.26 crook 7852: @noindent
1.29 crook 7853: (I would add a word @code{read} @i{( file -- object )} that uses
1.26 crook 7854: @code{read1} internally, but that's beyond the point illustrated
7855: here.)
1.12 anton 7856:
1.26 crook 7857: Note that you cannot use @code{protected} in an interface; and
7858: of course you cannot define fields.
1.12 anton 7859:
1.26 crook 7860: In the Neon model, all selectors are available for all classes;
7861: therefore it does not need interfaces. The price you pay in this model
7862: is slower late binding, and therefore, added complexity to avoid late
7863: binding.
1.12 anton 7864:
1.26 crook 7865: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
7866: @subsubsection @file{objects.fs} Implementation
7867: @cindex @file{objects.fs} implementation
1.12 anton 7868:
1.26 crook 7869: @cindex @code{object-map} discussion
7870: An object is a piece of memory, like one of the data structures
7871: described with @code{struct...end-struct}. It has a field
7872: @code{object-map} that points to the method map for the object's
7873: class.
1.12 anton 7874:
1.26 crook 7875: @cindex method map
7876: @cindex virtual function table
7877: The @emph{method map}@footnote{This is Self terminology; in C++
7878: terminology: virtual function table.} is an array that contains the
1.29 crook 7879: execution tokens (@i{xt}s) of the methods for the object's class. Each
1.26 crook 7880: selector contains an offset into a method map.
1.12 anton 7881:
1.26 crook 7882: @cindex @code{selector} implementation, class
7883: @code{selector} is a defining word that uses
7884: @code{CREATE} and @code{DOES>}. The body of the
7885: selector contains the offset; the @code{does>} action for a
7886: class selector is, basically:
1.21 crook 7887:
1.26 crook 7888: @example
7889: ( object addr ) @@ over object-map @@ + @@ execute
7890: @end example
1.12 anton 7891:
1.26 crook 7892: Since @code{object-map} is the first field of the object, it
7893: does not generate any code. As you can see, calling a selector has a
7894: small, constant cost.
1.12 anton 7895:
1.26 crook 7896: @cindex @code{current-interface} discussion
7897: @cindex class implementation and representation
7898: A class is basically a @code{struct} combined with a method
7899: map. During the class definition the alignment and size of the class
7900: are passed on the stack, just as with @code{struct}s, so
7901: @code{field} can also be used for defining class
7902: fields. However, passing more items on the stack would be
7903: inconvenient, so @code{class} builds a data structure in memory,
7904: which is accessed through the variable
7905: @code{current-interface}. After its definition is complete, the
7906: class is represented on the stack by a pointer (e.g., as parameter for
7907: a child class definition).
1.1 anton 7908:
1.26 crook 7909: A new class starts off with the alignment and size of its parent,
7910: and a copy of the parent's method map. Defining new fields extends the
7911: size and alignment; likewise, defining new selectors extends the
1.29 crook 7912: method map. @code{overrides} just stores a new @i{xt} in the method
1.26 crook 7913: map at the offset given by the selector.
1.20 pazsan 7914:
1.26 crook 7915: @cindex class binding, implementation
1.29 crook 7916: Class binding just gets the @i{xt} at the offset given by the selector
1.26 crook 7917: from the class's method map and @code{compile,}s (in the case of
7918: @code{[bind]}) it.
1.21 crook 7919:
1.26 crook 7920: @cindex @code{this} implementation
7921: @cindex @code{catch} and @code{this}
7922: @cindex @code{this} and @code{catch}
7923: I implemented @code{this} as a @code{value}. At the
7924: start of an @code{m:...;m} method the old @code{this} is
7925: stored to the return stack and restored at the end; and the object on
7926: the TOS is stored @code{TO this}. This technique has one
7927: disadvantage: If the user does not leave the method via
7928: @code{;m}, but via @code{throw} or @code{exit},
7929: @code{this} is not restored (and @code{exit} may
7930: crash). To deal with the @code{throw} problem, I have redefined
7931: @code{catch} to save and restore @code{this}; the same
7932: should be done with any word that can catch an exception. As for
7933: @code{exit}, I simply forbid it (as a replacement, there is
7934: @code{exitm}).
1.21 crook 7935:
1.26 crook 7936: @cindex @code{inst-var} implementation
7937: @code{inst-var} is just the same as @code{field}, with
7938: a different @code{DOES>} action:
7939: @example
7940: @@ this +
7941: @end example
7942: Similar for @code{inst-value}.
1.21 crook 7943:
1.26 crook 7944: @cindex class scoping implementation
7945: Each class also has a word list that contains the words defined with
7946: @code{inst-var} and @code{inst-value}, and its protected
7947: words. It also has a pointer to its parent. @code{class} pushes
7948: the word lists of the class and all its ancestors onto the search order stack,
7949: and @code{end-class} drops them.
1.21 crook 7950:
1.26 crook 7951: @cindex interface implementation
7952: An interface is like a class without fields, parent and protected
7953: words; i.e., it just has a method map. If a class implements an
7954: interface, its method map contains a pointer to the method map of the
7955: interface. The positive offsets in the map are reserved for class
7956: methods, therefore interface map pointers have negative
7957: offsets. Interfaces have offsets that are unique throughout the
7958: system, unlike class selectors, whose offsets are only unique for the
7959: classes where the selector is available (invokable).
1.21 crook 7960:
1.26 crook 7961: This structure means that interface selectors have to perform one
7962: indirection more than class selectors to find their method. Their body
7963: contains the interface map pointer offset in the class method map, and
7964: the method offset in the interface method map. The
7965: @code{does>} action for an interface selector is, basically:
1.21 crook 7966:
7967: @example
1.26 crook 7968: ( object selector-body )
7969: 2dup selector-interface @@ ( object selector-body object interface-offset )
7970: swap object-map @@ + @@ ( object selector-body map )
7971: swap selector-offset @@ + @@ execute
1.21 crook 7972: @end example
7973:
1.26 crook 7974: where @code{object-map} and @code{selector-offset} are
7975: first fields and generate no code.
7976:
7977: As a concrete example, consider the following code:
1.21 crook 7978:
1.26 crook 7979: @example
7980: interface
7981: selector if1sel1
7982: selector if1sel2
7983: end-interface if1
1.21 crook 7984:
1.26 crook 7985: object class
7986: if1 implementation
7987: selector cl1sel1
7988: cell% inst-var cl1iv1
1.21 crook 7989:
1.26 crook 7990: ' m1 overrides construct
7991: ' m2 overrides if1sel1
7992: ' m3 overrides if1sel2
7993: ' m4 overrides cl1sel2
7994: end-class cl1
1.21 crook 7995:
1.26 crook 7996: create obj1 object dict-new drop
7997: create obj2 cl1 dict-new drop
7998: @end example
1.21 crook 7999:
1.26 crook 8000: The data structure created by this code (including the data structure
8001: for @code{object}) is shown in the <a
8002: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.29 crook 8003: @comment TODO add this diagram..
1.21 crook 8004:
1.26 crook 8005: @node Objects Glossary, , Objects Implementation, Objects
8006: @subsubsection @file{objects.fs} Glossary
8007: @cindex @file{objects.fs} Glossary
1.21 crook 8008:
1.26 crook 8009: doc---objects-bind
8010: doc---objects-<bind>
8011: doc---objects-bind'
8012: doc---objects-[bind]
8013: doc---objects-class
8014: doc---objects-class->map
8015: doc---objects-class-inst-size
8016: doc---objects-class-override!
8017: doc---objects-construct
8018: doc---objects-current'
8019: doc---objects-[current]
8020: doc---objects-current-interface
8021: doc---objects-dict-new
8022: doc---objects-drop-order
8023: doc---objects-end-class
8024: doc---objects-end-class-noname
8025: doc---objects-end-interface
8026: doc---objects-end-interface-noname
8027: doc---objects-exitm
8028: doc---objects-heap-new
8029: doc---objects-implementation
8030: doc---objects-init-object
8031: doc---objects-inst-value
8032: doc---objects-inst-var
8033: doc---objects-interface
8034: doc---objects-;m
8035: doc---objects-m:
8036: doc---objects-method
8037: doc---objects-object
8038: doc---objects-overrides
8039: doc---objects-[parent]
8040: doc---objects-print
8041: doc---objects-protected
8042: doc---objects-public
8043: doc---objects-push-order
8044: doc---objects-selector
8045: doc---objects-this
8046: doc---objects-<to-inst>
8047: doc---objects-[to-inst]
8048: doc---objects-to-this
8049: doc---objects-xt-new
1.21 crook 8050:
1.26 crook 8051: @c -------------------------------------------------------------
8052: @node OOF, Mini-OOF, Objects, Object-oriented Forth
8053: @subsection The @file{oof.fs} model
8054: @cindex oof
8055: @cindex object-oriented programming
1.21 crook 8056:
1.26 crook 8057: @cindex @file{objects.fs}
8058: @cindex @file{oof.fs}
1.21 crook 8059:
1.26 crook 8060: This section describes the @file{oof.fs} package.
1.21 crook 8061:
1.26 crook 8062: The package described in this section has been used in bigFORTH since 1991, and
8063: used for two large applications: a chromatographic system used to
8064: create new medicaments, and a graphic user interface library (MINOS).
1.21 crook 8065:
1.26 crook 8066: You can find a description (in German) of @file{oof.fs} in @cite{Object
8067: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
8068: 10(2), 1994.
1.21 crook 8069:
1.26 crook 8070: @menu
8071: * Properties of the OOF model::
8072: * Basic OOF Usage::
8073: * The OOF base class::
8074: * Class Declaration::
8075: * Class Implementation::
8076: @end menu
1.21 crook 8077:
1.26 crook 8078: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
8079: @subsubsection Properties of the @file{oof.fs} model
8080: @cindex @file{oof.fs} properties
1.21 crook 8081:
1.26 crook 8082: @itemize @bullet
8083: @item
8084: This model combines object oriented programming with information
8085: hiding. It helps you writing large application, where scoping is
8086: necessary, because it provides class-oriented scoping.
1.21 crook 8087:
1.26 crook 8088: @item
8089: Named objects, object pointers, and object arrays can be created,
8090: selector invocation uses the ``object selector'' syntax. Selector invocation
8091: to objects and/or selectors on the stack is a bit less convenient, but
8092: possible.
1.21 crook 8093:
1.26 crook 8094: @item
8095: Selector invocation and instance variable usage of the active object is
8096: straightforward, since both make use of the active object.
1.21 crook 8097:
1.26 crook 8098: @item
8099: Late binding is efficient and easy to use.
1.21 crook 8100:
1.26 crook 8101: @item
8102: State-smart objects parse selectors. However, extensibility is provided
8103: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21 crook 8104:
8105: @item
1.26 crook 8106: An implementation in ANS Forth is available.
8107:
1.21 crook 8108: @end itemize
8109:
8110:
1.26 crook 8111: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
8112: @subsubsection Basic @file{oof.fs} Usage
8113: @cindex @file{oof.fs} usage
8114:
8115: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21 crook 8116:
1.26 crook 8117: You can define a class for graphical objects like this:
1.21 crook 8118:
1.26 crook 8119: @cindex @code{class} usage
8120: @cindex @code{class;} usage
8121: @cindex @code{method} usage
8122: @example
8123: object class graphical \ "object" is the parent class
8124: method draw ( x y graphical -- )
8125: class;
8126: @end example
1.21 crook 8127:
1.26 crook 8128: This code defines a class @code{graphical} with an
8129: operation @code{draw}. We can perform the operation
8130: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 8131:
1.26 crook 8132: @example
8133: 100 100 t-rex draw
8134: @end example
1.21 crook 8135:
1.26 crook 8136: @noindent
8137: where @code{t-rex} is an object or object pointer, created with e.g.
8138: @code{graphical : t-rex}.
1.21 crook 8139:
1.26 crook 8140: @cindex abstract class
8141: How do we create a graphical object? With the present definitions,
8142: we cannot create a useful graphical object. The class
8143: @code{graphical} describes graphical objects in general, but not
8144: any concrete graphical object type (C++ users would call it an
8145: @emph{abstract class}); e.g., there is no method for the selector
8146: @code{draw} in the class @code{graphical}.
1.21 crook 8147:
1.26 crook 8148: For concrete graphical objects, we define child classes of the
8149: class @code{graphical}, e.g.:
1.21 crook 8150:
8151: @example
1.26 crook 8152: graphical class circle \ "graphical" is the parent class
8153: cell var circle-radius
8154: how:
8155: : draw ( x y -- )
8156: circle-radius @@ draw-circle ;
8157:
8158: : init ( n-radius -- (
8159: circle-radius ! ;
8160: class;
8161: @end example
8162:
8163: Here we define a class @code{circle} as a child of @code{graphical},
8164: with a field @code{circle-radius}; it defines new methods for the
8165: selectors @code{draw} and @code{init} (@code{init} is defined in
8166: @code{object}, the parent class of @code{graphical}).
1.21 crook 8167:
1.26 crook 8168: Now we can create a circle in the dictionary with:
1.21 crook 8169:
1.26 crook 8170: @example
8171: 50 circle : my-circle
1.21 crook 8172: @end example
8173:
1.26 crook 8174: @noindent
8175: @code{:} invokes @code{init}, thus initializing the field
8176: @code{circle-radius} with 50. We can draw this new circle at (100,100)
8177: with:
1.21 crook 8178:
8179: @example
1.26 crook 8180: 100 100 my-circle draw
1.21 crook 8181: @end example
8182:
1.26 crook 8183: @cindex selector invocation, restrictions
8184: @cindex class definition, restrictions
8185: Note: You can only invoke a selector if the receiving object belongs to
8186: the class where the selector was defined or one of its descendents;
8187: e.g., you can invoke @code{draw} only for objects belonging to
8188: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
8189: mechanism will check if you try to invoke a selector that is not
8190: defined in this class hierarchy, so you'll get an error at compilation
8191: time.
8192:
8193:
8194: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
8195: @subsubsection The @file{oof.fs} base class
8196: @cindex @file{oof.fs} base class
8197:
8198: When you define a class, you have to specify a parent class. So how do
8199: you start defining classes? There is one class available from the start:
8200: @code{object}. You have to use it as ancestor for all classes. It is the
8201: only class that has no parent. Classes are also objects, except that
8202: they don't have instance variables; class manipulation such as
8203: inheritance or changing definitions of a class is handled through
8204: selectors of the class @code{object}.
8205:
8206: @code{object} provides a number of selectors:
8207:
1.21 crook 8208: @itemize @bullet
8209: @item
1.26 crook 8210: @code{class} for subclassing, @code{definitions} to add definitions
8211: later on, and @code{class?} to get type informations (is the class a
8212: subclass of the class passed on the stack?).
8213: doc---object-class
8214: doc---object-definitions
8215: doc---object-class?
8216:
1.21 crook 8217: @item
1.26 crook 8218: @code{init} and @code{dispose} as constructor and destructor of the
8219: object. @code{init} is invocated after the object's memory is allocated,
8220: while @code{dispose} also handles deallocation. Thus if you redefine
8221: @code{dispose}, you have to call the parent's dispose with @code{super
8222: dispose}, too.
8223: doc---object-init
8224: doc---object-dispose
8225:
1.21 crook 8226: @item
1.26 crook 8227: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
8228: @code{[]} to create named and unnamed objects and object arrays or
8229: object pointers.
8230: doc---object-new
8231: doc---object-new[]
8232: doc---object-:
8233: doc---object-ptr
8234: doc---object-asptr
8235: doc---object-[]
1.21 crook 8236:
1.26 crook 8237: @item
8238: @code{::} and @code{super} for explicit scoping. You should use explicit
8239: scoping only for super classes or classes with the same set of instance
8240: variables. Explicitly-scoped selectors use early binding.
8241: doc---object-::
8242: doc---object-super
1.21 crook 8243:
1.26 crook 8244: @item
8245: @code{self} to get the address of the object
8246: doc---object-self
1.21 crook 8247:
8248: @item
1.26 crook 8249: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
8250: pointers and instance defers.
8251: doc---object-bind
8252: doc---object-bound
8253: doc---object-link
8254: doc---object-is
8255:
1.21 crook 8256: @item
1.26 crook 8257: @code{'} to obtain selector tokens, @code{send} to invocate selectors
8258: form the stack, and @code{postpone} to generate selector invocation code.
8259: doc---object-'
8260: doc---object-postpone
8261:
1.21 crook 8262: @item
1.26 crook 8263: @code{with} and @code{endwith} to select the active object from the
8264: stack, and enable its scope. Using @code{with} and @code{endwith}
8265: also allows you to create code using selector @code{postpone} without being
8266: trapped by the state-smart objects.
8267: doc---object-with
8268: doc---object-endwith
8269:
1.21 crook 8270: @end itemize
8271:
1.26 crook 8272: @node Class Declaration, Class Implementation, The OOF base class, OOF
8273: @subsubsection Class Declaration
8274: @cindex class declaration
8275:
8276: @itemize @bullet
8277: @item
8278: Instance variables
8279: doc---oof-var
1.21 crook 8280:
1.26 crook 8281: @item
8282: Object pointers
8283: doc---oof-ptr
8284: doc---oof-asptr
1.21 crook 8285:
1.26 crook 8286: @item
8287: Instance defers
8288: doc---oof-defer
1.21 crook 8289:
1.26 crook 8290: @item
8291: Method selectors
8292: doc---oof-early
8293: doc---oof-method
1.21 crook 8294:
1.26 crook 8295: @item
8296: Class-wide variables
8297: doc---oof-static
1.21 crook 8298:
1.26 crook 8299: @item
8300: End declaration
8301: doc---oof-how:
8302: doc---oof-class;
1.21 crook 8303:
1.26 crook 8304: @end itemize
1.21 crook 8305:
1.26 crook 8306: @c -------------------------------------------------------------
8307: @node Class Implementation, , Class Declaration, OOF
8308: @subsubsection Class Implementation
8309: @cindex class implementation
1.21 crook 8310:
1.26 crook 8311: @c -------------------------------------------------------------
8312: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
8313: @subsection The @file{mini-oof.fs} model
8314: @cindex mini-oof
1.1 anton 8315:
1.26 crook 8316: Gforth's third object oriented Forth package is a 12-liner. It uses a
8317: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
8318: and reduces to the bare minimum of features. This is based on a posting
8319: of Bernd Paysan in comp.arch.
1.1 anton 8320:
8321: @menu
1.26 crook 8322: * Basic Mini-OOF Usage::
8323: * Mini-OOF Example::
8324: * Mini-OOF Implementation::
1.1 anton 8325: @end menu
8326:
1.26 crook 8327: @c -------------------------------------------------------------
8328: @node Basic Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
8329: @subsubsection Basic @file{mini-oof.fs} Usage
8330: @cindex mini-oof usage
1.1 anton 8331:
1.28 crook 8332: There is a base class (@code{class}, which allocates one cell for the
8333: object pointer) plus seven other words: to define a method, a variable,
8334: a class; to end a class, to resolve binding, to allocate an object and
8335: to compile a class method.
1.26 crook 8336: @comment TODO better description of the last one
1.1 anton 8337:
1.26 crook 8338: doc-object
8339: doc-method
8340: doc-var
8341: doc-class
8342: doc-end-class
8343: doc-defines
8344: doc-new
8345: doc-::
1.1 anton 8346:
1.21 crook 8347:
1.26 crook 8348: @c -------------------------------------------------------------
8349: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
8350: @subsubsection Mini-OOF Example
8351: @cindex mini-oof example
1.21 crook 8352:
1.26 crook 8353: A short example shows how to use this package. This example, in slightly
8354: extended form, is supplied as @file{moof-exm.fs}
1.29 crook 8355: @comment TODO could flesh this out with some comments from the Forthwrite article
1.21 crook 8356:
1.26 crook 8357: @example
8358: object class
8359: method init
8360: method draw
8361: end-class graphical
8362: @end example
1.21 crook 8363:
1.26 crook 8364: This code defines a class @code{graphical} with an
8365: operation @code{draw}. We can perform the operation
8366: @code{draw} on any @code{graphical} object, e.g.:
1.1 anton 8367:
1.26 crook 8368: @example
8369: 100 100 t-rex draw
8370: @end example
1.1 anton 8371:
1.26 crook 8372: where @code{t-rex} is an object or object pointer, created with e.g.
8373: @code{graphical new Constant t-rex}.
1.1 anton 8374:
1.26 crook 8375: For concrete graphical objects, we define child classes of the
8376: class @code{graphical}, e.g.:
1.21 crook 8377:
8378: @example
1.26 crook 8379: graphical class
8380: cell var circle-radius
8381: end-class circle \ "graphical" is the parent class
1.21 crook 8382:
1.26 crook 8383: :noname ( x y -- )
8384: circle-radius @@ draw-circle ; circle defines draw
8385: :noname ( r -- )
8386: circle-radius ! ; circle defines init
1.21 crook 8387: @end example
8388:
1.26 crook 8389: There is no implicit init method, so we have to define one. The creation
8390: code of the object now has to call init explicitely.
1.21 crook 8391:
1.26 crook 8392: @example
8393: circle new Constant my-circle
8394: 50 my-circle init
8395: @end example
1.21 crook 8396:
1.26 crook 8397: It is also possible to add a function to create named objects with
8398: automatic call of @code{init}, given that all objects have @code{init}
8399: on the same place:
1.1 anton 8400:
8401: @example
1.26 crook 8402: : new: ( .. o "name" -- )
8403: new dup Constant init ;
8404: 80 circle new: large-circle
1.1 anton 8405: @end example
8406:
1.26 crook 8407: We can draw this new circle at (100,100) with:
1.1 anton 8408:
8409: @example
1.26 crook 8410: 100 100 my-circle draw
1.1 anton 8411: @end example
8412:
1.26 crook 8413: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
8414: @subsubsection @file{mini-oof.fs} Implementation
1.1 anton 8415:
1.26 crook 8416: Object-oriented systems with late binding typically use a
8417: ``vtable''-approach: the first variable in each object is a pointer to a
8418: table, which contains the methods as function pointers. The vtable
8419: may also contain other information.
1.1 anton 8420:
1.26 crook 8421: So first, let's declare methods:
1.1 anton 8422:
1.26 crook 8423: @example
8424: : method ( m v -- m' v ) Create over , swap cell+ swap
8425: DOES> ( ... o -- ... ) @ over @ + @ execute ;
8426: @end example
1.1 anton 8427:
1.26 crook 8428: During method declaration, the number of methods and instance
8429: variables is on the stack (in address units). @code{method} creates
8430: one method and increments the method number. To execute a method, it
8431: takes the object, fetches the vtable pointer, adds the offset, and
1.29 crook 8432: executes the @i{xt} stored there. Each method takes the object it is
1.26 crook 8433: invoked from as top of stack parameter. The method itself should
8434: consume that object.
1.1 anton 8435:
1.26 crook 8436: Now, we also have to declare instance variables
1.21 crook 8437:
1.26 crook 8438: @example
8439: : var ( m v size -- m v' ) Create over , +
8440: DOES> ( o -- addr ) @ + ;
8441: @end example
1.21 crook 8442:
1.26 crook 8443: As before, a word is created with the current offset. Instance
8444: variables can have different sizes (cells, floats, doubles, chars), so
8445: all we do is take the size and add it to the offset. If your machine
8446: has alignment restrictions, put the proper @code{aligned} or
8447: @code{faligned} before the variable, to adjust the variable
8448: offset. That's why it is on the top of stack.
1.2 jwilke 8449:
1.26 crook 8450: We need a starting point (the base object) and some syntactic sugar:
1.21 crook 8451:
1.26 crook 8452: @example
8453: Create object 1 cells , 2 cells ,
8454: : class ( class -- class methods vars ) dup 2@ ;
8455: @end example
1.21 crook 8456:
1.26 crook 8457: For inheritance, the vtable of the parent object has to be
8458: copied when a new, derived class is declared. This gives all the
8459: methods of the parent class, which can be overridden, though.
1.21 crook 8460:
1.2 jwilke 8461: @example
1.26 crook 8462: : end-class ( class methods vars -- )
8463: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
8464: cell+ dup cell+ r> rot @ 2 cells /string move ;
8465: @end example
8466:
8467: The first line creates the vtable, initialized with
8468: @code{noop}s. The second line is the inheritance mechanism, it
8469: copies the xts from the parent vtable.
1.2 jwilke 8470:
1.26 crook 8471: We still have no way to define new methods, let's do that now:
1.2 jwilke 8472:
1.26 crook 8473: @example
8474: : defines ( xt class -- ) ' >body @ + ! ;
1.2 jwilke 8475: @end example
8476:
1.26 crook 8477: To allocate a new object, we need a word, too:
1.2 jwilke 8478:
1.26 crook 8479: @example
8480: : new ( class -- o ) here over @ allot swap over ! ;
8481: @end example
1.2 jwilke 8482:
1.26 crook 8483: Sometimes derived classes want to access the method of the
8484: parent object. There are two ways to achieve this with Mini-OOF:
8485: first, you could use named words, and second, you could look up the
8486: vtable of the parent object.
1.2 jwilke 8487:
1.26 crook 8488: @example
8489: : :: ( class "name" -- ) ' >body @ + @ compile, ;
8490: @end example
1.2 jwilke 8491:
8492:
1.26 crook 8493: Nothing can be more confusing than a good example, so here is
8494: one. First let's declare a text object (called
8495: @code{button}), that stores text and position:
1.2 jwilke 8496:
1.26 crook 8497: @example
8498: object class
8499: cell var text
8500: cell var len
8501: cell var x
8502: cell var y
8503: method init
8504: method draw
8505: end-class button
8506: @end example
1.2 jwilke 8507:
1.26 crook 8508: @noindent
8509: Now, implement the two methods, @code{draw} and @code{init}:
1.2 jwilke 8510:
1.26 crook 8511: @example
8512: :noname ( o -- )
8513: >r r@ x @ r@ y @ at-xy r@ text @ r> len @ type ;
8514: button defines draw
8515: :noname ( addr u o -- )
8516: >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
8517: button defines init
8518: @end example
1.2 jwilke 8519:
1.26 crook 8520: @noindent
8521: To demonstrate inheritance, we define a class @code{bold-button}, with no
8522: new data and no new methods:
1.2 jwilke 8523:
1.26 crook 8524: @example
8525: button class
8526: end-class bold-button
1.1 anton 8527:
1.26 crook 8528: : bold 27 emit ." [1m" ;
8529: : normal 27 emit ." [0m" ;
8530: @end example
1.1 anton 8531:
1.26 crook 8532: @noindent
8533: The class @code{bold-button} has a different draw method to
8534: @code{button}, but the new method is defined in terms of the draw method
8535: for @code{button}:
1.1 anton 8536:
1.26 crook 8537: @example
8538: :noname bold [ button :: draw ] normal ; bold-button defines draw
8539: @end example
1.1 anton 8540:
1.26 crook 8541: @noindent
8542: Finally, create two objects and apply methods:
1.1 anton 8543:
1.26 crook 8544: @example
8545: button new Constant foo
8546: s" thin foo" foo init
8547: page
8548: foo draw
8549: bold-button new Constant bar
8550: s" fat bar" bar init
8551: 1 bar y !
8552: bar draw
8553: @end example
1.1 anton 8554:
8555:
1.26 crook 8556: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
8557: @subsubsection Comparison with other object models
8558: @cindex comparison of object models
8559: @cindex object models, comparison
1.1 anton 8560:
1.26 crook 8561: Many object-oriented Forth extensions have been proposed (@cite{A survey
8562: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
8563: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
8564: relation of the object models described here to two well-known and two
8565: closely-related (by the use of method maps) models.
1.1 anton 8566:
1.26 crook 8567: @cindex Neon model
8568: The most popular model currently seems to be the Neon model (see
8569: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
8570: 1997) by Andrew McKewan) but this model has a number of limitations
8571: @footnote{A longer version of this critique can be
8572: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
8573: Dimensions, May 1997) by Anton Ertl.}:
1.1 anton 8574:
1.26 crook 8575: @itemize @bullet
8576: @item
8577: It uses a @code{@emph{selector
8578: object}} syntax, which makes it unnatural to pass objects on the
8579: stack.
1.1 anton 8580:
1.26 crook 8581: @item
8582: It requires that the selector parses the input stream (at
8583: compile time); this leads to reduced extensibility and to bugs that are+
8584: hard to find.
1.1 anton 8585:
1.26 crook 8586: @item
8587: It allows using every selector to every object;
8588: this eliminates the need for classes, but makes it harder to create
8589: efficient implementations.
8590: @end itemize
1.1 anton 8591:
1.26 crook 8592: @cindex Pountain's object-oriented model
8593: Another well-known publication is @cite{Object-Oriented Forth} (Academic
8594: Press, London, 1987) by Dick Pountain. However, it is not really about
8595: object-oriented programming, because it hardly deals with late
8596: binding. Instead, it focuses on features like information hiding and
8597: overloading that are characteristic of modular languages like Ada (83).
1.1 anton 8598:
1.26 crook 8599: @cindex Zsoter's object-oriented model
8600: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1) 1996, pages 31-35)
8601: Andras Zsoter describes a model that makes heavy use of an active object
8602: (like @code{this} in @file{objects.fs}): The active object is not only
8603: used for accessing all fields, but also specifies the receiving object
8604: of every selector invocation; you have to change the active object
8605: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
8606: changes more or less implicitly at @code{m: ... ;m}. Such a change at
8607: the method entry point is unnecessary with the Zsoter's model, because
8608: the receiving object is the active object already. On the other hand, the explicit
8609: change is absolutely necessary in that model, because otherwise no one
8610: could ever change the active object. An ANS Forth implementation of this
8611: model is available at @url{http://www.forth.org/fig/oopf.html}.
1.1 anton 8612:
1.26 crook 8613: @cindex @file{oof.fs}, differences to other models
8614: The @file{oof.fs} model combines information hiding and overloading
8615: resolution (by keeping names in various word lists) with object-oriented
8616: programming. It sets the active object implicitly on method entry, but
8617: also allows explicit changing (with @code{>o...o>} or with
8618: @code{with...endwith}). It uses parsing and state-smart objects and
8619: classes for resolving overloading and for early binding: the object or
8620: class parses the selector and determines the method from this. If the
8621: selector is not parsed by an object or class, it performs a call to the
8622: selector for the active object (late binding), like Zsoter's model.
8623: Fields are always accessed through the active object. The big
8624: disadvantage of this model is the parsing and the state-smartness, which
8625: reduces extensibility and increases the opportunities for subtle bugs;
8626: essentially, you are only safe if you never tick or @code{postpone} an
8627: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1 anton 8628:
1.26 crook 8629: @cindex @file{mini-oof.fs}, differences to other models
8630: The @file{mini-oof.fs} model is quite similar to a very stripped-down version of
8631: the @file{objects.fs} model, but syntactically it is a mixture of the @file{objects.fs} and
8632: @file{oof.fs} models.
1.1 anton 8633:
1.26 crook 8634: @c -------------------------------------------------------------
8635: @node Passing Commands to the OS, Miscellaneous Words, Object-oriented Forth, Words
1.21 crook 8636: @section Passing Commands to the Operating System
8637: @cindex operating system - passing commands
8638: @cindex shell commands
8639:
8640: Gforth allows you to pass an arbitrary string to the host operating
8641: system shell (if such a thing exists) for execution.
8642:
8643: doc-sh
8644: doc-system
8645: doc-$?
1.23 crook 8646: doc-getenv
1.21 crook 8647:
1.26 crook 8648: @c -------------------------------------------------------------
1.21 crook 8649: @node Miscellaneous Words, , Passing Commands to the OS, Words
8650: @section Miscellaneous Words
8651: @cindex miscellaneous words
8652:
1.29 crook 8653: @comment TODO find homes for these
8654:
1.26 crook 8655: These section lists the ANS Forth words that are not documented
1.21 crook 8656: elsewhere in this manual. Ultimately, they all need proper homes.
8657:
8658: doc-ms
8659: doc-time&date
1.27 crook 8660:
1.21 crook 8661: doc-[compile]
8662:
1.26 crook 8663: The following ANS Forth words are not currently supported by Gforth
1.27 crook 8664: (@pxref{ANS conformance}):
1.21 crook 8665:
8666: @code{EDITOR}
8667: @code{EKEY}
8668: @code{EKEY>CHAR}
8669: @code{EKEY?}
8670: @code{EMIT?}
8671: @code{FORGET}
8672:
1.24 anton 8673: @c ******************************************************************
8674: @node Error messages, Tools, Words, Top
8675: @chapter Error messages
8676: @cindex error messages
8677: @cindex backtrace
8678:
8679: A typical Gforth error message looks like this:
8680:
8681: @example
8682: in file included from :-1
8683: in file included from ./yyy.fs:1
8684: ./xxx.fs:4: Invalid memory address
8685: bar
8686: ^^^
1.25 anton 8687: $400E664C @@
8688: $400E6664 foo
1.24 anton 8689: @end example
8690:
8691: The message identifying the error is @code{Invalid memory address}. The
8692: error happened when text-interpreting line 4 of the file
8693: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
8694: word on the line where the error happened, is pointed out (with
8695: @code{^^^}).
8696:
8697: The file containing the error was included in line 1 of @file{./yyy.fs},
8698: and @file{yyy.fs} was included from a non-file (in this case, by giving
8699: @file{yyy.fs} as command-line parameter to Gforth).
8700:
8701: At the end of the error message you find a return stack dump that can be
8702: interpreted as a backtrace (possibly empty). On top you find the top of
8703: the return stack when the @code{throw} happened, and at the bottom you
8704: find the return stack entry just above the return stack of the topmost
8705: text interpreter.
8706:
8707: To the right of most return stack entries you see a guess for the word
8708: that pushed that return stack entry as its return address. This gives a
8709: backtrace. In our case we see that @code{bar} called @code{foo}, and
8710: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
8711: address} exception).
8712:
8713: Note that the backtrace is not perfect: We don't know which return stack
8714: entries are return addresses (so we may get false positives); and in
8715: some cases (e.g., for @code{abort"}) we cannot determine from the return
8716: address the word that pushed the return address, so for some return
8717: addresses you see no names in the return stack dump.
1.25 anton 8718:
8719: @cindex @code{catch} and backtraces
8720: The return stack dump represents the return stack at the time when a
8721: specific @code{throw} was executed. In programs that make use of
8722: @code{catch}, it is not necessarily clear which @code{throw} should be
8723: used for the return stack dump (e.g., consider one @code{throw} that
8724: indicates an error, which is caught, and during recovery another error
8725: happens; which @code{throw} should be used for the stack dump). Gforth
8726: presents the return stack dump for the first @code{throw} after the last
8727: executed (not returned-to) @code{catch}; this works well in the usual
8728: case.
8729:
8730: @cindex @code{gforth-fast} and backtraces
8731: @cindex @code{gforth-fast}, difference from @code{gforth}
8732: @cindex backtraces with @code{gforth-fast}
8733: @cindex return stack dump with @code{gforth-fast}
8734: @code{gforth} is able to do a return stack dump for throws generated
8735: from primitives (e.g., invalid memory address, stack empty etc.);
8736: @code{gforth-fast} is only able to do a return stack dump from a
8737: directly called @code{throw} (including @code{abort} etc.). This is the
1.30 anton 8738: only difference (apart from a speed factor of between 1.15 (K6-2) and
8739: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}. Given an
8740: exception caused by a primitive in @code{gforth-fast}, you will
8741: typically see no return stack dump at all; however, if the exception is
8742: caught by @code{catch} (e.g., for restoring some state), and then
8743: @code{throw}n again, the return stack dump will be for the first such
8744: @code{throw}.
1.2 jwilke 8745:
1.5 anton 8746: @c ******************************************************************
1.24 anton 8747: @node Tools, ANS conformance, Error messages, Top
1.1 anton 8748: @chapter Tools
8749:
8750: @menu
8751: * ANS Report:: Report the words used, sorted by wordset.
8752: @end menu
8753:
8754: See also @ref{Emacs and Gforth}.
8755:
8756: @node ANS Report, , Tools, Tools
8757: @section @file{ans-report.fs}: Report the words used, sorted by wordset
8758: @cindex @file{ans-report.fs}
8759: @cindex report the words used in your program
8760: @cindex words used in your program
8761:
8762: If you want to label a Forth program as ANS Forth Program, you must
8763: document which wordsets the program uses; for extension wordsets, it is
8764: helpful to list the words the program requires from these wordsets
8765: (because Forth systems are allowed to provide only some words of them).
8766:
8767: The @file{ans-report.fs} tool makes it easy for you to determine which
8768: words from which wordset and which non-ANS words your application
8769: uses. You simply have to include @file{ans-report.fs} before loading the
8770: program you want to check. After loading your program, you can get the
8771: report with @code{print-ans-report}. A typical use is to run this as
8772: batch job like this:
8773: @example
8774: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
8775: @end example
8776:
8777: The output looks like this (for @file{compat/control.fs}):
8778: @example
8779: The program uses the following words
8780: from CORE :
8781: : POSTPONE THEN ; immediate ?dup IF 0=
8782: from BLOCK-EXT :
8783: \
8784: from FILE :
8785: (
8786: @end example
8787:
8788: @subsection Caveats
8789:
8790: Note that @file{ans-report.fs} just checks which words are used, not whether
8791: they are used in an ANS Forth conforming way!
8792:
8793: Some words are defined in several wordsets in the
8794: standard. @file{ans-report.fs} reports them for only one of the
8795: wordsets, and not necessarily the one you expect. It depends on usage
8796: which wordset is the right one to specify. E.g., if you only use the
8797: compilation semantics of @code{S"}, it is a Core word; if you also use
8798: its interpretation semantics, it is a File word.
8799:
8800: @c ******************************************************************
8801: @node ANS conformance, Model, Tools, Top
8802: @chapter ANS conformance
8803: @cindex ANS conformance of Gforth
8804:
8805: To the best of our knowledge, Gforth is an
8806:
8807: ANS Forth System
8808: @itemize @bullet
8809: @item providing the Core Extensions word set
8810: @item providing the Block word set
8811: @item providing the Block Extensions word set
8812: @item providing the Double-Number word set
8813: @item providing the Double-Number Extensions word set
8814: @item providing the Exception word set
8815: @item providing the Exception Extensions word set
8816: @item providing the Facility word set
8817: @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
8818: @item providing the File Access word set
8819: @item providing the File Access Extensions word set
8820: @item providing the Floating-Point word set
8821: @item providing the Floating-Point Extensions word set
8822: @item providing the Locals word set
8823: @item providing the Locals Extensions word set
8824: @item providing the Memory-Allocation word set
8825: @item providing the Memory-Allocation Extensions word set (that one's easy)
8826: @item providing the Programming-Tools word set
8827: @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
8828: @item providing the Search-Order word set
8829: @item providing the Search-Order Extensions word set
8830: @item providing the String word set
8831: @item providing the String Extensions word set (another easy one)
8832: @end itemize
8833:
8834: @cindex system documentation
8835: In addition, ANS Forth systems are required to document certain
8836: implementation choices. This chapter tries to meet these
8837: requirements. In many cases it gives a way to ask the system for the
8838: information instead of providing the information directly, in
8839: particular, if the information depends on the processor, the operating
8840: system or the installation options chosen, or if they are likely to
8841: change during the maintenance of Gforth.
8842:
8843: @comment The framework for the rest has been taken from pfe.
8844:
8845: @menu
8846: * The Core Words::
8847: * The optional Block word set::
8848: * The optional Double Number word set::
8849: * The optional Exception word set::
8850: * The optional Facility word set::
8851: * The optional File-Access word set::
8852: * The optional Floating-Point word set::
8853: * The optional Locals word set::
8854: * The optional Memory-Allocation word set::
8855: * The optional Programming-Tools word set::
8856: * The optional Search-Order word set::
8857: @end menu
8858:
8859:
8860: @c =====================================================================
8861: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
8862: @comment node-name, next, previous, up
8863: @section The Core Words
8864: @c =====================================================================
8865: @cindex core words, system documentation
8866: @cindex system documentation, core words
8867:
8868: @menu
8869: * core-idef:: Implementation Defined Options
8870: * core-ambcond:: Ambiguous Conditions
8871: * core-other:: Other System Documentation
8872: @end menu
8873:
8874: @c ---------------------------------------------------------------------
8875: @node core-idef, core-ambcond, The Core Words, The Core Words
8876: @subsection Implementation Defined Options
8877: @c ---------------------------------------------------------------------
8878: @cindex core words, implementation-defined options
8879: @cindex implementation-defined options, core words
8880:
8881:
8882: @table @i
8883: @item (Cell) aligned addresses:
8884: @cindex cell-aligned addresses
8885: @cindex aligned addresses
8886: processor-dependent. Gforth's alignment words perform natural alignment
8887: (e.g., an address aligned for a datum of size 8 is divisible by
8888: 8). Unaligned accesses usually result in a @code{-23 THROW}.
8889:
8890: @item @code{EMIT} and non-graphic characters:
8891: @cindex @code{EMIT} and non-graphic characters
8892: @cindex non-graphic characters and @code{EMIT}
8893: The character is output using the C library function (actually, macro)
8894: @code{putc}.
8895:
8896: @item character editing of @code{ACCEPT} and @code{EXPECT}:
8897: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
8898: @cindex editing in @code{ACCEPT} and @code{EXPECT}
8899: @cindex @code{ACCEPT}, editing
8900: @cindex @code{EXPECT}, editing
8901: This is modeled on the GNU readline library (@pxref{Readline
8902: Interaction, , Command Line Editing, readline, The GNU Readline
8903: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
8904: producing a full word completion every time you type it (instead of
1.28 crook 8905: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 8906:
8907: @item character set:
8908: @cindex character set
8909: The character set of your computer and display device. Gforth is
8910: 8-bit-clean (but some other component in your system may make trouble).
8911:
8912: @item Character-aligned address requirements:
8913: @cindex character-aligned address requirements
8914: installation-dependent. Currently a character is represented by a C
8915: @code{unsigned char}; in the future we might switch to @code{wchar_t}
8916: (Comments on that requested).
8917:
8918: @item character-set extensions and matching of names:
8919: @cindex character-set extensions and matching of names
1.26 crook 8920: @cindex case-sensitivity for name lookup
8921: @cindex name lookup, case-sensitivity
8922: @cindex locale and case-sensitivity
1.21 crook 8923: Any character except the ASCII NUL character can be used in a
1.1 anton 8924: name. Matching is case-insensitive (except in @code{TABLE}s). The
8925: matching is performed using the C function @code{strncasecmp}, whose
8926: function is probably influenced by the locale. E.g., the @code{C} locale
8927: does not know about accents and umlauts, so they are matched
8928: case-sensitively in that locale. For portability reasons it is best to
8929: write programs such that they work in the @code{C} locale. Then one can
8930: use libraries written by a Polish programmer (who might use words
8931: containing ISO Latin-2 encoded characters) and by a French programmer
8932: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
8933: funny results for some of the words (which ones, depends on the font you
8934: are using)). Also, the locale you prefer may not be available in other
8935: operating systems. Hopefully, Unicode will solve these problems one day.
8936:
8937: @item conditions under which control characters match a space delimiter:
8938: @cindex space delimiters
8939: @cindex control characters as delimiters
8940: If @code{WORD} is called with the space character as a delimiter, all
8941: white-space characters (as identified by the C macro @code{isspace()})
8942: are delimiters. @code{PARSE}, on the other hand, treats space like other
8943: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
8944: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
8945: interpreter (aka text interpreter) by default, treats all white-space
8946: characters as delimiters.
8947:
1.26 crook 8948: @item format of the control-flow stack:
8949: @cindex control-flow stack, format
8950: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 8951: stack item in cells is given by the constant @code{cs-item-size}. At the
8952: time of this writing, an item consists of a (pointer to a) locals list
8953: (third), an address in the code (second), and a tag for identifying the
8954: item (TOS). The following tags are used: @code{defstart},
8955: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
8956: @code{scopestart}.
8957:
8958: @item conversion of digits > 35
8959: @cindex digits > 35
8960: The characters @code{[\]^_'} are the digits with the decimal value
8961: 36@minus{}41. There is no way to input many of the larger digits.
8962:
8963: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
8964: @cindex @code{EXPECT}, display after end of input
8965: @cindex @code{ACCEPT}, display after end of input
8966: The cursor is moved to the end of the entered string. If the input is
8967: terminated using the @kbd{Return} key, a space is typed.
8968:
8969: @item exception abort sequence of @code{ABORT"}:
8970: @cindex exception abort sequence of @code{ABORT"}
8971: @cindex @code{ABORT"}, exception abort sequence
8972: The error string is stored into the variable @code{"error} and a
8973: @code{-2 throw} is performed.
8974:
8975: @item input line terminator:
8976: @cindex input line terminator
8977: @cindex line terminator on input
1.26 crook 8978: @cindex newline character on input
1.1 anton 8979: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
8980: lines. One of these characters is typically produced when you type the
8981: @kbd{Enter} or @kbd{Return} key.
8982:
8983: @item maximum size of a counted string:
8984: @cindex maximum size of a counted string
8985: @cindex counted string, maximum size
8986: @code{s" /counted-string" environment? drop .}. Currently 255 characters
8987: on all ports, but this may change.
8988:
8989: @item maximum size of a parsed string:
8990: @cindex maximum size of a parsed string
8991: @cindex parsed string, maximum size
8992: Given by the constant @code{/line}. Currently 255 characters.
8993:
8994: @item maximum size of a definition name, in characters:
8995: @cindex maximum size of a definition name, in characters
8996: @cindex name, maximum length
8997: 31
8998:
8999: @item maximum string length for @code{ENVIRONMENT?}, in characters:
9000: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
9001: @cindex @code{ENVIRONMENT?} string length, maximum
9002: 31
9003:
9004: @item method of selecting the user input device:
9005: @cindex user input device, method of selecting
9006: The user input device is the standard input. There is currently no way to
9007: change it from within Gforth. However, the input can typically be
9008: redirected in the command line that starts Gforth.
9009:
9010: @item method of selecting the user output device:
9011: @cindex user output device, method of selecting
9012: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 9013: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
9014: output when the user output device is a terminal, otherwise the output
9015: is buffered.
1.1 anton 9016:
9017: @item methods of dictionary compilation:
9018: What are we expected to document here?
9019:
9020: @item number of bits in one address unit:
9021: @cindex number of bits in one address unit
9022: @cindex address unit, size in bits
9023: @code{s" address-units-bits" environment? drop .}. 8 in all current
9024: ports.
9025:
9026: @item number representation and arithmetic:
9027: @cindex number representation and arithmetic
9028: Processor-dependent. Binary two's complement on all current ports.
9029:
9030: @item ranges for integer types:
9031: @cindex ranges for integer types
9032: @cindex integer types, ranges
9033: Installation-dependent. Make environmental queries for @code{MAX-N},
9034: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
9035: unsigned (and positive) types is 0. The lower bound for signed types on
9036: two's complement and one's complement machines machines can be computed
9037: by adding 1 to the upper bound.
9038:
9039: @item read-only data space regions:
9040: @cindex read-only data space regions
9041: @cindex data-space, read-only regions
9042: The whole Forth data space is writable.
9043:
9044: @item size of buffer at @code{WORD}:
9045: @cindex size of buffer at @code{WORD}
9046: @cindex @code{WORD} buffer size
9047: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
9048: shared with the pictured numeric output string. If overwriting
9049: @code{PAD} is acceptable, it is as large as the remaining dictionary
9050: space, although only as much can be sensibly used as fits in a counted
9051: string.
9052:
9053: @item size of one cell in address units:
9054: @cindex cell size
9055: @code{1 cells .}.
9056:
9057: @item size of one character in address units:
9058: @cindex char size
9059: @code{1 chars .}. 1 on all current ports.
9060:
9061: @item size of the keyboard terminal buffer:
9062: @cindex size of the keyboard terminal buffer
9063: @cindex terminal buffer, size
9064: Varies. You can determine the size at a specific time using @code{lp@@
9065: tib - .}. It is shared with the locals stack and TIBs of files that
9066: include the current file. You can change the amount of space for TIBs
9067: and locals stack at Gforth startup with the command line option
9068: @code{-l}.
9069:
9070: @item size of the pictured numeric output buffer:
9071: @cindex size of the pictured numeric output buffer
9072: @cindex pictured numeric output buffer, size
9073: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
9074: shared with @code{WORD}.
9075:
9076: @item size of the scratch area returned by @code{PAD}:
9077: @cindex size of the scratch area returned by @code{PAD}
9078: @cindex @code{PAD} size
9079: The remainder of dictionary space. @code{unused pad here - - .}.
9080:
9081: @item system case-sensitivity characteristics:
9082: @cindex case-sensitivity characteristics
1.26 crook 9083: Dictionary searches are case-insensitive (except in
1.1 anton 9084: @code{TABLE}s). However, as explained above under @i{character-set
9085: extensions}, the matching for non-ASCII characters is determined by the
9086: locale you are using. In the default @code{C} locale all non-ASCII
9087: characters are matched case-sensitively.
9088:
9089: @item system prompt:
9090: @cindex system prompt
9091: @cindex prompt
9092: @code{ ok} in interpret state, @code{ compiled} in compile state.
9093:
9094: @item division rounding:
9095: @cindex division rounding
9096: installation dependent. @code{s" floored" environment? drop .}. We leave
9097: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
9098: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
9099:
9100: @item values of @code{STATE} when true:
9101: @cindex @code{STATE} values
9102: -1.
9103:
9104: @item values returned after arithmetic overflow:
9105: On two's complement machines, arithmetic is performed modulo
9106: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
9107: arithmetic (with appropriate mapping for signed types). Division by zero
9108: typically results in a @code{-55 throw} (Floating-point unidentified
9109: fault), although a @code{-10 throw} (divide by zero) would be more
9110: appropriate.
9111:
9112: @item whether the current definition can be found after @t{DOES>}:
9113: @cindex @t{DOES>}, visibility of current definition
9114: No.
9115:
9116: @end table
9117:
9118: @c ---------------------------------------------------------------------
9119: @node core-ambcond, core-other, core-idef, The Core Words
9120: @subsection Ambiguous conditions
9121: @c ---------------------------------------------------------------------
9122: @cindex core words, ambiguous conditions
9123: @cindex ambiguous conditions, core words
9124:
9125: @table @i
9126:
9127: @item a name is neither a word nor a number:
9128: @cindex name not found
1.26 crook 9129: @cindex undefined word
1.1 anton 9130: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
9131: preserves the data and FP stack, so you don't lose more work than
9132: necessary.
9133:
9134: @item a definition name exceeds the maximum length allowed:
1.26 crook 9135: @cindex word name too long
1.1 anton 9136: @code{-19 throw} (Word name too long)
9137:
9138: @item addressing a region not inside the various data spaces of the forth system:
9139: @cindex Invalid memory address
1.32 anton 9140: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 9141: typically readable. Accessing other addresses gives results dependent on
9142: the operating system. On decent systems: @code{-9 throw} (Invalid memory
9143: address).
9144:
9145: @item argument type incompatible with parameter:
1.26 crook 9146: @cindex argument type mismatch
1.1 anton 9147: This is usually not caught. Some words perform checks, e.g., the control
9148: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
9149: mismatch).
9150:
9151: @item attempting to obtain the execution token of a word with undefined execution semantics:
9152: @cindex Interpreting a compile-only word, for @code{'} etc.
9153: @cindex execution token of words with undefined execution semantics
9154: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
9155: get an execution token for @code{compile-only-error} (which performs a
9156: @code{-14 throw} when executed).
9157:
9158: @item dividing by zero:
9159: @cindex dividing by zero
9160: @cindex floating point unidentified fault, integer division
1.24 anton 9161: On better platforms, this produces a @code{-10 throw} (Division by
9162: zero); on other systems, this typically results in a @code{-55 throw}
9163: (Floating-point unidentified fault).
1.1 anton 9164:
9165: @item insufficient data stack or return stack space:
9166: @cindex insufficient data stack or return stack space
9167: @cindex stack overflow
1.26 crook 9168: @cindex address alignment exception, stack overflow
1.1 anton 9169: @cindex Invalid memory address, stack overflow
9170: Depending on the operating system, the installation, and the invocation
9171: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 9172: it is not checked. If it is checked, you typically get a @code{-3 throw}
9173: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
9174: throw} (Invalid memory address) (depending on the platform and how you
9175: achieved the overflow) as soon as the overflow happens. If it is not
9176: checked, overflows typically result in mysterious illegal memory
9177: accesses, producing @code{-9 throw} (Invalid memory address) or
9178: @code{-23 throw} (Address alignment exception); they might also destroy
9179: the internal data structure of @code{ALLOCATE} and friends, resulting in
9180: various errors in these words.
1.1 anton 9181:
9182: @item insufficient space for loop control parameters:
9183: @cindex insufficient space for loop control parameters
9184: like other return stack overflows.
9185:
9186: @item insufficient space in the dictionary:
9187: @cindex insufficient space in the dictionary
9188: @cindex dictionary overflow
1.12 anton 9189: If you try to allot (either directly with @code{allot}, or indirectly
9190: with @code{,}, @code{create} etc.) more memory than available in the
9191: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
9192: to access memory beyond the end of the dictionary, the results are
9193: similar to stack overflows.
1.1 anton 9194:
9195: @item interpreting a word with undefined interpretation semantics:
9196: @cindex interpreting a word with undefined interpretation semantics
9197: @cindex Interpreting a compile-only word
9198: For some words, we have defined interpretation semantics. For the
9199: others: @code{-14 throw} (Interpreting a compile-only word).
9200:
9201: @item modifying the contents of the input buffer or a string literal:
9202: @cindex modifying the contents of the input buffer or a string literal
9203: These are located in writable memory and can be modified.
9204:
9205: @item overflow of the pictured numeric output string:
9206: @cindex overflow of the pictured numeric output string
9207: @cindex pictured numeric output string, overflow
1.24 anton 9208: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 9209:
9210: @item parsed string overflow:
9211: @cindex parsed string overflow
9212: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
9213:
9214: @item producing a result out of range:
9215: @cindex result out of range
9216: On two's complement machines, arithmetic is performed modulo
9217: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
9218: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 9219: typically results in a @code{-10 throw} (divide by zero) or @code{-55
9220: throw} (floating point unidentified fault). @code{convert} and
9221: @code{>number} currently overflow silently.
1.1 anton 9222:
9223: @item reading from an empty data or return stack:
9224: @cindex stack empty
9225: @cindex stack underflow
1.24 anton 9226: @cindex return stack underflow
1.1 anton 9227: The data stack is checked by the outer (aka text) interpreter after
9228: every word executed. If it has underflowed, a @code{-4 throw} (Stack
9229: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 9230: depending on operating system, installation, and invocation. If they are
9231: caught by a check, they typically result in @code{-4 throw} (Stack
9232: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
9233: (Invalid memory address), depending on the platform and which stack
9234: underflows and by how much. Note that even if the system uses checking
9235: (through the MMU), your program may have to underflow by a significant
9236: number of stack items to trigger the reaction (the reason for this is
9237: that the MMU, and therefore the checking, works with a page-size
9238: granularity). If there is no checking, the symptoms resulting from an
9239: underflow are similar to those from an overflow. Unbalanced return
9240: stack errors result in a variaty of symptoms, including @code{-9 throw}
9241: (Invalid memory address) and Illegal Instruction (typically @code{-260
9242: throw}).
1.1 anton 9243:
9244: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
9245: @cindex unexpected end of the input buffer
9246: @cindex zero-length string as a name
9247: @cindex Attempt to use zero-length string as a name
9248: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
9249: use zero-length string as a name). Words like @code{'} probably will not
9250: find what they search. Note that it is possible to create zero-length
9251: names with @code{nextname} (should it not?).
9252:
9253: @item @code{>IN} greater than input buffer:
9254: @cindex @code{>IN} greater than input buffer
9255: The next invocation of a parsing word returns a string with length 0.
9256:
9257: @item @code{RECURSE} appears after @code{DOES>}:
9258: @cindex @code{RECURSE} appears after @code{DOES>}
9259: Compiles a recursive call to the defining word, not to the defined word.
9260:
9261: @item argument input source different than current input source for @code{RESTORE-INPUT}:
9262: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 9263: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 9264: @cindex @code{RESTORE-INPUT}, Argument type mismatch
9265: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
9266: the end of the file was reached), its source-id may be
9267: reused. Therefore, restoring an input source specification referencing a
9268: closed file may lead to unpredictable results instead of a @code{-12
9269: THROW}.
9270:
9271: In the future, Gforth may be able to restore input source specifications
9272: from other than the current input source.
9273:
9274: @item data space containing definitions gets de-allocated:
9275: @cindex data space containing definitions gets de-allocated
9276: Deallocation with @code{allot} is not checked. This typically results in
9277: memory access faults or execution of illegal instructions.
9278:
9279: @item data space read/write with incorrect alignment:
9280: @cindex data space read/write with incorrect alignment
9281: @cindex alignment faults
1.26 crook 9282: @cindex address alignment exception
1.1 anton 9283: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 9284: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 9285: alignment turned on, incorrect alignment results in a @code{-9 throw}
9286: (Invalid memory address). There are reportedly some processors with
1.12 anton 9287: alignment restrictions that do not report violations.
1.1 anton 9288:
9289: @item data space pointer not properly aligned, @code{,}, @code{C,}:
9290: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
9291: Like other alignment errors.
9292:
9293: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
9294: Like other stack underflows.
9295:
9296: @item loop control parameters not available:
9297: @cindex loop control parameters not available
9298: Not checked. The counted loop words simply assume that the top of return
9299: stack items are loop control parameters and behave accordingly.
9300:
9301: @item most recent definition does not have a name (@code{IMMEDIATE}):
9302: @cindex most recent definition does not have a name (@code{IMMEDIATE})
9303: @cindex last word was headerless
9304: @code{abort" last word was headerless"}.
9305:
9306: @item name not defined by @code{VALUE} used by @code{TO}:
9307: @cindex name not defined by @code{VALUE} used by @code{TO}
9308: @cindex @code{TO} on non-@code{VALUE}s
9309: @cindex Invalid name argument, @code{TO}
9310: @code{-32 throw} (Invalid name argument) (unless name is a local or was
9311: defined by @code{CONSTANT}; in the latter case it just changes the constant).
9312:
9313: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
9314: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 9315: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 9316: @code{-13 throw} (Undefined word)
9317:
9318: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
9319: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
9320: Gforth behaves as if they were of the same type. I.e., you can predict
9321: the behaviour by interpreting all parameters as, e.g., signed.
9322:
9323: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
9324: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
9325: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
9326: compilation semantics of @code{TO}.
9327:
9328: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 9329: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 9330: @cindex @code{WORD}, string overflow
9331: Not checked. The string will be ok, but the count will, of course,
9332: contain only the least significant bits of the length.
9333:
9334: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
9335: @cindex @code{LSHIFT}, large shift counts
9336: @cindex @code{RSHIFT}, large shift counts
9337: Processor-dependent. Typical behaviours are returning 0 and using only
9338: the low bits of the shift count.
9339:
9340: @item word not defined via @code{CREATE}:
9341: @cindex @code{>BODY} of non-@code{CREATE}d words
9342: @code{>BODY} produces the PFA of the word no matter how it was defined.
9343:
9344: @cindex @code{DOES>} of non-@code{CREATE}d words
9345: @code{DOES>} changes the execution semantics of the last defined word no
9346: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
9347: @code{CREATE , DOES>}.
9348:
9349: @item words improperly used outside @code{<#} and @code{#>}:
9350: Not checked. As usual, you can expect memory faults.
9351:
9352: @end table
9353:
9354:
9355: @c ---------------------------------------------------------------------
9356: @node core-other, , core-ambcond, The Core Words
9357: @subsection Other system documentation
9358: @c ---------------------------------------------------------------------
9359: @cindex other system documentation, core words
9360: @cindex core words, other system documentation
9361:
9362: @table @i
9363: @item nonstandard words using @code{PAD}:
9364: @cindex @code{PAD} use by nonstandard words
9365: None.
9366:
9367: @item operator's terminal facilities available:
9368: @cindex operator's terminal facilities available
9369: After processing the command line, Gforth goes into interactive mode,
9370: and you can give commands to Gforth interactively. The actual facilities
9371: available depend on how you invoke Gforth.
9372:
9373: @item program data space available:
9374: @cindex program data space available
9375: @cindex data space available
9376: @code{UNUSED .} gives the remaining dictionary space. The total
9377: dictionary space can be specified with the @code{-m} switch
9378: (@pxref{Invoking Gforth}) when Gforth starts up.
9379:
9380: @item return stack space available:
9381: @cindex return stack space available
9382: You can compute the total return stack space in cells with
9383: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
9384: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
9385:
9386: @item stack space available:
9387: @cindex stack space available
9388: You can compute the total data stack space in cells with
9389: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
9390: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
9391:
9392: @item system dictionary space required, in address units:
9393: @cindex system dictionary space required, in address units
9394: Type @code{here forthstart - .} after startup. At the time of this
9395: writing, this gives 80080 (bytes) on a 32-bit system.
9396: @end table
9397:
9398:
9399: @c =====================================================================
9400: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
9401: @section The optional Block word set
9402: @c =====================================================================
9403: @cindex system documentation, block words
9404: @cindex block words, system documentation
9405:
9406: @menu
9407: * block-idef:: Implementation Defined Options
9408: * block-ambcond:: Ambiguous Conditions
9409: * block-other:: Other System Documentation
9410: @end menu
9411:
9412:
9413: @c ---------------------------------------------------------------------
9414: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
9415: @subsection Implementation Defined Options
9416: @c ---------------------------------------------------------------------
9417: @cindex implementation-defined options, block words
9418: @cindex block words, implementation-defined options
9419:
9420: @table @i
9421: @item the format for display by @code{LIST}:
9422: @cindex @code{LIST} display format
9423: First the screen number is displayed, then 16 lines of 64 characters,
9424: each line preceded by the line number.
9425:
9426: @item the length of a line affected by @code{\}:
9427: @cindex length of a line affected by @code{\}
9428: @cindex @code{\}, line length in blocks
9429: 64 characters.
9430: @end table
9431:
9432:
9433: @c ---------------------------------------------------------------------
9434: @node block-ambcond, block-other, block-idef, The optional Block word set
9435: @subsection Ambiguous conditions
9436: @c ---------------------------------------------------------------------
9437: @cindex block words, ambiguous conditions
9438: @cindex ambiguous conditions, block words
9439:
9440: @table @i
9441: @item correct block read was not possible:
9442: @cindex block read not possible
9443: Typically results in a @code{throw} of some OS-derived value (between
9444: -512 and -2048). If the blocks file was just not long enough, blanks are
9445: supplied for the missing portion.
9446:
9447: @item I/O exception in block transfer:
9448: @cindex I/O exception in block transfer
9449: @cindex block transfer, I/O exception
9450: Typically results in a @code{throw} of some OS-derived value (between
9451: -512 and -2048).
9452:
9453: @item invalid block number:
9454: @cindex invalid block number
9455: @cindex block number invalid
9456: @code{-35 throw} (Invalid block number)
9457:
9458: @item a program directly alters the contents of @code{BLK}:
9459: @cindex @code{BLK}, altering @code{BLK}
9460: The input stream is switched to that other block, at the same
9461: position. If the storing to @code{BLK} happens when interpreting
9462: non-block input, the system will get quite confused when the block ends.
9463:
9464: @item no current block buffer for @code{UPDATE}:
9465: @cindex @code{UPDATE}, no current block buffer
9466: @code{UPDATE} has no effect.
9467:
9468: @end table
9469:
9470: @c ---------------------------------------------------------------------
9471: @node block-other, , block-ambcond, The optional Block word set
9472: @subsection Other system documentation
9473: @c ---------------------------------------------------------------------
9474: @cindex other system documentation, block words
9475: @cindex block words, other system documentation
9476:
9477: @table @i
9478: @item any restrictions a multiprogramming system places on the use of buffer addresses:
9479: No restrictions (yet).
9480:
9481: @item the number of blocks available for source and data:
9482: depends on your disk space.
9483:
9484: @end table
9485:
9486:
9487: @c =====================================================================
9488: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
9489: @section The optional Double Number word set
9490: @c =====================================================================
9491: @cindex system documentation, double words
9492: @cindex double words, system documentation
9493:
9494: @menu
9495: * double-ambcond:: Ambiguous Conditions
9496: @end menu
9497:
9498:
9499: @c ---------------------------------------------------------------------
9500: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
9501: @subsection Ambiguous conditions
9502: @c ---------------------------------------------------------------------
9503: @cindex double words, ambiguous conditions
9504: @cindex ambiguous conditions, double words
9505:
9506: @table @i
1.29 crook 9507: @item @i{d} outside of range of @i{n} in @code{D>S}:
9508: @cindex @code{D>S}, @i{d} out of range of @i{n}
9509: The least significant cell of @i{d} is produced.
1.1 anton 9510:
9511: @end table
9512:
9513:
9514: @c =====================================================================
9515: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
9516: @section The optional Exception word set
9517: @c =====================================================================
9518: @cindex system documentation, exception words
9519: @cindex exception words, system documentation
9520:
9521: @menu
9522: * exception-idef:: Implementation Defined Options
9523: @end menu
9524:
9525:
9526: @c ---------------------------------------------------------------------
9527: @node exception-idef, , The optional Exception word set, The optional Exception word set
9528: @subsection Implementation Defined Options
9529: @c ---------------------------------------------------------------------
9530: @cindex implementation-defined options, exception words
9531: @cindex exception words, implementation-defined options
9532:
9533: @table @i
9534: @item @code{THROW}-codes used in the system:
9535: @cindex @code{THROW}-codes used in the system
9536: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 9537: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 9538: codes -512@minus{}-2047 are used for OS errors (for file and memory
9539: allocation operations). The mapping from OS error numbers to throw codes
9540: is -512@minus{}@code{errno}. One side effect of this mapping is that
9541: undefined OS errors produce a message with a strange number; e.g.,
9542: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
9543: @end table
9544:
9545: @c =====================================================================
9546: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
9547: @section The optional Facility word set
9548: @c =====================================================================
9549: @cindex system documentation, facility words
9550: @cindex facility words, system documentation
9551:
9552: @menu
9553: * facility-idef:: Implementation Defined Options
9554: * facility-ambcond:: Ambiguous Conditions
9555: @end menu
9556:
9557:
9558: @c ---------------------------------------------------------------------
9559: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
9560: @subsection Implementation Defined Options
9561: @c ---------------------------------------------------------------------
9562: @cindex implementation-defined options, facility words
9563: @cindex facility words, implementation-defined options
9564:
9565: @table @i
9566: @item encoding of keyboard events (@code{EKEY}):
9567: @cindex keyboard events, encoding in @code{EKEY}
9568: @cindex @code{EKEY}, encoding of keyboard events
9569: Not yet implemented.
9570:
9571: @item duration of a system clock tick:
9572: @cindex duration of a system clock tick
9573: @cindex clock tick duration
9574: System dependent. With respect to @code{MS}, the time is specified in
9575: microseconds. How well the OS and the hardware implement this, is
9576: another question.
9577:
9578: @item repeatability to be expected from the execution of @code{MS}:
9579: @cindex repeatability to be expected from the execution of @code{MS}
9580: @cindex @code{MS}, repeatability to be expected
9581: System dependent. On Unix, a lot depends on load. If the system is
9582: lightly loaded, and the delay is short enough that Gforth does not get
9583: swapped out, the performance should be acceptable. Under MS-DOS and
9584: other single-tasking systems, it should be good.
9585:
9586: @end table
9587:
9588:
9589: @c ---------------------------------------------------------------------
9590: @node facility-ambcond, , facility-idef, The optional Facility word set
9591: @subsection Ambiguous conditions
9592: @c ---------------------------------------------------------------------
9593: @cindex facility words, ambiguous conditions
9594: @cindex ambiguous conditions, facility words
9595:
9596: @table @i
9597: @item @code{AT-XY} can't be performed on user output device:
9598: @cindex @code{AT-XY} can't be performed on user output device
9599: Largely terminal dependent. No range checks are done on the arguments.
9600: No errors are reported. You may see some garbage appearing, you may see
9601: simply nothing happen.
9602:
9603: @end table
9604:
9605:
9606: @c =====================================================================
9607: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
9608: @section The optional File-Access word set
9609: @c =====================================================================
9610: @cindex system documentation, file words
9611: @cindex file words, system documentation
9612:
9613: @menu
9614: * file-idef:: Implementation Defined Options
9615: * file-ambcond:: Ambiguous Conditions
9616: @end menu
9617:
9618: @c ---------------------------------------------------------------------
9619: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
9620: @subsection Implementation Defined Options
9621: @c ---------------------------------------------------------------------
9622: @cindex implementation-defined options, file words
9623: @cindex file words, implementation-defined options
9624:
9625: @table @i
9626: @item file access methods used:
9627: @cindex file access methods used
9628: @code{R/O}, @code{R/W} and @code{BIN} work as you would
9629: expect. @code{W/O} translates into the C file opening mode @code{w} (or
9630: @code{wb}): The file is cleared, if it exists, and created, if it does
9631: not (with both @code{open-file} and @code{create-file}). Under Unix
9632: @code{create-file} creates a file with 666 permissions modified by your
9633: umask.
9634:
9635: @item file exceptions:
9636: @cindex file exceptions
9637: The file words do not raise exceptions (except, perhaps, memory access
9638: faults when you pass illegal addresses or file-ids).
9639:
9640: @item file line terminator:
9641: @cindex file line terminator
9642: System-dependent. Gforth uses C's newline character as line
9643: terminator. What the actual character code(s) of this are is
9644: system-dependent.
9645:
9646: @item file name format:
9647: @cindex file name format
9648: System dependent. Gforth just uses the file name format of your OS.
9649:
9650: @item information returned by @code{FILE-STATUS}:
9651: @cindex @code{FILE-STATUS}, returned information
9652: @code{FILE-STATUS} returns the most powerful file access mode allowed
9653: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
9654: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
9655: along with the returned mode.
9656:
9657: @item input file state after an exception when including source:
9658: @cindex exception when including source
9659: All files that are left via the exception are closed.
9660:
1.29 crook 9661: @item @i{ior} values and meaning:
9662: @cindex @i{ior} values and meaning
9663: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 9664: intended as throw codes. They typically are in the range
9665: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 9666: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 9667:
9668: @item maximum depth of file input nesting:
9669: @cindex maximum depth of file input nesting
9670: @cindex file input nesting, maximum depth
9671: limited by the amount of return stack, locals/TIB stack, and the number
9672: of open files available. This should not give you troubles.
9673:
9674: @item maximum size of input line:
9675: @cindex maximum size of input line
9676: @cindex input line size, maximum
9677: @code{/line}. Currently 255.
9678:
9679: @item methods of mapping block ranges to files:
9680: @cindex mapping block ranges to files
9681: @cindex files containing blocks
9682: @cindex blocks in files
9683: By default, blocks are accessed in the file @file{blocks.fb} in the
9684: current working directory. The file can be switched with @code{USE}.
9685:
9686: @item number of string buffers provided by @code{S"}:
9687: @cindex @code{S"}, number of string buffers
9688: 1
9689:
9690: @item size of string buffer used by @code{S"}:
9691: @cindex @code{S"}, size of string buffer
9692: @code{/line}. currently 255.
9693:
9694: @end table
9695:
9696: @c ---------------------------------------------------------------------
9697: @node file-ambcond, , file-idef, The optional File-Access word set
9698: @subsection Ambiguous conditions
9699: @c ---------------------------------------------------------------------
9700: @cindex file words, ambiguous conditions
9701: @cindex ambiguous conditions, file words
9702:
9703: @table @i
9704: @item attempting to position a file outside its boundaries:
9705: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
9706: @code{REPOSITION-FILE} is performed as usual: Afterwards,
9707: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
9708:
9709: @item attempting to read from file positions not yet written:
9710: @cindex reading from file positions not yet written
9711: End-of-file, i.e., zero characters are read and no error is reported.
9712:
1.29 crook 9713: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
9714: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 9715: An appropriate exception may be thrown, but a memory fault or other
9716: problem is more probable.
9717:
1.29 crook 9718: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
9719: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
9720: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
9721: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 9722: thrown.
9723:
9724: @item named file cannot be opened (@code{INCLUDED}):
9725: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 9726: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 9727:
9728: @item requesting an unmapped block number:
9729: @cindex unmapped block numbers
9730: There are no unmapped legal block numbers. On some operating systems,
9731: writing a block with a large number may overflow the file system and
9732: have an error message as consequence.
9733:
9734: @item using @code{source-id} when @code{blk} is non-zero:
9735: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
9736: @code{source-id} performs its function. Typically it will give the id of
9737: the source which loaded the block. (Better ideas?)
9738:
9739: @end table
9740:
9741:
9742: @c =====================================================================
9743: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
9744: @section The optional Floating-Point word set
9745: @c =====================================================================
9746: @cindex system documentation, floating-point words
9747: @cindex floating-point words, system documentation
9748:
9749: @menu
9750: * floating-idef:: Implementation Defined Options
9751: * floating-ambcond:: Ambiguous Conditions
9752: @end menu
9753:
9754:
9755: @c ---------------------------------------------------------------------
9756: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
9757: @subsection Implementation Defined Options
9758: @c ---------------------------------------------------------------------
9759: @cindex implementation-defined options, floating-point words
9760: @cindex floating-point words, implementation-defined options
9761:
9762: @table @i
9763: @item format and range of floating point numbers:
9764: @cindex format and range of floating point numbers
9765: @cindex floating point numbers, format and range
9766: System-dependent; the @code{double} type of C.
9767:
1.29 crook 9768: @item results of @code{REPRESENT} when @i{float} is out of range:
9769: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 9770: System dependent; @code{REPRESENT} is implemented using the C library
9771: function @code{ecvt()} and inherits its behaviour in this respect.
9772:
9773: @item rounding or truncation of floating-point numbers:
9774: @cindex rounding of floating-point numbers
9775: @cindex truncation of floating-point numbers
9776: @cindex floating-point numbers, rounding or truncation
9777: System dependent; the rounding behaviour is inherited from the hosting C
9778: compiler. IEEE-FP-based (i.e., most) systems by default round to
9779: nearest, and break ties by rounding to even (i.e., such that the last
9780: bit of the mantissa is 0).
9781:
9782: @item size of floating-point stack:
9783: @cindex floating-point stack size
9784: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
9785: the floating-point stack (in floats). You can specify this on startup
9786: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
9787:
9788: @item width of floating-point stack:
9789: @cindex floating-point stack width
9790: @code{1 floats}.
9791:
9792: @end table
9793:
9794:
9795: @c ---------------------------------------------------------------------
9796: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
9797: @subsection Ambiguous conditions
9798: @c ---------------------------------------------------------------------
9799: @cindex floating-point words, ambiguous conditions
9800: @cindex ambiguous conditions, floating-point words
9801:
9802: @table @i
9803: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
9804: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
9805: System-dependent. Typically results in a @code{-23 THROW} like other
9806: alignment violations.
9807:
9808: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
9809: @cindex @code{f@@} used with an address that is not float aligned
9810: @cindex @code{f!} used with an address that is not float aligned
9811: System-dependent. Typically results in a @code{-23 THROW} like other
9812: alignment violations.
9813:
9814: @item floating-point result out of range:
9815: @cindex floating-point result out of range
9816: System-dependent. Can result in a @code{-55 THROW} (Floating-point
9817: unidentified fault), or can produce a special value representing, e.g.,
9818: Infinity.
9819:
9820: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
9821: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
9822: System-dependent. Typically results in an alignment fault like other
9823: alignment violations.
9824:
9825: @item @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
9826: @cindex @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
9827: The floating-point number is converted into decimal nonetheless.
9828:
9829: @item Both arguments are equal to zero (@code{FATAN2}):
9830: @cindex @code{FATAN2}, both arguments are equal to zero
9831: System-dependent. @code{FATAN2} is implemented using the C library
9832: function @code{atan2()}.
9833:
1.29 crook 9834: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
9835: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
9836: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 9837: because of small errors and the tan will be a very large (or very small)
9838: but finite number.
9839:
1.29 crook 9840: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
9841: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 9842: The result is rounded to the nearest float.
9843:
9844: @item dividing by zero:
9845: @cindex dividing by zero, floating-point
9846: @cindex floating-point dividing by zero
9847: @cindex floating-point unidentified fault, FP divide-by-zero
9848: @code{-55 throw} (Floating-point unidentified fault)
9849:
9850: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
9851: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
9852: System dependent. On IEEE-FP based systems the number is converted into
9853: an infinity.
9854:
1.29 crook 9855: @item @i{float}<1 (@code{FACOSH}):
9856: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 9857: @cindex floating-point unidentified fault, @code{FACOSH}
9858: @code{-55 throw} (Floating-point unidentified fault)
9859:
1.29 crook 9860: @item @i{float}=<-1 (@code{FLNP1}):
9861: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 9862: @cindex floating-point unidentified fault, @code{FLNP1}
9863: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29 crook 9864: negative infinity is typically produced for @i{float}=-1.
1.1 anton 9865:
1.29 crook 9866: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
9867: @cindex @code{FLN}, @i{float}=<0
9868: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 9869: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
9870: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29 crook 9871: negative infinity is typically produced for @i{float}=0.
1.1 anton 9872:
1.29 crook 9873: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
9874: @cindex @code{FASINH}, @i{float}<0
9875: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 9876: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
9877: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
9878: produces values for these inputs on my Linux box (Bug in the C library?)
9879:
1.29 crook 9880: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
9881: @cindex @code{FACOS}, |@i{float}|>1
9882: @cindex @code{FASIN}, |@i{float}|>1
9883: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 9884: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
9885: @code{-55 throw} (Floating-point unidentified fault).
9886:
1.29 crook 9887: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
9888: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 9889: @cindex floating-point unidentified fault, @code{F>D}
9890: @code{-55 throw} (Floating-point unidentified fault).
9891:
9892: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
9893: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
9894: This does not happen.
9895: @end table
9896:
9897: @c =====================================================================
9898: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
9899: @section The optional Locals word set
9900: @c =====================================================================
9901: @cindex system documentation, locals words
9902: @cindex locals words, system documentation
9903:
9904: @menu
9905: * locals-idef:: Implementation Defined Options
9906: * locals-ambcond:: Ambiguous Conditions
9907: @end menu
9908:
9909:
9910: @c ---------------------------------------------------------------------
9911: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
9912: @subsection Implementation Defined Options
9913: @c ---------------------------------------------------------------------
9914: @cindex implementation-defined options, locals words
9915: @cindex locals words, implementation-defined options
9916:
9917: @table @i
9918: @item maximum number of locals in a definition:
9919: @cindex maximum number of locals in a definition
9920: @cindex locals, maximum number in a definition
9921: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
9922: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
9923: characters. The number of locals in a definition is bounded by the size
9924: of locals-buffer, which contains the names of the locals.
9925:
9926: @end table
9927:
9928:
9929: @c ---------------------------------------------------------------------
9930: @node locals-ambcond, , locals-idef, The optional Locals word set
9931: @subsection Ambiguous conditions
9932: @c ---------------------------------------------------------------------
9933: @cindex locals words, ambiguous conditions
9934: @cindex ambiguous conditions, locals words
9935:
9936: @table @i
9937: @item executing a named local in interpretation state:
9938: @cindex local in interpretation state
9939: @cindex Interpreting a compile-only word, for a local
9940: Locals have no interpretation semantics. If you try to perform the
9941: interpretation semantics, you will get a @code{-14 throw} somewhere
9942: (Interpreting a compile-only word). If you perform the compilation
9943: semantics, the locals access will be compiled (irrespective of state).
9944:
1.29 crook 9945: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 9946: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
9947: @cindex @code{TO} on non-@code{VALUE}s and non-locals
9948: @cindex Invalid name argument, @code{TO}
9949: @code{-32 throw} (Invalid name argument)
9950:
9951: @end table
9952:
9953:
9954: @c =====================================================================
9955: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
9956: @section The optional Memory-Allocation word set
9957: @c =====================================================================
9958: @cindex system documentation, memory-allocation words
9959: @cindex memory-allocation words, system documentation
9960:
9961: @menu
9962: * memory-idef:: Implementation Defined Options
9963: @end menu
9964:
9965:
9966: @c ---------------------------------------------------------------------
9967: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
9968: @subsection Implementation Defined Options
9969: @c ---------------------------------------------------------------------
9970: @cindex implementation-defined options, memory-allocation words
9971: @cindex memory-allocation words, implementation-defined options
9972:
9973: @table @i
1.29 crook 9974: @item values and meaning of @i{ior}:
9975: @cindex @i{ior} values and meaning
9976: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 9977: intended as throw codes. They typically are in the range
9978: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 9979: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 9980:
9981: @end table
9982:
9983: @c =====================================================================
9984: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
9985: @section The optional Programming-Tools word set
9986: @c =====================================================================
9987: @cindex system documentation, programming-tools words
9988: @cindex programming-tools words, system documentation
9989:
9990: @menu
9991: * programming-idef:: Implementation Defined Options
9992: * programming-ambcond:: Ambiguous Conditions
9993: @end menu
9994:
9995:
9996: @c ---------------------------------------------------------------------
9997: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
9998: @subsection Implementation Defined Options
9999: @c ---------------------------------------------------------------------
10000: @cindex implementation-defined options, programming-tools words
10001: @cindex programming-tools words, implementation-defined options
10002:
10003: @table @i
10004: @item ending sequence for input following @code{;CODE} and @code{CODE}:
10005: @cindex @code{;CODE} ending sequence
10006: @cindex @code{CODE} ending sequence
10007: @code{END-CODE}
10008:
10009: @item manner of processing input following @code{;CODE} and @code{CODE}:
10010: @cindex @code{;CODE}, processing input
10011: @cindex @code{CODE}, processing input
10012: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
10013: the input is processed by the text interpreter, (starting) in interpret
10014: state.
10015:
10016: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
10017: @cindex @code{ASSEMBLER}, search order capability
10018: The ANS Forth search order word set.
10019:
10020: @item source and format of display by @code{SEE}:
10021: @cindex @code{SEE}, source and format of output
10022: The source for @code{see} is the intermediate code used by the inner
10023: interpreter. The current @code{see} tries to output Forth source code
10024: as well as possible.
10025:
10026: @end table
10027:
10028: @c ---------------------------------------------------------------------
10029: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
10030: @subsection Ambiguous conditions
10031: @c ---------------------------------------------------------------------
10032: @cindex programming-tools words, ambiguous conditions
10033: @cindex ambiguous conditions, programming-tools words
10034:
10035: @table @i
10036:
1.21 crook 10037: @item deleting the compilation word list (@code{FORGET}):
10038: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 10039: Not implemented (yet).
10040:
1.29 crook 10041: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
10042: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
10043: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 10044: @cindex control-flow stack underflow
10045: This typically results in an @code{abort"} with a descriptive error
10046: message (may change into a @code{-22 throw} (Control structure mismatch)
10047: in the future). You may also get a memory access error. If you are
10048: unlucky, this ambiguous condition is not caught.
10049:
1.29 crook 10050: @item @i{name} can't be found (@code{FORGET}):
10051: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 10052: Not implemented (yet).
10053:
1.29 crook 10054: @item @i{name} not defined via @code{CREATE}:
10055: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 10056: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
10057: the execution semantics of the last defined word no matter how it was
10058: defined.
10059:
10060: @item @code{POSTPONE} applied to @code{[IF]}:
10061: @cindex @code{POSTPONE} applied to @code{[IF]}
10062: @cindex @code{[IF]} and @code{POSTPONE}
10063: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
10064: equivalent to @code{[IF]}.
10065:
10066: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
10067: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
10068: Continue in the same state of conditional compilation in the next outer
10069: input source. Currently there is no warning to the user about this.
10070:
10071: @item removing a needed definition (@code{FORGET}):
10072: @cindex @code{FORGET}, removing a needed definition
10073: Not implemented (yet).
10074:
10075: @end table
10076:
10077:
10078: @c =====================================================================
10079: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
10080: @section The optional Search-Order word set
10081: @c =====================================================================
10082: @cindex system documentation, search-order words
10083: @cindex search-order words, system documentation
10084:
10085: @menu
10086: * search-idef:: Implementation Defined Options
10087: * search-ambcond:: Ambiguous Conditions
10088: @end menu
10089:
10090:
10091: @c ---------------------------------------------------------------------
10092: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
10093: @subsection Implementation Defined Options
10094: @c ---------------------------------------------------------------------
10095: @cindex implementation-defined options, search-order words
10096: @cindex search-order words, implementation-defined options
10097:
10098: @table @i
10099: @item maximum number of word lists in search order:
10100: @cindex maximum number of word lists in search order
10101: @cindex search order, maximum depth
10102: @code{s" wordlists" environment? drop .}. Currently 16.
10103:
10104: @item minimum search order:
10105: @cindex minimum search order
10106: @cindex search order, minimum
10107: @code{root root}.
10108:
10109: @end table
10110:
10111: @c ---------------------------------------------------------------------
10112: @node search-ambcond, , search-idef, The optional Search-Order word set
10113: @subsection Ambiguous conditions
10114: @c ---------------------------------------------------------------------
10115: @cindex search-order words, ambiguous conditions
10116: @cindex ambiguous conditions, search-order words
10117:
10118: @table @i
1.21 crook 10119: @item changing the compilation word list (during compilation):
10120: @cindex changing the compilation word list (during compilation)
10121: @cindex compilation word list, change before definition ends
10122: The word is entered into the word list that was the compilation word list
1.1 anton 10123: at the start of the definition. Any changes to the name field (e.g.,
10124: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
10125: are applied to the latest defined word (as reported by @code{last} or
1.21 crook 10126: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1 anton 10127:
10128: @item search order empty (@code{previous}):
10129: @cindex @code{previous}, search order empty
1.26 crook 10130: @cindex vocstack empty, @code{previous}
1.1 anton 10131: @code{abort" Vocstack empty"}.
10132:
10133: @item too many word lists in search order (@code{also}):
10134: @cindex @code{also}, too many word lists in search order
1.26 crook 10135: @cindex vocstack full, @code{also}
1.1 anton 10136: @code{abort" Vocstack full"}.
10137:
10138: @end table
10139:
10140: @c ***************************************************************
10141: @node Model, Integrating Gforth, ANS conformance, Top
10142: @chapter Model
10143:
10144: This chapter has yet to be written. It will contain information, on
10145: which internal structures you can rely.
10146:
10147: @c ***************************************************************
10148: @node Integrating Gforth, Emacs and Gforth, Model, Top
10149: @chapter Integrating Gforth into C programs
10150:
10151: This is not yet implemented.
10152:
10153: Several people like to use Forth as scripting language for applications
10154: that are otherwise written in C, C++, or some other language.
10155:
10156: The Forth system ATLAST provides facilities for embedding it into
10157: applications; unfortunately it has several disadvantages: most
10158: importantly, it is not based on ANS Forth, and it is apparently dead
10159: (i.e., not developed further and not supported). The facilities
1.21 crook 10160: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 10161: making the switch should not be hard.
10162:
10163: We also tried to design the interface such that it can easily be
10164: implemented by other Forth systems, so that we may one day arrive at a
10165: standardized interface. Such a standard interface would allow you to
10166: replace the Forth system without having to rewrite C code.
10167:
10168: You embed the Gforth interpreter by linking with the library
10169: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
10170: global symbols in this library that belong to the interface, have the
10171: prefix @code{forth_}. (Global symbols that are used internally have the
10172: prefix @code{gforth_}).
10173:
10174: You can include the declarations of Forth types and the functions and
10175: variables of the interface with @code{#include <forth.h>}.
10176:
10177: Types.
10178:
10179: Variables.
10180:
10181: Data and FP Stack pointer. Area sizes.
10182:
10183: functions.
10184:
10185: forth_init(imagefile)
10186: forth_evaluate(string) exceptions?
10187: forth_goto(address) (or forth_execute(xt)?)
10188: forth_continue() (a corountining mechanism)
10189:
10190: Adding primitives.
10191:
10192: No checking.
10193:
10194: Signals?
10195:
10196: Accessing the Stacks
10197:
1.26 crook 10198: @c ******************************************************************
1.1 anton 10199: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
10200: @chapter Emacs and Gforth
10201: @cindex Emacs and Gforth
10202:
10203: @cindex @file{gforth.el}
10204: @cindex @file{forth.el}
10205: @cindex Rydqvist, Goran
10206: @cindex comment editing commands
10207: @cindex @code{\}, editing with Emacs
10208: @cindex debug tracer editing commands
10209: @cindex @code{~~}, removal with Emacs
10210: @cindex Forth mode in Emacs
10211: Gforth comes with @file{gforth.el}, an improved version of
10212: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 10213: improvements are:
10214:
10215: @itemize @bullet
10216: @item
10217: A better (but still not perfect) handling of indentation.
10218: @item
10219: Comment paragraph filling (@kbd{M-q})
10220: @item
10221: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
10222: @item
10223: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
10224: @end itemize
10225:
10226: I left the stuff I do not use alone, even though some of it only makes
10227: sense for TILE. To get a description of these features, enter Forth mode
10228: and type @kbd{C-h m}.
1.1 anton 10229:
10230: @cindex source location of error or debugging output in Emacs
10231: @cindex error output, finding the source location in Emacs
10232: @cindex debugging output, finding the source location in Emacs
10233: In addition, Gforth supports Emacs quite well: The source code locations
10234: given in error messages, debugging output (from @code{~~}) and failed
10235: assertion messages are in the right format for Emacs' compilation mode
10236: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
10237: Manual}) so the source location corresponding to an error or other
10238: message is only a few keystrokes away (@kbd{C-x `} for the next error,
10239: @kbd{C-c C-c} for the error under the cursor).
10240:
10241: @cindex @file{TAGS} file
10242: @cindex @file{etags.fs}
10243: @cindex viewing the source of a word in Emacs
1.26 crook 10244: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file will
10245: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 10246: contains the definitions of all words defined afterwards. You can then
10247: find the source for a word using @kbd{M-.}. Note that emacs can use
10248: several tags files at the same time (e.g., one for the Gforth sources
10249: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
10250: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
10251: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
10252: @file{/usr/local/share/gforth/0.2.0/TAGS}).
10253:
10254: @cindex @file{.emacs}
10255: To get all these benefits, add the following lines to your @file{.emacs}
10256: file:
10257:
10258: @example
10259: (autoload 'forth-mode "gforth.el")
10260: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
10261: @end example
10262:
1.26 crook 10263: @c ******************************************************************
1.1 anton 10264: @node Image Files, Engine, Emacs and Gforth, Top
10265: @chapter Image Files
1.26 crook 10266: @cindex image file
10267: @cindex @file{.fi} files
1.1 anton 10268: @cindex precompiled Forth code
10269: @cindex dictionary in persistent form
10270: @cindex persistent form of dictionary
10271:
10272: An image file is a file containing an image of the Forth dictionary,
10273: i.e., compiled Forth code and data residing in the dictionary. By
10274: convention, we use the extension @code{.fi} for image files.
10275:
10276: @menu
1.18 anton 10277: * Image Licensing Issues:: Distribution terms for images.
10278: * Image File Background:: Why have image files?
1.29 crook 10279: * Non-Relocatable Image Files:: don't always work.
1.18 anton 10280: * Data-Relocatable Image Files:: are better.
1.29 crook 10281: * Fully Relocatable Image Files:: better yet.
1.18 anton 10282: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 10283: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 10284: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 10285: @end menu
10286:
1.18 anton 10287: @node Image Licensing Issues, Image File Background, Image Files, Image Files
10288: @section Image Licensing Issues
10289: @cindex license for images
10290: @cindex image license
10291:
10292: An image created with @code{gforthmi} (@pxref{gforthmi}) or
10293: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
10294: original image; i.e., according to copyright law it is a derived work of
10295: the original image.
10296:
10297: Since Gforth is distributed under the GNU GPL, the newly created image
10298: falls under the GNU GPL, too. In particular, this means that if you
10299: distribute the image, you have to make all of the sources for the image
10300: available, including those you wrote. For details see @ref{License, ,
10301: GNU General Public License (Section 3)}.
10302:
10303: If you create an image with @code{cross} (@pxref{cross.fs}), the image
10304: contains only code compiled from the sources you gave it; if none of
10305: these sources is under the GPL, the terms discussed above do not apply
10306: to the image. However, if your image needs an engine (a gforth binary)
10307: that is under the GPL, you should make sure that you distribute both in
10308: a way that is at most a @emph{mere aggregation}, if you don't want the
10309: terms of the GPL to apply to the image.
10310:
10311: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 10312: @section Image File Background
10313: @cindex image file background
10314:
10315: Our Forth system consists not only of primitives, but also of
10316: definitions written in Forth. Since the Forth compiler itself belongs to
10317: those definitions, it is not possible to start the system with the
10318: primitives and the Forth source alone. Therefore we provide the Forth
1.26 crook 10319: code as an image file in nearly executable form. When Gforth starts up,
10320: a C routine loads the image file into memory, optionally relocates the
10321: addresses, then sets up the memory (stacks etc.) according to
10322: information in the image file, and (finally) starts executing Forth
10323: code.
1.1 anton 10324:
10325: The image file variants represent different compromises between the
10326: goals of making it easy to generate image files and making them
10327: portable.
10328:
10329: @cindex relocation at run-time
1.26 crook 10330: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 10331: run-time. This avoids many of the complications discussed below (image
10332: files are data relocatable without further ado), but costs performance
10333: (one addition per memory access).
10334:
10335: @cindex relocation at load-time
1.26 crook 10336: By contrast, the Gforth loader performs relocation at image load time. The
10337: loader also has to replace tokens that represent primitive calls with the
1.1 anton 10338: appropriate code-field addresses (or code addresses in the case of
10339: direct threading).
10340:
10341: There are three kinds of image files, with different degrees of
10342: relocatability: non-relocatable, data-relocatable, and fully relocatable
10343: image files.
10344:
10345: @cindex image file loader
10346: @cindex relocating loader
10347: @cindex loader for image files
10348: These image file variants have several restrictions in common; they are
10349: caused by the design of the image file loader:
10350:
10351: @itemize @bullet
10352: @item
10353: There is only one segment; in particular, this means, that an image file
10354: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 10355: them). The contents of the stacks are not represented, either.
1.1 anton 10356:
10357: @item
10358: The only kinds of relocation supported are: adding the same offset to
10359: all cells that represent data addresses; and replacing special tokens
10360: with code addresses or with pieces of machine code.
10361:
10362: If any complex computations involving addresses are performed, the
10363: results cannot be represented in the image file. Several applications that
10364: use such computations come to mind:
10365: @itemize @minus
10366: @item
10367: Hashing addresses (or data structures which contain addresses) for table
10368: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
10369: purpose, you will have no problem, because the hash tables are
10370: recomputed automatically when the system is started. If you use your own
10371: hash tables, you will have to do something similar.
10372:
10373: @item
10374: There's a cute implementation of doubly-linked lists that uses
10375: @code{XOR}ed addresses. You could represent such lists as singly-linked
10376: in the image file, and restore the doubly-linked representation on
10377: startup.@footnote{In my opinion, though, you should think thrice before
10378: using a doubly-linked list (whatever implementation).}
10379:
10380: @item
10381: The code addresses of run-time routines like @code{docol:} cannot be
10382: represented in the image file (because their tokens would be replaced by
10383: machine code in direct threaded implementations). As a workaround,
10384: compute these addresses at run-time with @code{>code-address} from the
10385: executions tokens of appropriate words (see the definitions of
10386: @code{docol:} and friends in @file{kernel.fs}).
10387:
10388: @item
10389: On many architectures addresses are represented in machine code in some
10390: shifted or mangled form. You cannot put @code{CODE} words that contain
10391: absolute addresses in this form in a relocatable image file. Workarounds
10392: are representing the address in some relative form (e.g., relative to
10393: the CFA, which is present in some register), or loading the address from
10394: a place where it is stored in a non-mangled form.
10395: @end itemize
10396: @end itemize
10397:
10398: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
10399: @section Non-Relocatable Image Files
10400: @cindex non-relocatable image files
1.26 crook 10401: @cindex image file, non-relocatable
1.1 anton 10402:
10403: These files are simple memory dumps of the dictionary. They are specific
10404: to the executable (i.e., @file{gforth} file) they were created
10405: with. What's worse, they are specific to the place on which the
10406: dictionary resided when the image was created. Now, there is no
10407: guarantee that the dictionary will reside at the same place the next
10408: time you start Gforth, so there's no guarantee that a non-relocatable
10409: image will work the next time (Gforth will complain instead of crashing,
10410: though).
10411:
10412: You can create a non-relocatable image file with
10413:
10414: doc-savesystem
10415:
10416: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
10417: @section Data-Relocatable Image Files
10418: @cindex data-relocatable image files
1.26 crook 10419: @cindex image file, data-relocatable
1.1 anton 10420:
10421: These files contain relocatable data addresses, but fixed code addresses
10422: (instead of tokens). They are specific to the executable (i.e.,
10423: @file{gforth} file) they were created with. For direct threading on some
10424: architectures (e.g., the i386), data-relocatable images do not work. You
10425: get a data-relocatable image, if you use @file{gforthmi} with a
10426: Gforth binary that is not doubly indirect threaded (@pxref{Fully
10427: Relocatable Image Files}).
10428:
10429: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
10430: @section Fully Relocatable Image Files
10431: @cindex fully relocatable image files
1.26 crook 10432: @cindex image file, fully relocatable
1.1 anton 10433:
10434: @cindex @file{kern*.fi}, relocatability
10435: @cindex @file{gforth.fi}, relocatability
10436: These image files have relocatable data addresses, and tokens for code
10437: addresses. They can be used with different binaries (e.g., with and
10438: without debugging) on the same machine, and even across machines with
10439: the same data formats (byte order, cell size, floating point
10440: format). However, they are usually specific to the version of Gforth
10441: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
10442: are fully relocatable.
10443:
10444: There are two ways to create a fully relocatable image file:
10445:
10446: @menu
1.29 crook 10447: * gforthmi:: The normal way
1.1 anton 10448: * cross.fs:: The hard way
10449: @end menu
10450:
10451: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
10452: @subsection @file{gforthmi}
10453: @cindex @file{comp-i.fs}
10454: @cindex @file{gforthmi}
10455:
10456: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 10457: image @i{file} that contains everything you would load by invoking
10458: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 10459: @example
1.29 crook 10460: gforthmi @i{file} @i{options}
1.1 anton 10461: @end example
10462:
10463: E.g., if you want to create an image @file{asm.fi} that has the file
10464: @file{asm.fs} loaded in addition to the usual stuff, you could do it
10465: like this:
10466:
10467: @example
10468: gforthmi asm.fi asm.fs
10469: @end example
10470:
1.27 crook 10471: @file{gforthmi} is implemented as a sh script and works like this: It
10472: produces two non-relocatable images for different addresses and then
10473: compares them. Its output reflects this: first you see the output (if
10474: any) of the two Gforth invocations that produce the nonrelocatable image
10475: files, then you see the output of the comparing program: It displays the
10476: offset used for data addresses and the offset used for code addresses;
1.1 anton 10477: moreover, for each cell that cannot be represented correctly in the
10478: image files, it displays a line like the following one:
10479:
10480: @example
10481: 78DC BFFFFA50 BFFFFA40
10482: @end example
10483:
10484: This means that at offset $78dc from @code{forthstart}, one input image
10485: contains $bffffa50, and the other contains $bffffa40. Since these cells
10486: cannot be represented correctly in the output image, you should examine
10487: these places in the dictionary and verify that these cells are dead
10488: (i.e., not read before they are written).
10489:
1.27 crook 10490: If you type @file{gforthmi} with no arguments, it prints some usage
10491: instructions.
10492:
1.1 anton 10493: @cindex @code{savesystem} during @file{gforthmi}
10494: @cindex @code{bye} during @file{gforthmi}
10495: @cindex doubly indirect threaded code
10496: @cindex environment variable @code{GFORTHD}
10497: @cindex @code{GFORTHD} environment variable
10498: @cindex @code{gforth-ditc}
1.29 crook 10499: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 10500: words @code{savesystem} and @code{bye} must be visible. A special doubly
10501: indirect threaded version of the @file{gforth} executable is used for
10502: creating the nonrelocatable images; you can pass the exact filename of
10503: this executable through the environment variable @code{GFORTHD}
10504: (default: @file{gforth-ditc}); if you pass a version that is not doubly
10505: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 10506: data-relocatable image (because there is no code address offset). The
10507: normal @file{gforth} executable is used for creating the relocatable
10508: image; you can pass the exact filename of this executable through the
10509: environment variable @code{GFORTH}.
1.1 anton 10510:
10511: @node cross.fs, , gforthmi, Fully Relocatable Image Files
10512: @subsection @file{cross.fs}
10513: @cindex @file{cross.fs}
10514: @cindex cross-compiler
10515: @cindex metacompiler
10516:
10517: You can also use @code{cross}, a batch compiler that accepts a Forth-like
10518: programming language. This @code{cross} language has to be documented
10519: yet.
10520:
10521: @cindex target compiler
10522: @code{cross} also allows you to create image files for machines with
10523: different data sizes and data formats than the one used for generating
10524: the image file. You can also use it to create an application image that
10525: does not contain a Forth compiler. These features are bought with
10526: restrictions and inconveniences in programming. E.g., addresses have to
10527: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
10528: order to make the code relocatable.
10529:
10530:
10531: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
10532: @section Stack and Dictionary Sizes
10533: @cindex image file, stack and dictionary sizes
10534: @cindex dictionary size default
10535: @cindex stack size default
10536:
10537: If you invoke Gforth with a command line flag for the size
10538: (@pxref{Invoking Gforth}), the size you specify is stored in the
10539: dictionary. If you save the dictionary with @code{savesystem} or create
10540: an image with @file{gforthmi}, this size will become the default
10541: for the resulting image file. E.g., the following will create a
1.21 crook 10542: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 10543:
10544: @example
10545: gforthmi gforth.fi -m 1M
10546: @end example
10547:
10548: In other words, if you want to set the default size for the dictionary
10549: and the stacks of an image, just invoke @file{gforthmi} with the
10550: appropriate options when creating the image.
10551:
10552: @cindex stack size, cache-friendly
10553: Note: For cache-friendly behaviour (i.e., good performance), you should
10554: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
10555: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
10556: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
10557:
10558: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
10559: @section Running Image Files
10560: @cindex running image files
10561: @cindex invoking image files
10562: @cindex image file invocation
10563:
10564: @cindex -i, invoke image file
10565: @cindex --image file, invoke image file
1.29 crook 10566: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 10567: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
10568: @example
1.29 crook 10569: gforth -i @i{image}
1.1 anton 10570: @end example
10571:
10572: @cindex executable image file
1.26 crook 10573: @cindex image file, executable
1.1 anton 10574: If your operating system supports starting scripts with a line of the
10575: form @code{#! ...}, you just have to type the image file name to start
10576: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 10577: just a convention). I.e., to run Gforth with the image file @i{image},
10578: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 10579: This works because every @code{.fi} file starts with a line of this
10580: format:
10581:
10582: @example
10583: #! /usr/local/bin/gforth-0.4.0 -i
10584: @end example
10585:
10586: The file and pathname for the Gforth engine specified on this line is
10587: the specific Gforth executable that it was built against; i.e. the value
10588: of the environment variable @code{GFORTH} at the time that
10589: @file{gforthmi} was executed.
1.1 anton 10590:
1.27 crook 10591: You can make use of the same shell capability to make a Forth source
10592: file into an executable. For example, if you place this text in a file:
1.26 crook 10593:
10594: @example
10595: #! /usr/local/bin/gforth
10596:
10597: ." Hello, world" CR
10598: bye
10599: @end example
10600:
10601: @noindent
1.27 crook 10602: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 10603: directly from the command line. The sequence @code{#!} is used in two
10604: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 10605: system@footnote{The Unix kernel actually recognises two types of files:
10606: executable files and files of data, where the data is processed by an
10607: interpreter that is specified on the ``interpreter line'' -- the first
10608: line of the file, starting with the sequence #!. There may be a small
10609: limit (e.g., 32) on the number of characters that may be specified on
10610: the interpreter line.} secondly it is treated as a comment character by
10611: Gforth. Because of the second usage, a space is required between
10612: @code{#!} and the path to the executable.
1.27 crook 10613:
10614: The disadvantage of this latter technique, compared with using
10615: @file{gforthmi}, is that it is slower; the Forth source code is compiled
10616: on-the-fly, each time the program is invoked.
10617:
1.26 crook 10618: @comment TODO describe the #! magic with reference to the Power Tools book.
10619:
1.1 anton 10620: doc-#!
10621:
10622: @node Modifying the Startup Sequence, , Running Image Files, Image Files
10623: @section Modifying the Startup Sequence
10624: @cindex startup sequence for image file
10625: @cindex image file initialization sequence
10626: @cindex initialization sequence of image file
10627:
10628: You can add your own initialization to the startup sequence through the
1.26 crook 10629: deferred word @code{'cold}. @code{'cold} is invoked just before the
10630: image-specific command line processing (by default, loading files and
10631: evaluating (@code{-e}) strings) starts.
1.1 anton 10632:
10633: A sequence for adding your initialization usually looks like this:
10634:
10635: @example
10636: :noname
10637: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
10638: ... \ your stuff
10639: ; IS 'cold
10640: @end example
10641:
10642: @cindex turnkey image files
1.26 crook 10643: @cindex image file, turnkey applications
1.1 anton 10644: You can make a turnkey image by letting @code{'cold} execute a word
10645: (your turnkey application) that never returns; instead, it exits Gforth
10646: via @code{bye} or @code{throw}.
10647:
10648: @cindex command-line arguments, access
10649: @cindex arguments on the command line, access
10650: You can access the (image-specific) command-line arguments through the
1.26 crook 10651: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1 anton 10652: access to @code{argv}.
10653:
1.26 crook 10654: If @code{'cold} exits normally, Gforth processes the command-line
10655: arguments as files to be loaded and strings to be evaluated. Therefore,
10656: @code{'cold} should remove the arguments it has used in this case.
10657:
10658: doc-'cold
1.1 anton 10659: doc-argc
10660: doc-argv
10661: doc-arg
10662:
10663:
10664: @c ******************************************************************
1.13 pazsan 10665: @node Engine, Binding to System Library, Image Files, Top
1.1 anton 10666: @chapter Engine
10667: @cindex engine
10668: @cindex virtual machine
10669:
1.26 crook 10670: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 10671: may be helpful for finding your way in the Gforth sources.
10672:
10673: The ideas in this section have also been published in the papers
10674: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
10675: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
10676: Ertl, presented at EuroForth '93; the latter is available at
10677: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
10678:
10679: @menu
10680: * Portability::
10681: * Threading::
10682: * Primitives::
10683: * Performance::
10684: @end menu
10685:
10686: @node Portability, Threading, Engine, Engine
10687: @section Portability
10688: @cindex engine portability
10689:
1.26 crook 10690: An important goal of the Gforth Project is availability across a wide
10691: range of personal machines. fig-Forth, and, to a lesser extent, F83,
10692: achieved this goal by manually coding the engine in assembly language
10693: for several then-popular processors. This approach is very
10694: labor-intensive and the results are short-lived due to progress in
10695: computer architecture.
1.1 anton 10696:
10697: @cindex C, using C for the engine
10698: Others have avoided this problem by coding in C, e.g., Mitch Bradley
10699: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
10700: particularly popular for UNIX-based Forths due to the large variety of
10701: architectures of UNIX machines. Unfortunately an implementation in C
10702: does not mix well with the goals of efficiency and with using
10703: traditional techniques: Indirect or direct threading cannot be expressed
10704: in C, and switch threading, the fastest technique available in C, is
10705: significantly slower. Another problem with C is that it is very
10706: cumbersome to express double integer arithmetic.
10707:
10708: @cindex GNU C for the engine
10709: @cindex long long
10710: Fortunately, there is a portable language that does not have these
10711: limitations: GNU C, the version of C processed by the GNU C compiler
10712: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
10713: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
10714: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
10715: threading possible, its @code{long long} type (@pxref{Long Long, ,
10716: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
10717: double numbers@footnote{Unfortunately, long longs are not implemented
10718: properly on all machines (e.g., on alpha-osf1, long longs are only 64
10719: bits, the same size as longs (and pointers), but they should be twice as
1.4 anton 10720: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1 anton 10721: C Manual}). So, we had to implement doubles in C after all. Still, on
10722: most machines we can use long longs and achieve better performance than
10723: with the emulation package.}. GNU C is available for free on all
10724: important (and many unimportant) UNIX machines, VMS, 80386s running
10725: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
10726: on all these machines.
10727:
10728: Writing in a portable language has the reputation of producing code that
10729: is slower than assembly. For our Forth engine we repeatedly looked at
10730: the code produced by the compiler and eliminated most compiler-induced
10731: inefficiencies by appropriate changes in the source code.
10732:
10733: @cindex explicit register declarations
10734: @cindex --enable-force-reg, configuration flag
10735: @cindex -DFORCE_REG
10736: However, register allocation cannot be portably influenced by the
10737: programmer, leading to some inefficiencies on register-starved
10738: machines. We use explicit register declarations (@pxref{Explicit Reg
10739: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
10740: improve the speed on some machines. They are turned on by using the
10741: configuration flag @code{--enable-force-reg} (@code{gcc} switch
10742: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
10743: machine, but also on the compiler version: On some machines some
10744: compiler versions produce incorrect code when certain explicit register
10745: declarations are used. So by default @code{-DFORCE_REG} is not used.
10746:
10747: @node Threading, Primitives, Portability, Engine
10748: @section Threading
10749: @cindex inner interpreter implementation
10750: @cindex threaded code implementation
10751:
10752: @cindex labels as values
10753: GNU C's labels as values extension (available since @code{gcc-2.0},
10754: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 10755: makes it possible to take the address of @i{label} by writing
10756: @code{&&@i{label}}. This address can then be used in a statement like
10757: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 10758: @code{goto x}.
10759:
1.26 crook 10760: @cindex @code{NEXT}, indirect threaded
1.1 anton 10761: @cindex indirect threaded inner interpreter
10762: @cindex inner interpreter, indirect threaded
1.26 crook 10763: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 10764: @example
10765: cfa = *ip++;
10766: ca = *cfa;
10767: goto *ca;
10768: @end example
10769: @cindex instruction pointer
10770: For those unfamiliar with the names: @code{ip} is the Forth instruction
10771: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
10772: execution token and points to the code field of the next word to be
10773: executed; The @code{ca} (code address) fetched from there points to some
10774: executable code, e.g., a primitive or the colon definition handler
10775: @code{docol}.
10776:
1.26 crook 10777: @cindex @code{NEXT}, direct threaded
1.1 anton 10778: @cindex direct threaded inner interpreter
10779: @cindex inner interpreter, direct threaded
10780: Direct threading is even simpler:
10781: @example
10782: ca = *ip++;
10783: goto *ca;
10784: @end example
10785:
10786: Of course we have packaged the whole thing neatly in macros called
1.26 crook 10787: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 10788:
10789: @menu
10790: * Scheduling::
10791: * Direct or Indirect Threaded?::
10792: * DOES>::
10793: @end menu
10794:
10795: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
10796: @subsection Scheduling
10797: @cindex inner interpreter optimization
10798:
10799: There is a little complication: Pipelined and superscalar processors,
10800: i.e., RISC and some modern CISC machines can process independent
10801: instructions while waiting for the results of an instruction. The
10802: compiler usually reorders (schedules) the instructions in a way that
10803: achieves good usage of these delay slots. However, on our first tries
10804: the compiler did not do well on scheduling primitives. E.g., for
10805: @code{+} implemented as
10806: @example
10807: n=sp[0]+sp[1];
10808: sp++;
10809: sp[0]=n;
10810: NEXT;
10811: @end example
1.26 crook 10812: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1 anton 10813: scheduling. After a little thought the problem becomes clear: The
1.21 crook 10814: compiler cannot know that @code{sp} and @code{ip} point to different
10815: addresses (and the version of @code{gcc} we used would not know it even
10816: if it was possible), so it could not move the load of the cfa above the
10817: store to the TOS. Indeed the pointers could be the same, if code on or
10818: very near the top of stack were executed. In the interest of speed we
10819: chose to forbid this probably unused ``feature'' and helped the compiler
1.26 crook 10820: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21 crook 10821: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1 anton 10822: @example
10823: n=sp[0]+sp[1];
10824: sp++;
10825: NEXT_P1;
10826: sp[0]=n;
10827: NEXT_P2;
10828: @end example
10829: This can be scheduled optimally by the compiler.
10830:
10831: This division can be turned off with the switch @code{-DCISC_NEXT}. This
10832: switch is on by default on machines that do not profit from scheduling
10833: (e.g., the 80386), in order to preserve registers.
10834:
10835: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
10836: @subsection Direct or Indirect Threaded?
10837: @cindex threading, direct or indirect?
10838:
10839: @cindex -DDIRECT_THREADED
10840: Both! After packaging the nasty details in macro definitions we
10841: realized that we could switch between direct and indirect threading by
10842: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
10843: defining a few machine-specific macros for the direct-threading case.
10844: On the Forth level we also offer access words that hide the
10845: differences between the threading methods (@pxref{Threading Words}).
10846:
10847: Indirect threading is implemented completely machine-independently.
10848: Direct threading needs routines for creating jumps to the executable
1.21 crook 10849: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
10850: machine-dependent, but they do not amount to many source lines. Therefore,
10851: even porting direct threading to a new machine requires little effort.
1.1 anton 10852:
10853: @cindex --enable-indirect-threaded, configuration flag
10854: @cindex --enable-direct-threaded, configuration flag
10855: The default threading method is machine-dependent. You can enforce a
10856: specific threading method when building Gforth with the configuration
10857: flag @code{--enable-direct-threaded} or
10858: @code{--enable-indirect-threaded}. Note that direct threading is not
10859: supported on all machines.
10860:
10861: @node DOES>, , Direct or Indirect Threaded?, Threading
10862: @subsection DOES>
10863: @cindex @code{DOES>} implementation
10864:
1.26 crook 10865: @cindex @code{dodoes} routine
10866: @cindex @code{DOES>}-code
1.1 anton 10867: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
10868: the chunk of code executed by every word defined by a
10869: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
10870: the Forth code to be executed, i.e. the code after the
1.26 crook 10871: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1 anton 10872:
1.21 crook 10873: In fig-Forth the code field points directly to the @code{dodoes} and the
1.26 crook 10874: @code{DOES>}code address is stored in the cell after the code address (i.e. at
1.29 crook 10875: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1 anton 10876: the Forth-79 and all later standards, because in fig-Forth this address
10877: lies in the body (which is illegal in these standards). However, by
10878: making the code field larger for all words this solution becomes legal
10879: again. We use this approach for the indirect threaded version and for
10880: direct threading on some machines. Leaving a cell unused in most words
10881: is a bit wasteful, but on the machines we are targeting this is hardly a
10882: problem. The other reason for having a code field size of two cells is
10883: to avoid having different image files for direct and indirect threaded
10884: systems (direct threaded systems require two-cell code fields on many
10885: machines).
10886:
1.26 crook 10887: @cindex @code{DOES>}-handler
1.1 anton 10888: The other approach is that the code field points or jumps to the cell
1.26 crook 10889: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
10890: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
10891: @code{DOES>}-code address by computing the code address, i.e., the address of
1.1 anton 10892: the jump to dodoes, and add the length of that jump field. A variant of
10893: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
10894: return address (which can be found in the return register on RISCs) is
1.26 crook 10895: the @code{DOES>}-code address. Since the two cells available in the code field
1.1 anton 10896: are used up by the jump to the code address in direct threading on many
10897: architectures, we use this approach for direct threading on these
10898: architectures. We did not want to add another cell to the code field.
10899:
10900: @node Primitives, Performance, Threading, Engine
10901: @section Primitives
10902: @cindex primitives, implementation
10903: @cindex virtual machine instructions, implementation
10904:
10905: @menu
10906: * Automatic Generation::
10907: * TOS Optimization::
10908: * Produced code::
10909: @end menu
10910:
10911: @node Automatic Generation, TOS Optimization, Primitives, Primitives
10912: @subsection Automatic Generation
10913: @cindex primitives, automatic generation
10914:
10915: @cindex @file{prims2x.fs}
10916: Since the primitives are implemented in a portable language, there is no
10917: longer any need to minimize the number of primitives. On the contrary,
10918: having many primitives has an advantage: speed. In order to reduce the
10919: number of errors in primitives and to make programming them easier, we
10920: provide a tool, the primitive generator (@file{prims2x.fs}), that
10921: automatically generates most (and sometimes all) of the C code for a
10922: primitive from the stack effect notation. The source for a primitive
10923: has the following form:
10924:
10925: @cindex primitive source format
10926: @format
1.29 crook 10927: @i{Forth-name} @i{stack-effect} @i{category} [@i{pronounc.}]
10928: [@code{""}@i{glossary entry}@code{""}]
10929: @i{C code}
1.1 anton 10930: [@code{:}
1.29 crook 10931: @i{Forth code}]
1.1 anton 10932: @end format
10933:
10934: The items in brackets are optional. The category and glossary fields
10935: are there for generating the documentation, the Forth code is there
10936: for manual implementations on machines without GNU C. E.g., the source
10937: for the primitive @code{+} is:
10938: @example
10939: + n1 n2 -- n core plus
10940: n = n1+n2;
10941: @end example
10942:
10943: This looks like a specification, but in fact @code{n = n1+n2} is C
10944: code. Our primitive generation tool extracts a lot of information from
10945: the stack effect notations@footnote{We use a one-stack notation, even
10946: though we have separate data and floating-point stacks; The separate
10947: notation can be generated easily from the unified notation.}: The number
10948: of items popped from and pushed on the stack, their type, and by what
10949: name they are referred to in the C code. It then generates a C code
10950: prelude and postlude for each primitive. The final C code for @code{+}
10951: looks like this:
10952:
10953: @example
10954: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
10955: /* */ /* documentation */
10956: @{
10957: DEF_CA /* definition of variable ca (indirect threading) */
10958: Cell n1; /* definitions of variables */
10959: Cell n2;
10960: Cell n;
10961: n1 = (Cell) sp[1]; /* input */
10962: n2 = (Cell) TOS;
10963: sp += 1; /* stack adjustment */
10964: NAME("+") /* debugging output (with -DDEBUG) */
10965: @{
10966: n = n1+n2; /* C code taken from the source */
10967: @}
10968: NEXT_P1; /* NEXT part 1 */
10969: TOS = (Cell)n; /* output */
10970: NEXT_P2; /* NEXT part 2 */
10971: @}
10972: @end example
10973:
10974: This looks long and inefficient, but the GNU C compiler optimizes quite
10975: well and produces optimal code for @code{+} on, e.g., the R3000 and the
10976: HP RISC machines: Defining the @code{n}s does not produce any code, and
10977: using them as intermediate storage also adds no cost.
10978:
1.26 crook 10979: There are also other optimizations that are not illustrated by this
10980: example: assignments between simple variables are usually for free (copy
1.1 anton 10981: propagation). If one of the stack items is not used by the primitive
10982: (e.g. in @code{drop}), the compiler eliminates the load from the stack
10983: (dead code elimination). On the other hand, there are some things that
10984: the compiler does not do, therefore they are performed by
10985: @file{prims2x.fs}: The compiler does not optimize code away that stores
10986: a stack item to the place where it just came from (e.g., @code{over}).
10987:
10988: While programming a primitive is usually easy, there are a few cases
10989: where the programmer has to take the actions of the generator into
10990: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 10991: fall through to @code{NEXT}.
1.1 anton 10992:
10993: @node TOS Optimization, Produced code, Automatic Generation, Primitives
10994: @subsection TOS Optimization
10995: @cindex TOS optimization for primitives
10996: @cindex primitives, keeping the TOS in a register
10997:
10998: An important optimization for stack machine emulators, e.g., Forth
10999: engines, is keeping one or more of the top stack items in
1.29 crook 11000: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
11001: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 11002: @itemize @bullet
11003: @item
1.29 crook 11004: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 11005: due to fewer loads from and stores to the stack.
1.29 crook 11006: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
11007: @i{y<n}, due to additional moves between registers.
1.1 anton 11008: @end itemize
11009:
11010: @cindex -DUSE_TOS
11011: @cindex -DUSE_NO_TOS
11012: In particular, keeping one item in a register is never a disadvantage,
11013: if there are enough registers. Keeping two items in registers is a
11014: disadvantage for frequent words like @code{?branch}, constants,
11015: variables, literals and @code{i}. Therefore our generator only produces
11016: code that keeps zero or one items in registers. The generated C code
11017: covers both cases; the selection between these alternatives is made at
11018: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
11019: code for @code{+} is just a simple variable name in the one-item case,
11020: otherwise it is a macro that expands into @code{sp[0]}. Note that the
11021: GNU C compiler tries to keep simple variables like @code{TOS} in
11022: registers, and it usually succeeds, if there are enough registers.
11023:
11024: @cindex -DUSE_FTOS
11025: @cindex -DUSE_NO_FTOS
11026: The primitive generator performs the TOS optimization for the
11027: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
11028: operations the benefit of this optimization is even larger:
11029: floating-point operations take quite long on most processors, but can be
11030: performed in parallel with other operations as long as their results are
11031: not used. If the FP-TOS is kept in a register, this works. If
11032: it is kept on the stack, i.e., in memory, the store into memory has to
11033: wait for the result of the floating-point operation, lengthening the
11034: execution time of the primitive considerably.
11035:
11036: The TOS optimization makes the automatic generation of primitives a
11037: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
11038: @code{TOS} is not sufficient. There are some special cases to
11039: consider:
11040: @itemize @bullet
11041: @item In the case of @code{dup ( w -- w w )} the generator must not
11042: eliminate the store to the original location of the item on the stack,
11043: if the TOS optimization is turned on.
11044: @item Primitives with stack effects of the form @code{--}
1.29 crook 11045: @i{out1}...@i{outy} must store the TOS to the stack at the start.
11046: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 11047: must load the TOS from the stack at the end. But for the null stack
11048: effect @code{--} no stores or loads should be generated.
11049: @end itemize
11050:
11051: @node Produced code, , TOS Optimization, Primitives
11052: @subsection Produced code
11053: @cindex primitives, assembly code listing
11054:
11055: @cindex @file{engine.s}
11056: To see what assembly code is produced for the primitives on your machine
11057: with your compiler and your flag settings, type @code{make engine.s} and
11058: look at the resulting file @file{engine.s}.
11059:
11060: @node Performance, , Primitives, Engine
11061: @section Performance
11062: @cindex performance of some Forth interpreters
11063: @cindex engine performance
11064: @cindex benchmarking Forth systems
11065: @cindex Gforth performance
11066:
11067: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
11068: impossible to write a significantly faster engine.
11069:
11070: On register-starved machines like the 386 architecture processors
11071: improvements are possible, because @code{gcc} does not utilize the
11072: registers as well as a human, even with explicit register declarations;
11073: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
11074: and hand-tuned it for the 486; this system is 1.19 times faster on the
11075: Sieve benchmark on a 486DX2/66 than Gforth compiled with
11076: @code{gcc-2.6.3} with @code{-DFORCE_REG}.
11077:
11078: @cindex Win32Forth performance
11079: @cindex NT Forth performance
11080: @cindex eforth performance
11081: @cindex ThisForth performance
11082: @cindex PFE performance
11083: @cindex TILE performance
11084: However, this potential advantage of assembly language implementations
11085: is not necessarily realized in complete Forth systems: We compared
11086: Gforth (direct threaded, compiled with @code{gcc-2.6.3} and
11087: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
11088: 1994) and Eforth (with and without peephole (aka pinhole) optimization
11089: of the threaded code); all these systems were written in assembly
11090: language. We also compared Gforth with three systems written in C:
11091: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
11092: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21 crook 11093: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
11094: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1 anton 11095: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
11096: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
11097: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
11098: 486DX2/66 with similar memory performance under Windows NT. Marcel
11099: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
11100: added the peephole optimizer, ran the benchmarks and reported the
11101: results.
11102:
11103: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
11104: matrix multiplication come from the Stanford integer benchmarks and have
11105: been translated into Forth by Martin Fraeman; we used the versions
11106: included in the TILE Forth package, but with bigger data set sizes; and
11107: a recursive Fibonacci number computation for benchmarking calling
11108: performance. The following table shows the time taken for the benchmarks
11109: scaled by the time taken by Gforth (in other words, it shows the speedup
11110: factor that Gforth achieved over the other systems).
11111:
11112: @example
11113: relative Win32- NT eforth This-
11114: time Gforth Forth Forth eforth +opt PFE Forth TILE
11115: sieve 1.00 1.39 1.14 1.39 0.85 1.58 3.18 8.58
11116: bubble 1.00 1.31 1.41 1.48 0.88 1.50 3.88
11117: matmul 1.00 1.47 1.35 1.46 0.74 1.58 4.09
11118: fib 1.00 1.52 1.34 1.22 0.86 1.74 2.99 4.30
11119: @end example
11120:
1.26 crook 11121: You may be quite surprised by the good performance of Gforth when
11122: compared with systems written in assembly language. One important reason
11123: for the disappointing performance of these other systems is probably
11124: that they are not written optimally for the 486 (e.g., they use the
11125: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
11126: but costly method for relocating the Forth image: like @code{cforth}, it
11127: computes the actual addresses at run time, resulting in two address
11128: computations per @code{NEXT} (@pxref{Image File Background}).
11129:
11130: Only Eforth with the peephole optimizer has a performance that is
11131: comparable to Gforth. The speedups achieved with peephole optimization
11132: of threaded code are quite remarkable. Adding a peephole optimizer to
11133: Gforth should cause similar speedups.
1.1 anton 11134:
11135: The speedup of Gforth over PFE, ThisForth and TILE can be easily
11136: explained with the self-imposed restriction of the latter systems to
11137: standard C, which makes efficient threading impossible (however, the
1.4 anton 11138: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 11139: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
11140: Moreover, current C compilers have a hard time optimizing other aspects
11141: of the ThisForth and the TILE source.
11142:
1.26 crook 11143: The performance of Gforth on 386 architecture processors varies widely
11144: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
11145: allocate any of the virtual machine registers into real machine
11146: registers by itself and would not work correctly with explicit register
11147: declarations, giving a 1.3 times slower engine (on a 486DX2/66 running
11148: the Sieve) than the one measured above.
1.1 anton 11149:
1.26 crook 11150: Note that there have been several releases of Win32Forth since the
11151: release presented here, so the results presented above may have little
1.1 anton 11152: predictive value for the performance of Win32Forth today.
11153:
11154: @cindex @file{Benchres}
11155: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
11156: Maierhofer (presented at EuroForth '95), an indirect threaded version of
11157: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
11158: version of Gforth is 2%@minus{}8% slower on a 486 than the direct
11159: threaded version used here. The paper available at
11160: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
11161: it also contains numbers for some native code systems. You can find a
11162: newer version of these measurements at
11163: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
11164: find numbers for Gforth on various machines in @file{Benchres}.
11165:
1.26 crook 11166: @c ******************************************************************
1.13 pazsan 11167: @node Binding to System Library, Cross Compiler, Engine, Top
1.14 pazsan 11168: @chapter Binding to System Library
1.13 pazsan 11169:
11170: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14 pazsan 11171: @chapter Cross Compiler
1.13 pazsan 11172:
11173: Cross Compiler
11174:
11175: @menu
11176: * Using the Cross Compiler::
11177: * How the Cross Compiler Works::
11178: @end menu
11179:
1.21 crook 11180: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 11181: @section Using the Cross Compiler
1.13 pazsan 11182:
1.21 crook 11183: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 11184: @section How the Cross Compiler Works
1.13 pazsan 11185:
11186: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 11187: @appendix Bugs
1.1 anton 11188: @cindex bug reporting
11189:
1.21 crook 11190: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 11191:
11192: If you find a bug, please send a bug report to
1.33 ! anton 11193: @email{bug-gforth@@gnu.org}. A bug report should include this
1.21 crook 11194: information:
11195:
11196: @itemize @bullet
11197: @item
11198: The Gforth version used (it is announced at the start of an
11199: interactive Gforth session).
11200: @item
11201: The machine and operating system (on Unix
11202: systems @code{uname -a} will report this information).
11203: @item
11204: The installation options (send the file @file{config.status}).
11205: @item
11206: A complete list of changes (if any) you (or your installer) have made to the
11207: Gforth sources.
11208: @item
11209: A program (or a sequence of keyboard commands) that reproduces the bug.
11210: @item
11211: A description of what you think constitutes the buggy behaviour.
11212: @end itemize
1.1 anton 11213:
11214: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
11215: to Report Bugs, gcc.info, GNU C Manual}.
11216:
11217:
1.21 crook 11218: @node Origin, Forth-related information, Bugs, Top
11219: @appendix Authors and Ancestors of Gforth
1.1 anton 11220:
11221: @section Authors and Contributors
11222: @cindex authors of Gforth
11223: @cindex contributors to Gforth
11224:
11225: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
11226: Ertl. The third major author was Jens Wilke. Lennart Benschop (who was
11227: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
11228: with their continuous feedback. Lennart Benshop contributed
11229: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
11230: support for calling C libraries. Helpful comments also came from Paul
11231: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.12 anton 11232: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
11233: release of Gforth-0.2.1 there were also helpful comments from many
11234: others; thank you all, sorry for not listing you here (but digging
1.23 crook 11235: through my mailbox to extract your names is on my to-do list). Since the
11236: release of Gforth-0.4.0 Neal Crook worked on the manual.
1.1 anton 11237:
11238: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
11239: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 11240: was developed across the Internet, and its authors did not meet
1.20 pazsan 11241: physically for the first 4 years of development.
1.1 anton 11242:
11243: @section Pedigree
1.26 crook 11244: @cindex pedigree of Gforth
1.1 anton 11245:
1.20 pazsan 11246: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1 anton 11247: Dirk Zoller) will cross-fertilize each other. Of course, a significant
11248: part of the design of Gforth was prescribed by ANS Forth.
11249:
1.20 pazsan 11250: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 11251: 32 bit native code version of VolksForth for the Atari ST, written
11252: mostly by Dietrich Weineck.
11253:
11254: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
11255: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
11256: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
11257:
11258: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
11259: Forth-83 standard. !! Pedigree? When?
11260:
11261: A team led by Bill Ragsdale implemented fig-Forth on many processors in
11262: 1979. Robert Selzer and Bill Ragsdale developed the original
11263: implementation of fig-Forth for the 6502 based on microForth.
11264:
11265: The principal architect of microForth was Dean Sanderson. microForth was
11266: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
11267: the 1802, and subsequently implemented on the 8080, the 6800 and the
11268: Z80.
11269:
11270: All earlier Forth systems were custom-made, usually by Charles Moore,
11271: who discovered (as he puts it) Forth during the late 60s. The first full
11272: Forth existed in 1971.
11273:
11274: A part of the information in this section comes from @cite{The Evolution
11275: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
11276: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
11277: Notices 28(3), 1993. You can find more historical and genealogical
11278: information about Forth there.
11279:
1.21 crook 11280: @node Forth-related information, Word Index, Origin, Top
11281: @appendix Other Forth-related information
11282: @cindex Forth-related information
11283:
11284: @menu
11285: * Internet resources::
11286: * Books::
11287: * The Forth Interest Group::
11288: * Conferences::
11289: @end menu
11290:
11291:
11292: @node Internet resources, Books, Forth-related information, Forth-related information
11293: @section Internet resources
1.26 crook 11294: @cindex internet resources
1.21 crook 11295:
11296: @cindex comp.lang.forth
11297: @cindex frequently asked questions
11298: There is an active newsgroup (comp.lang.forth) discussing Forth and
11299: Forth-related issues. A frequently-asked-questions (FAQ) list
11300: is posted to the newsgroup regulary, and archived at these sites:
11301:
11302: @itemize @bullet
11303: @item
11304: @url{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
11305: @item
11306: @url{ftp://ftp.forth.org/pub/Forth/FAQ/}
11307: @end itemize
11308:
11309: The FAQ list should be considered mandatory reading before posting to
11310: the newsgroup.
11311:
11312: Here are some other web sites holding Forth-related material:
11313:
11314: @itemize @bullet
11315: @item
11316: @url{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
11317: @item
11318: @url{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
11319: @item
11320: @url{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
11321: @item
11322: @url{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
11323: Research page, including links to the Journal of Forth Application and
11324: Research (JFAR) and a searchable Forth bibliography.
11325: @end itemize
11326:
11327:
11328: @node Books, The Forth Interest Group, Internet resources, Forth-related information
11329: @section Books
1.26 crook 11330: @cindex books on Forth
1.21 crook 11331:
11332: As the Standard is relatively new, there are not many books out yet. It
11333: is not recommended to learn Forth by using Gforth and a book that is not
11334: written for ANS Forth, as you will not know your mistakes from the
11335: deviations of the book. However, books based on the Forth-83 standard
11336: should be ok, because ANS Forth is primarily an extension of Forth-83.
11337:
11338: @cindex standard document for ANS Forth
11339: @cindex ANS Forth document
11340: The definite reference if you want to write ANS Forth programs is, of
1.26 crook 11341: course, the ANS Forth document. It is available in printed form from the
1.21 crook 11342: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
11343: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
11344: $200. You can also get it from Global Engineering Documents (Tel.: USA
11345: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
11346:
11347: @cite{dpANS6}, the last draft of the standard, which was then submitted
11348: to ANSI for publication is available electronically and for free in some
11349: MS Word format, and it has been converted to HTML
11350: (@url{http://www.taygeta.com/forth/dpans.html}; this is my favourite
11351: format); this HTML version also includes the answers to Requests for
11352: Interpretation (RFIs). Some pointers to these versions can be found
11353: through @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
11354:
1.26 crook 11355: @cindex introductory book on Forth
11356: @cindex book on Forth, introductory
1.21 crook 11357: @cindex Woehr, Jack: @cite{Forth: The New Model}
11358: @cindex @cite{Forth: The new model} (book)
11359: @cite{Forth: The New Model} by Jack Woehr (Prentice-Hall, 1993) is an
11360: introductory book based on a draft version of the standard. It does not
11361: cover the whole standard. It also contains interesting background
11362: information (Jack Woehr was in the ANS Forth Technical Committee). It is
11363: not appropriate for complete newbies, but programmers experienced in
11364: other languages should find it ok.
11365:
11366: @cindex Conklin, Edward K., and Elizabeth Rather: @cite{Forth Programmer's Handbook}
11367: @cindex Rather, Elizabeth and Edward K. Conklin: @cite{Forth Programmer's Handbook}
11368: @cindex @cite{Forth Programmer's Handbook} (book)
11369: @cite{Forth Programmer's Handbook} by Edward K. Conklin, Elizabeth
11370: D. Rather and the technical staff of Forth, Inc. (Forth, Inc., 1997;
11371: ISBN 0-9662156-0-5) contains little introductory material. The majority
11372: of the book is similar to @ref{Words}, but the book covers most of the
11373: standard words and some non-standard words (whereas this manual is
11374: quite incomplete). In addition, the book contains a chapter on
11375: programming style. The major drawback of this book is that it usually
11376: does not identify what is standard and what is specific to the Forth
11377: system described in the book (probably one of Forth, Inc.'s systems).
11378: Fortunately, many of the non-standard programming practices described in
11379: the book work in Gforth, too. Still, this drawback makes the book
11380: hardly more useful than a pre-ANS book.
11381:
11382: @node The Forth Interest Group, Conferences, Books, Forth-related information
11383: @section The Forth Interest Group
11384: @cindex Forth interest group (FIG)
11385:
11386: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26 crook 11387: member-supported organisation. It publishes a regular magazine,
11388: @var{FORTH Dimensions}, and offers other benefits of membership. You can
11389: contact the FIG through their office email address:
11390: @email{office@@forth.org} or by visiting their web site at
11391: @url{http://www.forth.org/}. This web site also includes links to FIG
11392: chapters in other countries and American cities
1.21 crook 11393: (@url{http://www.forth.org/chapters.html}).
11394:
11395: @node Conferences, , The Forth Interest Group, Forth-related information
11396: @section Conferences
11397: @cindex Conferences
11398:
11399: There are several regular conferences related to Forth. They are all
1.26 crook 11400: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
11401: news group:
1.21 crook 11402:
11403: @itemize @bullet
11404: @item
11405: FORML -- the Forth modification laboratory convenes every year near
11406: Monterey, California.
11407: @item
11408: The Rochester Forth Conference -- an annual conference traditionally
11409: held in Rochester, New York.
11410: @item
11411: EuroForth -- this European conference takes place annually.
11412: @end itemize
11413:
11414:
11415: @node Word Index, Concept Index, Forth-related information, Top
1.1 anton 11416: @unnumbered Word Index
11417:
1.26 crook 11418: This index is a list of Forth words that have ``glossary'' entries
11419: within this manual. Each word is listed with its stack effect and
11420: wordset.
1.1 anton 11421:
11422: @printindex fn
11423:
11424: @node Concept Index, , Word Index, Top
11425: @unnumbered Concept and Word Index
11426:
1.26 crook 11427: Not all entries listed in this index are present verbatim in the
11428: text. This index also duplicates, in abbreviated form, all of the words
11429: listed in the Word Index (only the names are listed for the words here).
1.1 anton 11430:
11431: @printindex cp
11432:
11433: @contents
11434: @bye
11435:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>