Annotation of gforth/doc/gforth.ds, revision 1.34
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
1.34 ! anton 90: @center Neal Crook
1.1 anton 91: @center Anton Ertl
1.6 pazsan 92: @center Bernd Paysan
1.5 anton 93: @center Jens Wilke
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:
1.34 ! anton 3710: doc-create
! 3711:
1.29 crook 3712: By extending this example to reserve some memory in data space, we end
3713: up with a @i{variable}. Here are two different ways to do it:
3714:
3715: @example
3716: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
3717: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
3718: @end example
3719:
3720: The variable can be examined and modified using @code{@@} (``fetch'') and
3721: @code{!} (``store'') like this:
3722:
3723: @example
3724: new-word2 @@ . \ get address, fetch from it and display
3725: 1234 new-word2 ! \ new value, get address, store to it
3726: @end example
3727:
3728: As a final refinement, the whole code sequence can be wrapped up in a
3729: defining word (pre-empting the subject of the next section), making it
3730: easier to create new variables:
3731:
3732: @example
1.33 anton 3733: : myvariable ( "name" -- a-addr ) CREATE 0 , ;
1.29 crook 3734:
3735: myvariable foo
3736: myvariable joe
3737:
3738: 45 3 * foo ! \ set foo to 135
3739: 1234 joe ! \ set joe to 1234
3740: 3 joe +! \ increment joe by 3.. to 1237
3741: @end example
3742:
3743: Not surprisingly, there is no need to define @code{myvariable}, since
3744: Forth already has a definition @code{Variable}. It behaves in exactly
1.33 anton 3745: the same way as @code{myvariable}. Forth also provides @code{2Variable}
3746: and @code{fvariable} for double and floating-point variables,
3747: respectively.
1.29 crook 3748:
1.34 ! anton 3749: doc-variable
! 3750: doc-2variable
! 3751: doc-fvariable
! 3752:
1.29 crook 3753: @cindex arrays
3754: A similar mechanism can be used to create arrays. For example, an
3755: 80-character text input buffer:
3756:
3757: @example
3758: CREATE text-buf 80 chars allot
3759:
3760: text-buf 0 chars c@@ \ the 1st character (offset 0)
3761: text-buf 3 chars c@@ \ the 4th character (offset 3)
3762: @end example
3763:
3764: You can build arbitrarily complex data structures by allocating
3765: appropriate areas of memory. @xref{Structures} for further discussions
3766: of this, and to learn about some Gforth tools that make it easier.
3767:
3768: @cindex user variables
3769: @cindex user space
3770: The defining word @code{User} behaves in the same way as @code{Variable}.
3771: The difference is that it reserves space in @i{user (data) space} rather
3772: than normal data space. In a Forth system that has a multi-tasker, each
3773: task has its own set of user variables.
3774:
1.34 ! anton 3775: doc-user
! 3776:
1.29 crook 3777: @comment TODO is that stuff about user variables strictly correct? Is it
3778: @comment just terminal tasks that have user variables?
3779: @comment should document tasker.fs (with some examples) elsewhere
3780: @comment in this manual, then expand on user space and user variables.
3781:
3782: After @code{CREATE} and @code{Variable}s, the next defining word to
3783: consider is @code{Constant}. @code{Constant} allows you to declare a
3784: fixed value and refer to it by name. For example:
3785:
3786: @example
3787: 12 Constant INCHES-PER-FOOT
3788: 3E+08 fconstant SPEED-O-LIGHT
3789: @end example
3790:
3791: A @code{Variable} can be both read and written, so its run-time
3792: behaviour is to supply an address through which its current value can be
3793: manipulated. In contrast, the value of a @code{Constant} cannot be
3794: changed once it has been declared@footnote{Well, often it can be -- but
3795: not in a Standard, portable way. It's safer to use a @code{Value} (read
3796: on).} so it's not necessary to supply the address -- it is more
3797: efficient to return the value of the constant directly. That's exactly
3798: what happens; the run-time effect of a constant is to put its value on
3799: the top of the stack (@ref{User-defined Defining Words} describes one
3800: way of implementing @code{Constant}).
3801:
3802: Gforth also provides @code{2Constant} and @code{fconstant} for defining
3803: double and floating-point constants, respectively.
3804:
1.34 ! anton 3805: doc-constant
! 3806: doc-2constant
! 3807: doc-fconstant
! 3808:
! 3809: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.29 crook 3810: Constants in Forth behave differently from their equivalents in other
3811: programming languages. In other languages, a constant (such as an EQU in
3812: assembler or a #define in C) only exists at compile-time; in the
3813: executable program the constant has been translated into an absolute
3814: number and, unless you are using a symbolic debugger, it's impossible to
3815: know what abstract thing that number represents. In Forth a constant has
1.32 anton 3816: an entry in the header space and remains there after the code that
1.29 crook 3817: uses it has been defined. In fact, it must remain in the dictionary
3818: since it has run-time duties to perform. For example:
3819:
3820: @example
3821: 12 Constant INCHES-PER-FOOT
3822: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
3823: @end example
3824:
3825: @cindex in-lining of constants
3826: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
3827: associated with the constant @code{INCHES-PER-FOOT}. If you use
3828: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
3829: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
3830: attempt to optimise constants by in-lining them where they are used. You
3831: can force Gforth to in-line a constant like this:
3832:
3833: @example
3834: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
3835: @end example
3836:
3837: If you use @code{see} to decompile @i{this} version of
3838: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.33 anton 3839: longer present. @xref{Interpret/Compile states} and @ref{Literals} on
3840: how this works.
1.29 crook 3841:
3842: In-lining constants in this way might improve execution time
3843: fractionally, and can ensure that a constant is now only referenced at
3844: compile-time. However, the definition of the constant still remains in
3845: the dictionary. Some Forth compilers provide a mechanism for controlling
3846: a second dictionary for holding transient words such that this second
3847: dictionary can be deleted later in order to recover memory
3848: space. However, there is no standard way of doing this.
3849:
3850: One aspect of constants and variables that can sometimes be confusing is
3851: that they have different stack effects; one returns its value whilst the
3852: other returns the address of its value. The defining word @code{Value}
3853: provides an alternative to @code{Variable}, and has the same stack
3854: effect as a constant. A @code{Value} needs an additional word, @code{TO}
3855: to allow its value to be changed. Here are some examples:
3856:
3857: @example
3858: 12 Value APPLES \ a Value is initialised when it is declared.. like a
3859: \ constant but unlike a variable
3860: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
3861: APPLES \ puts 34 on the top of the stack.
3862: @end example
3863:
1.34 ! anton 3864: doc-value
! 3865: doc-to
! 3866:
1.29 crook 3867: The defining word @code{Defer} allows you to define a word by name
3868: without defining its behaviour; the definition of its behaviour is
3869: deferred. Here are two situation where this can be useful:
3870:
3871: @itemize @bullet
3872: @item
3873: Where you want to allow the behaviour of a word to be altered later, and
3874: for all precompiled references to the word to change when its behaviour
3875: is changed.
3876: @item
3877: For mutual recursion; @xref{Calls and returns}.
3878: @end itemize
3879:
3880: In the following example, @code{foo} always invokes the version of
3881: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
3882: always invokes the version that prints ``@code{Hello}''. There is no way
3883: of getting @code{foo} to use the later version without re-ordering the
3884: source code and recompilng it.
3885:
3886: @example
3887: : greet ." Good morning" ;
3888: : foo ... greet ... ;
3889: : greet ." Hello" ;
3890: : bar ... greet ... ;
3891: @end example
3892:
3893: This problem can be solved by defining @code{greet} as a @code{Defer}red
3894: word. The behaviour of a @code{Defer}red word can be defined and
3895: redefined at any time by using @code{IS} to associate the xt of a
3896: previously-defined word with it. The previous example becomes:
3897:
3898: @example
3899: Defer greet
3900: : foo ... greet ... ;
3901: : bar ... greet ... ;
3902: : greet1 ." Good morning" ;
3903: : greet2 ." Hello" ;
3904: ' greet2 IS greet \ make greet behave like greet2
3905: @end example
3906:
3907: A deferred word can only inherit default semantics from the xt (because
3908: that is all that an xt can represent -- @pxref{Tokens for Words} for
3909: more discussion of this). However, the semantics of the deferred word
3910: itself can be modified at the time that it is defined. For example:
3911:
3912: @example
3913: : bar .... ; compile-only
3914: Defer fred immediate
3915: Defer jim
3916:
3917: ' bar IS jim \ jim has default semantics
3918: ' bar IS fred \ fred is immediate
3919: @end example
1.1 anton 3920:
1.34 ! anton 3921: doc-defer
! 3922: doc-is
! 3923: @comment TODO document these: what's defers <is> [is]
! 3924: doc-what's
! 3925: doc-defers
! 3926:
! 3927: Definitions in ANS Forth for @code{defer}, @code{<is>} and
! 3928: @code{[is]} are provided in @file{compat/defer.fs}.
! 3929:
1.29 crook 3930: The defining word @code{Alias} allows you to define a word by name that
3931: has the same behaviour as some other word. Here are two situation where
3932: this can be useful:
1.1 anton 3933:
1.29 crook 3934: @itemize @bullet
3935: @item
3936: When you want access to a word's definition from a different word list
3937: (for an example of this, see the definition of the @code{Root} word list
3938: in the Gforth source).
3939: @item
3940: When you want to create a synonym; a definition that can be known by
3941: either of two names (for example, @code{THEN} and @code{ENDIF} are
3942: aliases).
3943: @end itemize
1.1 anton 3944:
1.29 crook 3945: The word whose behaviour the alias is to inherit is represented by an
1.34 ! anton 3946: xt. Therefore, the alias only inherits default semantics from its
1.29 crook 3947: ancestor. The semantics of the alias itself can be modified at the time
3948: that it is defined. For example:
1.1 anton 3949:
1.29 crook 3950: @example
3951: : foo ... ; immediate
1.1 anton 3952:
1.29 crook 3953: ' foo Alias bar \ bar is not an immediate word
3954: ' foo Alias fooby immediate \ fooby is an immediate word
3955: @end example
1.26 crook 3956:
1.34 ! anton 3957: @c "combined words" is an undefined term
! 3958: Words that are aliases have the same xt, different headers in the
! 3959: dictionary, and consequently different name tokens (@pxref{Tokens for
! 3960: Words}) and possibly different immediate flags. An alias can only have
! 3961: default or immediate compilation semantics; you can define aliases for
! 3962: combined words with @code{interpret/compile:}.
1.27 crook 3963:
1.33 anton 3964: @c distribute this to the appropriate paragraphs? - anton
1.29 crook 3965: doc-alias
1.1 anton 3966:
1.26 crook 3967: @node Colon Definitions, User-defined Defining Words, Simple Defining Words, Defining Words
3968: @subsection Colon Definitions
3969: @cindex colon definitions
1.1 anton 3970:
1.26 crook 3971: @example
3972: : name ( ... -- ... )
3973: word1 word2 word3 ;
3974: @end example
1.1 anton 3975:
1.29 crook 3976: @noindent
3977: Creates a word called @code{name} that, upon execution, executes
1.26 crook 3978: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.1 anton 3979:
1.29 crook 3980: The explanation above is somewhat superficial. @xref{Your first
3981: definition} for simple examples of colon definitions, then
3982: @xref{Interpretation and Compilation Semantics} for an in-depth
3983: discussion of some of the issues involved.
1.26 crook 3984:
3985: doc-:
3986: doc-;
1.1 anton 3987:
1.26 crook 3988: @node User-defined Defining Words, Supplying names, Colon Definitions, Defining Words
3989: @subsection User-defined Defining Words
3990: @cindex user-defined defining words
3991: @cindex defining words, user-defined
1.1 anton 3992:
1.29 crook 3993: You can create a new defining word by wrapping defining-time code around
3994: an existing defining word and putting the sequence in a colon
3995: definition. For example, suppose that you have a word @code{stats} that
3996: gathers statistics about colon definitions given the @i{xt} of the
3997: definition, and you want every colon definition in your application to
3998: make a call to @code{stats}. You can define and use a new version of
3999: @code{:} like this:
4000:
4001: @example
4002: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
4003: ... ; \ other code
4004:
4005: : my: : lastxt postpone literal ['] stats compile, ;
4006:
4007: my: foo + - ;
4008: @end example
4009:
4010: When @code{foo} is defined using @code{my:} these steps occur:
4011:
4012: @itemize @bullet
4013: @item
4014: @code{my:} is executed.
4015: @item
4016: The @code{:} within the definition (the one between @code{my:} and
4017: @code{lastxt}) is executed, and does just what it always does; it parses
4018: the input stream for a name, builds a dictionary header for the name
4019: @code{foo} and switches @code{state} from interpret to compile.
4020: @item
4021: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
4022: being defined -- @code{foo} -- onto the stack.
4023: @item
4024: The code that was produced by @code{postpone literal} is executed; this
4025: causes the value on the stack to be compiled as a literal in the code
4026: area of @code{foo}.
4027: @item
4028: The code @code{['] stats} compiles a literal into the definition of
4029: @code{my:}. When @code{compile,} is executed, that literal -- the
4030: execution token for @code{stats} -- is layed down in the code area of
4031: @code{foo} , following the literal@footnote{Strictly speaking, the
4032: mechanism that @code{compile,} uses to convert an @i{xt} into something
4033: in the code area is implementation-dependent. A threaded implementation
4034: might spit out the execution token directly whilst another
4035: implementation might spit out a native code sequence.}.
4036: @item
4037: At this point, the execution of @code{my:} is complete, and control
4038: returns to the text interpreter. The text interpreter is in compile
4039: state, so subsequent text @code{+ -} is compiled into the definition of
4040: @code{foo} and the @code{;} terminates the definition as always.
4041: @end itemize
4042:
4043: You can use @code{see} to decompile a word that was defined using
4044: @code{my:} and see how it is different from a normal @code{:}
4045: definition. For example:
4046:
4047: @example
4048: : bar + - ; \ like foo but using : rather than my:
4049: see bar
4050: : bar
4051: + - ;
4052: see foo
4053: : foo
4054: 107645672 stats + - ;
4055:
4056: \ use ' stats . to show that 107645672 is the xt for stats
4057: @end example
4058:
4059:
1.33 anton 4060: @c a deferred word is not neccessary for these examples. - anton
1.29 crook 4061: Rather than edit your application's source code to change every @code{:}
4062: to a @code{my:}, use a deferred word:
4063:
4064: @example
4065: : real: : ; \ retain access to the original
4066: defer : \ redefine as a deferred word
4067: ' my: IS : \ use special version of :
4068: \
4069: \ load application here
4070: \
4071: ' real: IS : \ go back to the original
4072: @end example
4073:
4074: You can use techniques like this to make new defining words in terms of
4075: @i{any} existing defining word.
1.1 anton 4076:
4077:
1.29 crook 4078: @cindex defining defining words
1.26 crook 4079: @cindex @code{CREATE} ... @code{DOES>}
4080: If you want the words defined with your defining words to behave
4081: differently from words defined with standard defining words, you can
4082: write your defining word like this:
1.1 anton 4083:
4084: @example
1.26 crook 4085: : def-word ( "name" -- )
1.29 crook 4086: CREATE @i{code1}
1.26 crook 4087: DOES> ( ... -- ... )
1.29 crook 4088: @i{code2} ;
1.26 crook 4089:
4090: def-word name
1.1 anton 4091: @end example
4092:
1.29 crook 4093: @cindex child words
4094: This fragment defines a @dfn{defining word} @code{def-word} and then
4095: executes it. When @code{def-word} executes, it @code{CREATE}s a new
4096: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
4097: is not executed at this time. The word @code{name} is sometimes called a
4098: @dfn{child} of @code{def-word}.
4099:
4100: When you execute @code{name}, the address of the body of @code{name} is
4101: put on the data stack and @i{code2} is executed (the address of the body
4102: of @code{name} is the address @code{HERE} returns immediately after the
4103: @code{CREATE}).
4104:
4105: @cindex atavism in child words
1.33 anton 4106: You can use @code{def-word} to define a set of child words that behave
1.29 crook 4107: differently, though atavistically; they all have a common run-time
4108: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
4109: builds a data area in the body of the child word. The structure of the
4110: data is common to all children of @code{def-word}, but the data values
4111: are specific -- and private -- to each child word. When a child word is
4112: executed, the address of its private data area is passed as a parameter
4113: on TOS to be used and manipulated@footnote{It is legitimate both to read
4114: and write to this data area.} by @i{code2}.
4115:
4116: The two fragments of code that make up the defining words act (are
4117: executed) at two completely separate times:
1.1 anton 4118:
1.29 crook 4119: @itemize @bullet
4120: @item
4121: At @i{define time}, the defining word executes @i{code1} to generate a
4122: child word
4123: @item
4124: At @i{child execution time}, when a child word is invoked, @i{code2}
4125: is executed, using parameters (data) that are private and specific to
4126: the child word.
4127: @end itemize
4128:
4129: @c NAC I think this is a really bad example, because it diminishes
4130: @c rather than emphasising the fact that some important stuff happens
4131: @c at define time, and other important stuff happens at child-invocation
4132: @c time, and that those two times are potentially very different.
1.33 anton 4133:
4134: @c Well, IMO CREATE-DOES> is usually presented with much ado, making
4135: @c people think that it's hard to understand, and making those people who
4136: @c understand it easily think that it's hyped. I prefer presenting it in a
4137: @c diminished way and only emphasize the special issues later. - anton
4138:
4139: In other words, if you make the following definitions:
4140: @example
4141: : def-word1 ( "name" -- )
4142: CREATE @i{code1} ;
4143:
4144: : action1 ( ... -- ... )
4145: @i{code2} ;
4146:
4147: def-word1 name1
4148: @end example
4149:
4150: Using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 4151:
1.29 crook 4152: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 4153:
1.1 anton 4154: @example
1.29 crook 4155: : CONSTANT ( w "name" -- )
4156: CREATE ,
1.26 crook 4157: DOES> ( -- w )
4158: @@ ;
1.1 anton 4159: @end example
4160:
1.29 crook 4161: @comment There is a beautiful description of how this works and what
4162: @comment it does in the Forthwrite 100th edition.. as well as an elegant
4163: @comment commentary on the Counting Fruits problem.
4164:
4165: When you create a constant with @code{5 CONSTANT five}, a set of
4166: define-time actions take place; first a new word @code{five} is created,
4167: then the value 5 is laid down in the body of @code{five} with
4168: @code{,}. When @code{five} is invoked, the address of the body is put on
4169: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
4170: no code of its own; it simply contains a data field and a pointer to the
4171: code that follows @code{DOES>} in its defining word. That makes words
4172: created in this way very compact.
4173:
4174: The final example in this section is intended to remind you that space
4175: reserved in @code{CREATE}d words is @i{data} space and therefore can be
4176: both read and written by a Standard program@footnote{Exercise: use this
4177: example as a starting point for your own implementation of @code{Value}
4178: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
4179: @code{[']}.}:
4180:
4181: @example
4182: : foo ( "name" -- )
4183: CREATE -1 ,
4184: DOES> ( -- )
1.33 anton 4185: @@ . ;
1.29 crook 4186:
4187: foo first-word
4188: foo second-word
4189:
4190: 123 ' first-word >BODY !
4191: @end example
4192:
4193: If @code{first-word} had been a @code{CREATE}d word, we could simply
4194: have executed it to get the address of its data field. However, since it
4195: was defined to have @code{DOES>} actions, its execution semantics are to
4196: perform those @code{DOES>} actions. To get the address of its data field
4197: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
4198: translate the xt into the address of the data field. When you execute
4199: @code{first-word}, it will display @code{123}. When you execute
4200: @code{second-word} it will display @code{-1}.
1.26 crook 4201:
4202: @cindex stack effect of @code{DOES>}-parts
4203: @cindex @code{DOES>}-parts, stack effect
1.29 crook 4204: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 4205: the stack effect of the defined words, not the stack effect of the
4206: following code (the following code expects the address of the body on
4207: the top of stack, which is not reflected in the stack comment). This is
4208: the convention that I use and recommend (it clashes a bit with using
4209: locals declarations for stack effect specification, though).
1.1 anton 4210:
1.26 crook 4211: @subsubsection Applications of @code{CREATE..DOES>}
4212: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 4213:
1.26 crook 4214: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 4215:
1.26 crook 4216: @cindex factoring similar colon definitions
4217: When you see a sequence of code occurring several times, and you can
4218: identify a meaning, you will factor it out as a colon definition. When
4219: you see similar colon definitions, you can factor them using
4220: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
4221: that look very similar:
1.1 anton 4222: @example
1.26 crook 4223: : ori, ( reg-target reg-source n -- )
4224: 0 asm-reg-reg-imm ;
4225: : andi, ( reg-target reg-source n -- )
4226: 1 asm-reg-reg-imm ;
1.1 anton 4227: @end example
4228:
1.26 crook 4229: @noindent
4230: This could be factored with:
4231: @example
4232: : reg-reg-imm ( op-code -- )
4233: CREATE ,
4234: DOES> ( reg-target reg-source n -- )
4235: @@ asm-reg-reg-imm ;
4236:
4237: 0 reg-reg-imm ori,
4238: 1 reg-reg-imm andi,
4239: @end example
1.1 anton 4240:
1.26 crook 4241: @cindex currying
4242: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
4243: supply a part of the parameters for a word (known as @dfn{currying} in
4244: the functional language community). E.g., @code{+} needs two
4245: parameters. Creating versions of @code{+} with one parameter fixed can
4246: be done like this:
1.1 anton 4247: @example
1.26 crook 4248: : curry+ ( n1 -- )
4249: CREATE ,
4250: DOES> ( n2 -- n1+n2 )
4251: @@ + ;
4252:
4253: 3 curry+ 3+
4254: -2 curry+ 2-
1.1 anton 4255: @end example
4256:
1.26 crook 4257: @subsubsection The gory details of @code{CREATE..DOES>}
4258: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 4259:
1.26 crook 4260: doc-does>
1.1 anton 4261:
1.26 crook 4262: @cindex @code{DOES>} in a separate definition
4263: This means that you need not use @code{CREATE} and @code{DOES>} in the
4264: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 4265: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 4266: @example
4267: : does1
4268: DOES> ( ... -- ... )
4269: ... ;
1.1 anton 4270:
1.26 crook 4271: : does2
4272: DOES> ( ... -- ... )
4273: ... ;
1.1 anton 4274:
1.26 crook 4275: : def-word ( ... -- ... )
4276: create ...
4277: IF
4278: does1
4279: ELSE
4280: does2
4281: ENDIF ;
4282: @end example
1.1 anton 4283:
1.26 crook 4284: In this example, the selection of whether to use @code{does1} or
4285: @code{does2} is made at compile-time; at the time that the child word is
1.29 crook 4286: @code{CREATE}d.
1.1 anton 4287:
1.26 crook 4288: @cindex @code{DOES>} in interpretation state
4289: In a standard program you can apply a @code{DOES>}-part only if the last
4290: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
4291: will override the behaviour of the last word defined in any case. In a
4292: standard program, you can use @code{DOES>} only in a colon
4293: definition. In Gforth, you can also use it in interpretation state, in a
4294: kind of one-shot mode; for example:
1.1 anton 4295: @example
1.26 crook 4296: CREATE name ( ... -- ... )
1.29 crook 4297: @i{initialization}
1.26 crook 4298: DOES>
1.29 crook 4299: @i{code} ;
1.1 anton 4300: @end example
4301:
1.26 crook 4302: @noindent
4303: is equivalent to the standard:
1.1 anton 4304: @example
1.26 crook 4305: :noname
4306: DOES>
1.29 crook 4307: @i{code} ;
1.26 crook 4308: CREATE name EXECUTE ( ... -- ... )
1.29 crook 4309: @i{initialization}
1.1 anton 4310: @end example
4311:
1.26 crook 4312: You can get the address of the body of a word with:
4313:
4314: doc->body
1.1 anton 4315:
1.26 crook 4316: @node Supplying names, Interpretation and Compilation Semantics, User-defined Defining Words, Defining Words
1.29 crook 4317: @subsection Supplying the name of a defined word
1.26 crook 4318: @cindex names for defined words
4319: @cindex defining words, name parameter
1.1 anton 4320:
1.26 crook 4321: @cindex defining words, name given in a string
1.29 crook 4322: By default, a defining word takes the name for the defined word from the
1.26 crook 4323: input stream. Sometimes you want to supply the name from a string. You
4324: can do this with:
1.1 anton 4325:
1.26 crook 4326: doc-nextname
1.1 anton 4327:
1.26 crook 4328: For example:
1.1 anton 4329:
1.26 crook 4330: @example
4331: s" foo" nextname create
4332: @end example
4333: @noindent
4334: is equivalent to:
4335: @example
4336: create foo
4337: @end example
1.1 anton 4338:
1.26 crook 4339: @cindex defining words without name
1.29 crook 4340: Sometimes you want to define an @dfn{anonymous word}; a word without a
1.26 crook 4341: name. You can do this with:
1.1 anton 4342:
1.26 crook 4343: doc-:noname
1.1 anton 4344:
1.26 crook 4345: This leaves the execution token for the word on the stack after the
4346: closing @code{;}. Here's an example in which a deferred word is
4347: initialised with an @code{xt} from an anonymous colon definition:
4348: @example
4349: Defer deferred
4350: :noname ( ... -- ... )
4351: ... ;
4352: IS deferred
4353: @end example
1.1 anton 4354:
1.29 crook 4355: @noindent
1.26 crook 4356: Gforth provides an alternative way of doing this, using two separate
4357: words:
1.1 anton 4358:
1.26 crook 4359: doc-noname
4360: @cindex execution token of last defined word
4361: doc-lastxt
1.1 anton 4362:
1.29 crook 4363: @noindent
1.26 crook 4364: The previous example can be rewritten using @code{noname} and
4365: @code{lastxt}:
1.1 anton 4366:
1.26 crook 4367: @example
4368: Defer deferred
4369: noname : ( ... -- ... )
4370: ... ;
4371: lastxt IS deferred
4372: @end example
1.1 anton 4373:
1.29 crook 4374: @noindent
1.33 anton 4375: @code{noname} and @code{nextname} work with any defining word, not just
4376: @code{:}.
4377:
1.26 crook 4378: @code{lastxt} also works when the last word was not defined as
1.29 crook 4379: @code{noname}. It also has the useful property that is is valid as soon
4380: as the header for a definition has been build. Thus:
4381:
4382: @example
4383: lastxt . : foo [ lastxt . ] ; ' foo .
4384: @end example
4385:
4386: @noindent
4387: prints 3 numbers; the last two are the same.
1.1 anton 4388:
4389:
1.26 crook 4390: @node Interpretation and Compilation Semantics, , Supplying names, Defining Words
4391: @subsection Interpretation and Compilation Semantics
4392: @cindex semantics, interpretation and compilation
1.1 anton 4393:
1.26 crook 4394: @cindex interpretation semantics
4395: The @dfn{interpretation semantics} of a word are what the text
4396: interpreter does when it encounters the word in interpret state. It also
4397: appears in some other contexts, e.g., the execution token returned by
1.29 crook 4398: @code{' @i{word}} identifies the interpretation semantics of
4399: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
4400: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 4401:
1.26 crook 4402: @cindex compilation semantics
4403: The @dfn{compilation semantics} of a word are what the text interpreter
4404: does when it encounters the word in compile state. It also appears in
1.29 crook 4405: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
1.26 crook 4406: standard terminology, ``appends to the current definition''.} the
1.29 crook 4407: compilation semantics of @i{word}.
1.1 anton 4408:
1.26 crook 4409: @cindex execution semantics
4410: The standard also talks about @dfn{execution semantics}. They are used
4411: only for defining the interpretation and compilation semantics of many
4412: words. By default, the interpretation semantics of a word are to
4413: @code{execute} its execution semantics, and the compilation semantics of
4414: a word are to @code{compile,} its execution semantics.@footnote{In
4415: standard terminology: The default interpretation semantics are its
4416: execution semantics; the default compilation semantics are to append its
4417: execution semantics to the execution semantics of the current
4418: definition.}
4419:
4420: @comment TODO expand, make it co-operate with new sections on text interpreter.
4421:
4422: @cindex immediate words
4423: @cindex compile-only words
4424: You can change the semantics of the most-recently defined word:
4425:
4426: doc-immediate
4427: doc-compile-only
4428: doc-restrict
4429:
4430: Note that ticking (@code{'}) a compile-only word gives an error
4431: (``Interpreting a compile-only word'').
1.1 anton 4432:
1.26 crook 4433: Gforth also allows you to define words with arbitrary combinations of
4434: interpretation and compilation semantics.
1.1 anton 4435:
1.26 crook 4436: doc-interpret/compile:
1.1 anton 4437:
1.26 crook 4438: This feature was introduced for implementing @code{TO} and @code{S"}. I
4439: recommend that you do not define such words, as cute as they may be:
4440: they make it hard to get at both parts of the word in some contexts.
4441: E.g., assume you want to get an execution token for the compilation
4442: part. Instead, define two words, one that embodies the interpretation
4443: part, and one that embodies the compilation part. Once you have done
4444: that, you can define a combined word with @code{interpret/compile:} for
4445: the convenience of your users.
1.1 anton 4446:
1.26 crook 4447: You might try to use this feature to provide an optimizing
4448: implementation of the default compilation semantics of a word. For
4449: example, by defining:
1.1 anton 4450: @example
1.26 crook 4451: :noname
4452: foo bar ;
4453: :noname
4454: POSTPONE foo POSTPONE bar ;
1.29 crook 4455: interpret/compile: opti-foobar
1.1 anton 4456: @end example
1.26 crook 4457:
1.23 crook 4458: @noindent
1.26 crook 4459: as an optimizing version of:
4460:
1.1 anton 4461: @example
1.26 crook 4462: : foobar
4463: foo bar ;
1.1 anton 4464: @end example
4465:
1.26 crook 4466: Unfortunately, this does not work correctly with @code{[compile]},
4467: because @code{[compile]} assumes that the compilation semantics of all
4468: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 4469: opti-foobar} would compile compilation semantics, whereas
4470: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 4471:
1.26 crook 4472: @cindex state-smart words (are a bad idea)
1.29 crook 4473: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 4474: by @code{interpret/compile:} (words are state-smart if they check
4475: @code{STATE} during execution). E.g., they would try to code
4476: @code{foobar} like this:
1.1 anton 4477:
1.26 crook 4478: @example
4479: : foobar
4480: STATE @@
4481: IF ( compilation state )
4482: POSTPONE foo POSTPONE bar
4483: ELSE
4484: foo bar
4485: ENDIF ; immediate
4486: @end example
1.1 anton 4487:
1.26 crook 4488: Although this works if @code{foobar} is only processed by the text
4489: interpreter, it does not work in other contexts (like @code{'} or
4490: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
4491: for a state-smart word, not for the interpretation semantics of the
4492: original @code{foobar}; when you execute this execution token (directly
4493: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
4494: state, the result will not be what you expected (i.e., it will not
4495: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
4496: write them@footnote{For a more detailed discussion of this topic, see
4497: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
4498: Ertl; presented at EuroForth '98 and available from
1.33 anton 4499: @url{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz}}!
1.1 anton 4500:
1.26 crook 4501: @cindex defining words with arbitrary semantics combinations
4502: It is also possible to write defining words that define words with
4503: arbitrary combinations of interpretation and compilation semantics. In
4504: general, they look like this:
1.1 anton 4505:
1.26 crook 4506: @example
4507: : def-word
4508: create-interpret/compile
1.29 crook 4509: @i{code1}
1.26 crook 4510: interpretation>
1.29 crook 4511: @i{code2}
1.26 crook 4512: <interpretation
4513: compilation>
1.29 crook 4514: @i{code3}
1.26 crook 4515: <compilation ;
4516: @end example
1.1 anton 4517:
1.29 crook 4518: For a @i{word} defined with @code{def-word}, the interpretation
4519: semantics are to push the address of the body of @i{word} and perform
4520: @i{code2}, and the compilation semantics are to push the address of
4521: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 4522: can also be defined like this (except that the defined constants don't
4523: behave correctly when @code{[compile]}d):
1.1 anton 4524:
1.26 crook 4525: @example
4526: : constant ( n "name" -- )
4527: create-interpret/compile
4528: ,
4529: interpretation> ( -- n )
4530: @@
4531: <interpretation
4532: compilation> ( compilation. -- ; run-time. -- n )
4533: @@ postpone literal
4534: <compilation ;
4535: @end example
1.1 anton 4536:
1.26 crook 4537: doc-create-interpret/compile
4538: doc-interpretation>
4539: doc-<interpretation
4540: doc-compilation>
4541: doc-<compilation
1.1 anton 4542:
1.29 crook 4543: Words defined with @code{interpret/compile:} and
1.26 crook 4544: @code{create-interpret/compile} have an extended header structure that
4545: differs from other words; however, unless you try to access them with
4546: plain address arithmetic, you should not notice this. Words for
4547: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 4548: @code{'} @i{word} @code{>body} also gives you the body of a word created
4549: with @code{create-interpret/compile}.
1.1 anton 4550:
1.27 crook 4551: doc-postpone
1.29 crook 4552: @comment TODO -- expand glossary text for POSTPONE
1.27 crook 4553:
1.26 crook 4554: @c ----------------------------------------------------------
4555: @node The Text Interpreter, Tokens for Words, Defining Words, Words
4556: @section The Text Interpreter
4557: @cindex interpreter - outer
4558: @cindex text interpreter
4559: @cindex outer interpreter
1.1 anton 4560:
1.34 ! anton 4561: @c Should we really describe all these ugly details? IMO the text
! 4562: @c interpreter should be much cleaner, but that may not be possible within
! 4563: @c ANS Forth. - anton
! 4564:
1.29 crook 4565: The text interpreter@footnote{This is an expanded version of the
4566: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 ! anton 4567: that processes input from the current input device. It is also called
! 4568: the outer interpreter, in contrast to the inner interpreter
! 4569: (@pxref{Engine}) which executes the compiled Forth code on interpretive
! 4570: implementations.
1.27 crook 4571:
1.29 crook 4572: @cindex interpret state
4573: @cindex compile state
4574: The text interpreter operates in one of two states: @dfn{interpret
4575: state} and @dfn{compile state}. The current state is defined by the
4576: aptly-named variable, @code{state}.
4577:
4578: This section starts by describing how the text interpreter behaves when
4579: it is in interpret state, processing input from the user input device --
4580: the keyboard. This is the mode that a Forth system is in after it starts
4581: up.
4582:
4583: @cindex input buffer
4584: @cindex terminal input buffer
4585: The text interpreter works from an area of memory called the @dfn{input
4586: buffer}@footnote{When the text interpreter is processing input from the
4587: keyboard, this area of memory is called the @dfn{terminal input buffer}
4588: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
4589: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 4590: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 4591: leading spaces (called @dfn{delimiters}) then parses a string (a
4592: sequence of non-space characters) until it reaches either a space
4593: character or the end of the buffer. Having parsed a string, it makes two
4594: attempts to process it:
1.27 crook 4595:
1.29 crook 4596: @cindex dictionary
1.27 crook 4597: @itemize @bullet
4598: @item
1.29 crook 4599: It looks for the string in a @dfn{dictionary} of definitions. If the
4600: string is found, the string names a @dfn{definition} (also known as a
4601: @dfn{word}) and the dictionary search returns information that allows
4602: the text interpreter to perform the word's @dfn{interpretation
4603: semantics}. In most cases, this simply means that the word will be
4604: executed.
1.27 crook 4605: @item
4606: If the string is not found in the dictionary, the text interpreter
1.29 crook 4607: attempts to treat it as a number, using the rules described in
4608: @ref{Number Conversion}. If the string represents a legal number in the
4609: current radix, the number is pushed onto a parameter stack (the data
4610: stack for integers, the floating-point stack for floating-point
4611: numbers).
4612: @end itemize
4613:
4614: If both attempts fail, or if the word is found in the dictionary but has
4615: no interpretation semantics@footnote{This happens if the word was
4616: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
4617: remainder of the input buffer, issues an error message and waits for
4618: more input. If one of the attempts succeeds, the text interpreter
4619: repeats the parsing process until the whole of the input buffer has been
4620: processed, at which point it prints the status message ``@code{ ok}''
4621: and waits for more input.
4622:
4623: @cindex parse area
4624: The text interpreter keeps track of its position in the input buffer by
4625: updating a variable called @code{>IN} (pronounced ``to-in''). The value
4626: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
4627: of the input buffer. The region from offset @code{>IN @@} to the end of
4628: the input buffer is called the @dfn{parse area}@footnote{In other words,
4629: the text interpreter processes the contents of the input buffer by
4630: parsing strings from the parse area until the parse area is empty.}.
4631: This example shows how @code{>IN} changes as the text interpreter parses
4632: the input buffer:
4633:
4634: @example
4635: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
4636: CR ." ->" TYPE ." <-" ; IMMEDIATE
4637:
4638: 1 2 3 remaining + remaining .
4639:
4640: : foo 1 2 3 remaining SWAP remaining ;
4641: @end example
4642:
4643: @noindent
4644: The result is:
4645:
4646: @example
4647: ->+ remaining .<-
4648: ->.<-5 ok
4649:
4650: ->SWAP remaining ;-<
4651: ->;<- ok
4652: @end example
4653:
4654: @cindex parsing words
4655: The value of @code{>IN} can also be modified by a word in the input
4656: buffer that is executed by the text interpreter. This means that a word
4657: can ``trick'' the text interpreter into either skipping a section of the
4658: input buffer@footnote{This is how parsing words work.} or into parsing a
4659: section twice. For example:
1.27 crook 4660:
1.29 crook 4661: @example
4662: : lat ." <<lat>>" ;
4663: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
4664: @end example
4665:
4666: @noindent
4667: When @code{flat} is executed, this output is produced@footnote{Exercise
4668: for the reader: what would happen if the @code{3} were replaced with
4669: @code{4}?}:
4670:
4671: @example
4672: <<flat>><<lat>>
4673: @end example
4674:
4675: @noindent
4676: Two important notes about the behaviour of the text interpreter:
1.27 crook 4677:
4678: @itemize @bullet
4679: @item
4680: It processes each input string to completion before parsing additional
1.29 crook 4681: characters from the input buffer.
4682: @item
4683: It treats the input buffer as a read-only region (and so must your code).
4684: @end itemize
4685:
4686: @noindent
4687: When the text interpreter is in compile state, its behaviour changes in
4688: these ways:
4689:
4690: @itemize @bullet
4691: @item
4692: If a parsed string is found in the dictionary, the text interpreter will
4693: perform the word's @dfn{compilation semantics}. In most cases, this
4694: simply means that the execution semantics of the word will be appended
4695: to the current definition.
1.27 crook 4696: @item
1.29 crook 4697: When a number is encountered, it is compiled into the current definition
4698: (as a literal) rather than being pushed onto a parameter stack.
4699: @item
4700: If an error occurs, @code{state} is modified to put the text interpreter
4701: back into interpret state.
4702: @item
4703: Each time a line is entered from the keyboard, Gforth prints
4704: ``@code{ compiled}'' rather than `` @code{ok}''.
4705: @end itemize
4706:
4707: @cindex text interpreter - input sources
4708: When the text interpreter is using an input device other than the
4709: keyboard, its behaviour changes in these ways:
4710:
4711: @itemize @bullet
4712: @item
4713: When the parse area is empty, the text interpreter attempts to refill
4714: the input buffer from the input source. When the input source is
4715: exhausted, the input source is set back to the user input device.
4716: @item
4717: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
4718: time the parse area is emptied.
4719: @item
4720: If an error occurs, the input source is set back to the user input
4721: device.
1.27 crook 4722: @end itemize
1.21 crook 4723:
1.29 crook 4724: @ref{Input Sources} describes this in more detail.
4725:
1.26 crook 4726: doc->in
1.27 crook 4727: doc-source
4728:
1.26 crook 4729: doc-tib
4730: doc-#tib
1.1 anton 4731:
1.26 crook 4732: @menu
1.29 crook 4733: * Input Sources::
1.26 crook 4734: * Number Conversion::
4735: * Interpret/Compile states::
4736: * Literals::
4737: * Interpreter Directives::
4738: @end menu
1.1 anton 4739:
1.29 crook 4740: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
4741: @subsection Input Sources
4742: @cindex input sources
4743: @cindex text interpreter - input sources
4744:
4745: By default, the text interpreter accepts input from the user input
4746: device (the keyboard) when Forth starts up. The text interpreter can
4747: process input from any of these sources:
4748:
4749: @itemize @bullet
4750: @item
4751: The user input device -- the keyboard.
4752: @item
4753: A file, using the words described in @ref{Forth source files}.
4754: @item
4755: A block, using the words described in @ref{Blocks}.
4756: @item
4757: A text string, using @code{evaluate}.
4758: @end itemize
4759:
4760: A program can identify the current input device from the values of
4761: @code{source-id} and @code{blk}.
4762:
4763: doc-source-id
4764: doc-blk
4765:
4766: doc-save-input
4767: doc-restore-input
4768:
4769: doc-evaluate
1.1 anton 4770:
1.29 crook 4771:
4772: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 4773: @subsection Number Conversion
4774: @cindex number conversion
4775: @cindex double-cell numbers, input format
4776: @cindex input format for double-cell numbers
4777: @cindex single-cell numbers, input format
4778: @cindex input format for single-cell numbers
4779: @cindex floating-point numbers, input format
4780: @cindex input format for floating-point numbers
1.1 anton 4781:
1.29 crook 4782: This section describes the rules that the text interpreter uses when it
4783: tries to convert a string into a number.
1.1 anton 4784:
1.26 crook 4785: Let <digit> represent any character that is a legal digit in the current
1.29 crook 4786: number base@footnote{For example, 0-9 when the number base is decimal or
4787: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 4788:
1.26 crook 4789: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 4790:
1.29 crook 4791: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
4792: in the braces (@i{a} or @i{b} or neither).
1.1 anton 4793:
1.26 crook 4794: Let * represent any number of instances of the previous character
4795: (including none).
1.1 anton 4796:
1.26 crook 4797: Let any other character represent itself.
1.1 anton 4798:
1.29 crook 4799: @noindent
1.26 crook 4800: Now, the conversion rules are:
1.21 crook 4801:
1.26 crook 4802: @itemize @bullet
4803: @item
4804: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 4805: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 4806: @item
4807: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 4808: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 4809: arithmetic. Examples are -45 -5681 -0
4810: @item
4811: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 4812: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
4813: (all three of these represent the same number).
1.26 crook 4814: @item
4815: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 4816: double-precision (double-cell-sized) negative integer, and is
1.26 crook 4817: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 4818: -34.65 (all three of these represent the same number).
1.26 crook 4819: @item
1.29 crook 4820: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
4821: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.26 crook 4822: number. Examples are 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 4823: number) +12.E-4
1.26 crook 4824: @end itemize
1.1 anton 4825:
1.26 crook 4826: By default, the number base used for integer number conversion is given
1.29 crook 4827: by the contents of the variable @code{BASE}. Base 10 (decimal) is
1.26 crook 4828: always used for floating-point number conversion.
1.1 anton 4829:
1.29 crook 4830: doc-dpl
1.26 crook 4831: doc-base
4832: doc-hex
4833: doc-decimal
1.1 anton 4834:
1.26 crook 4835: @cindex '-prefix for character strings
4836: @cindex &-prefix for decimal numbers
4837: @cindex %-prefix for binary numbers
4838: @cindex $-prefix for hexadecimal numbers
1.29 crook 4839: Gforth allows you to override the value of @code{BASE} by using a
4840: prefix@footnote{Some Forth implementations provide a similar scheme by
4841: implementing @code{$} etc. as parsing words that process the subsequent
4842: number in the input stream and push it onto the stack. For example, see
4843: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
4844: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
4845: is required between the prefix and the number.} before the first digit
4846: of an (integer) number. Four prefixes are supported:
1.1 anton 4847:
1.26 crook 4848: @itemize @bullet
4849: @item
4850: @code{&} -- decimal number
4851: @item
4852: @code{%} -- binary number
4853: @item
4854: @code{$} -- hexadecimal number
4855: @item
4856: @code{'} -- base 256 number
4857: @end itemize
1.1 anton 4858:
1.26 crook 4859: Here are some examples, with the equivalent decimal number shown after
4860: in braces:
1.1 anton 4861:
1.26 crook 4862: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
4863: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
4864: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
4865: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 4866:
1.26 crook 4867: @cindex number conversion - traps for the unwary
1.29 crook 4868: @noindent
1.26 crook 4869: Number conversion has a number of traps for the unwary:
1.1 anton 4870:
1.26 crook 4871: @itemize @bullet
4872: @item
4873: You cannot determine the current number base using the code sequence
4874: @code{BASE @@ .} -- the number base is always 10 in the current number
4875: base. Instead, use something like @code{BASE @@ DECIMAL DUP . BASE !}
4876: @item
4877: If the number base is set to a value greater than 14 (for example,
4878: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
4879: it to be intepreted as either a single-precision integer or a
4880: floating-point number (Gforth treats it as an integer). The ambiguity
4881: can be resolved by explicitly stating the sign of the mantissa and/or
4882: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
4883: ambiguity arises; either representation will be treated as a
4884: floating-point number.
4885: @item
1.29 crook 4886: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 4887: It is used to specify file types.
4888: @item
4889: ANS Forth requires the @code{.} of a double-precision number to
4890: be the final character in the string. Allowing the @code{.} to be
4891: anywhere after the first digit is a Gforth extension.
4892: @item
4893: The number conversion process does not check for overflow.
4894: @item
4895: In Gforth, number conversion to floating-point numbers always use base
4896: 10, irrespective of the value of @code{BASE}. In ANS Forth,
4897: conversion to floating-point numbers whilst the value of
4898: @code{BASE} is not 10 is an ambiguous condition.
4899: @end itemize
1.1 anton 4900:
1.29 crook 4901: @ref{Input} describes words that you can use to read numbers into your
4902: programs.
1.1 anton 4903:
1.26 crook 4904: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
4905: @subsection Interpret/Compile states
4906: @cindex Interpret/Compile states
1.1 anton 4907:
1.29 crook 4908: A standard program is not permitted to change @code{state}
4909: explicitly. However, it can change @code{state} implicitly, using the
4910: words @code{[} and @code{]}. When @code{[} is executed it switches
4911: @code{state} to interpret state, and therefore the text interpreter
4912: starts interpreting. When @code{]} is executed it switches @code{state}
4913: to compile state and therefore the text interpreter starts
4914: compiling. The most common usage for these words is to compile literals,
4915: as shown in @ref{Literals}. However, they give you the freedom to switch
4916: modes at will. Here is an example of building a jump-table of execution
4917: tokens:
4918:
4919: @example
4920: : AA ." this is A" ;
4921: : BB ." this is B" ;
4922: : CC ." this is C" ;
4923:
4924: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
4925: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
4926: cells table + @ execute ;
4927: @end example
4928:
4929: @noindent
4930: Now @code{0 go} will display ``@code{this is A}''. The table can be
4931: built far more neatly@footnote{The source code is neater.. what is
4932: compiled in memory in each case is identical.} like this:
4933:
4934: @example
4935: create table ] aa bb cc [
4936: @end example
4937:
4938: The problem with this code is that it is not portable; it will only work
4939: on systems where code space and data space co-incide. The reason is that
4940: both tables @i{compile} execution tokens -- into code space. The
4941: Standard only allows data space to be assigned for a @code{CREATE}d
4942: word. In addition, the Standard only allows @code{@@} to access data
4943: space, whilst this example is using it to access code space. The only
4944: portable, Standard way to build this table is to build it in data space,
4945: like this:
4946:
4947: @example
4948: create table ' aa , ' bb , ' cc ,
4949: @end example
4950:
4951: @noindent
4952: A similar technique can be used to build a table of constants:
4953:
4954: @example
4955: create primes 1 , 3 , 5 , 7 , 11 ,
4956: @end example
1.1 anton 4957:
1.26 crook 4958: doc-state
4959: doc-[
4960: doc-]
1.1 anton 4961:
1.26 crook 4962: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
4963: @subsection Literals
4964: @cindex Literals
1.21 crook 4965:
1.29 crook 4966: Often, you want to use a number within a colon definition. When you do
4967: this, the text interpreter automatically compiles the number as a
4968: @i{literal}. A literal is a number whose run-time effect is to be pushed
4969: onto the stack. If you had to do some maths to generate the number, you
4970: might write it like this:
4971:
4972: @example
4973: : HOUR-TO-SEC ( n1 -- n2 )
4974: 60 * \ to minutes
4975: 60 * ; \ to seconds
4976: @end example
4977:
4978: It is very clear what this definition is doing, but it's inefficient
4979: since it is performing 2 multiples at run-time. An alternative would be
4980: to write:
4981:
4982: @example
4983: : HOUR-TO-SEC ( n1 -- n2 )
4984: 3600 * ; \ to seconds
4985: @end example
4986:
4987: Which does the same thing, and has the advantage of using a single
4988: multiply. Ideally, we'd like the efficiency of the second with the
4989: readability of the first.
4990:
4991: @code{Literal} allows us to achieve that. It takes a number from the
4992: stack and lays it down in the current definition just as though the
4993: number had been typed directly into the definition. Our first attempt
4994: might look like this:
4995:
4996: @example
4997: 60 \ mins per hour
4998: 60 * \ seconds per minute
4999: : HOUR-TO-SEC ( n1 -- n2 )
5000: Literal * ; \ to seconds
5001: @end example
5002:
5003: But this produces the error message @code{unstructured}. What happened?
5004: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
5005: @i{colon-sys} is implementation-defined. In other words, once we start a
5006: colon definition we can't portably access anything that was on the stack
5007: before the definition began@footnote{@cite{Two Problems in ANS Forth},
5008: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
5009: some situations where you might want to access stack items above
5010: colon-sys, and provides a solution to the problem.}. The correct way of
5011: solving this problem in this instance is to use @code{[ ]} like this:
5012:
5013: @example
5014: : HOUR-TO-SEC ( n1 -- n2 )
5015: [ 60 \ minutes per hour
5016: 60 * ] \ seconds per minute
5017: LITERAL * ; \ to seconds
5018: @end example
1.23 crook 5019:
1.26 crook 5020: doc-literal
5021: doc-]L
5022: doc-2literal
5023: doc-fliteral
1.1 anton 5024:
1.29 crook 5025: @node Interpreter Directives, , Literals, The Text Interpreter
1.26 crook 5026: @subsection Interpreter Directives
5027: @cindex interpreter directives
1.1 anton 5028:
1.29 crook 5029: These words are usually used in interpret state; typically to control
5030: which parts of a source file are processed by the text
1.26 crook 5031: interpreter. There are only a few ANS Forth Standard words, but Gforth
5032: supplements these with a rich set of immediate control structure words
5033: to compensate for the fact that the non-immediate versions can only be
1.29 crook 5034: used in compile state (@pxref{Control Structures}). Typical usages:
5035:
5036: @example
5037: FALSE Constant ASSEMBLER
5038: .
5039: .
5040: ASSEMBLER [IF]
5041: : ASSEMBLER-FEATURE
5042: ...
5043: ;
5044: [ENDIF]
5045: .
5046: .
5047: : SEE
5048: ... \ general-purpose SEE code
5049: [ ASSEMBLER [IF] ]
5050: ... \ assembler-specific SEE code
5051: [ [ENDIF] ]
5052: ;
5053: @end example
1.1 anton 5054:
1.26 crook 5055: doc-[IF]
5056: doc-[ELSE]
5057: doc-[THEN]
5058: doc-[ENDIF]
1.1 anton 5059:
1.26 crook 5060: doc-[IFDEF]
5061: doc-[IFUNDEF]
1.1 anton 5062:
1.26 crook 5063: doc-[?DO]
5064: doc-[DO]
5065: doc-[FOR]
5066: doc-[LOOP]
5067: doc-[+LOOP]
5068: doc-[NEXT]
1.1 anton 5069:
1.26 crook 5070: doc-[BEGIN]
5071: doc-[UNTIL]
5072: doc-[AGAIN]
5073: doc-[WHILE]
5074: doc-[REPEAT]
1.1 anton 5075:
1.27 crook 5076:
5077:
1.26 crook 5078: @c -------------------------------------------------------------
5079: @node Tokens for Words, Word Lists, The Text Interpreter, Words
5080: @section Tokens for Words
5081: @cindex tokens for words
1.1 anton 5082:
1.28 crook 5083: This section describes the creation and use of tokens that represent
1.29 crook 5084: words.
5085:
1.32 anton 5086: Named words have information stored in their header space entries to
1.29 crook 5087: indicate any non-default semantics (@pxref{Interpretation and
5088: Compilation Semantics}). The semantics can be modified, using
5089: @code{immediate} and/or @code{compile-only}, at the time that the words
1.32 anton 5090: are defined. Unnamed words have (by definition) no header space
1.29 crook 5091: entry, and therefore must have default semantics.
1.21 crook 5092:
1.26 crook 5093: Named words have interpretation and compilation semantics. Unnamed words
5094: just have execution semantics.
1.21 crook 5095:
1.29 crook 5096: @cindex xt
5097: @cindex execution token
5098: The execution semantics of an unnamed word are represented by an
5099: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
5100: the execution token of the last word defined can be produced with
5101: @code{lastxt}.
5102:
5103: The interpretation semantics of a named word are also represented by an
5104: execution token. You can produce the execution token using @code{'} or
5105: @code{[']}. A simple example shows the difference between the two:
1.21 crook 5106:
1.29 crook 5107: @example
5108: : greet ( -- ) ." Hello" ;
5109: : foo ( -- xt ) ['] greet ; \ ['] parses greet at compile-time
5110: : bar ( -- ) ' EXECUTE ; \ ' parses at run-time
1.1 anton 5111:
1.29 crook 5112: \ the next four lines all do the same thing
5113: foo EXECUTE
5114: greet
5115: ' greet EXECUTE
5116: boo greet
5117: @end example
1.1 anton 5118:
1.29 crook 5119: An execution token occupies one cell.
1.26 crook 5120: @cindex code field address
5121: @cindex CFA
1.29 crook 5122: In Gforth, the abstract data type @i{execution token} is implemented
1.26 crook 5123: as a code field address (CFA).
5124: @comment TODO note that the standard does not say what it represents..
5125: @comment and you cannot necessarily compile it in all Forths (eg native
5126: @comment compilers?).
1.1 anton 5127:
1.29 crook 5128: For literals, use @code{'} in interpreted code and @code{[']} in
5129: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
5130: unusually by complaining about compile-only words. To get the execution
5131: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
5132: or @code{[COMP'] @i{name} DROP}.
1.1 anton 5133:
1.26 crook 5134: @cindex compilation token
1.29 crook 5135: The compilation semantics of a named word are represented by a
5136: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
5137: @i{xt} is an execution token. The compilation semantics represented by
5138: the compilation token can be performed with @code{execute}, which
5139: consumes the whole compilation token, with an additional stack effect
5140: determined by the represented compilation semantics.
5141:
5142: At present, the @i{w} part of a compilation token is an execution token,
5143: and the @i{xt} part represents either @code{execute} or
5144: @code{compile,}@footnote{Depending upon the compilation semantics of the
5145: word. If the word has default compilation semantics, the @i{xt} will
5146: represent @code{compile,}. If the word is @code{immediate}, the @i{xt}
5147: will represent @code{execute}.}. However, don't rely on that knowledge,
5148: unless necessary; future versions of Gforth may introduce unusual
5149: compilation tokens (e.g., a compilation token that represents the
5150: compilation semantics of a literal).
1.1 anton 5151:
1.26 crook 5152: You can compile the compilation semantics with @code{postpone,}. I.e.,
1.29 crook 5153: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
5154: @i{word}}.
1.21 crook 5155:
1.26 crook 5156: @cindex name token
5157: @cindex name field address
5158: @cindex NFA
1.29 crook 5159: Named words are also represented by the @dfn{name token}, (@i{nt}). In
5160: Gforth, the abstract data type @emph{name token} is implemented as a
5161: name field address (NFA).
5162:
5163: doc-execute
5164: doc-compile,
5165: doc-[']
5166: doc-'
5167: doc-[comp']
5168: doc-comp'
5169: doc-postpone,
1.1 anton 5170:
1.26 crook 5171: doc-find-name
5172: doc-name>int
5173: doc-name?int
5174: doc-name>comp
5175: doc-name>string
1.1 anton 5176:
1.26 crook 5177: @c -------------------------------------------------------------
5178: @node Word Lists, Environmental Queries, Tokens for Words, Words
5179: @section Word Lists
5180: @cindex word lists
1.32 anton 5181: @cindex header space
1.1 anton 5182:
1.26 crook 5183: @cindex wid
5184: All definitions other than those created by @code{:noname} have an entry
1.32 anton 5185: in the header space. The header space is fragmented into a number
1.29 crook 5186: of parts, called @dfn{word lists}. A word list is identified by a
5187: cell-sized word list identifier (@i{wid}) in much the same way as a
1.26 crook 5188: file is identified by a file handle. The numerical value of the wid has
5189: no (portable) meaning, and might change from session to session.
1.1 anton 5190:
1.26 crook 5191: @cindex compilation word list
5192: At any one time, a single word list is defined as the word list to which
1.29 crook 5193: all new definitions will be added -- this is called the @dfn{compilation
1.26 crook 5194: word list}. When Gforth is started, the compilation word list is the
5195: word list called @code{FORTH-WORDLIST}.
1.1 anton 5196:
1.26 crook 5197: @cindex search order stack
1.29 crook 5198: Forth maintains a stack of word lists, representing the @dfn{search
1.32 anton 5199: order}. When the header space is searched (for example, when
1.26 crook 5200: attempting to find a word's execution token during compilation), only
5201: those word lists that are currently in the search order are
5202: searched. The most recently-defined word in the word list at the top of
5203: the word list stack is searched first, and the search proceeds until
5204: either the word is located or the oldest definition in the word list at
5205: the bottom of the stack is reached. Definitions of the word may exist in
5206: more than one word lists; the search order determines which version will
5207: be found.
1.1 anton 5208:
1.29 crook 5209: The ANS Forth ``Search order'' word set is intended to provide a set of
5210: low-level tools that allow various different schemes to be
1.26 crook 5211: implemented. Gforth provides @code{vocabulary}, a traditional Forth
5212: word. @file{compat/vocabulary.fs} provides an implementation in ANS
5213: Standard Forth.
1.1 anton 5214:
1.27 crook 5215: @comment TODO: locals section refers to here, saying that every word list (aka
5216: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.1 anton 5217:
1.27 crook 5218: @comment the thisone- prefix is used to pick out the true definition of a
5219: @comment word from the source files, rather than some alias.
1.26 crook 5220: doc-forth-wordlist
5221: doc-definitions
5222: doc-get-current
5223: doc-set-current
5224: doc-get-order
1.27 crook 5225: doc---thisone-set-order
1.26 crook 5226: doc-wordlist
1.30 anton 5227: doc-table
1.26 crook 5228: doc-also
1.27 crook 5229: doc---thisone-forth
1.26 crook 5230: doc-only
1.27 crook 5231: doc---thisone-order
1.26 crook 5232: doc-previous
1.15 anton 5233:
1.26 crook 5234: doc-find
5235: doc-search-wordlist
1.15 anton 5236:
1.26 crook 5237: doc-words
5238: doc-vlist
1.1 anton 5239:
1.26 crook 5240: doc-mappedwordlist
5241: doc-root
5242: doc-vocabulary
5243: doc-seal
5244: doc-vocs
5245: doc-current
5246: doc-context
1.1 anton 5247:
1.26 crook 5248: @menu
5249: * Why use word lists?::
5250: * Word list examples::
5251: @end menu
5252:
5253: @node Why use word lists?, Word list examples, Word Lists, Word Lists
5254: @subsection Why use word lists?
5255: @cindex word lists - why use them?
5256:
1.29 crook 5257: Here are some reasons for using multiple word lists:
1.26 crook 5258:
5259: @itemize @bullet
5260: @item
1.32 anton 5261: To improve compilation speed by reducing the number of header space
1.26 crook 5262: entries that must be searched. This is achieved by creating a new
5263: word list that contains all of the definitions that are used in the
5264: definition of a Forth system but which would not usually be used by
5265: programs running on that system. That word list would be on the search
5266: list when the Forth system was compiled but would be removed from the
5267: search list for normal operation. This can be a useful technique for
5268: low-performance systems (for example, 8-bit processors in embedded
5269: systems) but is unlikely to be necessary in high-performance desktop
5270: systems.
5271: @item
5272: To prevent a set of words from being used outside the context in which
5273: they are valid. Two classic examples of this are an integrated editor
5274: (all of the edit commands are defined in a separate word list; the
5275: search order is set to the editor word list when the editor is invoked;
5276: the old search order is restored when the editor is terminated) and an
5277: integrated assembler (the op-codes for the machine are defined in a
5278: separate word list which is used when a @code{CODE} word is defined).
5279: @item
5280: To prevent a name-space clash between multiple definitions with the same
5281: name. For example, when building a cross-compiler you might have a word
5282: @code{IF} that generates conditional code for your target system. By
5283: placing this definition in a different word list you can control whether
5284: the host system's @code{IF} or the target system's @code{IF} get used in
5285: any particular context by controlling the order of the word lists on the
5286: search order stack.
5287: @end itemize
1.1 anton 5288:
1.26 crook 5289: @node Word list examples, ,Why use word lists?, Word Lists
5290: @subsection Word list examples
5291: @cindex word lists - examples
1.1 anton 5292:
1.26 crook 5293: Here is an example of creating and using a new wordlist using ANS
5294: Forth Standard words:
1.1 anton 5295:
5296: @example
1.26 crook 5297: wordlist constant my-new-words-wordlist
5298: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
1.21 crook 5299:
1.26 crook 5300: \ add it to the search order
5301: also my-new-words
1.21 crook 5302:
1.26 crook 5303: \ alternatively, add it to the search order and make it
5304: \ the compilation word list
5305: also my-new-words definitions
5306: \ type "order" to see the problem
1.21 crook 5307: @end example
5308:
1.26 crook 5309: The problem with this example is that @code{order} has no way to
5310: associate the name @code{my-new-words} with the wid of the word list (in
5311: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
5312: that has no associated name). There is no Standard way of associating a
5313: name with a wid.
5314:
5315: In Gforth, this example can be re-coded using @code{vocabulary}, which
5316: associates a name with a wid:
1.21 crook 5317:
1.26 crook 5318: @example
5319: vocabulary my-new-words
1.21 crook 5320:
1.26 crook 5321: \ add it to the search order
5322: my-new-words
1.21 crook 5323:
1.26 crook 5324: \ alternatively, add it to the search order and make it
5325: \ the compilation word list
5326: my-new-words definitions
5327: \ type "order" to see that the problem is solved
5328: @end example
1.23 crook 5329:
1.26 crook 5330: @c -------------------------------------------------------------
5331: @node Environmental Queries, Files, Word Lists, Words
5332: @section Environmental Queries
5333: @cindex environmental queries
1.21 crook 5334:
1.26 crook 5335: ANS Forth introduced the idea of ``environmental queries'' as a way
5336: for a program running on a system to determine certain characteristics of the system.
5337: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 5338:
1.32 anton 5339: The Standard requires that the header space used for environmental queries
5340: be distinct from the header space used for definitions.
1.21 crook 5341:
1.26 crook 5342: Typically, environmental queries are supported by creating a set of
1.29 crook 5343: definitions in a word list that is @i{only} used during environmental
1.26 crook 5344: queries; that is what Gforth does. There is no Standard way of adding
5345: definitions to the set of recognised environmental queries, but any
5346: implementation that supports the loading of optional word sets must have
5347: some mechanism for doing this (after loading the word set, the
5348: associated environmental query string must return @code{true}). In
5349: Gforth, the word list used to honour environmental queries can be
5350: manipulated just like any other word list.
1.21 crook 5351:
1.26 crook 5352: doc-environment?
5353: doc-environment-wordlist
1.21 crook 5354:
1.26 crook 5355: doc-gforth
5356: doc-os-class
1.21 crook 5357:
1.26 crook 5358: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
5359: returning two items on the stack, querying it using @code{environment?}
5360: will return an additional item; the @code{true} flag that shows that the
5361: string was recognised.
1.21 crook 5362:
1.26 crook 5363: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 5364:
1.26 crook 5365: Here are some examples of using environmental queries:
1.21 crook 5366:
1.26 crook 5367: @example
5368: s" address-unit-bits" environment? 0=
5369: [IF]
5370: cr .( environmental attribute address-units-bits unknown... ) cr
5371: [THEN]
1.21 crook 5372:
1.26 crook 5373: s" block" environment? [IF] DROP include block.fs [THEN]
1.21 crook 5374:
1.26 crook 5375: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
1.21 crook 5376:
1.26 crook 5377: s" gforth" environment? [IF] .( Gforth version ) TYPE
5378: [ELSE] .( Not Gforth..) [THEN]
5379: @end example
1.21 crook 5380:
5381:
1.26 crook 5382: Here is an example of adding a definition to the environment word list:
1.21 crook 5383:
1.26 crook 5384: @example
5385: get-current environment-wordlist set-current
5386: true constant block
5387: true constant block-ext
5388: set-current
5389: @end example
1.21 crook 5390:
1.26 crook 5391: You can see what definitions are in the environment word list like this:
1.21 crook 5392:
1.26 crook 5393: @example
5394: get-order 1+ environment-wordlist swap set-order words previous
5395: @end example
1.21 crook 5396:
5397:
1.26 crook 5398: @c -------------------------------------------------------------
5399: @node Files, Blocks, Environmental Queries, Words
5400: @section Files
1.28 crook 5401: @cindex files
5402: @cindex I/O - file-handling
1.21 crook 5403:
1.26 crook 5404: Gforth provides facilities for accessing files that are stored in the
5405: host operating system's file-system. Files that are processed by Gforth
5406: can be divided into two categories:
1.21 crook 5407:
1.23 crook 5408: @itemize @bullet
5409: @item
1.29 crook 5410: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 5411: @item
1.29 crook 5412: Files that are processed by some other program (@dfn{general files}).
1.26 crook 5413: @end itemize
5414:
5415: @menu
5416: * Forth source files::
5417: * General files::
5418: * Search Paths::
5419: * Forth Search Paths::
5420: * General Search Paths::
5421: @end menu
5422:
1.21 crook 5423:
1.26 crook 5424: @c -------------------------------------------------------------
5425: @node Forth source files, General files, Files, Files
5426: @subsection Forth source files
5427: @cindex including files
5428: @cindex Forth source files
1.21 crook 5429:
1.26 crook 5430: The simplest way to interpret the contents of a file is to use one of
5431: these two formats:
1.21 crook 5432:
1.26 crook 5433: @example
5434: include mysource.fs
5435: s" mysource.fs" included
5436: @end example
1.21 crook 5437:
1.26 crook 5438: Sometimes you want to include a file only if it is not included already
5439: (by, say, another source file). In that case, you can use one of these
5440: fomats:
1.21 crook 5441:
1.26 crook 5442: @example
5443: require mysource.fs
5444: needs mysource.fs
5445: s" mysource.fs" required
5446: @end example
1.21 crook 5447:
1.26 crook 5448: @cindex stack effect of included files
5449: @cindex including files, stack effect
5450: I recommend that you write your source files such that interpreting them
5451: does not change the stack. This allows using these files with
5452: @code{required} and friends without complications. For example:
1.21 crook 5453:
1.26 crook 5454: @example
5455: 1 require foo.fs drop
5456: @end example
1.21 crook 5457:
1.26 crook 5458: doc-include-file
5459: doc-included
1.28 crook 5460: doc-included?
1.26 crook 5461: doc-include
5462: doc-required
5463: doc-require
5464: doc-needs
1.28 crook 5465: doc-init-included-files
1.21 crook 5466:
1.26 crook 5467: A definition in ANS Forth for @code{required} is provided in
5468: @file{compat/required.fs}.
1.21 crook 5469:
1.26 crook 5470: @c -------------------------------------------------------------
5471: @node General files, Search Paths, Forth source files, Files
5472: @subsection General files
5473: @cindex general files
5474: @cindex file-handling
1.21 crook 5475:
1.26 crook 5476: Files are opened/created by name and type. The following types are
5477: recognised:
1.1 anton 5478:
1.26 crook 5479: doc-r/o
5480: doc-r/w
5481: doc-w/o
5482: doc-bin
1.1 anton 5483:
1.26 crook 5484: When a file is opened/created, it returns a file identifier,
1.29 crook 5485: @i{wfileid} that is used for all other file commands. All file
5486: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 5487: successful operation and an implementation-defined non-zero value in the
5488: case of an error.
1.21 crook 5489:
1.26 crook 5490: doc-open-file
5491: doc-create-file
1.21 crook 5492:
1.26 crook 5493: doc-close-file
5494: doc-delete-file
5495: doc-rename-file
5496: doc-read-file
5497: doc-read-line
5498: doc-write-file
5499: doc-write-line
5500: doc-emit-file
5501: doc-flush-file
1.21 crook 5502:
1.26 crook 5503: doc-file-status
5504: doc-file-position
5505: doc-reposition-file
5506: doc-file-size
5507: doc-resize-file
1.21 crook 5508:
1.26 crook 5509: @c ---------------------------------------------------------
5510: @node Search Paths, Forth Search Paths, General files, Files
5511: @subsection Search Paths
5512: @cindex path for @code{included}
5513: @cindex file search path
5514: @cindex @code{include} search path
5515: @cindex search path for files
1.21 crook 5516:
1.26 crook 5517: If you specify an absolute filename (i.e., a filename starting with
5518: @file{/} or @file{~}, or with @file{:} in the second position (as in
5519: @samp{C:...})) for @code{included} and friends, that file is included
5520: just as you would expect.
1.21 crook 5521:
1.26 crook 5522: For relative filenames, Gforth uses a search path similar to Forth's
5523: search order (@pxref{Word Lists}). It tries to find the given filename
5524: in the directories present in the path, and includes the first one it
5525: finds. There are separate search paths for Forth source files and
5526: general files.
1.21 crook 5527:
1.26 crook 5528: If the search path contains the directory @file{.} (as it should), this
5529: refers to the directory that the present file was @code{included}
5530: from. This allows files to include other files relative to their own
5531: position (irrespective of the current working directory or the absolute
5532: position). This feature is essential for libraries consisting of
5533: several files, where a file may include other files from the library.
5534: It corresponds to @code{#include "..."} in C. If the current input
5535: source is not a file, @file{.} refers to the directory of the innermost
5536: file being included, or, if there is no file being included, to the
5537: current working directory.
1.21 crook 5538:
1.26 crook 5539: Use @file{~+} to refer to the current working directory (as in the
5540: @code{bash}).
1.1 anton 5541:
1.26 crook 5542: If the filename starts with @file{./}, the search path is not searched
5543: (just as with absolute filenames), and the @file{.} has the same meaning
5544: as described above.
1.1 anton 5545:
1.26 crook 5546: @c ---------------------------------------------------------
5547: @node Forth Search Paths, General Search Paths, Search Paths, Files
5548: @subsubsection Forth Search Paths
1.28 crook 5549: @cindex search path control - Forth
1.5 anton 5550:
1.26 crook 5551: The search path is initialized when you start Gforth (@pxref{Invoking
5552: Gforth}). You can display it and change it using these words:
1.5 anton 5553:
1.26 crook 5554: doc-.fpath
5555: doc-fpath+
5556: doc-fpath=
5557: doc-open-fpath-file
1.5 anton 5558:
1.26 crook 5559: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 5560:
1.26 crook 5561: @example
5562: fpath= /usr/lib/forth/|./
5563: require timer.fs
5564: @end example
1.5 anton 5565:
1.26 crook 5566: @c ---------------------------------------------------------
5567: @node General Search Paths, , Forth Search Paths, Files
5568: @subsubsection General Search Paths
5569: @cindex search path control - for user applications
1.5 anton 5570:
1.26 crook 5571: Your application may need to search files in several directories, like
5572: @code{included} does. To facilitate this, Gforth allows you to define
5573: and use your own search paths, by providing generic equivalents of the
5574: Forth search path words:
1.5 anton 5575:
1.26 crook 5576: doc-.path
5577: doc-path+
5578: doc-path=
5579: doc-open-path-file
1.5 anton 5580:
1.26 crook 5581: Here's an example of creating a search path:
1.5 anton 5582:
1.26 crook 5583: @example
5584: \ Make a buffer for the path:
5585: create mypath 100 chars , \ maximum length (is checked)
5586: 0 , \ real len
5587: 100 chars allot \ space for path
5588: @end example
1.5 anton 5589:
1.26 crook 5590: @c -------------------------------------------------------------
5591: @node Blocks, Other I/O, Files, Words
5592: @section Blocks
1.28 crook 5593: @cindex I/O - blocks
5594: @cindex blocks
5595:
5596: When you run Gforth on a modern desk-top computer, it runs under the
5597: control of an operating system which provides certain services. One of
5598: these services is @var{file services}, which allows Forth source code
5599: and data to be stored in files and read into Gforth (@pxref{Files}).
5600:
5601: Traditionally, Forth has been an important programming language on
5602: systems where it has interfaced directly to the underlying hardware with
5603: no intervening operating system. Forth provides a mechanism, called
1.29 crook 5604: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 5605:
5606: A block is a 1024-byte data area, which can be used to hold data or
5607: Forth source code. No structure is imposed on the contents of the
5608: block. A block is identified by its number; blocks are numbered
5609: contiguously from 1 to an implementation-defined maximum.
5610:
5611: A typical system that used blocks but no operating system might use a
5612: single floppy-disk drive for mass storage, with the disks formatted to
5613: provide 256-byte sectors. Blocks would be implemented by assigning the
5614: first four sectors of the disk to block 1, the second four sectors to
5615: block 2 and so on, up to the limit of the capacity of the disk. The disk
5616: would not contain any file system information, just the set of blocks.
5617:
1.29 crook 5618: @cindex blocks file
1.28 crook 5619: On systems that do provide file services, blocks are typically
1.29 crook 5620: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 5621: file}. The size of the blocks file will be an exact multiple of 1024
5622: bytes, corresponding to the number of blocks it contains. This is the
5623: mechanism that Gforth uses.
5624:
1.29 crook 5625: @cindex @file{blocks.fb}
1.28 crook 5626: Only 1 blocks file can be open at a time. If you use block words without
5627: having specified a blocks file, Gforth defaults to the blocks file
5628: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
5629: locate a blocks file (@pxref{Forth Search Paths}).
5630:
1.29 crook 5631: @cindex block buffers
1.28 crook 5632: When you read and write blocks under program control, Gforth uses a
1.29 crook 5633: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 5634: not used when you use @code{load} to interpret the contents of a block.
5635:
5636: The behaviour of the block buffers is directly analagous to that of a
5637: cache. Each block buffer has three states:
5638:
5639: @itemize @bullet
5640: @item
5641: Unassigned
5642: @item
5643: Assigned-clean
5644: @item
5645: Assigned-dirty
5646: @end itemize
5647:
1.29 crook 5648: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 5649: block, the block (specified by its block number) must be assigned to a
5650: block buffer.
5651:
5652: The assignment of a block to a block buffer is performed by @code{block}
5653: or @code{buffer}. Use @code{block} when you wish to modify the existing
5654: contents of a block. Use @code{buffer} when you don't care about the
5655: existing contents of the block@footnote{The ANS Forth definition of
5656: @code{block} is intended not to cause disk I/O; if the data associated
5657: with the particular block is already stored in a block buffer due to an
5658: earlier @code{block} command, @code{buffer} will return that block
5659: buffer and the existing contents of the block will be
5660: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 5661: block buffer for the block.}.
1.28 crook 5662:
5663: Once a block has been assigned to a block buffer, the block buffer state
1.29 crook 5664: becomes @i{assigned-clean}. Data can now be manipulated within the
1.28 crook 5665: block buffer.
5666:
5667: When the contents of a block buffer is changed it is necessary,
5668: @i{before calling} @code{block} @i{or} @code{buffer} @i{again}, to
5669: either abandon the changes (by doing nothing) or commit the changes,
5670: using @code{update}. Using @code{update} does not change the blocks
1.29 crook 5671: file; it simply changes a block buffer's state to @i{assigned-dirty}.
1.28 crook 5672:
1.29 crook 5673: The word @code{flush} causes all @i{assigned-dirty} blocks to be
1.28 crook 5674: written back to the blocks file on disk. Leaving Gforth using @code{bye}
5675: also causes a @code{flush} to be performed.
5676:
1.29 crook 5677: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 5678: algorithm to assign a block buffer to a block. That means that any
5679: particular block can only be assigned to one specific block buffer,
1.29 crook 5680: called (for the particular operation) the @i{victim buffer}. If the
5681: victim buffer is @i{unassigned} or @i{assigned-clean} it can be
5682: allocated to the new block immediately. If it is @i{assigned-dirty}
1.28 crook 5683: its current contents must be written out to disk before it can be
5684: allocated to the new block.
5685:
5686: Although no structure is imposed on the contents of a block, it is
5687: traditional to display the contents as 16 lines each of 64 characters. A
5688: block provides a single, continuous stream of input (for example, it
5689: acts as a single parse area) -- there are no end-of-line characters
5690: within a block, and no end-of-file character at the end of a
5691: block. There are two consequences of this:
1.26 crook 5692:
1.28 crook 5693: @itemize @bullet
5694: @item
5695: The last character of one line wraps straight into the first character
5696: of the following line
5697: @item
5698: The word @code{\} -- comment to end of line -- requires special
5699: treatment; in the context of a block it causes all characters until the
5700: end of the current 64-character ``line'' to be ignored.
5701: @end itemize
5702:
5703: In Gforth, when you use @code{block} with a non-existent block number,
5704: the current block file will be extended to the appropriate size and the
5705: block buffer will be initialised with spaces.
5706:
1.29 crook 5707: Gforth doesn't encourage the use of blocks; the mechanism is only
5708: provided for backward compatibility -- ANS Forth requires blocks to be
5709: available when files are.
1.28 crook 5710:
5711: Common techniques that are used when working with blocks include:
5712:
5713: @itemize @bullet
5714: @item
5715: A screen editor that allows you to edit blocks without leaving the Forth
5716: environment.
5717: @item
5718: Shadow screens; where every code block has an associated block
5719: containing comments (for example: code in odd block numbers, comments in
5720: even block numbers). Typically, the block editor provides a convenient
5721: mechanism to toggle between code and comments.
5722: @item
5723: Load blocks; a single block (typically block 1) contains a number of
5724: @code{thru} commands which @code{load} the whole of the application.
5725: @item
5726: Chaining blocks; a block terminates with a @code{-->} so that a whole
5727: application can be @code{load}ed by @code{load}ing a single block.
5728: @end itemize
1.26 crook 5729:
1.29 crook 5730: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
5731: integrated into a Forth programming environment.
1.26 crook 5732:
5733: @comment TODO what about errors on open-blocks?
5734: doc-open-blocks
5735: doc-use
5736: doc-get-block-fid
5737: doc-block-position
1.28 crook 5738:
5739: doc-scr
5740: doc-list
5741:
5742: doc---block-block
5743: doc-buffer
5744:
1.26 crook 5745: doc-update
1.28 crook 5746: doc-updated?
1.26 crook 5747: doc-save-buffers
5748: doc-empty-buffers
5749: doc-empty-buffer
5750: doc-flush
1.28 crook 5751:
1.26 crook 5752: doc-load
5753: doc-thru
5754: doc-+load
5755: doc-+thru
5756: doc---block--->
5757: doc-block-included
5758:
5759: @c -------------------------------------------------------------
5760: @node Other I/O, Programming Tools, Blocks, Words
5761: @section Other I/O
1.28 crook 5762: @cindex I/O - keyboard and display
1.26 crook 5763:
5764: @menu
5765: * Simple numeric output:: Predefined formats
5766: * Formatted numeric output:: Formatted (pictured) output
5767: * String Formats:: How Forth stores strings in memory
5768: * Displaying characters and strings:: Other stuff
5769: * Input:: Input
5770: @end menu
5771:
5772: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
5773: @subsection Simple numeric output
1.28 crook 5774: @cindex numeric output - simple/free-format
1.5 anton 5775:
1.26 crook 5776: The simplest output functions are those that display numbers from the
5777: data or floating-point stacks. Floating-point output is always displayed
5778: using base 10. Numbers displayed from the data stack use the value stored
5779: in @code{base}.
1.5 anton 5780:
1.26 crook 5781: doc-.
5782: doc-dec.
5783: doc-hex.
5784: doc-u.
5785: doc-.r
5786: doc-u.r
5787: doc-d.
5788: doc-ud.
5789: doc-d.r
5790: doc-ud.r
5791: doc-f.
5792: doc-fe.
5793: doc-fs.
1.5 anton 5794:
1.26 crook 5795: Examples of printing the number 1234.5678E23 in the different floating-point output
5796: formats are shown below:
1.5 anton 5797:
5798: @example
1.26 crook 5799: f. 123456779999999000000000000.
5800: fe. 123.456779999999E24
5801: fs. 1.23456779999999E26
1.5 anton 5802: @end example
5803:
5804:
1.26 crook 5805: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
5806: @subsection Formatted numeric output
1.28 crook 5807: @cindex formatted numeric output
1.26 crook 5808: @cindex pictured numeric output
1.28 crook 5809: @cindex numeric output - formatted
1.26 crook 5810:
1.29 crook 5811: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 5812: output} for formatted printing of integers. In this technique, digits
5813: are extracted from the number (using the current output radix defined by
5814: @code{base}), converted to ASCII codes and appended to a string that is
5815: built in a scratch-pad area of memory (@pxref{core-idef,
5816: Implementation-defined options, Implementation-defined
5817: options}). Arbitrary characters can be appended to the string during the
5818: extraction process. The completed string is specified by an address
5819: and length and can be manipulated (@code{TYPE}ed, copied, modified)
5820: under program control.
1.5 anton 5821:
1.26 crook 5822: All of the words described in the previous section for simple numeric
5823: output are implemented in Gforth using pictured numeric output.
1.5 anton 5824:
1.26 crook 5825: Three important things to remember about Pictured Numeric Output:
1.5 anton 5826:
1.26 crook 5827: @itemize @bullet
5828: @item
1.28 crook 5829: It always operates on double-precision numbers; to display a
5830: single-precision number, convert it first (@pxref{Double precision} for
5831: ways of doing this).
1.26 crook 5832: @item
1.28 crook 5833: It always treats the double-precision number as though it were
5834: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 5835: @item
5836: The string is built up from right to left; least significant digit first.
5837: @end itemize
1.5 anton 5838:
1.26 crook 5839: doc-<#
5840: doc-#
5841: doc-#s
5842: doc-hold
5843: doc-sign
5844: doc-#>
1.5 anton 5845:
1.26 crook 5846: doc-represent
1.5 anton 5847:
1.26 crook 5848: Here are some examples of using pictured numeric output:
1.5 anton 5849:
5850: @example
1.26 crook 5851: : my-u. ( u -- )
5852: \ Simplest use of pns.. behaves like Standard u.
5853: 0 \ convert to unsigned double
5854: <# \ start conversion
5855: #s \ convert all digits
5856: #> \ complete conversion
5857: TYPE SPACE ; \ display, with trailing space
1.5 anton 5858:
1.26 crook 5859: : cents-only ( u -- )
5860: 0 \ convert to unsigned double
5861: <# \ start conversion
5862: # # \ convert two least-significant digits
5863: #> \ complete conversion, discard other digits
5864: TYPE SPACE ; \ display, with trailing space
1.5 anton 5865:
1.26 crook 5866: : dollars-and-cents ( u -- )
5867: 0 \ convert to unsigned double
5868: <# \ start conversion
5869: # # \ convert two least-significant digits
5870: [char] . hold \ insert decimal point
5871: #s \ convert remaining digits
5872: [char] $ hold \ append currency symbol
5873: #> \ complete conversion
5874: TYPE SPACE ; \ display, with trailing space
1.5 anton 5875:
1.26 crook 5876: : my-. ( n -- )
5877: \ handling negatives.. behaves like Standard .
5878: s>d \ convert to signed double
5879: swap over dabs \ leave sign byte followed by unsigned double
5880: <# \ start conversion
5881: #s \ convert all digits
5882: rot sign \ get at sign byte, append "-" if needed
5883: #> \ complete conversion
5884: TYPE SPACE ; \ display, with trailing space
1.5 anton 5885:
1.26 crook 5886: : account. ( n -- )
5887: \ accountants don't like minus signs, they use braces
5888: \ for negative numbers
5889: s>d \ convert to signed double
5890: swap over dabs \ leave sign byte followed by unsigned double
5891: <# \ start conversion
5892: 2 pick \ get copy of sign byte
5893: 0< IF [char] ) hold THEN \ right-most character of output
5894: #s \ convert all digits
5895: rot \ get at sign byte
5896: 0< IF [char] ( hold THEN
5897: #> \ complete conversion
5898: TYPE SPACE ; \ display, with trailing space
1.5 anton 5899: @end example
5900:
1.26 crook 5901: Here are some examples of using these words:
1.5 anton 5902:
5903: @example
1.26 crook 5904: 1 my-u. 1
5905: hex -1 my-u. decimal FFFFFFFF
5906: 1 cents-only 01
5907: 1234 cents-only 34
5908: 2 dollars-and-cents $0.02
5909: 1234 dollars-and-cents $12.34
5910: 123 my-. 123
5911: -123 my. -123
5912: 123 account. 123
5913: -456 account. (456)
1.5 anton 5914: @end example
5915:
5916:
1.26 crook 5917: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
5918: @subsection String Formats
1.27 crook 5919: @cindex strings - see character strings
5920: @cindex character strings - formats
1.28 crook 5921: @cindex I/O - see character strings
1.26 crook 5922:
1.27 crook 5923: Forth commonly uses two different methods for representing character
5924: strings:
1.26 crook 5925:
5926: @itemize @bullet
5927: @item
5928: @cindex address of counted string
1.29 crook 5929: As a @dfn{counted string}, represented by a @i{c-addr}. The char
5930: addressed by @i{c-addr} contains a character-count, @i{n}, of the
5931: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 5932: memory.
5933: @item
1.29 crook 5934: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
5935: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 5936: first byte of the string.
5937: @end itemize
5938:
5939: ANS Forth encourages the use of the second format when representing
5940: strings on the stack, whilst conceeding that the counted string format
5941: remains useful as a way of storing strings in memory.
5942:
5943: doc-count
5944:
5945: @xref{Memory Blocks} for words that move, copy and search
5946: for strings. @xref{Displaying characters and strings,} for words that
5947: display characters and strings.
5948:
5949:
5950: @node Displaying characters and strings, Input, String Formats, Other I/O
5951: @subsection Displaying characters and strings
1.27 crook 5952: @cindex characters - compiling and displaying
5953: @cindex character strings - compiling and displaying
1.26 crook 5954:
5955: This section starts with a glossary of Forth words and ends with a set
5956: of examples.
5957:
5958: doc-bl
5959: doc-space
5960: doc-spaces
5961: doc-emit
5962: doc-toupper
5963: doc-."
5964: doc-.(
5965: doc-type
5966: doc-cr
1.27 crook 5967: @cindex cursor control
1.26 crook 5968: doc-at-xy
5969: doc-page
5970: doc-s"
5971: doc-c"
5972: doc-char
5973: doc-[char]
5974: doc-sliteral
5975:
5976: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 5977:
5978: @example
1.26 crook 5979: .( text-1)
5980: : my-word
5981: ." text-2" cr
5982: .( text-3)
5983: ;
5984:
5985: ." text-4"
5986:
5987: : my-char
5988: [char] ALPHABET emit
5989: char emit
5990: ;
1.5 anton 5991: @end example
5992:
1.26 crook 5993: When you load this code into Gforth, the following output is generated:
1.5 anton 5994:
1.26 crook 5995: @example
1.30 anton 5996: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 5997: @end example
1.5 anton 5998:
1.26 crook 5999: @itemize @bullet
6000: @item
6001: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
6002: is an immediate word; it behaves in the same way whether it is used inside
6003: or outside a colon definition.
6004: @item
6005: Message @code{text-4} is displayed because of Gforth's added interpretation
6006: semantics for @code{."}.
6007: @item
1.29 crook 6008: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 6009: performs the compilation semantics for @code{."} within the definition of
6010: @code{my-word}.
6011: @end itemize
1.5 anton 6012:
1.26 crook 6013: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 6014:
1.26 crook 6015: @example
1.30 anton 6016: @kbd{my-word @key{RET}} text-2
1.26 crook 6017: ok
1.30 anton 6018: @kbd{my-char fred @key{RET}} Af ok
6019: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 6020: @end example
1.5 anton 6021:
6022: @itemize @bullet
6023: @item
1.26 crook 6024: Message @code{text-2} is displayed because of the run-time behaviour of
6025: @code{."}.
6026: @item
6027: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
6028: on the stack at run-time. @code{emit} always displays the character
6029: when @code{my-char} is executed.
6030: @item
6031: @code{char} parses a string at run-time and the second @code{emit} displays
6032: the first character of the string.
1.5 anton 6033: @item
1.26 crook 6034: If you type @code{see my-char} you can see that @code{[char]} discarded
6035: the text ``LPHABET'' and only compiled the display code for ``A'' into the
6036: definition of @code{my-char}.
1.5 anton 6037: @end itemize
6038:
6039:
6040:
1.26 crook 6041: @node Input, , Displaying characters and strings, Other I/O
6042: @subsection Input
6043: @cindex input
1.28 crook 6044: @cindex I/O - see input
6045: @cindex parsing a string
1.5 anton 6046:
1.27 crook 6047: @xref{String Formats} for ways of storing character strings in memory.
1.5 anton 6048:
1.27 crook 6049: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 6050: @comment then index them
1.27 crook 6051:
6052: doc-key
6053: doc-key?
1.26 crook 6054: doc->number
6055: doc->float
6056: doc-accept
1.27 crook 6057: doc-pad
6058: doc-parse
6059: doc-word
6060: doc-sword
6061: doc-refill
6062: @comment obsolescent words..
6063: doc-convert
1.26 crook 6064: doc-query
6065: doc-expect
1.27 crook 6066: doc-span
1.5 anton 6067:
6068:
6069: @c -------------------------------------------------------------
1.26 crook 6070: @node Programming Tools, Assembler and Code Words, Other I/O, Words
6071: @section Programming Tools
6072: @cindex programming tools
1.12 anton 6073:
6074: @menu
1.26 crook 6075: * Debugging:: Simple and quick.
6076: * Assertions:: Making your programs self-checking.
6077: * Singlestep Debugger:: Executing your program word by word.
1.5 anton 6078: @end menu
6079:
1.26 crook 6080: @node Debugging, Assertions, Programming Tools, Programming Tools
6081: @subsection Debugging
6082: @cindex debugging
1.5 anton 6083:
1.26 crook 6084: Languages with a slow edit/compile/link/test development loop tend to
6085: require sophisticated tracing/stepping debuggers to facilate
6086: productive debugging.
1.5 anton 6087:
1.26 crook 6088: A much better (faster) way in fast-compiling languages is to add
6089: printing code at well-selected places, let the program run, look at
6090: the output, see where things went wrong, add more printing code, etc.,
6091: until the bug is found.
1.5 anton 6092:
1.26 crook 6093: The simple debugging aids provided in @file{debugs.fs}
6094: are meant to support this style of debugging. In addition, there are
6095: words for non-destructively inspecting the stack and memory:
1.5 anton 6096:
1.26 crook 6097: doc-.s
6098: doc-f.s
1.5 anton 6099:
1.29 crook 6100: There is a word @code{.r} but it does @i{not} display the return
1.26 crook 6101: stack! It is used for formatted numeric output.
1.5 anton 6102:
1.26 crook 6103: doc-depth
6104: doc-fdepth
6105: doc-clearstack
6106: doc-?
6107: doc-dump
1.5 anton 6108:
1.26 crook 6109: The word @code{~~} prints debugging information (by default the source
6110: location and the stack contents). It is easy to insert. If you use Emacs
6111: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
6112: query-replace them with nothing). The deferred words
6113: @code{printdebugdata} and @code{printdebugline} control the output of
6114: @code{~~}. The default source location output format works well with
6115: Emacs' compilation mode, so you can step through the program at the
6116: source level using @kbd{C-x `} (the advantage over a stepping debugger
6117: is that you can step in any direction and you know where the crash has
6118: happened or where the strange data has occurred).
1.5 anton 6119:
1.26 crook 6120: The default actions of @code{~~} clobber the contents of the pictured
6121: numeric output string, so you should not use @code{~~}, e.g., between
6122: @code{<#} and @code{#>}.
1.5 anton 6123:
1.26 crook 6124: doc-~~
6125: doc-printdebugdata
6126: doc-printdebugline
1.5 anton 6127:
1.26 crook 6128: doc-see
6129: doc-marker
1.5 anton 6130:
1.26 crook 6131: Here's an example of using @code{marker} at the start of a source file
6132: that you are debugging; it ensures that you only ever have one copy of
6133: the file's definitions compiled at any time:
1.5 anton 6134:
1.26 crook 6135: @example
6136: [IFDEF] my-code
6137: my-code
6138: [ENDIF]
1.5 anton 6139:
1.26 crook 6140: marker my-code
1.28 crook 6141: init-included-files
1.5 anton 6142:
1.26 crook 6143: \ .. definitions start here
6144: \ .
6145: \ .
6146: \ end
6147: @end example
1.5 anton 6148:
6149:
6150:
1.26 crook 6151: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
6152: @subsection Assertions
6153: @cindex assertions
1.5 anton 6154:
1.26 crook 6155: It is a good idea to make your programs self-checking, especially if you
6156: make an assumption that may become invalid during maintenance (for
6157: example, that a certain field of a data structure is never zero). Gforth
1.29 crook 6158: supports @dfn{assertions} for this purpose. They are used like this:
1.23 crook 6159:
1.26 crook 6160: @example
1.29 crook 6161: assert( @i{flag} )
1.26 crook 6162: @end example
1.23 crook 6163:
1.26 crook 6164: The code between @code{assert(} and @code{)} should compute a flag, that
6165: should be true if everything is alright and false otherwise. It should
6166: not change anything else on the stack. The overall stack effect of the
6167: assertion is @code{( -- )}. E.g.
1.23 crook 6168:
1.26 crook 6169: @example
6170: assert( 1 1 + 2 = ) \ what we learn in school
6171: assert( dup 0<> ) \ assert that the top of stack is not zero
6172: assert( false ) \ this code should not be reached
6173: @end example
1.23 crook 6174:
1.26 crook 6175: The need for assertions is different at different times. During
6176: debugging, we want more checking, in production we sometimes care more
6177: for speed. Therefore, assertions can be turned off, i.e., the assertion
6178: becomes a comment. Depending on the importance of an assertion and the
6179: time it takes to check it, you may want to turn off some assertions and
6180: keep others turned on. Gforth provides several levels of assertions for
6181: this purpose:
1.23 crook 6182:
1.26 crook 6183: doc-assert0(
6184: doc-assert1(
6185: doc-assert2(
6186: doc-assert3(
6187: doc-assert(
6188: doc-)
1.23 crook 6189:
1.26 crook 6190: The variable @code{assert-level} specifies the highest assertions that
6191: are turned on. I.e., at the default @code{assert-level} of one,
6192: @code{assert0(} and @code{assert1(} assertions perform checking, while
6193: @code{assert2(} and @code{assert3(} assertions are treated as comments.
6194:
6195: The value of @code{assert-level} is evaluated at compile-time, not at
6196: run-time. Therefore you cannot turn assertions on or off at run-time;
6197: you have to set the @code{assert-level} appropriately before compiling a
6198: piece of code. You can compile different pieces of code at different
6199: @code{assert-level}s (e.g., a trusted library at level 1 and
6200: newly-written code at level 3).
1.23 crook 6201:
1.26 crook 6202: doc-assert-level
1.23 crook 6203:
1.26 crook 6204: If an assertion fails, a message compatible with Emacs' compilation mode
6205: is produced and the execution is aborted (currently with @code{ABORT"}.
6206: If there is interest, we will introduce a special throw code. But if you
6207: intend to @code{catch} a specific condition, using @code{throw} is
6208: probably more appropriate than an assertion).
1.23 crook 6209:
1.26 crook 6210: Definitions in ANS Forth for these assertion words are provided
6211: in @file{compat/assert.fs}.
1.23 crook 6212:
6213:
1.26 crook 6214: @node Singlestep Debugger, , Assertions, Programming Tools
6215: @subsection Singlestep Debugger
6216: @cindex singlestep Debugger
6217: @cindex debugging Singlestep
6218: @cindex @code{dbg}
6219: @cindex @code{BREAK:}
6220: @cindex @code{BREAK"}
1.23 crook 6221:
1.26 crook 6222: When you create a new word there's often the need to check whether it
6223: behaves correctly or not. You can do this by typing @code{dbg
6224: badword}. A debug session might look like this:
1.23 crook 6225:
1.26 crook 6226: @example
6227: : badword 0 DO i . LOOP ; ok
6228: 2 dbg badword
6229: : badword
6230: Scanning code...
1.23 crook 6231:
1.26 crook 6232: Nesting debugger ready!
1.23 crook 6233:
1.26 crook 6234: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
6235: 400D4740 8049F68 DO -> [ 0 ]
6236: 400D4744 804A0C8 i -> [ 1 ] 00000
6237: 400D4748 400C5E60 . -> 0 [ 0 ]
6238: 400D474C 8049D0C LOOP -> [ 0 ]
6239: 400D4744 804A0C8 i -> [ 1 ] 00001
6240: 400D4748 400C5E60 . -> 1 [ 0 ]
6241: 400D474C 8049D0C LOOP -> [ 0 ]
6242: 400D4758 804B384 ; -> ok
6243: @end example
1.23 crook 6244:
1.26 crook 6245: Each line displayed is one step. You always have to hit return to
6246: execute the next word that is displayed. If you don't want to execute
6247: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
6248: an overview what keys are available:
1.23 crook 6249:
1.26 crook 6250: @table @i
1.23 crook 6251:
1.30 anton 6252: @item @key{RET}
1.26 crook 6253: Next; Execute the next word.
1.23 crook 6254:
1.26 crook 6255: @item n
6256: Nest; Single step through next word.
1.5 anton 6257:
1.26 crook 6258: @item u
6259: Unnest; Stop debugging and execute rest of word. If we got to this word
6260: with nest, continue debugging with the calling word.
1.5 anton 6261:
1.26 crook 6262: @item d
6263: Done; Stop debugging and execute rest.
1.5 anton 6264:
1.26 crook 6265: @item s
6266: Stop; Abort immediately.
1.5 anton 6267:
1.26 crook 6268: @end table
1.5 anton 6269:
1.26 crook 6270: Debugging large application with this mechanism is very difficult, because
6271: you have to nest very deeply into the program before the interesting part
6272: begins. This takes a lot of time.
1.5 anton 6273:
1.26 crook 6274: To do it more directly put a @code{BREAK:} command into your source code.
6275: When program execution reaches @code{BREAK:} the single step debugger is
6276: invoked and you have all the features described above.
1.23 crook 6277:
1.26 crook 6278: If you have more than one part to debug it is useful to know where the
6279: program has stopped at the moment. You can do this by the
6280: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
6281: string is typed out when the ``breakpoint'' is reached.
6282:
6283: doc-dbg
6284: doc-BREAK:
6285: doc-BREAK"
6286:
6287:
6288: @c -------------------------------------------------------------
6289: @node Assembler and Code Words, Threading Words, Programming Tools, Words
6290: @section Assembler and Code Words
6291: @cindex assembler
6292: @cindex code words
1.5 anton 6293:
1.26 crook 6294: Gforth provides some words for defining primitives (words written in
1.29 crook 6295: machine code), and for defining the machine-code equivalent of
1.26 crook 6296: @code{DOES>}-based defining words. However, the machine-independent
6297: nature of Gforth poses a few problems: First of all, Gforth runs on
6298: several architectures, so it can provide no standard assembler. What's
6299: worse is that the register allocation not only depends on the processor,
6300: but also on the @code{gcc} version and options used.
1.5 anton 6301:
1.29 crook 6302: The words that Gforth offers encapsulate some system dependences (e.g.,
6303: the header structure), so a system-independent assembler may be used in
1.26 crook 6304: Gforth. If you do not have an assembler, you can compile machine code
1.29 crook 6305: directly with @code{,} and @code{c,}@footnote{This isn't portable,
6306: because these words emit stuff in @i{data} space; it works because
6307: Gforth has unified code/data spaces. Assembler isn't likely to be
6308: portable anyway.}.
1.5 anton 6309:
1.26 crook 6310: doc-assembler
6311: doc-code
6312: doc-end-code
6313: doc-;code
6314: doc-flush-icache
1.5 anton 6315:
1.26 crook 6316: If @code{flush-icache} does not work correctly, @code{code} words
6317: etc. will not work (reliably), either.
1.5 anton 6318:
1.29 crook 6319: The typical usage of these @code{code} words can be shown most easily by
6320: analogy to the equivalent high-level defining words:
6321:
6322: @example
6323: : foo code foo
6324: <high-level Forth words> <assembler>
6325: ; end-code
6326:
6327: : bar : bar
6328: <high-level Forth words> <high-level Forth words>
6329: CREATE CREATE
6330: <high-level Forth words> <high-level Forth words>
6331: DOES> ;code
6332: <high-level Forth words> <assembler>
6333: ; end-code
6334: @end example
6335:
1.26 crook 6336: @code{flush-icache} is always present. The other words are rarely used
6337: and reside in @code{code.fs}, which is usually not loaded. You can load
6338: it with @code{require code.fs}.
1.5 anton 6339:
1.26 crook 6340: @cindex registers of the inner interpreter
6341: In the assembly code you will want to refer to the inner interpreter's
6342: registers (e.g., the data stack pointer) and you may want to use other
6343: registers for temporary storage. Unfortunately, the register allocation
6344: is installation-dependent.
1.5 anton 6345:
1.26 crook 6346: The easiest solution is to use explicit register declarations
6347: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
6348: GNU C Manual}) for all of the inner interpreter's registers: You have to
6349: compile Gforth with @code{-DFORCE_REG} (configure option
6350: @code{--enable-force-reg}) and the appropriate declarations must be
6351: present in the @code{machine.h} file (see @code{mips.h} for an example;
6352: you can find a full list of all declarable register symbols with
6353: @code{grep register engine.c}). If you give explicit registers to all
6354: variables that are declared at the beginning of @code{engine()}, you
6355: should be able to use the other caller-saved registers for temporary
6356: storage. Alternatively, you can use the @code{gcc} option
6357: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
6358: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
6359: (however, this restriction on register allocation may slow Gforth
6360: significantly).
1.5 anton 6361:
1.26 crook 6362: If this solution is not viable (e.g., because @code{gcc} does not allow
6363: you to explicitly declare all the registers you need), you have to find
6364: out by looking at the code where the inner interpreter's registers
6365: reside and which registers can be used for temporary storage. You can
6366: get an assembly listing of the engine's code with @code{make engine.s}.
1.5 anton 6367:
1.26 crook 6368: In any case, it is good practice to abstract your assembly code from the
6369: actual register allocation. E.g., if the data stack pointer resides in
6370: register @code{$17}, create an alias for this register called @code{sp},
6371: and use that in your assembly code.
1.5 anton 6372:
1.26 crook 6373: @cindex code words, portable
6374: Another option for implementing normal and defining words efficiently
6375: is to add the desired functionality to the source of Gforth. For normal
6376: words you just have to edit @file{primitives} (@pxref{Automatic
6377: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
6378: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
6379: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5 anton 6380:
6381:
1.26 crook 6382: @c -------------------------------------------------------------
6383: @node Threading Words, Locals, Assembler and Code Words, Words
6384: @section Threading Words
6385: @cindex threading words
1.5 anton 6386:
1.26 crook 6387: @cindex code address
6388: These words provide access to code addresses and other threading stuff
6389: in Gforth (and, possibly, other interpretive Forths). It more or less
6390: abstracts away the differences between direct and indirect threading
6391: (and, for direct threading, the machine dependences). However, at
6392: present this wordset is still incomplete. It is also pretty low-level;
6393: some day it will hopefully be made unnecessary by an internals wordset
6394: that abstracts implementation details away completely.
1.5 anton 6395:
1.26 crook 6396: doc-threading-method
6397: doc->code-address
6398: doc->does-code
6399: doc-code-address!
6400: doc-does-code!
6401: doc-does-handler!
6402: doc-/does-handler
1.5 anton 6403:
1.26 crook 6404: The code addresses produced by various defining words are produced by
6405: the following words:
1.5 anton 6406:
1.26 crook 6407: doc-docol:
6408: doc-docon:
6409: doc-dovar:
6410: doc-douser:
6411: doc-dodefer:
6412: doc-dofield:
1.5 anton 6413:
1.26 crook 6414: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
6415: with @code{>does-code}. If the word was defined in that way, the value
6416: returned is non-zero and identifies the @code{DOES>} used by the
6417: defining word.
6418: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5 anton 6419:
1.26 crook 6420: @c -------------------------------------------------------------
6421: @node Locals, Structures, Threading Words, Words
6422: @section Locals
6423: @cindex locals
1.5 anton 6424:
1.26 crook 6425: Local variables can make Forth programming more enjoyable and Forth
6426: programs easier to read. Unfortunately, the locals of ANS Forth are
6427: laden with restrictions. Therefore, we provide not only the ANS Forth
6428: locals wordset, but also our own, more powerful locals wordset (we
6429: implemented the ANS Forth locals wordset through our locals wordset).
1.5 anton 6430:
1.26 crook 6431: The ideas in this section have also been published in the paper
6432: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
6433: at EuroForth '94; it is available at
6434: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
1.5 anton 6435:
1.26 crook 6436: @menu
6437: * Gforth locals::
6438: * ANS Forth locals::
6439: @end menu
1.5 anton 6440:
1.26 crook 6441: @node Gforth locals, ANS Forth locals, Locals, Locals
6442: @subsection Gforth locals
6443: @cindex Gforth locals
6444: @cindex locals, Gforth style
1.5 anton 6445:
1.26 crook 6446: Locals can be defined with
1.5 anton 6447:
6448: @example
1.26 crook 6449: @{ local1 local2 ... -- comment @}
6450: @end example
6451: or
6452: @example
6453: @{ local1 local2 ... @}
1.5 anton 6454: @end example
6455:
1.26 crook 6456: E.g.,
1.5 anton 6457: @example
1.26 crook 6458: : max @{ n1 n2 -- n3 @}
6459: n1 n2 > if
6460: n1
6461: else
6462: n2
6463: endif ;
1.5 anton 6464: @end example
6465:
1.26 crook 6466: The similarity of locals definitions with stack comments is intended. A
6467: locals definition often replaces the stack comment of a word. The order
6468: of the locals corresponds to the order in a stack comment and everything
6469: after the @code{--} is really a comment.
1.5 anton 6470:
1.26 crook 6471: This similarity has one disadvantage: It is too easy to confuse locals
6472: declarations with stack comments, causing bugs and making them hard to
6473: find. However, this problem can be avoided by appropriate coding
6474: conventions: Do not use both notations in the same program. If you do,
6475: they should be distinguished using additional means, e.g. by position.
6476:
6477: @cindex types of locals
6478: @cindex locals types
6479: The name of the local may be preceded by a type specifier, e.g.,
6480: @code{F:} for a floating point value:
6481:
6482: @example
6483: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
6484: \ complex multiplication
6485: Ar Br f* Ai Bi f* f-
6486: Ar Bi f* Ai Br f* f+ ;
6487: @end example
6488:
6489: @cindex flavours of locals
6490: @cindex locals flavours
6491: @cindex value-flavoured locals
6492: @cindex variable-flavoured locals
6493: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
6494: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
6495: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
6496: with @code{W:}, @code{D:} etc.) produces its value and can be changed
6497: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
6498: produces its address (which becomes invalid when the variable's scope is
6499: left). E.g., the standard word @code{emit} can be defined in terms of
6500: @code{type} like this:
1.5 anton 6501:
6502: @example
1.26 crook 6503: : emit @{ C^ char* -- @}
6504: char* 1 type ;
1.5 anton 6505: @end example
6506:
1.26 crook 6507: @cindex default type of locals
6508: @cindex locals, default type
6509: A local without type specifier is a @code{W:} local. Both flavours of
6510: locals are initialized with values from the data or FP stack.
1.5 anton 6511:
1.26 crook 6512: Currently there is no way to define locals with user-defined data
6513: structures, but we are working on it.
1.5 anton 6514:
1.26 crook 6515: Gforth allows defining locals everywhere in a colon definition. This
6516: poses the following questions:
1.5 anton 6517:
1.26 crook 6518: @menu
6519: * Where are locals visible by name?::
6520: * How long do locals live?::
6521: * Programming Style::
6522: * Implementation::
6523: @end menu
1.5 anton 6524:
1.26 crook 6525: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
6526: @subsubsection Where are locals visible by name?
6527: @cindex locals visibility
6528: @cindex visibility of locals
6529: @cindex scope of locals
1.5 anton 6530:
1.26 crook 6531: Basically, the answer is that locals are visible where you would expect
6532: it in block-structured languages, and sometimes a little longer. If you
6533: want to restrict the scope of a local, enclose its definition in
6534: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 6535:
1.26 crook 6536: doc-scope
6537: doc-endscope
1.5 anton 6538:
1.26 crook 6539: These words behave like control structure words, so you can use them
6540: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
6541: arbitrary ways.
1.5 anton 6542:
1.26 crook 6543: If you want a more exact answer to the visibility question, here's the
6544: basic principle: A local is visible in all places that can only be
6545: reached through the definition of the local@footnote{In compiler
6546: construction terminology, all places dominated by the definition of the
6547: local.}. In other words, it is not visible in places that can be reached
6548: without going through the definition of the local. E.g., locals defined
6549: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
6550: defined in @code{BEGIN}...@code{UNTIL} are visible after the
6551: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5 anton 6552:
1.26 crook 6553: The reasoning behind this solution is: We want to have the locals
6554: visible as long as it is meaningful. The user can always make the
6555: visibility shorter by using explicit scoping. In a place that can
6556: only be reached through the definition of a local, the meaning of a
6557: local name is clear. In other places it is not: How is the local
6558: initialized at the control flow path that does not contain the
6559: definition? Which local is meant, if the same name is defined twice in
6560: two independent control flow paths?
1.5 anton 6561:
1.26 crook 6562: This should be enough detail for nearly all users, so you can skip the
6563: rest of this section. If you really must know all the gory details and
6564: options, read on.
1.5 anton 6565:
1.26 crook 6566: In order to implement this rule, the compiler has to know which places
6567: are unreachable. It knows this automatically after @code{AHEAD},
6568: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
6569: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
6570: compiler that the control flow never reaches that place. If
6571: @code{UNREACHABLE} is not used where it could, the only consequence is
6572: that the visibility of some locals is more limited than the rule above
6573: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
6574: lie to the compiler), buggy code will be produced.
1.5 anton 6575:
1.26 crook 6576: doc-unreachable
1.5 anton 6577:
1.26 crook 6578: Another problem with this rule is that at @code{BEGIN}, the compiler
6579: does not know which locals will be visible on the incoming
6580: back-edge. All problems discussed in the following are due to this
6581: ignorance of the compiler (we discuss the problems using @code{BEGIN}
6582: loops as examples; the discussion also applies to @code{?DO} and other
6583: loops). Perhaps the most insidious example is:
1.5 anton 6584: @example
1.26 crook 6585: AHEAD
6586: BEGIN
6587: x
6588: [ 1 CS-ROLL ] THEN
6589: @{ x @}
6590: ...
6591: UNTIL
6592: @end example
1.5 anton 6593:
1.26 crook 6594: This should be legal according to the visibility rule. The use of
6595: @code{x} can only be reached through the definition; but that appears
6596: textually below the use.
1.5 anton 6597:
1.26 crook 6598: From this example it is clear that the visibility rules cannot be fully
6599: implemented without major headaches. Our implementation treats common
6600: cases as advertised and the exceptions are treated in a safe way: The
6601: compiler makes a reasonable guess about the locals visible after a
6602: @code{BEGIN}; if it is too pessimistic, the
6603: user will get a spurious error about the local not being defined; if the
6604: compiler is too optimistic, it will notice this later and issue a
6605: warning. In the case above the compiler would complain about @code{x}
6606: being undefined at its use. You can see from the obscure examples in
6607: this section that it takes quite unusual control structures to get the
6608: compiler into trouble, and even then it will often do fine.
1.5 anton 6609:
1.26 crook 6610: If the @code{BEGIN} is reachable from above, the most optimistic guess
6611: is that all locals visible before the @code{BEGIN} will also be
6612: visible after the @code{BEGIN}. This guess is valid for all loops that
6613: are entered only through the @code{BEGIN}, in particular, for normal
6614: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
6615: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
6616: compiler. When the branch to the @code{BEGIN} is finally generated by
6617: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
6618: warns the user if it was too optimistic:
6619: @example
6620: IF
6621: @{ x @}
6622: BEGIN
6623: \ x ?
6624: [ 1 cs-roll ] THEN
6625: ...
6626: UNTIL
1.5 anton 6627: @end example
6628:
1.26 crook 6629: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
6630: optimistically assumes that it lives until the @code{THEN}. It notices
6631: this difference when it compiles the @code{UNTIL} and issues a
6632: warning. The user can avoid the warning, and make sure that @code{x}
6633: is not used in the wrong area by using explicit scoping:
6634: @example
6635: IF
6636: SCOPE
6637: @{ x @}
6638: ENDSCOPE
6639: BEGIN
6640: [ 1 cs-roll ] THEN
6641: ...
6642: UNTIL
6643: @end example
1.5 anton 6644:
1.26 crook 6645: Since the guess is optimistic, there will be no spurious error messages
6646: about undefined locals.
1.5 anton 6647:
1.26 crook 6648: If the @code{BEGIN} is not reachable from above (e.g., after
6649: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
6650: optimistic guess, as the locals visible after the @code{BEGIN} may be
6651: defined later. Therefore, the compiler assumes that no locals are
6652: visible after the @code{BEGIN}. However, the user can use
6653: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
6654: visible at the BEGIN as at the point where the top control-flow stack
6655: item was created.
1.5 anton 6656:
1.26 crook 6657: doc-assume-live
1.5 anton 6658:
1.26 crook 6659: E.g.,
1.5 anton 6660: @example
1.26 crook 6661: @{ x @}
6662: AHEAD
6663: ASSUME-LIVE
6664: BEGIN
6665: x
6666: [ 1 CS-ROLL ] THEN
6667: ...
6668: UNTIL
1.5 anton 6669: @end example
6670:
1.26 crook 6671: Other cases where the locals are defined before the @code{BEGIN} can be
6672: handled by inserting an appropriate @code{CS-ROLL} before the
6673: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
6674: behind the @code{ASSUME-LIVE}).
1.5 anton 6675:
1.26 crook 6676: Cases where locals are defined after the @code{BEGIN} (but should be
6677: visible immediately after the @code{BEGIN}) can only be handled by
6678: rearranging the loop. E.g., the ``most insidious'' example above can be
6679: arranged into:
1.5 anton 6680: @example
1.26 crook 6681: BEGIN
6682: @{ x @}
6683: ... 0=
6684: WHILE
6685: x
6686: REPEAT
1.5 anton 6687: @end example
6688:
1.26 crook 6689: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
6690: @subsubsection How long do locals live?
6691: @cindex locals lifetime
6692: @cindex lifetime of locals
1.5 anton 6693:
1.26 crook 6694: The right answer for the lifetime question would be: A local lives at
6695: least as long as it can be accessed. For a value-flavoured local this
6696: means: until the end of its visibility. However, a variable-flavoured
6697: local could be accessed through its address far beyond its visibility
6698: scope. Ultimately, this would mean that such locals would have to be
6699: garbage collected. Since this entails un-Forth-like implementation
6700: complexities, I adopted the same cowardly solution as some other
6701: languages (e.g., C): The local lives only as long as it is visible;
6702: afterwards its address is invalid (and programs that access it
6703: afterwards are erroneous).
1.5 anton 6704:
1.26 crook 6705: @node Programming Style, Implementation, How long do locals live?, Gforth locals
6706: @subsubsection Programming Style
6707: @cindex locals programming style
6708: @cindex programming style, locals
1.5 anton 6709:
1.26 crook 6710: The freedom to define locals anywhere has the potential to change
6711: programming styles dramatically. In particular, the need to use the
6712: return stack for intermediate storage vanishes. Moreover, all stack
6713: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
6714: determined arguments) can be eliminated: If the stack items are in the
6715: wrong order, just write a locals definition for all of them; then
6716: write the items in the order you want.
1.5 anton 6717:
1.26 crook 6718: This seems a little far-fetched and eliminating stack manipulations is
6719: unlikely to become a conscious programming objective. Still, the number
6720: of stack manipulations will be reduced dramatically if local variables
6721: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
6722: a traditional implementation of @code{max}).
1.5 anton 6723:
1.26 crook 6724: This shows one potential benefit of locals: making Forth programs more
6725: readable. Of course, this benefit will only be realized if the
6726: programmers continue to honour the principle of factoring instead of
6727: using the added latitude to make the words longer.
1.5 anton 6728:
1.26 crook 6729: @cindex single-assignment style for locals
6730: Using @code{TO} can and should be avoided. Without @code{TO},
6731: every value-flavoured local has only a single assignment and many
6732: advantages of functional languages apply to Forth. I.e., programs are
6733: easier to analyse, to optimize and to read: It is clear from the
6734: definition what the local stands for, it does not turn into something
6735: different later.
1.5 anton 6736:
1.26 crook 6737: E.g., a definition using @code{TO} might look like this:
1.5 anton 6738: @example
1.26 crook 6739: : strcmp @{ addr1 u1 addr2 u2 -- n @}
6740: u1 u2 min 0
6741: ?do
6742: addr1 c@@ addr2 c@@ -
6743: ?dup-if
6744: unloop exit
6745: then
6746: addr1 char+ TO addr1
6747: addr2 char+ TO addr2
6748: loop
6749: u1 u2 - ;
1.5 anton 6750: @end example
1.26 crook 6751: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
6752: every loop iteration. @code{strcmp} is a typical example of the
6753: readability problems of using @code{TO}. When you start reading
6754: @code{strcmp}, you think that @code{addr1} refers to the start of the
6755: string. Only near the end of the loop you realize that it is something
6756: else.
1.5 anton 6757:
1.26 crook 6758: This can be avoided by defining two locals at the start of the loop that
6759: are initialized with the right value for the current iteration.
1.5 anton 6760: @example
1.26 crook 6761: : strcmp @{ addr1 u1 addr2 u2 -- n @}
6762: addr1 addr2
6763: u1 u2 min 0
6764: ?do @{ s1 s2 @}
6765: s1 c@@ s2 c@@ -
6766: ?dup-if
6767: unloop exit
6768: then
6769: s1 char+ s2 char+
6770: loop
6771: 2drop
6772: u1 u2 - ;
1.5 anton 6773: @end example
1.26 crook 6774: Here it is clear from the start that @code{s1} has a different value
6775: in every loop iteration.
1.5 anton 6776:
1.26 crook 6777: @node Implementation, , Programming Style, Gforth locals
6778: @subsubsection Implementation
6779: @cindex locals implementation
6780: @cindex implementation of locals
1.5 anton 6781:
1.26 crook 6782: @cindex locals stack
6783: Gforth uses an extra locals stack. The most compelling reason for
6784: this is that the return stack is not float-aligned; using an extra stack
6785: also eliminates the problems and restrictions of using the return stack
6786: as locals stack. Like the other stacks, the locals stack grows toward
6787: lower addresses. A few primitives allow an efficient implementation:
1.5 anton 6788:
1.26 crook 6789: doc-@local#
6790: doc-f@local#
6791: doc-laddr#
6792: doc-lp+!#
6793: doc-lp!
6794: doc->l
6795: doc-f>l
1.5 anton 6796:
1.26 crook 6797: In addition to these primitives, some specializations of these
6798: primitives for commonly occurring inline arguments are provided for
6799: efficiency reasons, e.g., @code{@@local0} as specialization of
6800: @code{@@local#} for the inline argument 0. The following compiling words
6801: compile the right specialized version, or the general version, as
6802: appropriate:
1.6 pazsan 6803:
1.26 crook 6804: doc-compile-@local
6805: doc-compile-f@local
6806: doc-compile-lp+!
1.12 anton 6807:
1.26 crook 6808: Combinations of conditional branches and @code{lp+!#} like
6809: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
6810: is taken) are provided for efficiency and correctness in loops.
1.6 pazsan 6811:
1.26 crook 6812: A special area in the dictionary space is reserved for keeping the
6813: local variable names. @code{@{} switches the dictionary pointer to this
6814: area and @code{@}} switches it back and generates the locals
6815: initializing code. @code{W:} etc.@ are normal defining words. This
6816: special area is cleared at the start of every colon definition.
1.6 pazsan 6817:
1.26 crook 6818: @cindex word list for defining locals
6819: A special feature of Gforth's dictionary is used to implement the
6820: definition of locals without type specifiers: every word list (aka
6821: vocabulary) has its own methods for searching
6822: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
6823: with a special search method: When it is searched for a word, it
6824: actually creates that word using @code{W:}. @code{@{} changes the search
6825: order to first search the word list containing @code{@}}, @code{W:} etc.,
6826: and then the word list for defining locals without type specifiers.
1.12 anton 6827:
1.26 crook 6828: The lifetime rules support a stack discipline within a colon
6829: definition: The lifetime of a local is either nested with other locals
6830: lifetimes or it does not overlap them.
1.6 pazsan 6831:
1.26 crook 6832: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
6833: pointer manipulation is generated. Between control structure words
6834: locals definitions can push locals onto the locals stack. @code{AGAIN}
6835: is the simplest of the other three control flow words. It has to
6836: restore the locals stack depth of the corresponding @code{BEGIN}
6837: before branching. The code looks like this:
6838: @format
6839: @code{lp+!#} current-locals-size @minus{} dest-locals-size
6840: @code{branch} <begin>
6841: @end format
1.6 pazsan 6842:
1.26 crook 6843: @code{UNTIL} is a little more complicated: If it branches back, it
6844: must adjust the stack just like @code{AGAIN}. But if it falls through,
6845: the locals stack must not be changed. The compiler generates the
6846: following code:
6847: @format
6848: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
6849: @end format
6850: The locals stack pointer is only adjusted if the branch is taken.
1.6 pazsan 6851:
1.26 crook 6852: @code{THEN} can produce somewhat inefficient code:
6853: @format
6854: @code{lp+!#} current-locals-size @minus{} orig-locals-size
6855: <orig target>:
6856: @code{lp+!#} orig-locals-size @minus{} new-locals-size
6857: @end format
6858: The second @code{lp+!#} adjusts the locals stack pointer from the
1.29 crook 6859: level at the @i{orig} point to the level after the @code{THEN}. The
1.26 crook 6860: first @code{lp+!#} adjusts the locals stack pointer from the current
6861: level to the level at the orig point, so the complete effect is an
6862: adjustment from the current level to the right level after the
6863: @code{THEN}.
1.6 pazsan 6864:
1.26 crook 6865: @cindex locals information on the control-flow stack
6866: @cindex control-flow stack items, locals information
6867: In a conventional Forth implementation a dest control-flow stack entry
6868: is just the target address and an orig entry is just the address to be
6869: patched. Our locals implementation adds a word list to every orig or dest
6870: item. It is the list of locals visible (or assumed visible) at the point
6871: described by the entry. Our implementation also adds a tag to identify
6872: the kind of entry, in particular to differentiate between live and dead
6873: (reachable and unreachable) orig entries.
1.6 pazsan 6874:
1.26 crook 6875: A few unusual operations have to be performed on locals word lists:
1.6 pazsan 6876:
1.26 crook 6877: doc-common-list
6878: doc-sub-list?
6879: doc-list-size
1.6 pazsan 6880:
1.26 crook 6881: Several features of our locals word list implementation make these
6882: operations easy to implement: The locals word lists are organised as
6883: linked lists; the tails of these lists are shared, if the lists
6884: contain some of the same locals; and the address of a name is greater
6885: than the address of the names behind it in the list.
1.6 pazsan 6886:
1.26 crook 6887: Another important implementation detail is the variable
6888: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
6889: determine if they can be reached directly or only through the branch
6890: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
6891: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
6892: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6 pazsan 6893:
1.26 crook 6894: Counted loops are similar to other loops in most respects, but
6895: @code{LEAVE} requires special attention: It performs basically the same
6896: service as @code{AHEAD}, but it does not create a control-flow stack
6897: entry. Therefore the information has to be stored elsewhere;
6898: traditionally, the information was stored in the target fields of the
6899: branches created by the @code{LEAVE}s, by organizing these fields into a
6900: linked list. Unfortunately, this clever trick does not provide enough
6901: space for storing our extended control flow information. Therefore, we
6902: introduce another stack, the leave stack. It contains the control-flow
6903: stack entries for all unresolved @code{LEAVE}s.
1.6 pazsan 6904:
1.26 crook 6905: Local names are kept until the end of the colon definition, even if
6906: they are no longer visible in any control-flow path. In a few cases
6907: this may lead to increased space needs for the locals name area, but
6908: usually less than reclaiming this space would cost in code size.
1.6 pazsan 6909:
6910:
1.26 crook 6911: @node ANS Forth locals, , Gforth locals, Locals
6912: @subsection ANS Forth locals
6913: @cindex locals, ANS Forth style
1.6 pazsan 6914:
1.26 crook 6915: The ANS Forth locals wordset does not define a syntax for locals, but
6916: words that make it possible to define various syntaxes. One of the
6917: possible syntaxes is a subset of the syntax we used in the Gforth locals
6918: wordset, i.e.:
1.6 pazsan 6919:
6920: @example
1.26 crook 6921: @{ local1 local2 ... -- comment @}
1.6 pazsan 6922: @end example
1.23 crook 6923: @noindent
1.26 crook 6924: or
1.6 pazsan 6925: @example
1.26 crook 6926: @{ local1 local2 ... @}
1.6 pazsan 6927: @end example
6928:
1.26 crook 6929: The order of the locals corresponds to the order in a stack comment. The
6930: restrictions are:
1.6 pazsan 6931:
6932: @itemize @bullet
6933: @item
1.26 crook 6934: Locals can only be cell-sized values (no type specifiers are allowed).
1.6 pazsan 6935: @item
1.26 crook 6936: Locals can be defined only outside control structures.
1.6 pazsan 6937: @item
1.26 crook 6938: Locals can interfere with explicit usage of the return stack. For the
6939: exact (and long) rules, see the standard. If you don't use return stack
6940: accessing words in a definition using locals, you will be all right. The
6941: purpose of this rule is to make locals implementation on the return
6942: stack easier.
1.6 pazsan 6943: @item
1.26 crook 6944: The whole definition must be in one line.
6945: @end itemize
1.6 pazsan 6946:
1.26 crook 6947: Locals defined in this way behave like @code{VALUE}s (@xref{Simple
6948: Defining Words}). I.e., they are initialized from the stack. Using their
6949: name produces their value. Their value can be changed using @code{TO}.
1.6 pazsan 6950:
1.26 crook 6951: Since this syntax is supported by Gforth directly, you need not do
6952: anything to use it. If you want to port a program using this syntax to
6953: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
6954: syntax on the other system.
1.6 pazsan 6955:
1.26 crook 6956: Note that a syntax shown in the standard, section A.13 looks
6957: similar, but is quite different in having the order of locals
6958: reversed. Beware!
1.6 pazsan 6959:
1.26 crook 6960: The ANS Forth locals wordset itself consists of a word:
1.6 pazsan 6961:
1.26 crook 6962: doc-(local)
1.6 pazsan 6963:
1.26 crook 6964: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
6965: awful that we strongly recommend not to use it. We have implemented this
6966: syntax to make porting to Gforth easy, but do not document it here. The
6967: problem with this syntax is that the locals are defined in an order
6968: reversed with respect to the standard stack comment notation, making
6969: programs harder to read, and easier to misread and miswrite. The only
6970: merit of this syntax is that it is easy to implement using the ANS Forth
6971: locals wordset.
1.7 pazsan 6972:
6973:
1.26 crook 6974: @c ----------------------------------------------------------
6975: @node Structures, Object-oriented Forth, Locals, Words
6976: @section Structures
6977: @cindex structures
6978: @cindex records
1.7 pazsan 6979:
1.26 crook 6980: This section presents the structure package that comes with Gforth. A
6981: version of the package implemented in ANS Forth is available in
6982: @file{compat/struct.fs}. This package was inspired by a posting on
6983: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
6984: possibly John Hayes). A version of this section has been published in
6985: ???. Marcel Hendrix provided helpful comments.
1.7 pazsan 6986:
1.26 crook 6987: @menu
6988: * Why explicit structure support?::
6989: * Structure Usage::
6990: * Structure Naming Convention::
6991: * Structure Implementation::
6992: * Structure Glossary::
6993: @end menu
1.7 pazsan 6994:
1.26 crook 6995: @node Why explicit structure support?, Structure Usage, Structures, Structures
6996: @subsection Why explicit structure support?
1.7 pazsan 6997:
1.26 crook 6998: @cindex address arithmetic for structures
6999: @cindex structures using address arithmetic
7000: If we want to use a structure containing several fields, we could simply
7001: reserve memory for it, and access the fields using address arithmetic
1.32 anton 7002: (@pxref{Address arithmetic}). As an example, consider a structure with
1.26 crook 7003: the following fields
1.7 pazsan 7004:
1.26 crook 7005: @table @code
7006: @item a
7007: is a float
7008: @item b
7009: is a cell
7010: @item c
7011: is a float
7012: @end table
1.7 pazsan 7013:
1.26 crook 7014: Given the (float-aligned) base address of the structure we get the
7015: address of the field
1.13 pazsan 7016:
1.26 crook 7017: @table @code
7018: @item a
7019: without doing anything further.
7020: @item b
7021: with @code{float+}
7022: @item c
7023: with @code{float+ cell+ faligned}
7024: @end table
1.13 pazsan 7025:
1.26 crook 7026: It is easy to see that this can become quite tiring.
1.13 pazsan 7027:
1.26 crook 7028: Moreover, it is not very readable, because seeing a
7029: @code{cell+} tells us neither which kind of structure is
7030: accessed nor what field is accessed; we have to somehow infer the kind
7031: of structure, and then look up in the documentation, which field of
7032: that structure corresponds to that offset.
1.13 pazsan 7033:
1.26 crook 7034: Finally, this kind of address arithmetic also causes maintenance
7035: troubles: If you add or delete a field somewhere in the middle of the
7036: structure, you have to find and change all computations for the fields
7037: afterwards.
1.13 pazsan 7038:
1.26 crook 7039: So, instead of using @code{cell+} and friends directly, how
7040: about storing the offsets in constants:
1.13 pazsan 7041:
7042: @example
1.26 crook 7043: 0 constant a-offset
7044: 0 float+ constant b-offset
7045: 0 float+ cell+ faligned c-offset
1.13 pazsan 7046: @end example
7047:
1.26 crook 7048: Now we can get the address of field @code{x} with @code{x-offset
7049: +}. This is much better in all respects. Of course, you still
7050: have to change all later offset definitions if you add a field. You can
7051: fix this by declaring the offsets in the following way:
1.13 pazsan 7052:
7053: @example
1.26 crook 7054: 0 constant a-offset
7055: a-offset float+ constant b-offset
7056: b-offset cell+ faligned constant c-offset
1.13 pazsan 7057: @end example
7058:
1.26 crook 7059: Since we always use the offsets with @code{+}, we could use a defining
7060: word @code{cfield} that includes the @code{+} in the action of the
7061: defined word:
1.8 pazsan 7062:
7063: @example
1.26 crook 7064: : cfield ( n "name" -- )
7065: create ,
7066: does> ( name execution: addr1 -- addr2 )
7067: @@ + ;
1.13 pazsan 7068:
1.26 crook 7069: 0 cfield a
7070: 0 a float+ cfield b
7071: 0 b cell+ faligned cfield c
1.13 pazsan 7072: @end example
7073:
1.26 crook 7074: Instead of @code{x-offset +}, we now simply write @code{x}.
7075:
7076: The structure field words now can be used quite nicely. However,
7077: their definition is still a bit cumbersome: We have to repeat the
7078: name, the information about size and alignment is distributed before
7079: and after the field definitions etc. The structure package presented
7080: here addresses these problems.
7081:
7082: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
7083: @subsection Structure Usage
7084: @cindex structure usage
1.13 pazsan 7085:
1.26 crook 7086: @cindex @code{field} usage
7087: @cindex @code{struct} usage
7088: @cindex @code{end-struct} usage
7089: You can define a structure for a (data-less) linked list with:
1.13 pazsan 7090: @example
1.26 crook 7091: struct
7092: cell% field list-next
7093: end-struct list%
1.13 pazsan 7094: @end example
7095:
1.26 crook 7096: With the address of the list node on the stack, you can compute the
7097: address of the field that contains the address of the next node with
7098: @code{list-next}. E.g., you can determine the length of a list
7099: with:
1.13 pazsan 7100:
7101: @example
1.26 crook 7102: : list-length ( list -- n )
7103: \ "list" is a pointer to the first element of a linked list
7104: \ "n" is the length of the list
7105: 0 BEGIN ( list1 n1 )
7106: over
7107: WHILE ( list1 n1 )
7108: 1+ swap list-next @@ swap
7109: REPEAT
7110: nip ;
1.13 pazsan 7111: @end example
7112:
1.26 crook 7113: You can reserve memory for a list node in the dictionary with
7114: @code{list% %allot}, which leaves the address of the list node on the
7115: stack. For the equivalent allocation on the heap you can use @code{list%
7116: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
7117: use @code{list% %allocate}). You can get the the size of a list
7118: node with @code{list% %size} and its alignment with @code{list%
7119: %alignment}.
1.13 pazsan 7120:
1.26 crook 7121: Note that in ANS Forth the body of a @code{create}d word is
7122: @code{aligned} but not necessarily @code{faligned};
7123: therefore, if you do a:
1.13 pazsan 7124: @example
1.26 crook 7125: create @emph{name} foo% %allot
1.8 pazsan 7126: @end example
7127:
1.26 crook 7128: @noindent
7129: then the memory alloted for @code{foo%} is
7130: guaranteed to start at the body of @code{@emph{name}} only if
7131: @code{foo%} contains only character, cell and double fields.
1.20 pazsan 7132:
1.26 crook 7133: @cindex strcutures containing structures
7134: You can include a structure @code{foo%} as a field of
7135: another structure, like this:
1.20 pazsan 7136: @example
1.26 crook 7137: struct
7138: ...
7139: foo% field ...
7140: ...
7141: end-struct ...
1.20 pazsan 7142: @end example
7143:
1.26 crook 7144: @cindex structure extension
7145: @cindex extended records
7146: Instead of starting with an empty structure, you can extend an
7147: existing structure. E.g., a plain linked list without data, as defined
7148: above, is hardly useful; You can extend it to a linked list of integers,
7149: like this:@footnote{This feature is also known as @emph{extended
7150: records}. It is the main innovation in the Oberon language; in other
7151: words, adding this feature to Modula-2 led Wirth to create a new
7152: language, write a new compiler etc. Adding this feature to Forth just
7153: required a few lines of code.}
1.20 pazsan 7154:
7155: @example
1.26 crook 7156: list%
7157: cell% field intlist-int
7158: end-struct intlist%
1.20 pazsan 7159: @end example
7160:
1.26 crook 7161: @code{intlist%} is a structure with two fields:
7162: @code{list-next} and @code{intlist-int}.
1.20 pazsan 7163:
1.26 crook 7164: @cindex structures containing arrays
7165: You can specify an array type containing @emph{n} elements of
7166: type @code{foo%} like this:
1.20 pazsan 7167:
7168: @example
1.26 crook 7169: foo% @emph{n} *
1.20 pazsan 7170: @end example
7171:
1.26 crook 7172: You can use this array type in any place where you can use a normal
7173: type, e.g., when defining a @code{field}, or with
7174: @code{%allot}.
1.20 pazsan 7175:
1.26 crook 7176: @cindex first field optimization
7177: The first field is at the base address of a structure and the word
7178: for this field (e.g., @code{list-next}) actually does not change
7179: the address on the stack. You may be tempted to leave it away in the
7180: interest of run-time and space efficiency. This is not necessary,
7181: because the structure package optimizes this case and compiling such
7182: words does not generate any code. So, in the interest of readability
7183: and maintainability you should include the word for the field when
7184: accessing the field.
1.20 pazsan 7185:
1.26 crook 7186: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
7187: @subsection Structure Naming Convention
7188: @cindex structure naming convention
1.20 pazsan 7189:
1.26 crook 7190: The field names that come to (my) mind are often quite generic, and,
7191: if used, would cause frequent name clashes. E.g., many structures
7192: probably contain a @code{counter} field. The structure names
7193: that come to (my) mind are often also the logical choice for the names
7194: of words that create such a structure.
1.20 pazsan 7195:
1.26 crook 7196: Therefore, I have adopted the following naming conventions:
1.20 pazsan 7197:
1.26 crook 7198: @itemize @bullet
7199: @cindex field naming convention
7200: @item
7201: The names of fields are of the form
7202: @code{@emph{struct}-@emph{field}}, where
7203: @code{@emph{struct}} is the basic name of the structure, and
7204: @code{@emph{field}} is the basic name of the field. You can
7205: think of field words as converting the (address of the)
7206: structure into the (address of the) field.
1.20 pazsan 7207:
1.26 crook 7208: @cindex structure naming convention
7209: @item
7210: The names of structures are of the form
7211: @code{@emph{struct}%}, where
7212: @code{@emph{struct}} is the basic name of the structure.
7213: @end itemize
1.20 pazsan 7214:
1.26 crook 7215: This naming convention does not work that well for fields of extended
7216: structures; e.g., the integer list structure has a field
7217: @code{intlist-int}, but has @code{list-next}, not
7218: @code{intlist-next}.
1.20 pazsan 7219:
1.26 crook 7220: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
7221: @subsection Structure Implementation
7222: @cindex structure implementation
7223: @cindex implementation of structures
1.20 pazsan 7224:
1.26 crook 7225: The central idea in the implementation is to pass the data about the
7226: structure being built on the stack, not in some global
7227: variable. Everything else falls into place naturally once this design
7228: decision is made.
1.20 pazsan 7229:
1.26 crook 7230: The type description on the stack is of the form @emph{align
7231: size}. Keeping the size on the top-of-stack makes dealing with arrays
7232: very simple.
1.20 pazsan 7233:
1.26 crook 7234: @code{field} is a defining word that uses @code{Create}
7235: and @code{DOES>}. The body of the field contains the offset
7236: of the field, and the normal @code{DOES>} action is simply:
1.20 pazsan 7237:
7238: @example
1.26 crook 7239: @ +
1.20 pazsan 7240: @end example
7241:
1.23 crook 7242: @noindent
1.26 crook 7243: i.e., add the offset to the address, giving the stack effect
1.29 crook 7244: @i{addr1 -- addr2} for a field.
1.20 pazsan 7245:
1.26 crook 7246: @cindex first field optimization, implementation
7247: This simple structure is slightly complicated by the optimization
7248: for fields with offset 0, which requires a different
7249: @code{DOES>}-part (because we cannot rely on there being
7250: something on the stack if such a field is invoked during
7251: compilation). Therefore, we put the different @code{DOES>}-parts
7252: in separate words, and decide which one to invoke based on the
7253: offset. For a zero offset, the field is basically a noop; it is
7254: immediate, and therefore no code is generated when it is compiled.
1.20 pazsan 7255:
1.26 crook 7256: @node Structure Glossary, , Structure Implementation, Structures
7257: @subsection Structure Glossary
7258: @cindex structure glossary
1.20 pazsan 7259:
1.26 crook 7260: doc-%align
7261: doc-%alignment
7262: doc-%alloc
7263: doc-%allocate
7264: doc-%allot
7265: doc-cell%
7266: doc-char%
7267: doc-dfloat%
7268: doc-double%
7269: doc-end-struct
7270: doc-field
7271: doc-float%
7272: doc-naligned
7273: doc-sfloat%
7274: doc-%size
7275: doc-struct
1.23 crook 7276:
1.26 crook 7277: @c -------------------------------------------------------------
7278: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
7279: @section Object-oriented Forth
1.20 pazsan 7280:
1.26 crook 7281: Gforth comes with three packages for object-oriented programming:
7282: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
7283: is preloaded, so you have to @code{include} them before use. The most
7284: important differences between these packages (and others) are discussed
7285: in @ref{Comparison with other object models}. All packages are written
7286: in ANS Forth and can be used with any other ANS Forth.
1.20 pazsan 7287:
1.26 crook 7288: @menu
7289: * Why object-oriented programming?::
7290: * Object-Oriented Terminology::
7291: * Objects::
7292: * OOF::
7293: * Mini-OOF::
7294: * Comparison with other object models::
7295: @end menu
1.20 pazsan 7296:
1.23 crook 7297:
1.26 crook 7298: @node Why object-oriented programming?, Object-Oriented Terminology, , Object-oriented Forth
7299: @subsubsection Why object-oriented programming?
7300: @cindex object-oriented programming motivation
7301: @cindex motivation for object-oriented programming
1.23 crook 7302:
1.26 crook 7303: Often we have to deal with several data structures (@emph{objects}),
7304: that have to be treated similarly in some respects, but differently in
7305: others. Graphical objects are the textbook example: circles, triangles,
7306: dinosaurs, icons, and others, and we may want to add more during program
7307: development. We want to apply some operations to any graphical object,
7308: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
7309: has to do something different for every kind of object.
7310: @comment TODO add some other operations eg perimeter, area
7311: @comment and tie in to concrete examples later..
1.23 crook 7312:
1.26 crook 7313: We could implement @code{draw} as a big @code{CASE}
7314: control structure that executes the appropriate code depending on the
7315: kind of object to be drawn. This would be not be very elegant, and,
7316: moreover, we would have to change @code{draw} every time we add
7317: a new kind of graphical object (say, a spaceship).
1.23 crook 7318:
1.26 crook 7319: What we would rather do is: When defining spaceships, we would tell
7320: the system: ``Here's how you @code{draw} a spaceship; you figure
7321: out the rest''.
1.23 crook 7322:
1.26 crook 7323: This is the problem that all systems solve that (rightfully) call
7324: themselves object-oriented; the object-oriented packages presented here
7325: solve this problem (and not much else).
7326: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23 crook 7327:
1.26 crook 7328: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
7329: @subsubsection Object-Oriented Terminology
7330: @cindex object-oriented terminology
7331: @cindex terminology for object-oriented programming
1.23 crook 7332:
1.26 crook 7333: This section is mainly for reference, so you don't have to understand
7334: all of it right away. The terminology is mainly Smalltalk-inspired. In
7335: short:
1.23 crook 7336:
1.26 crook 7337: @table @emph
7338: @cindex class
7339: @item class
7340: a data structure definition with some extras.
1.23 crook 7341:
1.26 crook 7342: @cindex object
7343: @item object
7344: an instance of the data structure described by the class definition.
1.23 crook 7345:
1.26 crook 7346: @cindex instance variables
7347: @item instance variables
7348: fields of the data structure.
1.23 crook 7349:
1.26 crook 7350: @cindex selector
7351: @cindex method selector
7352: @cindex virtual function
7353: @item selector
7354: (or @emph{method selector}) a word (e.g.,
7355: @code{draw}) that performs an operation on a variety of data
7356: structures (classes). A selector describes @emph{what} operation to
7357: perform. In C++ terminology: a (pure) virtual function.
1.23 crook 7358:
1.26 crook 7359: @cindex method
7360: @item method
7361: the concrete definition that performs the operation
7362: described by the selector for a specific class. A method specifies
7363: @emph{how} the operation is performed for a specific class.
1.23 crook 7364:
1.26 crook 7365: @cindex selector invocation
7366: @cindex message send
7367: @cindex invoking a selector
7368: @item selector invocation
7369: a call of a selector. One argument of the call (the TOS (top-of-stack))
7370: is used for determining which method is used. In Smalltalk terminology:
7371: a message (consisting of the selector and the other arguments) is sent
7372: to the object.
1.1 anton 7373:
1.26 crook 7374: @cindex receiving object
7375: @item receiving object
7376: the object used for determining the method executed by a selector
7377: invocation. In the @file{objects.fs} model, it is the object that is on
7378: the TOS when the selector is invoked. (@emph{Receiving} comes from
7379: the Smalltalk @emph{message} terminology.)
1.1 anton 7380:
1.26 crook 7381: @cindex child class
7382: @cindex parent class
7383: @cindex inheritance
7384: @item child class
7385: a class that has (@emph{inherits}) all properties (instance variables,
7386: selectors, methods) from a @emph{parent class}. In Smalltalk
7387: terminology: The subclass inherits from the superclass. In C++
7388: terminology: The derived class inherits from the base class.
1.1 anton 7389:
1.26 crook 7390: @end table
1.21 crook 7391:
1.26 crook 7392: @c If you wonder about the message sending terminology, it comes from
7393: @c a time when each object had it's own task and objects communicated via
7394: @c message passing; eventually the Smalltalk developers realized that
7395: @c they can do most things through simple (indirect) calls. They kept the
7396: @c terminology.
1.1 anton 7397:
7398:
1.26 crook 7399: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
7400: @subsection The @file{objects.fs} model
7401: @cindex objects
7402: @cindex object-oriented programming
1.1 anton 7403:
1.26 crook 7404: @cindex @file{objects.fs}
7405: @cindex @file{oof.fs}
1.1 anton 7406:
1.26 crook 7407: 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}).
7408: @c McKewan's and Zsoter's packages
1.1 anton 7409:
1.26 crook 7410: This section assumes that you have read @ref{Structures}.
1.1 anton 7411:
1.26 crook 7412: The techniques on which this model is based have been used to implement
7413: the parser generator, Gray, and have also been used in Gforth for
7414: implementing the various flavours of word lists (hashed or not,
7415: case-sensitive or not, special-purpose word lists for locals etc.).
1.1 anton 7416:
7417:
1.26 crook 7418: @menu
7419: * Properties of the Objects model::
7420: * Basic Objects Usage::
7421: * The Objects base class::
7422: * Creating objects::
7423: * Object-Oriented Programming Style::
7424: * Class Binding::
7425: * Method conveniences::
7426: * Classes and Scoping::
7427: * Object Interfaces::
7428: * Objects Implementation::
7429: * Objects Glossary::
7430: @end menu
1.1 anton 7431:
1.26 crook 7432: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
7433: and Bernd Paysan helped me with the related works section.
1.1 anton 7434:
1.26 crook 7435: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
7436: @subsubsection Properties of the @file{objects.fs} model
7437: @cindex @file{objects.fs} properties
1.1 anton 7438:
1.26 crook 7439: @itemize @bullet
7440: @item
7441: It is straightforward to pass objects on the stack. Passing
7442: selectors on the stack is a little less convenient, but possible.
1.1 anton 7443:
1.26 crook 7444: @item
7445: Objects are just data structures in memory, and are referenced by their
7446: address. You can create words for objects with normal defining words
7447: like @code{constant}. Likewise, there is no difference between instance
7448: variables that contain objects and those that contain other data.
1.1 anton 7449:
1.26 crook 7450: @item
7451: Late binding is efficient and easy to use.
1.21 crook 7452:
1.26 crook 7453: @item
7454: It avoids parsing, and thus avoids problems with state-smartness
7455: and reduced extensibility; for convenience there are a few parsing
7456: words, but they have non-parsing counterparts. There are also a few
7457: defining words that parse. This is hard to avoid, because all standard
7458: defining words parse (except @code{:noname}); however, such
7459: words are not as bad as many other parsing words, because they are not
7460: state-smart.
1.21 crook 7461:
1.26 crook 7462: @item
7463: It does not try to incorporate everything. It does a few things and does
7464: them well (IMO). In particular, this model was not designed to support
7465: information hiding (although it has features that may help); you can use
7466: a separate package for achieving this.
1.21 crook 7467:
1.26 crook 7468: @item
7469: It is layered; you don't have to learn and use all features to use this
7470: model. Only a few features are necessary (@xref{Basic Objects Usage},
7471: @xref{The Objects base class}, @xref{Creating objects}.), the others
7472: are optional and independent of each other.
1.21 crook 7473:
1.26 crook 7474: @item
7475: An implementation in ANS Forth is available.
1.21 crook 7476:
1.26 crook 7477: @end itemize
1.21 crook 7478:
7479:
1.26 crook 7480: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
7481: @subsubsection Basic @file{objects.fs} Usage
7482: @cindex basic objects usage
7483: @cindex objects, basic usage
1.21 crook 7484:
1.26 crook 7485: You can define a class for graphical objects like this:
1.21 crook 7486:
1.26 crook 7487: @cindex @code{class} usage
7488: @cindex @code{end-class} usage
7489: @cindex @code{selector} usage
7490: @example
7491: object class \ "object" is the parent class
7492: selector draw ( x y graphical -- )
7493: end-class graphical
7494: @end example
1.21 crook 7495:
1.26 crook 7496: This code defines a class @code{graphical} with an
7497: operation @code{draw}. We can perform the operation
7498: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 7499:
1.26 crook 7500: @example
7501: 100 100 t-rex draw
7502: @end example
1.21 crook 7503:
1.26 crook 7504: @noindent
7505: where @code{t-rex} is a word (say, a constant) that produces a
7506: graphical object.
1.21 crook 7507:
1.29 crook 7508: @comment TODO add a 2nd operation eg perimeter.. and use for
1.26 crook 7509: @comment a concrete example
1.21 crook 7510:
1.26 crook 7511: @cindex abstract class
7512: How do we create a graphical object? With the present definitions,
7513: we cannot create a useful graphical object. The class
7514: @code{graphical} describes graphical objects in general, but not
7515: any concrete graphical object type (C++ users would call it an
7516: @emph{abstract class}); e.g., there is no method for the selector
7517: @code{draw} in the class @code{graphical}.
1.21 crook 7518:
1.26 crook 7519: For concrete graphical objects, we define child classes of the
7520: class @code{graphical}, e.g.:
1.21 crook 7521:
1.26 crook 7522: @cindex @code{overrides} usage
7523: @cindex @code{field} usage in class definition
7524: @example
7525: graphical class \ "graphical" is the parent class
7526: cell% field circle-radius
1.21 crook 7527:
1.26 crook 7528: :noname ( x y circle -- )
7529: circle-radius @@ draw-circle ;
7530: overrides draw
1.21 crook 7531:
1.26 crook 7532: :noname ( n-radius circle -- )
7533: circle-radius ! ;
7534: overrides construct
1.21 crook 7535:
1.26 crook 7536: end-class circle
1.21 crook 7537: @end example
7538:
1.26 crook 7539: Here we define a class @code{circle} as a child of @code{graphical},
7540: with field @code{circle-radius} (which behaves just like a field
7541: (@pxref{Structures}); it defines (using @code{overrides}) new methods
7542: for the selectors @code{draw} and @code{construct} (@code{construct} is
7543: defined in @code{object}, the parent class of @code{graphical}).
1.21 crook 7544:
1.26 crook 7545: Now we can create a circle on the heap (i.e.,
7546: @code{allocate}d memory) with:
1.21 crook 7547:
1.26 crook 7548: @cindex @code{heap-new} usage
1.21 crook 7549: @example
1.26 crook 7550: 50 circle heap-new constant my-circle
7551: @end example
1.21 crook 7552:
1.26 crook 7553: @noindent
7554: @code{heap-new} invokes @code{construct}, thus
7555: initializing the field @code{circle-radius} with 50. We can draw
7556: this new circle at (100,100) with:
1.21 crook 7557:
1.26 crook 7558: @example
7559: 100 100 my-circle draw
1.21 crook 7560: @end example
7561:
1.26 crook 7562: @cindex selector invocation, restrictions
7563: @cindex class definition, restrictions
7564: Note: You can only invoke a selector if the object on the TOS
7565: (the receiving object) belongs to the class where the selector was
7566: defined or one of its descendents; e.g., you can invoke
7567: @code{draw} only for objects belonging to @code{graphical}
7568: or its descendents (e.g., @code{circle}). Immediately before
7569: @code{end-class}, the search order has to be the same as
7570: immediately after @code{class}.
1.21 crook 7571:
1.26 crook 7572: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
7573: @subsubsection The @file{object.fs} base class
7574: @cindex @code{object} class
1.21 crook 7575:
1.26 crook 7576: When you define a class, you have to specify a parent class. So how do
7577: you start defining classes? There is one class available from the start:
7578: @code{object}. It is ancestor for all classes and so is the
7579: only class that has no parent. It has two selectors: @code{construct}
7580: and @code{print}.
1.21 crook 7581:
1.26 crook 7582: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
7583: @subsubsection Creating objects
7584: @cindex creating objects
7585: @cindex object creation
7586: @cindex object allocation options
1.21 crook 7587:
1.26 crook 7588: @cindex @code{heap-new} discussion
7589: @cindex @code{dict-new} discussion
7590: @cindex @code{construct} discussion
7591: You can create and initialize an object of a class on the heap with
7592: @code{heap-new} ( ... class -- object ) and in the dictionary
7593: (allocation with @code{allot}) with @code{dict-new} (
7594: ... class -- object ). Both words invoke @code{construct}, which
7595: consumes the stack items indicated by "..." above.
1.21 crook 7596:
1.26 crook 7597: @cindex @code{init-object} discussion
7598: @cindex @code{class-inst-size} discussion
7599: If you want to allocate memory for an object yourself, you can get its
7600: alignment and size with @code{class-inst-size 2@@} ( class --
7601: align size ). Once you have memory for an object, you can initialize
7602: it with @code{init-object} ( ... class object -- );
7603: @code{construct} does only a part of the necessary work.
1.21 crook 7604:
1.26 crook 7605: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
7606: @subsubsection Object-Oriented Programming Style
7607: @cindex object-oriented programming style
1.21 crook 7608:
1.26 crook 7609: This section is not exhaustive.
1.1 anton 7610:
1.26 crook 7611: @cindex stack effects of selectors
7612: @cindex selectors and stack effects
7613: In general, it is a good idea to ensure that all methods for the
7614: same selector have the same stack effect: when you invoke a selector,
7615: you often have no idea which method will be invoked, so, unless all
7616: methods have the same stack effect, you will not know the stack effect
7617: of the selector invocation.
1.21 crook 7618:
1.26 crook 7619: One exception to this rule is methods for the selector
7620: @code{construct}. We know which method is invoked, because we
7621: specify the class to be constructed at the same place. Actually, I
7622: defined @code{construct} as a selector only to give the users a
7623: convenient way to specify initialization. The way it is used, a
7624: mechanism different from selector invocation would be more natural
7625: (but probably would take more code and more space to explain).
1.21 crook 7626:
1.26 crook 7627: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
7628: @subsubsection Class Binding
7629: @cindex class binding
7630: @cindex early binding
1.21 crook 7631:
1.26 crook 7632: @cindex late binding
7633: Normal selector invocations determine the method at run-time depending
7634: on the class of the receiving object. This run-time selection is called
1.29 crook 7635: @i{late binding}.
1.21 crook 7636:
1.26 crook 7637: Sometimes it's preferable to invoke a different method. For example,
7638: you might want to use the simple method for @code{print}ing
7639: @code{object}s instead of the possibly long-winded @code{print} method
7640: of the receiver class. You can achieve this by replacing the invocation
7641: of @code{print} with:
1.21 crook 7642:
1.26 crook 7643: @cindex @code{[bind]} usage
7644: @example
7645: [bind] object print
1.21 crook 7646: @end example
7647:
1.26 crook 7648: @noindent
7649: in compiled code or:
1.21 crook 7650:
1.26 crook 7651: @cindex @code{bind} usage
1.21 crook 7652: @example
1.26 crook 7653: bind object print
1.21 crook 7654: @end example
7655:
1.26 crook 7656: @cindex class binding, alternative to
7657: @noindent
7658: in interpreted code. Alternatively, you can define the method with a
7659: name (e.g., @code{print-object}), and then invoke it through the
7660: name. Class binding is just a (often more convenient) way to achieve
7661: the same effect; it avoids name clutter and allows you to invoke
7662: methods directly without naming them first.
7663:
7664: @cindex superclass binding
7665: @cindex parent class binding
7666: A frequent use of class binding is this: When we define a method
7667: for a selector, we often want the method to do what the selector does
7668: in the parent class, and a little more. There is a special word for
7669: this purpose: @code{[parent]}; @code{[parent]
7670: @emph{selector}} is equivalent to @code{[bind] @emph{parent
7671: selector}}, where @code{@emph{parent}} is the parent
7672: class of the current class. E.g., a method definition might look like:
1.21 crook 7673:
1.26 crook 7674: @cindex @code{[parent]} usage
1.21 crook 7675: @example
1.26 crook 7676: :noname
7677: dup [parent] foo \ do parent's foo on the receiving object
7678: ... \ do some more
7679: ; overrides foo
1.21 crook 7680: @end example
7681:
1.26 crook 7682: @cindex class binding as optimization
7683: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
7684: March 1997), Andrew McKewan presents class binding as an optimization
7685: technique. I recommend not using it for this purpose unless you are in
7686: an emergency. Late binding is pretty fast with this model anyway, so the
7687: benefit of using class binding is small; the cost of using class binding
7688: where it is not appropriate is reduced maintainability.
1.21 crook 7689:
1.26 crook 7690: While we are at programming style questions: You should bind
7691: selectors only to ancestor classes of the receiving object. E.g., say,
7692: you know that the receiving object is of class @code{foo} or its
7693: descendents; then you should bind only to @code{foo} and its
7694: ancestors.
1.21 crook 7695:
1.26 crook 7696: @node Method conveniences, Classes and Scoping, Class Binding, Objects
7697: @subsubsection Method conveniences
7698: @cindex method conveniences
1.1 anton 7699:
1.26 crook 7700: In a method you usually access the receiving object pretty often. If
7701: you define the method as a plain colon definition (e.g., with
7702: @code{:noname}), you may have to do a lot of stack
7703: gymnastics. To avoid this, you can define the method with @code{m:
7704: ... ;m}. E.g., you could define the method for
7705: @code{draw}ing a @code{circle} with
1.20 pazsan 7706:
1.26 crook 7707: @cindex @code{this} usage
7708: @cindex @code{m:} usage
7709: @cindex @code{;m} usage
7710: @example
7711: m: ( x y circle -- )
7712: ( x y ) this circle-radius @@ draw-circle ;m
7713: @end example
1.20 pazsan 7714:
1.26 crook 7715: @cindex @code{exit} in @code{m: ... ;m}
7716: @cindex @code{exitm} discussion
7717: @cindex @code{catch} in @code{m: ... ;m}
7718: When this method is executed, the receiver object is removed from the
7719: stack; you can access it with @code{this} (admittedly, in this
7720: example the use of @code{m: ... ;m} offers no advantage). Note
7721: that I specify the stack effect for the whole method (i.e. including
7722: the receiver object), not just for the code between @code{m:}
7723: and @code{;m}. You cannot use @code{exit} in
7724: @code{m:...;m}; instead, use
7725: @code{exitm}.@footnote{Moreover, for any word that calls
7726: @code{catch} and was defined before loading
7727: @code{objects.fs}, you have to redefine it like I redefined
7728: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20 pazsan 7729:
1.26 crook 7730: @cindex @code{inst-var} usage
7731: You will frequently use sequences of the form @code{this
7732: @emph{field}} (in the example above: @code{this
7733: circle-radius}). If you use the field only in this way, you can
7734: define it with @code{inst-var} and eliminate the
7735: @code{this} before the field name. E.g., the @code{circle}
7736: class above could also be defined with:
1.20 pazsan 7737:
1.26 crook 7738: @example
7739: graphical class
7740: cell% inst-var radius
1.20 pazsan 7741:
1.26 crook 7742: m: ( x y circle -- )
7743: radius @@ draw-circle ;m
7744: overrides draw
1.20 pazsan 7745:
1.26 crook 7746: m: ( n-radius circle -- )
7747: radius ! ;m
7748: overrides construct
1.12 anton 7749:
1.26 crook 7750: end-class circle
7751: @end example
1.12 anton 7752:
1.26 crook 7753: @code{radius} can only be used in @code{circle} and its
7754: descendent classes and inside @code{m:...;m}.
1.12 anton 7755:
1.26 crook 7756: @cindex @code{inst-value} usage
7757: You can also define fields with @code{inst-value}, which is
7758: to @code{inst-var} what @code{value} is to
7759: @code{variable}. You can change the value of such a field with
7760: @code{[to-inst]}. E.g., we could also define the class
7761: @code{circle} like this:
1.12 anton 7762:
1.26 crook 7763: @example
7764: graphical class
7765: inst-value radius
1.12 anton 7766:
1.26 crook 7767: m: ( x y circle -- )
7768: radius draw-circle ;m
7769: overrides draw
1.12 anton 7770:
1.26 crook 7771: m: ( n-radius circle -- )
7772: [to-inst] radius ;m
7773: overrides construct
1.21 crook 7774:
1.26 crook 7775: end-class circle
1.12 anton 7776: @end example
7777:
7778:
1.26 crook 7779: @node Classes and Scoping, Object Interfaces, Method conveniences, Objects
7780: @subsubsection Classes and Scoping
7781: @cindex classes and scoping
7782: @cindex scoping and classes
1.12 anton 7783:
1.26 crook 7784: Inheritance is frequent, unlike structure extension. This exacerbates
7785: the problem with the field name convention (@pxref{Structure Naming
7786: Convention}): One always has to remember in which class the field was
7787: originally defined; changing a part of the class structure would require
7788: changes for renaming in otherwise unaffected code.
1.12 anton 7789:
1.26 crook 7790: @cindex @code{inst-var} visibility
7791: @cindex @code{inst-value} visibility
7792: To solve this problem, I added a scoping mechanism (which was not in my
7793: original charter): A field defined with @code{inst-var} (or
7794: @code{inst-value}) is visible only in the class where it is defined and in
7795: the descendent classes of this class. Using such fields only makes
7796: sense in @code{m:}-defined methods in these classes anyway.
1.12 anton 7797:
1.26 crook 7798: This scoping mechanism allows us to use the unadorned field name,
7799: because name clashes with unrelated words become much less likely.
1.12 anton 7800:
1.26 crook 7801: @cindex @code{protected} discussion
7802: @cindex @code{private} discussion
7803: Once we have this mechanism, we can also use it for controlling the
7804: visibility of other words: All words defined after
7805: @code{protected} are visible only in the current class and its
7806: descendents. @code{public} restores the compilation
7807: (i.e. @code{current}) word list that was in effect before. If you
7808: have several @code{protected}s without an intervening
7809: @code{public} or @code{set-current}, @code{public}
7810: will restore the compilation word list in effect before the first of
7811: these @code{protected}s.
1.12 anton 7812:
1.26 crook 7813: @node Object Interfaces, Objects Implementation, Classes and Scoping, Objects
7814: @subsubsection Object Interfaces
7815: @cindex object interfaces
7816: @cindex interfaces for objects
1.12 anton 7817:
1.26 crook 7818: In this model you can only call selectors defined in the class of the
7819: receiving objects or in one of its ancestors. If you call a selector
7820: with a receiving object that is not in one of these classes, the
7821: result is undefined; if you are lucky, the program crashes
7822: immediately.
1.12 anton 7823:
1.26 crook 7824: @cindex selectors common to hardly-related classes
7825: Now consider the case when you want to have a selector (or several)
7826: available in two classes: You would have to add the selector to a
7827: common ancestor class, in the worst case to @code{object}. You
7828: may not want to do this, e.g., because someone else is responsible for
7829: this ancestor class.
1.12 anton 7830:
1.26 crook 7831: The solution for this problem is interfaces. An interface is a
7832: collection of selectors. If a class implements an interface, the
7833: selectors become available to the class and its descendents. A class
7834: can implement an unlimited number of interfaces. For the problem
7835: discussed above, we would define an interface for the selector(s), and
7836: both classes would implement the interface.
1.12 anton 7837:
1.26 crook 7838: As an example, consider an interface @code{storage} for
7839: writing objects to disk and getting them back, and a class
7840: @code{foo} that implements it. The code would look like this:
1.12 anton 7841:
1.26 crook 7842: @cindex @code{interface} usage
7843: @cindex @code{end-interface} usage
7844: @cindex @code{implementation} usage
7845: @example
7846: interface
7847: selector write ( file object -- )
7848: selector read1 ( file object -- )
7849: end-interface storage
1.12 anton 7850:
1.26 crook 7851: bar class
7852: storage implementation
1.12 anton 7853:
1.26 crook 7854: ... overrides write
7855: ... overrides read
7856: ...
7857: end-class foo
1.12 anton 7858: @end example
7859:
1.26 crook 7860: @noindent
1.29 crook 7861: (I would add a word @code{read} @i{( file -- object )} that uses
1.26 crook 7862: @code{read1} internally, but that's beyond the point illustrated
7863: here.)
1.12 anton 7864:
1.26 crook 7865: Note that you cannot use @code{protected} in an interface; and
7866: of course you cannot define fields.
1.12 anton 7867:
1.26 crook 7868: In the Neon model, all selectors are available for all classes;
7869: therefore it does not need interfaces. The price you pay in this model
7870: is slower late binding, and therefore, added complexity to avoid late
7871: binding.
1.12 anton 7872:
1.26 crook 7873: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
7874: @subsubsection @file{objects.fs} Implementation
7875: @cindex @file{objects.fs} implementation
1.12 anton 7876:
1.26 crook 7877: @cindex @code{object-map} discussion
7878: An object is a piece of memory, like one of the data structures
7879: described with @code{struct...end-struct}. It has a field
7880: @code{object-map} that points to the method map for the object's
7881: class.
1.12 anton 7882:
1.26 crook 7883: @cindex method map
7884: @cindex virtual function table
7885: The @emph{method map}@footnote{This is Self terminology; in C++
7886: terminology: virtual function table.} is an array that contains the
1.29 crook 7887: execution tokens (@i{xt}s) of the methods for the object's class. Each
1.26 crook 7888: selector contains an offset into a method map.
1.12 anton 7889:
1.26 crook 7890: @cindex @code{selector} implementation, class
7891: @code{selector} is a defining word that uses
7892: @code{CREATE} and @code{DOES>}. The body of the
7893: selector contains the offset; the @code{does>} action for a
7894: class selector is, basically:
1.21 crook 7895:
1.26 crook 7896: @example
7897: ( object addr ) @@ over object-map @@ + @@ execute
7898: @end example
1.12 anton 7899:
1.26 crook 7900: Since @code{object-map} is the first field of the object, it
7901: does not generate any code. As you can see, calling a selector has a
7902: small, constant cost.
1.12 anton 7903:
1.26 crook 7904: @cindex @code{current-interface} discussion
7905: @cindex class implementation and representation
7906: A class is basically a @code{struct} combined with a method
7907: map. During the class definition the alignment and size of the class
7908: are passed on the stack, just as with @code{struct}s, so
7909: @code{field} can also be used for defining class
7910: fields. However, passing more items on the stack would be
7911: inconvenient, so @code{class} builds a data structure in memory,
7912: which is accessed through the variable
7913: @code{current-interface}. After its definition is complete, the
7914: class is represented on the stack by a pointer (e.g., as parameter for
7915: a child class definition).
1.1 anton 7916:
1.26 crook 7917: A new class starts off with the alignment and size of its parent,
7918: and a copy of the parent's method map. Defining new fields extends the
7919: size and alignment; likewise, defining new selectors extends the
1.29 crook 7920: method map. @code{overrides} just stores a new @i{xt} in the method
1.26 crook 7921: map at the offset given by the selector.
1.20 pazsan 7922:
1.26 crook 7923: @cindex class binding, implementation
1.29 crook 7924: Class binding just gets the @i{xt} at the offset given by the selector
1.26 crook 7925: from the class's method map and @code{compile,}s (in the case of
7926: @code{[bind]}) it.
1.21 crook 7927:
1.26 crook 7928: @cindex @code{this} implementation
7929: @cindex @code{catch} and @code{this}
7930: @cindex @code{this} and @code{catch}
7931: I implemented @code{this} as a @code{value}. At the
7932: start of an @code{m:...;m} method the old @code{this} is
7933: stored to the return stack and restored at the end; and the object on
7934: the TOS is stored @code{TO this}. This technique has one
7935: disadvantage: If the user does not leave the method via
7936: @code{;m}, but via @code{throw} or @code{exit},
7937: @code{this} is not restored (and @code{exit} may
7938: crash). To deal with the @code{throw} problem, I have redefined
7939: @code{catch} to save and restore @code{this}; the same
7940: should be done with any word that can catch an exception. As for
7941: @code{exit}, I simply forbid it (as a replacement, there is
7942: @code{exitm}).
1.21 crook 7943:
1.26 crook 7944: @cindex @code{inst-var} implementation
7945: @code{inst-var} is just the same as @code{field}, with
7946: a different @code{DOES>} action:
7947: @example
7948: @@ this +
7949: @end example
7950: Similar for @code{inst-value}.
1.21 crook 7951:
1.26 crook 7952: @cindex class scoping implementation
7953: Each class also has a word list that contains the words defined with
7954: @code{inst-var} and @code{inst-value}, and its protected
7955: words. It also has a pointer to its parent. @code{class} pushes
7956: the word lists of the class and all its ancestors onto the search order stack,
7957: and @code{end-class} drops them.
1.21 crook 7958:
1.26 crook 7959: @cindex interface implementation
7960: An interface is like a class without fields, parent and protected
7961: words; i.e., it just has a method map. If a class implements an
7962: interface, its method map contains a pointer to the method map of the
7963: interface. The positive offsets in the map are reserved for class
7964: methods, therefore interface map pointers have negative
7965: offsets. Interfaces have offsets that are unique throughout the
7966: system, unlike class selectors, whose offsets are only unique for the
7967: classes where the selector is available (invokable).
1.21 crook 7968:
1.26 crook 7969: This structure means that interface selectors have to perform one
7970: indirection more than class selectors to find their method. Their body
7971: contains the interface map pointer offset in the class method map, and
7972: the method offset in the interface method map. The
7973: @code{does>} action for an interface selector is, basically:
1.21 crook 7974:
7975: @example
1.26 crook 7976: ( object selector-body )
7977: 2dup selector-interface @@ ( object selector-body object interface-offset )
7978: swap object-map @@ + @@ ( object selector-body map )
7979: swap selector-offset @@ + @@ execute
1.21 crook 7980: @end example
7981:
1.26 crook 7982: where @code{object-map} and @code{selector-offset} are
7983: first fields and generate no code.
7984:
7985: As a concrete example, consider the following code:
1.21 crook 7986:
1.26 crook 7987: @example
7988: interface
7989: selector if1sel1
7990: selector if1sel2
7991: end-interface if1
1.21 crook 7992:
1.26 crook 7993: object class
7994: if1 implementation
7995: selector cl1sel1
7996: cell% inst-var cl1iv1
1.21 crook 7997:
1.26 crook 7998: ' m1 overrides construct
7999: ' m2 overrides if1sel1
8000: ' m3 overrides if1sel2
8001: ' m4 overrides cl1sel2
8002: end-class cl1
1.21 crook 8003:
1.26 crook 8004: create obj1 object dict-new drop
8005: create obj2 cl1 dict-new drop
8006: @end example
1.21 crook 8007:
1.26 crook 8008: The data structure created by this code (including the data structure
8009: for @code{object}) is shown in the <a
8010: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.29 crook 8011: @comment TODO add this diagram..
1.21 crook 8012:
1.26 crook 8013: @node Objects Glossary, , Objects Implementation, Objects
8014: @subsubsection @file{objects.fs} Glossary
8015: @cindex @file{objects.fs} Glossary
1.21 crook 8016:
1.26 crook 8017: doc---objects-bind
8018: doc---objects-<bind>
8019: doc---objects-bind'
8020: doc---objects-[bind]
8021: doc---objects-class
8022: doc---objects-class->map
8023: doc---objects-class-inst-size
8024: doc---objects-class-override!
8025: doc---objects-construct
8026: doc---objects-current'
8027: doc---objects-[current]
8028: doc---objects-current-interface
8029: doc---objects-dict-new
8030: doc---objects-drop-order
8031: doc---objects-end-class
8032: doc---objects-end-class-noname
8033: doc---objects-end-interface
8034: doc---objects-end-interface-noname
8035: doc---objects-exitm
8036: doc---objects-heap-new
8037: doc---objects-implementation
8038: doc---objects-init-object
8039: doc---objects-inst-value
8040: doc---objects-inst-var
8041: doc---objects-interface
8042: doc---objects-;m
8043: doc---objects-m:
8044: doc---objects-method
8045: doc---objects-object
8046: doc---objects-overrides
8047: doc---objects-[parent]
8048: doc---objects-print
8049: doc---objects-protected
8050: doc---objects-public
8051: doc---objects-push-order
8052: doc---objects-selector
8053: doc---objects-this
8054: doc---objects-<to-inst>
8055: doc---objects-[to-inst]
8056: doc---objects-to-this
8057: doc---objects-xt-new
1.21 crook 8058:
1.26 crook 8059: @c -------------------------------------------------------------
8060: @node OOF, Mini-OOF, Objects, Object-oriented Forth
8061: @subsection The @file{oof.fs} model
8062: @cindex oof
8063: @cindex object-oriented programming
1.21 crook 8064:
1.26 crook 8065: @cindex @file{objects.fs}
8066: @cindex @file{oof.fs}
1.21 crook 8067:
1.26 crook 8068: This section describes the @file{oof.fs} package.
1.21 crook 8069:
1.26 crook 8070: The package described in this section has been used in bigFORTH since 1991, and
8071: used for two large applications: a chromatographic system used to
8072: create new medicaments, and a graphic user interface library (MINOS).
1.21 crook 8073:
1.26 crook 8074: You can find a description (in German) of @file{oof.fs} in @cite{Object
8075: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
8076: 10(2), 1994.
1.21 crook 8077:
1.26 crook 8078: @menu
8079: * Properties of the OOF model::
8080: * Basic OOF Usage::
8081: * The OOF base class::
8082: * Class Declaration::
8083: * Class Implementation::
8084: @end menu
1.21 crook 8085:
1.26 crook 8086: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
8087: @subsubsection Properties of the @file{oof.fs} model
8088: @cindex @file{oof.fs} properties
1.21 crook 8089:
1.26 crook 8090: @itemize @bullet
8091: @item
8092: This model combines object oriented programming with information
8093: hiding. It helps you writing large application, where scoping is
8094: necessary, because it provides class-oriented scoping.
1.21 crook 8095:
1.26 crook 8096: @item
8097: Named objects, object pointers, and object arrays can be created,
8098: selector invocation uses the ``object selector'' syntax. Selector invocation
8099: to objects and/or selectors on the stack is a bit less convenient, but
8100: possible.
1.21 crook 8101:
1.26 crook 8102: @item
8103: Selector invocation and instance variable usage of the active object is
8104: straightforward, since both make use of the active object.
1.21 crook 8105:
1.26 crook 8106: @item
8107: Late binding is efficient and easy to use.
1.21 crook 8108:
1.26 crook 8109: @item
8110: State-smart objects parse selectors. However, extensibility is provided
8111: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21 crook 8112:
8113: @item
1.26 crook 8114: An implementation in ANS Forth is available.
8115:
1.21 crook 8116: @end itemize
8117:
8118:
1.26 crook 8119: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
8120: @subsubsection Basic @file{oof.fs} Usage
8121: @cindex @file{oof.fs} usage
8122:
8123: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21 crook 8124:
1.26 crook 8125: You can define a class for graphical objects like this:
1.21 crook 8126:
1.26 crook 8127: @cindex @code{class} usage
8128: @cindex @code{class;} usage
8129: @cindex @code{method} usage
8130: @example
8131: object class graphical \ "object" is the parent class
8132: method draw ( x y graphical -- )
8133: class;
8134: @end example
1.21 crook 8135:
1.26 crook 8136: This code defines a class @code{graphical} with an
8137: operation @code{draw}. We can perform the operation
8138: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 8139:
1.26 crook 8140: @example
8141: 100 100 t-rex draw
8142: @end example
1.21 crook 8143:
1.26 crook 8144: @noindent
8145: where @code{t-rex} is an object or object pointer, created with e.g.
8146: @code{graphical : t-rex}.
1.21 crook 8147:
1.26 crook 8148: @cindex abstract class
8149: How do we create a graphical object? With the present definitions,
8150: we cannot create a useful graphical object. The class
8151: @code{graphical} describes graphical objects in general, but not
8152: any concrete graphical object type (C++ users would call it an
8153: @emph{abstract class}); e.g., there is no method for the selector
8154: @code{draw} in the class @code{graphical}.
1.21 crook 8155:
1.26 crook 8156: For concrete graphical objects, we define child classes of the
8157: class @code{graphical}, e.g.:
1.21 crook 8158:
8159: @example
1.26 crook 8160: graphical class circle \ "graphical" is the parent class
8161: cell var circle-radius
8162: how:
8163: : draw ( x y -- )
8164: circle-radius @@ draw-circle ;
8165:
8166: : init ( n-radius -- (
8167: circle-radius ! ;
8168: class;
8169: @end example
8170:
8171: Here we define a class @code{circle} as a child of @code{graphical},
8172: with a field @code{circle-radius}; it defines new methods for the
8173: selectors @code{draw} and @code{init} (@code{init} is defined in
8174: @code{object}, the parent class of @code{graphical}).
1.21 crook 8175:
1.26 crook 8176: Now we can create a circle in the dictionary with:
1.21 crook 8177:
1.26 crook 8178: @example
8179: 50 circle : my-circle
1.21 crook 8180: @end example
8181:
1.26 crook 8182: @noindent
8183: @code{:} invokes @code{init}, thus initializing the field
8184: @code{circle-radius} with 50. We can draw this new circle at (100,100)
8185: with:
1.21 crook 8186:
8187: @example
1.26 crook 8188: 100 100 my-circle draw
1.21 crook 8189: @end example
8190:
1.26 crook 8191: @cindex selector invocation, restrictions
8192: @cindex class definition, restrictions
8193: Note: You can only invoke a selector if the receiving object belongs to
8194: the class where the selector was defined or one of its descendents;
8195: e.g., you can invoke @code{draw} only for objects belonging to
8196: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
8197: mechanism will check if you try to invoke a selector that is not
8198: defined in this class hierarchy, so you'll get an error at compilation
8199: time.
8200:
8201:
8202: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
8203: @subsubsection The @file{oof.fs} base class
8204: @cindex @file{oof.fs} base class
8205:
8206: When you define a class, you have to specify a parent class. So how do
8207: you start defining classes? There is one class available from the start:
8208: @code{object}. You have to use it as ancestor for all classes. It is the
8209: only class that has no parent. Classes are also objects, except that
8210: they don't have instance variables; class manipulation such as
8211: inheritance or changing definitions of a class is handled through
8212: selectors of the class @code{object}.
8213:
8214: @code{object} provides a number of selectors:
8215:
1.21 crook 8216: @itemize @bullet
8217: @item
1.26 crook 8218: @code{class} for subclassing, @code{definitions} to add definitions
8219: later on, and @code{class?} to get type informations (is the class a
8220: subclass of the class passed on the stack?).
8221: doc---object-class
8222: doc---object-definitions
8223: doc---object-class?
8224:
1.21 crook 8225: @item
1.26 crook 8226: @code{init} and @code{dispose} as constructor and destructor of the
8227: object. @code{init} is invocated after the object's memory is allocated,
8228: while @code{dispose} also handles deallocation. Thus if you redefine
8229: @code{dispose}, you have to call the parent's dispose with @code{super
8230: dispose}, too.
8231: doc---object-init
8232: doc---object-dispose
8233:
1.21 crook 8234: @item
1.26 crook 8235: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
8236: @code{[]} to create named and unnamed objects and object arrays or
8237: object pointers.
8238: doc---object-new
8239: doc---object-new[]
8240: doc---object-:
8241: doc---object-ptr
8242: doc---object-asptr
8243: doc---object-[]
1.21 crook 8244:
1.26 crook 8245: @item
8246: @code{::} and @code{super} for explicit scoping. You should use explicit
8247: scoping only for super classes or classes with the same set of instance
8248: variables. Explicitly-scoped selectors use early binding.
8249: doc---object-::
8250: doc---object-super
1.21 crook 8251:
1.26 crook 8252: @item
8253: @code{self} to get the address of the object
8254: doc---object-self
1.21 crook 8255:
8256: @item
1.26 crook 8257: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
8258: pointers and instance defers.
8259: doc---object-bind
8260: doc---object-bound
8261: doc---object-link
8262: doc---object-is
8263:
1.21 crook 8264: @item
1.26 crook 8265: @code{'} to obtain selector tokens, @code{send} to invocate selectors
8266: form the stack, and @code{postpone} to generate selector invocation code.
8267: doc---object-'
8268: doc---object-postpone
8269:
1.21 crook 8270: @item
1.26 crook 8271: @code{with} and @code{endwith} to select the active object from the
8272: stack, and enable its scope. Using @code{with} and @code{endwith}
8273: also allows you to create code using selector @code{postpone} without being
8274: trapped by the state-smart objects.
8275: doc---object-with
8276: doc---object-endwith
8277:
1.21 crook 8278: @end itemize
8279:
1.26 crook 8280: @node Class Declaration, Class Implementation, The OOF base class, OOF
8281: @subsubsection Class Declaration
8282: @cindex class declaration
8283:
8284: @itemize @bullet
8285: @item
8286: Instance variables
8287: doc---oof-var
1.21 crook 8288:
1.26 crook 8289: @item
8290: Object pointers
8291: doc---oof-ptr
8292: doc---oof-asptr
1.21 crook 8293:
1.26 crook 8294: @item
8295: Instance defers
8296: doc---oof-defer
1.21 crook 8297:
1.26 crook 8298: @item
8299: Method selectors
8300: doc---oof-early
8301: doc---oof-method
1.21 crook 8302:
1.26 crook 8303: @item
8304: Class-wide variables
8305: doc---oof-static
1.21 crook 8306:
1.26 crook 8307: @item
8308: End declaration
8309: doc---oof-how:
8310: doc---oof-class;
1.21 crook 8311:
1.26 crook 8312: @end itemize
1.21 crook 8313:
1.26 crook 8314: @c -------------------------------------------------------------
8315: @node Class Implementation, , Class Declaration, OOF
8316: @subsubsection Class Implementation
8317: @cindex class implementation
1.21 crook 8318:
1.26 crook 8319: @c -------------------------------------------------------------
8320: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
8321: @subsection The @file{mini-oof.fs} model
8322: @cindex mini-oof
1.1 anton 8323:
1.26 crook 8324: Gforth's third object oriented Forth package is a 12-liner. It uses a
8325: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
8326: and reduces to the bare minimum of features. This is based on a posting
8327: of Bernd Paysan in comp.arch.
1.1 anton 8328:
8329: @menu
1.26 crook 8330: * Basic Mini-OOF Usage::
8331: * Mini-OOF Example::
8332: * Mini-OOF Implementation::
1.1 anton 8333: @end menu
8334:
1.26 crook 8335: @c -------------------------------------------------------------
8336: @node Basic Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
8337: @subsubsection Basic @file{mini-oof.fs} Usage
8338: @cindex mini-oof usage
1.1 anton 8339:
1.28 crook 8340: There is a base class (@code{class}, which allocates one cell for the
8341: object pointer) plus seven other words: to define a method, a variable,
8342: a class; to end a class, to resolve binding, to allocate an object and
8343: to compile a class method.
1.26 crook 8344: @comment TODO better description of the last one
1.1 anton 8345:
1.26 crook 8346: doc-object
8347: doc-method
8348: doc-var
8349: doc-class
8350: doc-end-class
8351: doc-defines
8352: doc-new
8353: doc-::
1.1 anton 8354:
1.21 crook 8355:
1.26 crook 8356: @c -------------------------------------------------------------
8357: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
8358: @subsubsection Mini-OOF Example
8359: @cindex mini-oof example
1.21 crook 8360:
1.26 crook 8361: A short example shows how to use this package. This example, in slightly
8362: extended form, is supplied as @file{moof-exm.fs}
1.29 crook 8363: @comment TODO could flesh this out with some comments from the Forthwrite article
1.21 crook 8364:
1.26 crook 8365: @example
8366: object class
8367: method init
8368: method draw
8369: end-class graphical
8370: @end example
1.21 crook 8371:
1.26 crook 8372: This code defines a class @code{graphical} with an
8373: operation @code{draw}. We can perform the operation
8374: @code{draw} on any @code{graphical} object, e.g.:
1.1 anton 8375:
1.26 crook 8376: @example
8377: 100 100 t-rex draw
8378: @end example
1.1 anton 8379:
1.26 crook 8380: where @code{t-rex} is an object or object pointer, created with e.g.
8381: @code{graphical new Constant t-rex}.
1.1 anton 8382:
1.26 crook 8383: For concrete graphical objects, we define child classes of the
8384: class @code{graphical}, e.g.:
1.21 crook 8385:
8386: @example
1.26 crook 8387: graphical class
8388: cell var circle-radius
8389: end-class circle \ "graphical" is the parent class
1.21 crook 8390:
1.26 crook 8391: :noname ( x y -- )
8392: circle-radius @@ draw-circle ; circle defines draw
8393: :noname ( r -- )
8394: circle-radius ! ; circle defines init
1.21 crook 8395: @end example
8396:
1.26 crook 8397: There is no implicit init method, so we have to define one. The creation
8398: code of the object now has to call init explicitely.
1.21 crook 8399:
1.26 crook 8400: @example
8401: circle new Constant my-circle
8402: 50 my-circle init
8403: @end example
1.21 crook 8404:
1.26 crook 8405: It is also possible to add a function to create named objects with
8406: automatic call of @code{init}, given that all objects have @code{init}
8407: on the same place:
1.1 anton 8408:
8409: @example
1.26 crook 8410: : new: ( .. o "name" -- )
8411: new dup Constant init ;
8412: 80 circle new: large-circle
1.1 anton 8413: @end example
8414:
1.26 crook 8415: We can draw this new circle at (100,100) with:
1.1 anton 8416:
8417: @example
1.26 crook 8418: 100 100 my-circle draw
1.1 anton 8419: @end example
8420:
1.26 crook 8421: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
8422: @subsubsection @file{mini-oof.fs} Implementation
1.1 anton 8423:
1.26 crook 8424: Object-oriented systems with late binding typically use a
8425: ``vtable''-approach: the first variable in each object is a pointer to a
8426: table, which contains the methods as function pointers. The vtable
8427: may also contain other information.
1.1 anton 8428:
1.26 crook 8429: So first, let's declare methods:
1.1 anton 8430:
1.26 crook 8431: @example
8432: : method ( m v -- m' v ) Create over , swap cell+ swap
8433: DOES> ( ... o -- ... ) @ over @ + @ execute ;
8434: @end example
1.1 anton 8435:
1.26 crook 8436: During method declaration, the number of methods and instance
8437: variables is on the stack (in address units). @code{method} creates
8438: one method and increments the method number. To execute a method, it
8439: takes the object, fetches the vtable pointer, adds the offset, and
1.29 crook 8440: executes the @i{xt} stored there. Each method takes the object it is
1.26 crook 8441: invoked from as top of stack parameter. The method itself should
8442: consume that object.
1.1 anton 8443:
1.26 crook 8444: Now, we also have to declare instance variables
1.21 crook 8445:
1.26 crook 8446: @example
8447: : var ( m v size -- m v' ) Create over , +
8448: DOES> ( o -- addr ) @ + ;
8449: @end example
1.21 crook 8450:
1.26 crook 8451: As before, a word is created with the current offset. Instance
8452: variables can have different sizes (cells, floats, doubles, chars), so
8453: all we do is take the size and add it to the offset. If your machine
8454: has alignment restrictions, put the proper @code{aligned} or
8455: @code{faligned} before the variable, to adjust the variable
8456: offset. That's why it is on the top of stack.
1.2 jwilke 8457:
1.26 crook 8458: We need a starting point (the base object) and some syntactic sugar:
1.21 crook 8459:
1.26 crook 8460: @example
8461: Create object 1 cells , 2 cells ,
8462: : class ( class -- class methods vars ) dup 2@ ;
8463: @end example
1.21 crook 8464:
1.26 crook 8465: For inheritance, the vtable of the parent object has to be
8466: copied when a new, derived class is declared. This gives all the
8467: methods of the parent class, which can be overridden, though.
1.21 crook 8468:
1.2 jwilke 8469: @example
1.26 crook 8470: : end-class ( class methods vars -- )
8471: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
8472: cell+ dup cell+ r> rot @ 2 cells /string move ;
8473: @end example
8474:
8475: The first line creates the vtable, initialized with
8476: @code{noop}s. The second line is the inheritance mechanism, it
8477: copies the xts from the parent vtable.
1.2 jwilke 8478:
1.26 crook 8479: We still have no way to define new methods, let's do that now:
1.2 jwilke 8480:
1.26 crook 8481: @example
8482: : defines ( xt class -- ) ' >body @ + ! ;
1.2 jwilke 8483: @end example
8484:
1.26 crook 8485: To allocate a new object, we need a word, too:
1.2 jwilke 8486:
1.26 crook 8487: @example
8488: : new ( class -- o ) here over @ allot swap over ! ;
8489: @end example
1.2 jwilke 8490:
1.26 crook 8491: Sometimes derived classes want to access the method of the
8492: parent object. There are two ways to achieve this with Mini-OOF:
8493: first, you could use named words, and second, you could look up the
8494: vtable of the parent object.
1.2 jwilke 8495:
1.26 crook 8496: @example
8497: : :: ( class "name" -- ) ' >body @ + @ compile, ;
8498: @end example
1.2 jwilke 8499:
8500:
1.26 crook 8501: Nothing can be more confusing than a good example, so here is
8502: one. First let's declare a text object (called
8503: @code{button}), that stores text and position:
1.2 jwilke 8504:
1.26 crook 8505: @example
8506: object class
8507: cell var text
8508: cell var len
8509: cell var x
8510: cell var y
8511: method init
8512: method draw
8513: end-class button
8514: @end example
1.2 jwilke 8515:
1.26 crook 8516: @noindent
8517: Now, implement the two methods, @code{draw} and @code{init}:
1.2 jwilke 8518:
1.26 crook 8519: @example
8520: :noname ( o -- )
8521: >r r@ x @ r@ y @ at-xy r@ text @ r> len @ type ;
8522: button defines draw
8523: :noname ( addr u o -- )
8524: >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
8525: button defines init
8526: @end example
1.2 jwilke 8527:
1.26 crook 8528: @noindent
8529: To demonstrate inheritance, we define a class @code{bold-button}, with no
8530: new data and no new methods:
1.2 jwilke 8531:
1.26 crook 8532: @example
8533: button class
8534: end-class bold-button
1.1 anton 8535:
1.26 crook 8536: : bold 27 emit ." [1m" ;
8537: : normal 27 emit ." [0m" ;
8538: @end example
1.1 anton 8539:
1.26 crook 8540: @noindent
8541: The class @code{bold-button} has a different draw method to
8542: @code{button}, but the new method is defined in terms of the draw method
8543: for @code{button}:
1.1 anton 8544:
1.26 crook 8545: @example
8546: :noname bold [ button :: draw ] normal ; bold-button defines draw
8547: @end example
1.1 anton 8548:
1.26 crook 8549: @noindent
8550: Finally, create two objects and apply methods:
1.1 anton 8551:
1.26 crook 8552: @example
8553: button new Constant foo
8554: s" thin foo" foo init
8555: page
8556: foo draw
8557: bold-button new Constant bar
8558: s" fat bar" bar init
8559: 1 bar y !
8560: bar draw
8561: @end example
1.1 anton 8562:
8563:
1.26 crook 8564: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
8565: @subsubsection Comparison with other object models
8566: @cindex comparison of object models
8567: @cindex object models, comparison
1.1 anton 8568:
1.26 crook 8569: Many object-oriented Forth extensions have been proposed (@cite{A survey
8570: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
8571: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
8572: relation of the object models described here to two well-known and two
8573: closely-related (by the use of method maps) models.
1.1 anton 8574:
1.26 crook 8575: @cindex Neon model
8576: The most popular model currently seems to be the Neon model (see
8577: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
8578: 1997) by Andrew McKewan) but this model has a number of limitations
8579: @footnote{A longer version of this critique can be
8580: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
8581: Dimensions, May 1997) by Anton Ertl.}:
1.1 anton 8582:
1.26 crook 8583: @itemize @bullet
8584: @item
8585: It uses a @code{@emph{selector
8586: object}} syntax, which makes it unnatural to pass objects on the
8587: stack.
1.1 anton 8588:
1.26 crook 8589: @item
8590: It requires that the selector parses the input stream (at
8591: compile time); this leads to reduced extensibility and to bugs that are+
8592: hard to find.
1.1 anton 8593:
1.26 crook 8594: @item
8595: It allows using every selector to every object;
8596: this eliminates the need for classes, but makes it harder to create
8597: efficient implementations.
8598: @end itemize
1.1 anton 8599:
1.26 crook 8600: @cindex Pountain's object-oriented model
8601: Another well-known publication is @cite{Object-Oriented Forth} (Academic
8602: Press, London, 1987) by Dick Pountain. However, it is not really about
8603: object-oriented programming, because it hardly deals with late
8604: binding. Instead, it focuses on features like information hiding and
8605: overloading that are characteristic of modular languages like Ada (83).
1.1 anton 8606:
1.26 crook 8607: @cindex Zsoter's object-oriented model
8608: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1) 1996, pages 31-35)
8609: Andras Zsoter describes a model that makes heavy use of an active object
8610: (like @code{this} in @file{objects.fs}): The active object is not only
8611: used for accessing all fields, but also specifies the receiving object
8612: of every selector invocation; you have to change the active object
8613: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
8614: changes more or less implicitly at @code{m: ... ;m}. Such a change at
8615: the method entry point is unnecessary with the Zsoter's model, because
8616: the receiving object is the active object already. On the other hand, the explicit
8617: change is absolutely necessary in that model, because otherwise no one
8618: could ever change the active object. An ANS Forth implementation of this
8619: model is available at @url{http://www.forth.org/fig/oopf.html}.
1.1 anton 8620:
1.26 crook 8621: @cindex @file{oof.fs}, differences to other models
8622: The @file{oof.fs} model combines information hiding and overloading
8623: resolution (by keeping names in various word lists) with object-oriented
8624: programming. It sets the active object implicitly on method entry, but
8625: also allows explicit changing (with @code{>o...o>} or with
8626: @code{with...endwith}). It uses parsing and state-smart objects and
8627: classes for resolving overloading and for early binding: the object or
8628: class parses the selector and determines the method from this. If the
8629: selector is not parsed by an object or class, it performs a call to the
8630: selector for the active object (late binding), like Zsoter's model.
8631: Fields are always accessed through the active object. The big
8632: disadvantage of this model is the parsing and the state-smartness, which
8633: reduces extensibility and increases the opportunities for subtle bugs;
8634: essentially, you are only safe if you never tick or @code{postpone} an
8635: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1 anton 8636:
1.26 crook 8637: @cindex @file{mini-oof.fs}, differences to other models
8638: The @file{mini-oof.fs} model is quite similar to a very stripped-down version of
8639: the @file{objects.fs} model, but syntactically it is a mixture of the @file{objects.fs} and
8640: @file{oof.fs} models.
1.1 anton 8641:
1.26 crook 8642: @c -------------------------------------------------------------
8643: @node Passing Commands to the OS, Miscellaneous Words, Object-oriented Forth, Words
1.21 crook 8644: @section Passing Commands to the Operating System
8645: @cindex operating system - passing commands
8646: @cindex shell commands
8647:
8648: Gforth allows you to pass an arbitrary string to the host operating
8649: system shell (if such a thing exists) for execution.
8650:
8651: doc-sh
8652: doc-system
8653: doc-$?
1.23 crook 8654: doc-getenv
1.21 crook 8655:
1.26 crook 8656: @c -------------------------------------------------------------
1.21 crook 8657: @node Miscellaneous Words, , Passing Commands to the OS, Words
8658: @section Miscellaneous Words
8659: @cindex miscellaneous words
8660:
1.29 crook 8661: @comment TODO find homes for these
8662:
1.26 crook 8663: These section lists the ANS Forth words that are not documented
1.21 crook 8664: elsewhere in this manual. Ultimately, they all need proper homes.
8665:
8666: doc-ms
8667: doc-time&date
1.27 crook 8668:
1.21 crook 8669: doc-[compile]
8670:
1.26 crook 8671: The following ANS Forth words are not currently supported by Gforth
1.27 crook 8672: (@pxref{ANS conformance}):
1.21 crook 8673:
8674: @code{EDITOR}
8675: @code{EKEY}
8676: @code{EKEY>CHAR}
8677: @code{EKEY?}
8678: @code{EMIT?}
8679: @code{FORGET}
8680:
1.24 anton 8681: @c ******************************************************************
8682: @node Error messages, Tools, Words, Top
8683: @chapter Error messages
8684: @cindex error messages
8685: @cindex backtrace
8686:
8687: A typical Gforth error message looks like this:
8688:
8689: @example
8690: in file included from :-1
8691: in file included from ./yyy.fs:1
8692: ./xxx.fs:4: Invalid memory address
8693: bar
8694: ^^^
1.25 anton 8695: $400E664C @@
8696: $400E6664 foo
1.24 anton 8697: @end example
8698:
8699: The message identifying the error is @code{Invalid memory address}. The
8700: error happened when text-interpreting line 4 of the file
8701: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
8702: word on the line where the error happened, is pointed out (with
8703: @code{^^^}).
8704:
8705: The file containing the error was included in line 1 of @file{./yyy.fs},
8706: and @file{yyy.fs} was included from a non-file (in this case, by giving
8707: @file{yyy.fs} as command-line parameter to Gforth).
8708:
8709: At the end of the error message you find a return stack dump that can be
8710: interpreted as a backtrace (possibly empty). On top you find the top of
8711: the return stack when the @code{throw} happened, and at the bottom you
8712: find the return stack entry just above the return stack of the topmost
8713: text interpreter.
8714:
8715: To the right of most return stack entries you see a guess for the word
8716: that pushed that return stack entry as its return address. This gives a
8717: backtrace. In our case we see that @code{bar} called @code{foo}, and
8718: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
8719: address} exception).
8720:
8721: Note that the backtrace is not perfect: We don't know which return stack
8722: entries are return addresses (so we may get false positives); and in
8723: some cases (e.g., for @code{abort"}) we cannot determine from the return
8724: address the word that pushed the return address, so for some return
8725: addresses you see no names in the return stack dump.
1.25 anton 8726:
8727: @cindex @code{catch} and backtraces
8728: The return stack dump represents the return stack at the time when a
8729: specific @code{throw} was executed. In programs that make use of
8730: @code{catch}, it is not necessarily clear which @code{throw} should be
8731: used for the return stack dump (e.g., consider one @code{throw} that
8732: indicates an error, which is caught, and during recovery another error
8733: happens; which @code{throw} should be used for the stack dump). Gforth
8734: presents the return stack dump for the first @code{throw} after the last
8735: executed (not returned-to) @code{catch}; this works well in the usual
8736: case.
8737:
8738: @cindex @code{gforth-fast} and backtraces
8739: @cindex @code{gforth-fast}, difference from @code{gforth}
8740: @cindex backtraces with @code{gforth-fast}
8741: @cindex return stack dump with @code{gforth-fast}
8742: @code{gforth} is able to do a return stack dump for throws generated
8743: from primitives (e.g., invalid memory address, stack empty etc.);
8744: @code{gforth-fast} is only able to do a return stack dump from a
8745: directly called @code{throw} (including @code{abort} etc.). This is the
1.30 anton 8746: only difference (apart from a speed factor of between 1.15 (K6-2) and
8747: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}. Given an
8748: exception caused by a primitive in @code{gforth-fast}, you will
8749: typically see no return stack dump at all; however, if the exception is
8750: caught by @code{catch} (e.g., for restoring some state), and then
8751: @code{throw}n again, the return stack dump will be for the first such
8752: @code{throw}.
1.2 jwilke 8753:
1.5 anton 8754: @c ******************************************************************
1.24 anton 8755: @node Tools, ANS conformance, Error messages, Top
1.1 anton 8756: @chapter Tools
8757:
8758: @menu
8759: * ANS Report:: Report the words used, sorted by wordset.
8760: @end menu
8761:
8762: See also @ref{Emacs and Gforth}.
8763:
8764: @node ANS Report, , Tools, Tools
8765: @section @file{ans-report.fs}: Report the words used, sorted by wordset
8766: @cindex @file{ans-report.fs}
8767: @cindex report the words used in your program
8768: @cindex words used in your program
8769:
8770: If you want to label a Forth program as ANS Forth Program, you must
8771: document which wordsets the program uses; for extension wordsets, it is
8772: helpful to list the words the program requires from these wordsets
8773: (because Forth systems are allowed to provide only some words of them).
8774:
8775: The @file{ans-report.fs} tool makes it easy for you to determine which
8776: words from which wordset and which non-ANS words your application
8777: uses. You simply have to include @file{ans-report.fs} before loading the
8778: program you want to check. After loading your program, you can get the
8779: report with @code{print-ans-report}. A typical use is to run this as
8780: batch job like this:
8781: @example
8782: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
8783: @end example
8784:
8785: The output looks like this (for @file{compat/control.fs}):
8786: @example
8787: The program uses the following words
8788: from CORE :
8789: : POSTPONE THEN ; immediate ?dup IF 0=
8790: from BLOCK-EXT :
8791: \
8792: from FILE :
8793: (
8794: @end example
8795:
8796: @subsection Caveats
8797:
8798: Note that @file{ans-report.fs} just checks which words are used, not whether
8799: they are used in an ANS Forth conforming way!
8800:
8801: Some words are defined in several wordsets in the
8802: standard. @file{ans-report.fs} reports them for only one of the
8803: wordsets, and not necessarily the one you expect. It depends on usage
8804: which wordset is the right one to specify. E.g., if you only use the
8805: compilation semantics of @code{S"}, it is a Core word; if you also use
8806: its interpretation semantics, it is a File word.
8807:
8808: @c ******************************************************************
8809: @node ANS conformance, Model, Tools, Top
8810: @chapter ANS conformance
8811: @cindex ANS conformance of Gforth
8812:
8813: To the best of our knowledge, Gforth is an
8814:
8815: ANS Forth System
8816: @itemize @bullet
8817: @item providing the Core Extensions word set
8818: @item providing the Block word set
8819: @item providing the Block Extensions word set
8820: @item providing the Double-Number word set
8821: @item providing the Double-Number Extensions word set
8822: @item providing the Exception word set
8823: @item providing the Exception Extensions word set
8824: @item providing the Facility word set
8825: @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
8826: @item providing the File Access word set
8827: @item providing the File Access Extensions word set
8828: @item providing the Floating-Point word set
8829: @item providing the Floating-Point Extensions word set
8830: @item providing the Locals word set
8831: @item providing the Locals Extensions word set
8832: @item providing the Memory-Allocation word set
8833: @item providing the Memory-Allocation Extensions word set (that one's easy)
8834: @item providing the Programming-Tools word set
8835: @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
8836: @item providing the Search-Order word set
8837: @item providing the Search-Order Extensions word set
8838: @item providing the String word set
8839: @item providing the String Extensions word set (another easy one)
8840: @end itemize
8841:
8842: @cindex system documentation
8843: In addition, ANS Forth systems are required to document certain
8844: implementation choices. This chapter tries to meet these
8845: requirements. In many cases it gives a way to ask the system for the
8846: information instead of providing the information directly, in
8847: particular, if the information depends on the processor, the operating
8848: system or the installation options chosen, or if they are likely to
8849: change during the maintenance of Gforth.
8850:
8851: @comment The framework for the rest has been taken from pfe.
8852:
8853: @menu
8854: * The Core Words::
8855: * The optional Block word set::
8856: * The optional Double Number word set::
8857: * The optional Exception word set::
8858: * The optional Facility word set::
8859: * The optional File-Access word set::
8860: * The optional Floating-Point word set::
8861: * The optional Locals word set::
8862: * The optional Memory-Allocation word set::
8863: * The optional Programming-Tools word set::
8864: * The optional Search-Order word set::
8865: @end menu
8866:
8867:
8868: @c =====================================================================
8869: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
8870: @comment node-name, next, previous, up
8871: @section The Core Words
8872: @c =====================================================================
8873: @cindex core words, system documentation
8874: @cindex system documentation, core words
8875:
8876: @menu
8877: * core-idef:: Implementation Defined Options
8878: * core-ambcond:: Ambiguous Conditions
8879: * core-other:: Other System Documentation
8880: @end menu
8881:
8882: @c ---------------------------------------------------------------------
8883: @node core-idef, core-ambcond, The Core Words, The Core Words
8884: @subsection Implementation Defined Options
8885: @c ---------------------------------------------------------------------
8886: @cindex core words, implementation-defined options
8887: @cindex implementation-defined options, core words
8888:
8889:
8890: @table @i
8891: @item (Cell) aligned addresses:
8892: @cindex cell-aligned addresses
8893: @cindex aligned addresses
8894: processor-dependent. Gforth's alignment words perform natural alignment
8895: (e.g., an address aligned for a datum of size 8 is divisible by
8896: 8). Unaligned accesses usually result in a @code{-23 THROW}.
8897:
8898: @item @code{EMIT} and non-graphic characters:
8899: @cindex @code{EMIT} and non-graphic characters
8900: @cindex non-graphic characters and @code{EMIT}
8901: The character is output using the C library function (actually, macro)
8902: @code{putc}.
8903:
8904: @item character editing of @code{ACCEPT} and @code{EXPECT}:
8905: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
8906: @cindex editing in @code{ACCEPT} and @code{EXPECT}
8907: @cindex @code{ACCEPT}, editing
8908: @cindex @code{EXPECT}, editing
8909: This is modeled on the GNU readline library (@pxref{Readline
8910: Interaction, , Command Line Editing, readline, The GNU Readline
8911: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
8912: producing a full word completion every time you type it (instead of
1.28 crook 8913: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 8914:
8915: @item character set:
8916: @cindex character set
8917: The character set of your computer and display device. Gforth is
8918: 8-bit-clean (but some other component in your system may make trouble).
8919:
8920: @item Character-aligned address requirements:
8921: @cindex character-aligned address requirements
8922: installation-dependent. Currently a character is represented by a C
8923: @code{unsigned char}; in the future we might switch to @code{wchar_t}
8924: (Comments on that requested).
8925:
8926: @item character-set extensions and matching of names:
8927: @cindex character-set extensions and matching of names
1.26 crook 8928: @cindex case-sensitivity for name lookup
8929: @cindex name lookup, case-sensitivity
8930: @cindex locale and case-sensitivity
1.21 crook 8931: Any character except the ASCII NUL character can be used in a
1.1 anton 8932: name. Matching is case-insensitive (except in @code{TABLE}s). The
8933: matching is performed using the C function @code{strncasecmp}, whose
8934: function is probably influenced by the locale. E.g., the @code{C} locale
8935: does not know about accents and umlauts, so they are matched
8936: case-sensitively in that locale. For portability reasons it is best to
8937: write programs such that they work in the @code{C} locale. Then one can
8938: use libraries written by a Polish programmer (who might use words
8939: containing ISO Latin-2 encoded characters) and by a French programmer
8940: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
8941: funny results for some of the words (which ones, depends on the font you
8942: are using)). Also, the locale you prefer may not be available in other
8943: operating systems. Hopefully, Unicode will solve these problems one day.
8944:
8945: @item conditions under which control characters match a space delimiter:
8946: @cindex space delimiters
8947: @cindex control characters as delimiters
8948: If @code{WORD} is called with the space character as a delimiter, all
8949: white-space characters (as identified by the C macro @code{isspace()})
8950: are delimiters. @code{PARSE}, on the other hand, treats space like other
8951: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
8952: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
8953: interpreter (aka text interpreter) by default, treats all white-space
8954: characters as delimiters.
8955:
1.26 crook 8956: @item format of the control-flow stack:
8957: @cindex control-flow stack, format
8958: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 8959: stack item in cells is given by the constant @code{cs-item-size}. At the
8960: time of this writing, an item consists of a (pointer to a) locals list
8961: (third), an address in the code (second), and a tag for identifying the
8962: item (TOS). The following tags are used: @code{defstart},
8963: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
8964: @code{scopestart}.
8965:
8966: @item conversion of digits > 35
8967: @cindex digits > 35
8968: The characters @code{[\]^_'} are the digits with the decimal value
8969: 36@minus{}41. There is no way to input many of the larger digits.
8970:
8971: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
8972: @cindex @code{EXPECT}, display after end of input
8973: @cindex @code{ACCEPT}, display after end of input
8974: The cursor is moved to the end of the entered string. If the input is
8975: terminated using the @kbd{Return} key, a space is typed.
8976:
8977: @item exception abort sequence of @code{ABORT"}:
8978: @cindex exception abort sequence of @code{ABORT"}
8979: @cindex @code{ABORT"}, exception abort sequence
8980: The error string is stored into the variable @code{"error} and a
8981: @code{-2 throw} is performed.
8982:
8983: @item input line terminator:
8984: @cindex input line terminator
8985: @cindex line terminator on input
1.26 crook 8986: @cindex newline character on input
1.1 anton 8987: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
8988: lines. One of these characters is typically produced when you type the
8989: @kbd{Enter} or @kbd{Return} key.
8990:
8991: @item maximum size of a counted string:
8992: @cindex maximum size of a counted string
8993: @cindex counted string, maximum size
8994: @code{s" /counted-string" environment? drop .}. Currently 255 characters
8995: on all ports, but this may change.
8996:
8997: @item maximum size of a parsed string:
8998: @cindex maximum size of a parsed string
8999: @cindex parsed string, maximum size
9000: Given by the constant @code{/line}. Currently 255 characters.
9001:
9002: @item maximum size of a definition name, in characters:
9003: @cindex maximum size of a definition name, in characters
9004: @cindex name, maximum length
9005: 31
9006:
9007: @item maximum string length for @code{ENVIRONMENT?}, in characters:
9008: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
9009: @cindex @code{ENVIRONMENT?} string length, maximum
9010: 31
9011:
9012: @item method of selecting the user input device:
9013: @cindex user input device, method of selecting
9014: The user input device is the standard input. There is currently no way to
9015: change it from within Gforth. However, the input can typically be
9016: redirected in the command line that starts Gforth.
9017:
9018: @item method of selecting the user output device:
9019: @cindex user output device, method of selecting
9020: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 9021: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
9022: output when the user output device is a terminal, otherwise the output
9023: is buffered.
1.1 anton 9024:
9025: @item methods of dictionary compilation:
9026: What are we expected to document here?
9027:
9028: @item number of bits in one address unit:
9029: @cindex number of bits in one address unit
9030: @cindex address unit, size in bits
9031: @code{s" address-units-bits" environment? drop .}. 8 in all current
9032: ports.
9033:
9034: @item number representation and arithmetic:
9035: @cindex number representation and arithmetic
9036: Processor-dependent. Binary two's complement on all current ports.
9037:
9038: @item ranges for integer types:
9039: @cindex ranges for integer types
9040: @cindex integer types, ranges
9041: Installation-dependent. Make environmental queries for @code{MAX-N},
9042: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
9043: unsigned (and positive) types is 0. The lower bound for signed types on
9044: two's complement and one's complement machines machines can be computed
9045: by adding 1 to the upper bound.
9046:
9047: @item read-only data space regions:
9048: @cindex read-only data space regions
9049: @cindex data-space, read-only regions
9050: The whole Forth data space is writable.
9051:
9052: @item size of buffer at @code{WORD}:
9053: @cindex size of buffer at @code{WORD}
9054: @cindex @code{WORD} buffer size
9055: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
9056: shared with the pictured numeric output string. If overwriting
9057: @code{PAD} is acceptable, it is as large as the remaining dictionary
9058: space, although only as much can be sensibly used as fits in a counted
9059: string.
9060:
9061: @item size of one cell in address units:
9062: @cindex cell size
9063: @code{1 cells .}.
9064:
9065: @item size of one character in address units:
9066: @cindex char size
9067: @code{1 chars .}. 1 on all current ports.
9068:
9069: @item size of the keyboard terminal buffer:
9070: @cindex size of the keyboard terminal buffer
9071: @cindex terminal buffer, size
9072: Varies. You can determine the size at a specific time using @code{lp@@
9073: tib - .}. It is shared with the locals stack and TIBs of files that
9074: include the current file. You can change the amount of space for TIBs
9075: and locals stack at Gforth startup with the command line option
9076: @code{-l}.
9077:
9078: @item size of the pictured numeric output buffer:
9079: @cindex size of the pictured numeric output buffer
9080: @cindex pictured numeric output buffer, size
9081: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
9082: shared with @code{WORD}.
9083:
9084: @item size of the scratch area returned by @code{PAD}:
9085: @cindex size of the scratch area returned by @code{PAD}
9086: @cindex @code{PAD} size
9087: The remainder of dictionary space. @code{unused pad here - - .}.
9088:
9089: @item system case-sensitivity characteristics:
9090: @cindex case-sensitivity characteristics
1.26 crook 9091: Dictionary searches are case-insensitive (except in
1.1 anton 9092: @code{TABLE}s). However, as explained above under @i{character-set
9093: extensions}, the matching for non-ASCII characters is determined by the
9094: locale you are using. In the default @code{C} locale all non-ASCII
9095: characters are matched case-sensitively.
9096:
9097: @item system prompt:
9098: @cindex system prompt
9099: @cindex prompt
9100: @code{ ok} in interpret state, @code{ compiled} in compile state.
9101:
9102: @item division rounding:
9103: @cindex division rounding
9104: installation dependent. @code{s" floored" environment? drop .}. We leave
9105: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
9106: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
9107:
9108: @item values of @code{STATE} when true:
9109: @cindex @code{STATE} values
9110: -1.
9111:
9112: @item values returned after arithmetic overflow:
9113: On two's complement machines, arithmetic is performed modulo
9114: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
9115: arithmetic (with appropriate mapping for signed types). Division by zero
9116: typically results in a @code{-55 throw} (Floating-point unidentified
9117: fault), although a @code{-10 throw} (divide by zero) would be more
9118: appropriate.
9119:
9120: @item whether the current definition can be found after @t{DOES>}:
9121: @cindex @t{DOES>}, visibility of current definition
9122: No.
9123:
9124: @end table
9125:
9126: @c ---------------------------------------------------------------------
9127: @node core-ambcond, core-other, core-idef, The Core Words
9128: @subsection Ambiguous conditions
9129: @c ---------------------------------------------------------------------
9130: @cindex core words, ambiguous conditions
9131: @cindex ambiguous conditions, core words
9132:
9133: @table @i
9134:
9135: @item a name is neither a word nor a number:
9136: @cindex name not found
1.26 crook 9137: @cindex undefined word
1.1 anton 9138: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
9139: preserves the data and FP stack, so you don't lose more work than
9140: necessary.
9141:
9142: @item a definition name exceeds the maximum length allowed:
1.26 crook 9143: @cindex word name too long
1.1 anton 9144: @code{-19 throw} (Word name too long)
9145:
9146: @item addressing a region not inside the various data spaces of the forth system:
9147: @cindex Invalid memory address
1.32 anton 9148: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 9149: typically readable. Accessing other addresses gives results dependent on
9150: the operating system. On decent systems: @code{-9 throw} (Invalid memory
9151: address).
9152:
9153: @item argument type incompatible with parameter:
1.26 crook 9154: @cindex argument type mismatch
1.1 anton 9155: This is usually not caught. Some words perform checks, e.g., the control
9156: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
9157: mismatch).
9158:
9159: @item attempting to obtain the execution token of a word with undefined execution semantics:
9160: @cindex Interpreting a compile-only word, for @code{'} etc.
9161: @cindex execution token of words with undefined execution semantics
9162: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
9163: get an execution token for @code{compile-only-error} (which performs a
9164: @code{-14 throw} when executed).
9165:
9166: @item dividing by zero:
9167: @cindex dividing by zero
9168: @cindex floating point unidentified fault, integer division
1.24 anton 9169: On better platforms, this produces a @code{-10 throw} (Division by
9170: zero); on other systems, this typically results in a @code{-55 throw}
9171: (Floating-point unidentified fault).
1.1 anton 9172:
9173: @item insufficient data stack or return stack space:
9174: @cindex insufficient data stack or return stack space
9175: @cindex stack overflow
1.26 crook 9176: @cindex address alignment exception, stack overflow
1.1 anton 9177: @cindex Invalid memory address, stack overflow
9178: Depending on the operating system, the installation, and the invocation
9179: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 9180: it is not checked. If it is checked, you typically get a @code{-3 throw}
9181: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
9182: throw} (Invalid memory address) (depending on the platform and how you
9183: achieved the overflow) as soon as the overflow happens. If it is not
9184: checked, overflows typically result in mysterious illegal memory
9185: accesses, producing @code{-9 throw} (Invalid memory address) or
9186: @code{-23 throw} (Address alignment exception); they might also destroy
9187: the internal data structure of @code{ALLOCATE} and friends, resulting in
9188: various errors in these words.
1.1 anton 9189:
9190: @item insufficient space for loop control parameters:
9191: @cindex insufficient space for loop control parameters
9192: like other return stack overflows.
9193:
9194: @item insufficient space in the dictionary:
9195: @cindex insufficient space in the dictionary
9196: @cindex dictionary overflow
1.12 anton 9197: If you try to allot (either directly with @code{allot}, or indirectly
9198: with @code{,}, @code{create} etc.) more memory than available in the
9199: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
9200: to access memory beyond the end of the dictionary, the results are
9201: similar to stack overflows.
1.1 anton 9202:
9203: @item interpreting a word with undefined interpretation semantics:
9204: @cindex interpreting a word with undefined interpretation semantics
9205: @cindex Interpreting a compile-only word
9206: For some words, we have defined interpretation semantics. For the
9207: others: @code{-14 throw} (Interpreting a compile-only word).
9208:
9209: @item modifying the contents of the input buffer or a string literal:
9210: @cindex modifying the contents of the input buffer or a string literal
9211: These are located in writable memory and can be modified.
9212:
9213: @item overflow of the pictured numeric output string:
9214: @cindex overflow of the pictured numeric output string
9215: @cindex pictured numeric output string, overflow
1.24 anton 9216: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 9217:
9218: @item parsed string overflow:
9219: @cindex parsed string overflow
9220: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
9221:
9222: @item producing a result out of range:
9223: @cindex result out of range
9224: On two's complement machines, arithmetic is performed modulo
9225: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
9226: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 9227: typically results in a @code{-10 throw} (divide by zero) or @code{-55
9228: throw} (floating point unidentified fault). @code{convert} and
9229: @code{>number} currently overflow silently.
1.1 anton 9230:
9231: @item reading from an empty data or return stack:
9232: @cindex stack empty
9233: @cindex stack underflow
1.24 anton 9234: @cindex return stack underflow
1.1 anton 9235: The data stack is checked by the outer (aka text) interpreter after
9236: every word executed. If it has underflowed, a @code{-4 throw} (Stack
9237: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 9238: depending on operating system, installation, and invocation. If they are
9239: caught by a check, they typically result in @code{-4 throw} (Stack
9240: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
9241: (Invalid memory address), depending on the platform and which stack
9242: underflows and by how much. Note that even if the system uses checking
9243: (through the MMU), your program may have to underflow by a significant
9244: number of stack items to trigger the reaction (the reason for this is
9245: that the MMU, and therefore the checking, works with a page-size
9246: granularity). If there is no checking, the symptoms resulting from an
9247: underflow are similar to those from an overflow. Unbalanced return
9248: stack errors result in a variaty of symptoms, including @code{-9 throw}
9249: (Invalid memory address) and Illegal Instruction (typically @code{-260
9250: throw}).
1.1 anton 9251:
9252: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
9253: @cindex unexpected end of the input buffer
9254: @cindex zero-length string as a name
9255: @cindex Attempt to use zero-length string as a name
9256: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
9257: use zero-length string as a name). Words like @code{'} probably will not
9258: find what they search. Note that it is possible to create zero-length
9259: names with @code{nextname} (should it not?).
9260:
9261: @item @code{>IN} greater than input buffer:
9262: @cindex @code{>IN} greater than input buffer
9263: The next invocation of a parsing word returns a string with length 0.
9264:
9265: @item @code{RECURSE} appears after @code{DOES>}:
9266: @cindex @code{RECURSE} appears after @code{DOES>}
9267: Compiles a recursive call to the defining word, not to the defined word.
9268:
9269: @item argument input source different than current input source for @code{RESTORE-INPUT}:
9270: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 9271: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 9272: @cindex @code{RESTORE-INPUT}, Argument type mismatch
9273: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
9274: the end of the file was reached), its source-id may be
9275: reused. Therefore, restoring an input source specification referencing a
9276: closed file may lead to unpredictable results instead of a @code{-12
9277: THROW}.
9278:
9279: In the future, Gforth may be able to restore input source specifications
9280: from other than the current input source.
9281:
9282: @item data space containing definitions gets de-allocated:
9283: @cindex data space containing definitions gets de-allocated
9284: Deallocation with @code{allot} is not checked. This typically results in
9285: memory access faults or execution of illegal instructions.
9286:
9287: @item data space read/write with incorrect alignment:
9288: @cindex data space read/write with incorrect alignment
9289: @cindex alignment faults
1.26 crook 9290: @cindex address alignment exception
1.1 anton 9291: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 9292: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 9293: alignment turned on, incorrect alignment results in a @code{-9 throw}
9294: (Invalid memory address). There are reportedly some processors with
1.12 anton 9295: alignment restrictions that do not report violations.
1.1 anton 9296:
9297: @item data space pointer not properly aligned, @code{,}, @code{C,}:
9298: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
9299: Like other alignment errors.
9300:
9301: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
9302: Like other stack underflows.
9303:
9304: @item loop control parameters not available:
9305: @cindex loop control parameters not available
9306: Not checked. The counted loop words simply assume that the top of return
9307: stack items are loop control parameters and behave accordingly.
9308:
9309: @item most recent definition does not have a name (@code{IMMEDIATE}):
9310: @cindex most recent definition does not have a name (@code{IMMEDIATE})
9311: @cindex last word was headerless
9312: @code{abort" last word was headerless"}.
9313:
9314: @item name not defined by @code{VALUE} used by @code{TO}:
9315: @cindex name not defined by @code{VALUE} used by @code{TO}
9316: @cindex @code{TO} on non-@code{VALUE}s
9317: @cindex Invalid name argument, @code{TO}
9318: @code{-32 throw} (Invalid name argument) (unless name is a local or was
9319: defined by @code{CONSTANT}; in the latter case it just changes the constant).
9320:
9321: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
9322: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 9323: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 9324: @code{-13 throw} (Undefined word)
9325:
9326: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
9327: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
9328: Gforth behaves as if they were of the same type. I.e., you can predict
9329: the behaviour by interpreting all parameters as, e.g., signed.
9330:
9331: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
9332: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
9333: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
9334: compilation semantics of @code{TO}.
9335:
9336: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 9337: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 9338: @cindex @code{WORD}, string overflow
9339: Not checked. The string will be ok, but the count will, of course,
9340: contain only the least significant bits of the length.
9341:
9342: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
9343: @cindex @code{LSHIFT}, large shift counts
9344: @cindex @code{RSHIFT}, large shift counts
9345: Processor-dependent. Typical behaviours are returning 0 and using only
9346: the low bits of the shift count.
9347:
9348: @item word not defined via @code{CREATE}:
9349: @cindex @code{>BODY} of non-@code{CREATE}d words
9350: @code{>BODY} produces the PFA of the word no matter how it was defined.
9351:
9352: @cindex @code{DOES>} of non-@code{CREATE}d words
9353: @code{DOES>} changes the execution semantics of the last defined word no
9354: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
9355: @code{CREATE , DOES>}.
9356:
9357: @item words improperly used outside @code{<#} and @code{#>}:
9358: Not checked. As usual, you can expect memory faults.
9359:
9360: @end table
9361:
9362:
9363: @c ---------------------------------------------------------------------
9364: @node core-other, , core-ambcond, The Core Words
9365: @subsection Other system documentation
9366: @c ---------------------------------------------------------------------
9367: @cindex other system documentation, core words
9368: @cindex core words, other system documentation
9369:
9370: @table @i
9371: @item nonstandard words using @code{PAD}:
9372: @cindex @code{PAD} use by nonstandard words
9373: None.
9374:
9375: @item operator's terminal facilities available:
9376: @cindex operator's terminal facilities available
9377: After processing the command line, Gforth goes into interactive mode,
9378: and you can give commands to Gforth interactively. The actual facilities
9379: available depend on how you invoke Gforth.
9380:
9381: @item program data space available:
9382: @cindex program data space available
9383: @cindex data space available
9384: @code{UNUSED .} gives the remaining dictionary space. The total
9385: dictionary space can be specified with the @code{-m} switch
9386: (@pxref{Invoking Gforth}) when Gforth starts up.
9387:
9388: @item return stack space available:
9389: @cindex return stack space available
9390: You can compute the total return stack space in cells with
9391: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
9392: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
9393:
9394: @item stack space available:
9395: @cindex stack space available
9396: You can compute the total data stack space in cells with
9397: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
9398: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
9399:
9400: @item system dictionary space required, in address units:
9401: @cindex system dictionary space required, in address units
9402: Type @code{here forthstart - .} after startup. At the time of this
9403: writing, this gives 80080 (bytes) on a 32-bit system.
9404: @end table
9405:
9406:
9407: @c =====================================================================
9408: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
9409: @section The optional Block word set
9410: @c =====================================================================
9411: @cindex system documentation, block words
9412: @cindex block words, system documentation
9413:
9414: @menu
9415: * block-idef:: Implementation Defined Options
9416: * block-ambcond:: Ambiguous Conditions
9417: * block-other:: Other System Documentation
9418: @end menu
9419:
9420:
9421: @c ---------------------------------------------------------------------
9422: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
9423: @subsection Implementation Defined Options
9424: @c ---------------------------------------------------------------------
9425: @cindex implementation-defined options, block words
9426: @cindex block words, implementation-defined options
9427:
9428: @table @i
9429: @item the format for display by @code{LIST}:
9430: @cindex @code{LIST} display format
9431: First the screen number is displayed, then 16 lines of 64 characters,
9432: each line preceded by the line number.
9433:
9434: @item the length of a line affected by @code{\}:
9435: @cindex length of a line affected by @code{\}
9436: @cindex @code{\}, line length in blocks
9437: 64 characters.
9438: @end table
9439:
9440:
9441: @c ---------------------------------------------------------------------
9442: @node block-ambcond, block-other, block-idef, The optional Block word set
9443: @subsection Ambiguous conditions
9444: @c ---------------------------------------------------------------------
9445: @cindex block words, ambiguous conditions
9446: @cindex ambiguous conditions, block words
9447:
9448: @table @i
9449: @item correct block read was not possible:
9450: @cindex block read not possible
9451: Typically results in a @code{throw} of some OS-derived value (between
9452: -512 and -2048). If the blocks file was just not long enough, blanks are
9453: supplied for the missing portion.
9454:
9455: @item I/O exception in block transfer:
9456: @cindex I/O exception in block transfer
9457: @cindex block transfer, I/O exception
9458: Typically results in a @code{throw} of some OS-derived value (between
9459: -512 and -2048).
9460:
9461: @item invalid block number:
9462: @cindex invalid block number
9463: @cindex block number invalid
9464: @code{-35 throw} (Invalid block number)
9465:
9466: @item a program directly alters the contents of @code{BLK}:
9467: @cindex @code{BLK}, altering @code{BLK}
9468: The input stream is switched to that other block, at the same
9469: position. If the storing to @code{BLK} happens when interpreting
9470: non-block input, the system will get quite confused when the block ends.
9471:
9472: @item no current block buffer for @code{UPDATE}:
9473: @cindex @code{UPDATE}, no current block buffer
9474: @code{UPDATE} has no effect.
9475:
9476: @end table
9477:
9478: @c ---------------------------------------------------------------------
9479: @node block-other, , block-ambcond, The optional Block word set
9480: @subsection Other system documentation
9481: @c ---------------------------------------------------------------------
9482: @cindex other system documentation, block words
9483: @cindex block words, other system documentation
9484:
9485: @table @i
9486: @item any restrictions a multiprogramming system places on the use of buffer addresses:
9487: No restrictions (yet).
9488:
9489: @item the number of blocks available for source and data:
9490: depends on your disk space.
9491:
9492: @end table
9493:
9494:
9495: @c =====================================================================
9496: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
9497: @section The optional Double Number word set
9498: @c =====================================================================
9499: @cindex system documentation, double words
9500: @cindex double words, system documentation
9501:
9502: @menu
9503: * double-ambcond:: Ambiguous Conditions
9504: @end menu
9505:
9506:
9507: @c ---------------------------------------------------------------------
9508: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
9509: @subsection Ambiguous conditions
9510: @c ---------------------------------------------------------------------
9511: @cindex double words, ambiguous conditions
9512: @cindex ambiguous conditions, double words
9513:
9514: @table @i
1.29 crook 9515: @item @i{d} outside of range of @i{n} in @code{D>S}:
9516: @cindex @code{D>S}, @i{d} out of range of @i{n}
9517: The least significant cell of @i{d} is produced.
1.1 anton 9518:
9519: @end table
9520:
9521:
9522: @c =====================================================================
9523: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
9524: @section The optional Exception word set
9525: @c =====================================================================
9526: @cindex system documentation, exception words
9527: @cindex exception words, system documentation
9528:
9529: @menu
9530: * exception-idef:: Implementation Defined Options
9531: @end menu
9532:
9533:
9534: @c ---------------------------------------------------------------------
9535: @node exception-idef, , The optional Exception word set, The optional Exception word set
9536: @subsection Implementation Defined Options
9537: @c ---------------------------------------------------------------------
9538: @cindex implementation-defined options, exception words
9539: @cindex exception words, implementation-defined options
9540:
9541: @table @i
9542: @item @code{THROW}-codes used in the system:
9543: @cindex @code{THROW}-codes used in the system
9544: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 9545: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 9546: codes -512@minus{}-2047 are used for OS errors (for file and memory
9547: allocation operations). The mapping from OS error numbers to throw codes
9548: is -512@minus{}@code{errno}. One side effect of this mapping is that
9549: undefined OS errors produce a message with a strange number; e.g.,
9550: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
9551: @end table
9552:
9553: @c =====================================================================
9554: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
9555: @section The optional Facility word set
9556: @c =====================================================================
9557: @cindex system documentation, facility words
9558: @cindex facility words, system documentation
9559:
9560: @menu
9561: * facility-idef:: Implementation Defined Options
9562: * facility-ambcond:: Ambiguous Conditions
9563: @end menu
9564:
9565:
9566: @c ---------------------------------------------------------------------
9567: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
9568: @subsection Implementation Defined Options
9569: @c ---------------------------------------------------------------------
9570: @cindex implementation-defined options, facility words
9571: @cindex facility words, implementation-defined options
9572:
9573: @table @i
9574: @item encoding of keyboard events (@code{EKEY}):
9575: @cindex keyboard events, encoding in @code{EKEY}
9576: @cindex @code{EKEY}, encoding of keyboard events
9577: Not yet implemented.
9578:
9579: @item duration of a system clock tick:
9580: @cindex duration of a system clock tick
9581: @cindex clock tick duration
9582: System dependent. With respect to @code{MS}, the time is specified in
9583: microseconds. How well the OS and the hardware implement this, is
9584: another question.
9585:
9586: @item repeatability to be expected from the execution of @code{MS}:
9587: @cindex repeatability to be expected from the execution of @code{MS}
9588: @cindex @code{MS}, repeatability to be expected
9589: System dependent. On Unix, a lot depends on load. If the system is
9590: lightly loaded, and the delay is short enough that Gforth does not get
9591: swapped out, the performance should be acceptable. Under MS-DOS and
9592: other single-tasking systems, it should be good.
9593:
9594: @end table
9595:
9596:
9597: @c ---------------------------------------------------------------------
9598: @node facility-ambcond, , facility-idef, The optional Facility word set
9599: @subsection Ambiguous conditions
9600: @c ---------------------------------------------------------------------
9601: @cindex facility words, ambiguous conditions
9602: @cindex ambiguous conditions, facility words
9603:
9604: @table @i
9605: @item @code{AT-XY} can't be performed on user output device:
9606: @cindex @code{AT-XY} can't be performed on user output device
9607: Largely terminal dependent. No range checks are done on the arguments.
9608: No errors are reported. You may see some garbage appearing, you may see
9609: simply nothing happen.
9610:
9611: @end table
9612:
9613:
9614: @c =====================================================================
9615: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
9616: @section The optional File-Access word set
9617: @c =====================================================================
9618: @cindex system documentation, file words
9619: @cindex file words, system documentation
9620:
9621: @menu
9622: * file-idef:: Implementation Defined Options
9623: * file-ambcond:: Ambiguous Conditions
9624: @end menu
9625:
9626: @c ---------------------------------------------------------------------
9627: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
9628: @subsection Implementation Defined Options
9629: @c ---------------------------------------------------------------------
9630: @cindex implementation-defined options, file words
9631: @cindex file words, implementation-defined options
9632:
9633: @table @i
9634: @item file access methods used:
9635: @cindex file access methods used
9636: @code{R/O}, @code{R/W} and @code{BIN} work as you would
9637: expect. @code{W/O} translates into the C file opening mode @code{w} (or
9638: @code{wb}): The file is cleared, if it exists, and created, if it does
9639: not (with both @code{open-file} and @code{create-file}). Under Unix
9640: @code{create-file} creates a file with 666 permissions modified by your
9641: umask.
9642:
9643: @item file exceptions:
9644: @cindex file exceptions
9645: The file words do not raise exceptions (except, perhaps, memory access
9646: faults when you pass illegal addresses or file-ids).
9647:
9648: @item file line terminator:
9649: @cindex file line terminator
9650: System-dependent. Gforth uses C's newline character as line
9651: terminator. What the actual character code(s) of this are is
9652: system-dependent.
9653:
9654: @item file name format:
9655: @cindex file name format
9656: System dependent. Gforth just uses the file name format of your OS.
9657:
9658: @item information returned by @code{FILE-STATUS}:
9659: @cindex @code{FILE-STATUS}, returned information
9660: @code{FILE-STATUS} returns the most powerful file access mode allowed
9661: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
9662: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
9663: along with the returned mode.
9664:
9665: @item input file state after an exception when including source:
9666: @cindex exception when including source
9667: All files that are left via the exception are closed.
9668:
1.29 crook 9669: @item @i{ior} values and meaning:
9670: @cindex @i{ior} values and meaning
9671: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 9672: intended as throw codes. They typically are in the range
9673: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 9674: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 9675:
9676: @item maximum depth of file input nesting:
9677: @cindex maximum depth of file input nesting
9678: @cindex file input nesting, maximum depth
9679: limited by the amount of return stack, locals/TIB stack, and the number
9680: of open files available. This should not give you troubles.
9681:
9682: @item maximum size of input line:
9683: @cindex maximum size of input line
9684: @cindex input line size, maximum
9685: @code{/line}. Currently 255.
9686:
9687: @item methods of mapping block ranges to files:
9688: @cindex mapping block ranges to files
9689: @cindex files containing blocks
9690: @cindex blocks in files
9691: By default, blocks are accessed in the file @file{blocks.fb} in the
9692: current working directory. The file can be switched with @code{USE}.
9693:
9694: @item number of string buffers provided by @code{S"}:
9695: @cindex @code{S"}, number of string buffers
9696: 1
9697:
9698: @item size of string buffer used by @code{S"}:
9699: @cindex @code{S"}, size of string buffer
9700: @code{/line}. currently 255.
9701:
9702: @end table
9703:
9704: @c ---------------------------------------------------------------------
9705: @node file-ambcond, , file-idef, The optional File-Access word set
9706: @subsection Ambiguous conditions
9707: @c ---------------------------------------------------------------------
9708: @cindex file words, ambiguous conditions
9709: @cindex ambiguous conditions, file words
9710:
9711: @table @i
9712: @item attempting to position a file outside its boundaries:
9713: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
9714: @code{REPOSITION-FILE} is performed as usual: Afterwards,
9715: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
9716:
9717: @item attempting to read from file positions not yet written:
9718: @cindex reading from file positions not yet written
9719: End-of-file, i.e., zero characters are read and no error is reported.
9720:
1.29 crook 9721: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
9722: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 9723: An appropriate exception may be thrown, but a memory fault or other
9724: problem is more probable.
9725:
1.29 crook 9726: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
9727: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
9728: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
9729: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 9730: thrown.
9731:
9732: @item named file cannot be opened (@code{INCLUDED}):
9733: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 9734: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 9735:
9736: @item requesting an unmapped block number:
9737: @cindex unmapped block numbers
9738: There are no unmapped legal block numbers. On some operating systems,
9739: writing a block with a large number may overflow the file system and
9740: have an error message as consequence.
9741:
9742: @item using @code{source-id} when @code{blk} is non-zero:
9743: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
9744: @code{source-id} performs its function. Typically it will give the id of
9745: the source which loaded the block. (Better ideas?)
9746:
9747: @end table
9748:
9749:
9750: @c =====================================================================
9751: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
9752: @section The optional Floating-Point word set
9753: @c =====================================================================
9754: @cindex system documentation, floating-point words
9755: @cindex floating-point words, system documentation
9756:
9757: @menu
9758: * floating-idef:: Implementation Defined Options
9759: * floating-ambcond:: Ambiguous Conditions
9760: @end menu
9761:
9762:
9763: @c ---------------------------------------------------------------------
9764: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
9765: @subsection Implementation Defined Options
9766: @c ---------------------------------------------------------------------
9767: @cindex implementation-defined options, floating-point words
9768: @cindex floating-point words, implementation-defined options
9769:
9770: @table @i
9771: @item format and range of floating point numbers:
9772: @cindex format and range of floating point numbers
9773: @cindex floating point numbers, format and range
9774: System-dependent; the @code{double} type of C.
9775:
1.29 crook 9776: @item results of @code{REPRESENT} when @i{float} is out of range:
9777: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 9778: System dependent; @code{REPRESENT} is implemented using the C library
9779: function @code{ecvt()} and inherits its behaviour in this respect.
9780:
9781: @item rounding or truncation of floating-point numbers:
9782: @cindex rounding of floating-point numbers
9783: @cindex truncation of floating-point numbers
9784: @cindex floating-point numbers, rounding or truncation
9785: System dependent; the rounding behaviour is inherited from the hosting C
9786: compiler. IEEE-FP-based (i.e., most) systems by default round to
9787: nearest, and break ties by rounding to even (i.e., such that the last
9788: bit of the mantissa is 0).
9789:
9790: @item size of floating-point stack:
9791: @cindex floating-point stack size
9792: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
9793: the floating-point stack (in floats). You can specify this on startup
9794: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
9795:
9796: @item width of floating-point stack:
9797: @cindex floating-point stack width
9798: @code{1 floats}.
9799:
9800: @end table
9801:
9802:
9803: @c ---------------------------------------------------------------------
9804: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
9805: @subsection Ambiguous conditions
9806: @c ---------------------------------------------------------------------
9807: @cindex floating-point words, ambiguous conditions
9808: @cindex ambiguous conditions, floating-point words
9809:
9810: @table @i
9811: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
9812: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
9813: System-dependent. Typically results in a @code{-23 THROW} like other
9814: alignment violations.
9815:
9816: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
9817: @cindex @code{f@@} used with an address that is not float aligned
9818: @cindex @code{f!} used with an address that is not float aligned
9819: System-dependent. Typically results in a @code{-23 THROW} like other
9820: alignment violations.
9821:
9822: @item floating-point result out of range:
9823: @cindex floating-point result out of range
9824: System-dependent. Can result in a @code{-55 THROW} (Floating-point
9825: unidentified fault), or can produce a special value representing, e.g.,
9826: Infinity.
9827:
9828: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
9829: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
9830: System-dependent. Typically results in an alignment fault like other
9831: alignment violations.
9832:
9833: @item @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
9834: @cindex @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
9835: The floating-point number is converted into decimal nonetheless.
9836:
9837: @item Both arguments are equal to zero (@code{FATAN2}):
9838: @cindex @code{FATAN2}, both arguments are equal to zero
9839: System-dependent. @code{FATAN2} is implemented using the C library
9840: function @code{atan2()}.
9841:
1.29 crook 9842: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
9843: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
9844: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 9845: because of small errors and the tan will be a very large (or very small)
9846: but finite number.
9847:
1.29 crook 9848: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
9849: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 9850: The result is rounded to the nearest float.
9851:
9852: @item dividing by zero:
9853: @cindex dividing by zero, floating-point
9854: @cindex floating-point dividing by zero
9855: @cindex floating-point unidentified fault, FP divide-by-zero
9856: @code{-55 throw} (Floating-point unidentified fault)
9857:
9858: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
9859: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
9860: System dependent. On IEEE-FP based systems the number is converted into
9861: an infinity.
9862:
1.29 crook 9863: @item @i{float}<1 (@code{FACOSH}):
9864: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 9865: @cindex floating-point unidentified fault, @code{FACOSH}
9866: @code{-55 throw} (Floating-point unidentified fault)
9867:
1.29 crook 9868: @item @i{float}=<-1 (@code{FLNP1}):
9869: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 9870: @cindex floating-point unidentified fault, @code{FLNP1}
9871: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29 crook 9872: negative infinity is typically produced for @i{float}=-1.
1.1 anton 9873:
1.29 crook 9874: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
9875: @cindex @code{FLN}, @i{float}=<0
9876: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 9877: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
9878: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29 crook 9879: negative infinity is typically produced for @i{float}=0.
1.1 anton 9880:
1.29 crook 9881: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
9882: @cindex @code{FASINH}, @i{float}<0
9883: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 9884: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
9885: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
9886: produces values for these inputs on my Linux box (Bug in the C library?)
9887:
1.29 crook 9888: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
9889: @cindex @code{FACOS}, |@i{float}|>1
9890: @cindex @code{FASIN}, |@i{float}|>1
9891: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 9892: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
9893: @code{-55 throw} (Floating-point unidentified fault).
9894:
1.29 crook 9895: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
9896: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 9897: @cindex floating-point unidentified fault, @code{F>D}
9898: @code{-55 throw} (Floating-point unidentified fault).
9899:
9900: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
9901: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
9902: This does not happen.
9903: @end table
9904:
9905: @c =====================================================================
9906: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
9907: @section The optional Locals word set
9908: @c =====================================================================
9909: @cindex system documentation, locals words
9910: @cindex locals words, system documentation
9911:
9912: @menu
9913: * locals-idef:: Implementation Defined Options
9914: * locals-ambcond:: Ambiguous Conditions
9915: @end menu
9916:
9917:
9918: @c ---------------------------------------------------------------------
9919: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
9920: @subsection Implementation Defined Options
9921: @c ---------------------------------------------------------------------
9922: @cindex implementation-defined options, locals words
9923: @cindex locals words, implementation-defined options
9924:
9925: @table @i
9926: @item maximum number of locals in a definition:
9927: @cindex maximum number of locals in a definition
9928: @cindex locals, maximum number in a definition
9929: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
9930: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
9931: characters. The number of locals in a definition is bounded by the size
9932: of locals-buffer, which contains the names of the locals.
9933:
9934: @end table
9935:
9936:
9937: @c ---------------------------------------------------------------------
9938: @node locals-ambcond, , locals-idef, The optional Locals word set
9939: @subsection Ambiguous conditions
9940: @c ---------------------------------------------------------------------
9941: @cindex locals words, ambiguous conditions
9942: @cindex ambiguous conditions, locals words
9943:
9944: @table @i
9945: @item executing a named local in interpretation state:
9946: @cindex local in interpretation state
9947: @cindex Interpreting a compile-only word, for a local
9948: Locals have no interpretation semantics. If you try to perform the
9949: interpretation semantics, you will get a @code{-14 throw} somewhere
9950: (Interpreting a compile-only word). If you perform the compilation
9951: semantics, the locals access will be compiled (irrespective of state).
9952:
1.29 crook 9953: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 9954: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
9955: @cindex @code{TO} on non-@code{VALUE}s and non-locals
9956: @cindex Invalid name argument, @code{TO}
9957: @code{-32 throw} (Invalid name argument)
9958:
9959: @end table
9960:
9961:
9962: @c =====================================================================
9963: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
9964: @section The optional Memory-Allocation word set
9965: @c =====================================================================
9966: @cindex system documentation, memory-allocation words
9967: @cindex memory-allocation words, system documentation
9968:
9969: @menu
9970: * memory-idef:: Implementation Defined Options
9971: @end menu
9972:
9973:
9974: @c ---------------------------------------------------------------------
9975: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
9976: @subsection Implementation Defined Options
9977: @c ---------------------------------------------------------------------
9978: @cindex implementation-defined options, memory-allocation words
9979: @cindex memory-allocation words, implementation-defined options
9980:
9981: @table @i
1.29 crook 9982: @item values and meaning of @i{ior}:
9983: @cindex @i{ior} values and meaning
9984: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 9985: intended as throw codes. They typically are in the range
9986: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 9987: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 9988:
9989: @end table
9990:
9991: @c =====================================================================
9992: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
9993: @section The optional Programming-Tools word set
9994: @c =====================================================================
9995: @cindex system documentation, programming-tools words
9996: @cindex programming-tools words, system documentation
9997:
9998: @menu
9999: * programming-idef:: Implementation Defined Options
10000: * programming-ambcond:: Ambiguous Conditions
10001: @end menu
10002:
10003:
10004: @c ---------------------------------------------------------------------
10005: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
10006: @subsection Implementation Defined Options
10007: @c ---------------------------------------------------------------------
10008: @cindex implementation-defined options, programming-tools words
10009: @cindex programming-tools words, implementation-defined options
10010:
10011: @table @i
10012: @item ending sequence for input following @code{;CODE} and @code{CODE}:
10013: @cindex @code{;CODE} ending sequence
10014: @cindex @code{CODE} ending sequence
10015: @code{END-CODE}
10016:
10017: @item manner of processing input following @code{;CODE} and @code{CODE}:
10018: @cindex @code{;CODE}, processing input
10019: @cindex @code{CODE}, processing input
10020: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
10021: the input is processed by the text interpreter, (starting) in interpret
10022: state.
10023:
10024: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
10025: @cindex @code{ASSEMBLER}, search order capability
10026: The ANS Forth search order word set.
10027:
10028: @item source and format of display by @code{SEE}:
10029: @cindex @code{SEE}, source and format of output
10030: The source for @code{see} is the intermediate code used by the inner
10031: interpreter. The current @code{see} tries to output Forth source code
10032: as well as possible.
10033:
10034: @end table
10035:
10036: @c ---------------------------------------------------------------------
10037: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
10038: @subsection Ambiguous conditions
10039: @c ---------------------------------------------------------------------
10040: @cindex programming-tools words, ambiguous conditions
10041: @cindex ambiguous conditions, programming-tools words
10042:
10043: @table @i
10044:
1.21 crook 10045: @item deleting the compilation word list (@code{FORGET}):
10046: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 10047: Not implemented (yet).
10048:
1.29 crook 10049: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
10050: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
10051: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 10052: @cindex control-flow stack underflow
10053: This typically results in an @code{abort"} with a descriptive error
10054: message (may change into a @code{-22 throw} (Control structure mismatch)
10055: in the future). You may also get a memory access error. If you are
10056: unlucky, this ambiguous condition is not caught.
10057:
1.29 crook 10058: @item @i{name} can't be found (@code{FORGET}):
10059: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 10060: Not implemented (yet).
10061:
1.29 crook 10062: @item @i{name} not defined via @code{CREATE}:
10063: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 10064: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
10065: the execution semantics of the last defined word no matter how it was
10066: defined.
10067:
10068: @item @code{POSTPONE} applied to @code{[IF]}:
10069: @cindex @code{POSTPONE} applied to @code{[IF]}
10070: @cindex @code{[IF]} and @code{POSTPONE}
10071: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
10072: equivalent to @code{[IF]}.
10073:
10074: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
10075: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
10076: Continue in the same state of conditional compilation in the next outer
10077: input source. Currently there is no warning to the user about this.
10078:
10079: @item removing a needed definition (@code{FORGET}):
10080: @cindex @code{FORGET}, removing a needed definition
10081: Not implemented (yet).
10082:
10083: @end table
10084:
10085:
10086: @c =====================================================================
10087: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
10088: @section The optional Search-Order word set
10089: @c =====================================================================
10090: @cindex system documentation, search-order words
10091: @cindex search-order words, system documentation
10092:
10093: @menu
10094: * search-idef:: Implementation Defined Options
10095: * search-ambcond:: Ambiguous Conditions
10096: @end menu
10097:
10098:
10099: @c ---------------------------------------------------------------------
10100: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
10101: @subsection Implementation Defined Options
10102: @c ---------------------------------------------------------------------
10103: @cindex implementation-defined options, search-order words
10104: @cindex search-order words, implementation-defined options
10105:
10106: @table @i
10107: @item maximum number of word lists in search order:
10108: @cindex maximum number of word lists in search order
10109: @cindex search order, maximum depth
10110: @code{s" wordlists" environment? drop .}. Currently 16.
10111:
10112: @item minimum search order:
10113: @cindex minimum search order
10114: @cindex search order, minimum
10115: @code{root root}.
10116:
10117: @end table
10118:
10119: @c ---------------------------------------------------------------------
10120: @node search-ambcond, , search-idef, The optional Search-Order word set
10121: @subsection Ambiguous conditions
10122: @c ---------------------------------------------------------------------
10123: @cindex search-order words, ambiguous conditions
10124: @cindex ambiguous conditions, search-order words
10125:
10126: @table @i
1.21 crook 10127: @item changing the compilation word list (during compilation):
10128: @cindex changing the compilation word list (during compilation)
10129: @cindex compilation word list, change before definition ends
10130: The word is entered into the word list that was the compilation word list
1.1 anton 10131: at the start of the definition. Any changes to the name field (e.g.,
10132: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
10133: are applied to the latest defined word (as reported by @code{last} or
1.21 crook 10134: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1 anton 10135:
10136: @item search order empty (@code{previous}):
10137: @cindex @code{previous}, search order empty
1.26 crook 10138: @cindex vocstack empty, @code{previous}
1.1 anton 10139: @code{abort" Vocstack empty"}.
10140:
10141: @item too many word lists in search order (@code{also}):
10142: @cindex @code{also}, too many word lists in search order
1.26 crook 10143: @cindex vocstack full, @code{also}
1.1 anton 10144: @code{abort" Vocstack full"}.
10145:
10146: @end table
10147:
10148: @c ***************************************************************
10149: @node Model, Integrating Gforth, ANS conformance, Top
10150: @chapter Model
10151:
10152: This chapter has yet to be written. It will contain information, on
10153: which internal structures you can rely.
10154:
10155: @c ***************************************************************
10156: @node Integrating Gforth, Emacs and Gforth, Model, Top
10157: @chapter Integrating Gforth into C programs
10158:
10159: This is not yet implemented.
10160:
10161: Several people like to use Forth as scripting language for applications
10162: that are otherwise written in C, C++, or some other language.
10163:
10164: The Forth system ATLAST provides facilities for embedding it into
10165: applications; unfortunately it has several disadvantages: most
10166: importantly, it is not based on ANS Forth, and it is apparently dead
10167: (i.e., not developed further and not supported). The facilities
1.21 crook 10168: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 10169: making the switch should not be hard.
10170:
10171: We also tried to design the interface such that it can easily be
10172: implemented by other Forth systems, so that we may one day arrive at a
10173: standardized interface. Such a standard interface would allow you to
10174: replace the Forth system without having to rewrite C code.
10175:
10176: You embed the Gforth interpreter by linking with the library
10177: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
10178: global symbols in this library that belong to the interface, have the
10179: prefix @code{forth_}. (Global symbols that are used internally have the
10180: prefix @code{gforth_}).
10181:
10182: You can include the declarations of Forth types and the functions and
10183: variables of the interface with @code{#include <forth.h>}.
10184:
10185: Types.
10186:
10187: Variables.
10188:
10189: Data and FP Stack pointer. Area sizes.
10190:
10191: functions.
10192:
10193: forth_init(imagefile)
10194: forth_evaluate(string) exceptions?
10195: forth_goto(address) (or forth_execute(xt)?)
10196: forth_continue() (a corountining mechanism)
10197:
10198: Adding primitives.
10199:
10200: No checking.
10201:
10202: Signals?
10203:
10204: Accessing the Stacks
10205:
1.26 crook 10206: @c ******************************************************************
1.1 anton 10207: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
10208: @chapter Emacs and Gforth
10209: @cindex Emacs and Gforth
10210:
10211: @cindex @file{gforth.el}
10212: @cindex @file{forth.el}
10213: @cindex Rydqvist, Goran
10214: @cindex comment editing commands
10215: @cindex @code{\}, editing with Emacs
10216: @cindex debug tracer editing commands
10217: @cindex @code{~~}, removal with Emacs
10218: @cindex Forth mode in Emacs
10219: Gforth comes with @file{gforth.el}, an improved version of
10220: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 10221: improvements are:
10222:
10223: @itemize @bullet
10224: @item
10225: A better (but still not perfect) handling of indentation.
10226: @item
10227: Comment paragraph filling (@kbd{M-q})
10228: @item
10229: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
10230: @item
10231: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
10232: @end itemize
10233:
10234: I left the stuff I do not use alone, even though some of it only makes
10235: sense for TILE. To get a description of these features, enter Forth mode
10236: and type @kbd{C-h m}.
1.1 anton 10237:
10238: @cindex source location of error or debugging output in Emacs
10239: @cindex error output, finding the source location in Emacs
10240: @cindex debugging output, finding the source location in Emacs
10241: In addition, Gforth supports Emacs quite well: The source code locations
10242: given in error messages, debugging output (from @code{~~}) and failed
10243: assertion messages are in the right format for Emacs' compilation mode
10244: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
10245: Manual}) so the source location corresponding to an error or other
10246: message is only a few keystrokes away (@kbd{C-x `} for the next error,
10247: @kbd{C-c C-c} for the error under the cursor).
10248:
10249: @cindex @file{TAGS} file
10250: @cindex @file{etags.fs}
10251: @cindex viewing the source of a word in Emacs
1.26 crook 10252: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file will
10253: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 10254: contains the definitions of all words defined afterwards. You can then
10255: find the source for a word using @kbd{M-.}. Note that emacs can use
10256: several tags files at the same time (e.g., one for the Gforth sources
10257: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
10258: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
10259: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
10260: @file{/usr/local/share/gforth/0.2.0/TAGS}).
10261:
10262: @cindex @file{.emacs}
10263: To get all these benefits, add the following lines to your @file{.emacs}
10264: file:
10265:
10266: @example
10267: (autoload 'forth-mode "gforth.el")
10268: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
10269: @end example
10270:
1.26 crook 10271: @c ******************************************************************
1.1 anton 10272: @node Image Files, Engine, Emacs and Gforth, Top
10273: @chapter Image Files
1.26 crook 10274: @cindex image file
10275: @cindex @file{.fi} files
1.1 anton 10276: @cindex precompiled Forth code
10277: @cindex dictionary in persistent form
10278: @cindex persistent form of dictionary
10279:
10280: An image file is a file containing an image of the Forth dictionary,
10281: i.e., compiled Forth code and data residing in the dictionary. By
10282: convention, we use the extension @code{.fi} for image files.
10283:
10284: @menu
1.18 anton 10285: * Image Licensing Issues:: Distribution terms for images.
10286: * Image File Background:: Why have image files?
1.29 crook 10287: * Non-Relocatable Image Files:: don't always work.
1.18 anton 10288: * Data-Relocatable Image Files:: are better.
1.29 crook 10289: * Fully Relocatable Image Files:: better yet.
1.18 anton 10290: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 10291: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 10292: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 10293: @end menu
10294:
1.18 anton 10295: @node Image Licensing Issues, Image File Background, Image Files, Image Files
10296: @section Image Licensing Issues
10297: @cindex license for images
10298: @cindex image license
10299:
10300: An image created with @code{gforthmi} (@pxref{gforthmi}) or
10301: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
10302: original image; i.e., according to copyright law it is a derived work of
10303: the original image.
10304:
10305: Since Gforth is distributed under the GNU GPL, the newly created image
10306: falls under the GNU GPL, too. In particular, this means that if you
10307: distribute the image, you have to make all of the sources for the image
10308: available, including those you wrote. For details see @ref{License, ,
10309: GNU General Public License (Section 3)}.
10310:
10311: If you create an image with @code{cross} (@pxref{cross.fs}), the image
10312: contains only code compiled from the sources you gave it; if none of
10313: these sources is under the GPL, the terms discussed above do not apply
10314: to the image. However, if your image needs an engine (a gforth binary)
10315: that is under the GPL, you should make sure that you distribute both in
10316: a way that is at most a @emph{mere aggregation}, if you don't want the
10317: terms of the GPL to apply to the image.
10318:
10319: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 10320: @section Image File Background
10321: @cindex image file background
10322:
10323: Our Forth system consists not only of primitives, but also of
10324: definitions written in Forth. Since the Forth compiler itself belongs to
10325: those definitions, it is not possible to start the system with the
10326: primitives and the Forth source alone. Therefore we provide the Forth
1.26 crook 10327: code as an image file in nearly executable form. When Gforth starts up,
10328: a C routine loads the image file into memory, optionally relocates the
10329: addresses, then sets up the memory (stacks etc.) according to
10330: information in the image file, and (finally) starts executing Forth
10331: code.
1.1 anton 10332:
10333: The image file variants represent different compromises between the
10334: goals of making it easy to generate image files and making them
10335: portable.
10336:
10337: @cindex relocation at run-time
1.26 crook 10338: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 10339: run-time. This avoids many of the complications discussed below (image
10340: files are data relocatable without further ado), but costs performance
10341: (one addition per memory access).
10342:
10343: @cindex relocation at load-time
1.26 crook 10344: By contrast, the Gforth loader performs relocation at image load time. The
10345: loader also has to replace tokens that represent primitive calls with the
1.1 anton 10346: appropriate code-field addresses (or code addresses in the case of
10347: direct threading).
10348:
10349: There are three kinds of image files, with different degrees of
10350: relocatability: non-relocatable, data-relocatable, and fully relocatable
10351: image files.
10352:
10353: @cindex image file loader
10354: @cindex relocating loader
10355: @cindex loader for image files
10356: These image file variants have several restrictions in common; they are
10357: caused by the design of the image file loader:
10358:
10359: @itemize @bullet
10360: @item
10361: There is only one segment; in particular, this means, that an image file
10362: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 10363: them). The contents of the stacks are not represented, either.
1.1 anton 10364:
10365: @item
10366: The only kinds of relocation supported are: adding the same offset to
10367: all cells that represent data addresses; and replacing special tokens
10368: with code addresses or with pieces of machine code.
10369:
10370: If any complex computations involving addresses are performed, the
10371: results cannot be represented in the image file. Several applications that
10372: use such computations come to mind:
10373: @itemize @minus
10374: @item
10375: Hashing addresses (or data structures which contain addresses) for table
10376: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
10377: purpose, you will have no problem, because the hash tables are
10378: recomputed automatically when the system is started. If you use your own
10379: hash tables, you will have to do something similar.
10380:
10381: @item
10382: There's a cute implementation of doubly-linked lists that uses
10383: @code{XOR}ed addresses. You could represent such lists as singly-linked
10384: in the image file, and restore the doubly-linked representation on
10385: startup.@footnote{In my opinion, though, you should think thrice before
10386: using a doubly-linked list (whatever implementation).}
10387:
10388: @item
10389: The code addresses of run-time routines like @code{docol:} cannot be
10390: represented in the image file (because their tokens would be replaced by
10391: machine code in direct threaded implementations). As a workaround,
10392: compute these addresses at run-time with @code{>code-address} from the
10393: executions tokens of appropriate words (see the definitions of
10394: @code{docol:} and friends in @file{kernel.fs}).
10395:
10396: @item
10397: On many architectures addresses are represented in machine code in some
10398: shifted or mangled form. You cannot put @code{CODE} words that contain
10399: absolute addresses in this form in a relocatable image file. Workarounds
10400: are representing the address in some relative form (e.g., relative to
10401: the CFA, which is present in some register), or loading the address from
10402: a place where it is stored in a non-mangled form.
10403: @end itemize
10404: @end itemize
10405:
10406: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
10407: @section Non-Relocatable Image Files
10408: @cindex non-relocatable image files
1.26 crook 10409: @cindex image file, non-relocatable
1.1 anton 10410:
10411: These files are simple memory dumps of the dictionary. They are specific
10412: to the executable (i.e., @file{gforth} file) they were created
10413: with. What's worse, they are specific to the place on which the
10414: dictionary resided when the image was created. Now, there is no
10415: guarantee that the dictionary will reside at the same place the next
10416: time you start Gforth, so there's no guarantee that a non-relocatable
10417: image will work the next time (Gforth will complain instead of crashing,
10418: though).
10419:
10420: You can create a non-relocatable image file with
10421:
10422: doc-savesystem
10423:
10424: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
10425: @section Data-Relocatable Image Files
10426: @cindex data-relocatable image files
1.26 crook 10427: @cindex image file, data-relocatable
1.1 anton 10428:
10429: These files contain relocatable data addresses, but fixed code addresses
10430: (instead of tokens). They are specific to the executable (i.e.,
10431: @file{gforth} file) they were created with. For direct threading on some
10432: architectures (e.g., the i386), data-relocatable images do not work. You
10433: get a data-relocatable image, if you use @file{gforthmi} with a
10434: Gforth binary that is not doubly indirect threaded (@pxref{Fully
10435: Relocatable Image Files}).
10436:
10437: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
10438: @section Fully Relocatable Image Files
10439: @cindex fully relocatable image files
1.26 crook 10440: @cindex image file, fully relocatable
1.1 anton 10441:
10442: @cindex @file{kern*.fi}, relocatability
10443: @cindex @file{gforth.fi}, relocatability
10444: These image files have relocatable data addresses, and tokens for code
10445: addresses. They can be used with different binaries (e.g., with and
10446: without debugging) on the same machine, and even across machines with
10447: the same data formats (byte order, cell size, floating point
10448: format). However, they are usually specific to the version of Gforth
10449: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
10450: are fully relocatable.
10451:
10452: There are two ways to create a fully relocatable image file:
10453:
10454: @menu
1.29 crook 10455: * gforthmi:: The normal way
1.1 anton 10456: * cross.fs:: The hard way
10457: @end menu
10458:
10459: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
10460: @subsection @file{gforthmi}
10461: @cindex @file{comp-i.fs}
10462: @cindex @file{gforthmi}
10463:
10464: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 10465: image @i{file} that contains everything you would load by invoking
10466: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 10467: @example
1.29 crook 10468: gforthmi @i{file} @i{options}
1.1 anton 10469: @end example
10470:
10471: E.g., if you want to create an image @file{asm.fi} that has the file
10472: @file{asm.fs} loaded in addition to the usual stuff, you could do it
10473: like this:
10474:
10475: @example
10476: gforthmi asm.fi asm.fs
10477: @end example
10478:
1.27 crook 10479: @file{gforthmi} is implemented as a sh script and works like this: It
10480: produces two non-relocatable images for different addresses and then
10481: compares them. Its output reflects this: first you see the output (if
10482: any) of the two Gforth invocations that produce the nonrelocatable image
10483: files, then you see the output of the comparing program: It displays the
10484: offset used for data addresses and the offset used for code addresses;
1.1 anton 10485: moreover, for each cell that cannot be represented correctly in the
10486: image files, it displays a line like the following one:
10487:
10488: @example
10489: 78DC BFFFFA50 BFFFFA40
10490: @end example
10491:
10492: This means that at offset $78dc from @code{forthstart}, one input image
10493: contains $bffffa50, and the other contains $bffffa40. Since these cells
10494: cannot be represented correctly in the output image, you should examine
10495: these places in the dictionary and verify that these cells are dead
10496: (i.e., not read before they are written).
10497:
1.27 crook 10498: If you type @file{gforthmi} with no arguments, it prints some usage
10499: instructions.
10500:
1.1 anton 10501: @cindex @code{savesystem} during @file{gforthmi}
10502: @cindex @code{bye} during @file{gforthmi}
10503: @cindex doubly indirect threaded code
10504: @cindex environment variable @code{GFORTHD}
10505: @cindex @code{GFORTHD} environment variable
10506: @cindex @code{gforth-ditc}
1.29 crook 10507: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 10508: words @code{savesystem} and @code{bye} must be visible. A special doubly
10509: indirect threaded version of the @file{gforth} executable is used for
10510: creating the nonrelocatable images; you can pass the exact filename of
10511: this executable through the environment variable @code{GFORTHD}
10512: (default: @file{gforth-ditc}); if you pass a version that is not doubly
10513: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 10514: data-relocatable image (because there is no code address offset). The
10515: normal @file{gforth} executable is used for creating the relocatable
10516: image; you can pass the exact filename of this executable through the
10517: environment variable @code{GFORTH}.
1.1 anton 10518:
10519: @node cross.fs, , gforthmi, Fully Relocatable Image Files
10520: @subsection @file{cross.fs}
10521: @cindex @file{cross.fs}
10522: @cindex cross-compiler
10523: @cindex metacompiler
10524:
10525: You can also use @code{cross}, a batch compiler that accepts a Forth-like
10526: programming language. This @code{cross} language has to be documented
10527: yet.
10528:
10529: @cindex target compiler
10530: @code{cross} also allows you to create image files for machines with
10531: different data sizes and data formats than the one used for generating
10532: the image file. You can also use it to create an application image that
10533: does not contain a Forth compiler. These features are bought with
10534: restrictions and inconveniences in programming. E.g., addresses have to
10535: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
10536: order to make the code relocatable.
10537:
10538:
10539: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
10540: @section Stack and Dictionary Sizes
10541: @cindex image file, stack and dictionary sizes
10542: @cindex dictionary size default
10543: @cindex stack size default
10544:
10545: If you invoke Gforth with a command line flag for the size
10546: (@pxref{Invoking Gforth}), the size you specify is stored in the
10547: dictionary. If you save the dictionary with @code{savesystem} or create
10548: an image with @file{gforthmi}, this size will become the default
10549: for the resulting image file. E.g., the following will create a
1.21 crook 10550: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 10551:
10552: @example
10553: gforthmi gforth.fi -m 1M
10554: @end example
10555:
10556: In other words, if you want to set the default size for the dictionary
10557: and the stacks of an image, just invoke @file{gforthmi} with the
10558: appropriate options when creating the image.
10559:
10560: @cindex stack size, cache-friendly
10561: Note: For cache-friendly behaviour (i.e., good performance), you should
10562: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
10563: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
10564: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
10565:
10566: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
10567: @section Running Image Files
10568: @cindex running image files
10569: @cindex invoking image files
10570: @cindex image file invocation
10571:
10572: @cindex -i, invoke image file
10573: @cindex --image file, invoke image file
1.29 crook 10574: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 10575: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
10576: @example
1.29 crook 10577: gforth -i @i{image}
1.1 anton 10578: @end example
10579:
10580: @cindex executable image file
1.26 crook 10581: @cindex image file, executable
1.1 anton 10582: If your operating system supports starting scripts with a line of the
10583: form @code{#! ...}, you just have to type the image file name to start
10584: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 10585: just a convention). I.e., to run Gforth with the image file @i{image},
10586: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 10587: This works because every @code{.fi} file starts with a line of this
10588: format:
10589:
10590: @example
10591: #! /usr/local/bin/gforth-0.4.0 -i
10592: @end example
10593:
10594: The file and pathname for the Gforth engine specified on this line is
10595: the specific Gforth executable that it was built against; i.e. the value
10596: of the environment variable @code{GFORTH} at the time that
10597: @file{gforthmi} was executed.
1.1 anton 10598:
1.27 crook 10599: You can make use of the same shell capability to make a Forth source
10600: file into an executable. For example, if you place this text in a file:
1.26 crook 10601:
10602: @example
10603: #! /usr/local/bin/gforth
10604:
10605: ." Hello, world" CR
10606: bye
10607: @end example
10608:
10609: @noindent
1.27 crook 10610: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 10611: directly from the command line. The sequence @code{#!} is used in two
10612: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 10613: system@footnote{The Unix kernel actually recognises two types of files:
10614: executable files and files of data, where the data is processed by an
10615: interpreter that is specified on the ``interpreter line'' -- the first
10616: line of the file, starting with the sequence #!. There may be a small
10617: limit (e.g., 32) on the number of characters that may be specified on
10618: the interpreter line.} secondly it is treated as a comment character by
10619: Gforth. Because of the second usage, a space is required between
10620: @code{#!} and the path to the executable.
1.27 crook 10621:
10622: The disadvantage of this latter technique, compared with using
10623: @file{gforthmi}, is that it is slower; the Forth source code is compiled
10624: on-the-fly, each time the program is invoked.
10625:
1.26 crook 10626: @comment TODO describe the #! magic with reference to the Power Tools book.
10627:
1.1 anton 10628: doc-#!
10629:
10630: @node Modifying the Startup Sequence, , Running Image Files, Image Files
10631: @section Modifying the Startup Sequence
10632: @cindex startup sequence for image file
10633: @cindex image file initialization sequence
10634: @cindex initialization sequence of image file
10635:
10636: You can add your own initialization to the startup sequence through the
1.26 crook 10637: deferred word @code{'cold}. @code{'cold} is invoked just before the
10638: image-specific command line processing (by default, loading files and
10639: evaluating (@code{-e}) strings) starts.
1.1 anton 10640:
10641: A sequence for adding your initialization usually looks like this:
10642:
10643: @example
10644: :noname
10645: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
10646: ... \ your stuff
10647: ; IS 'cold
10648: @end example
10649:
10650: @cindex turnkey image files
1.26 crook 10651: @cindex image file, turnkey applications
1.1 anton 10652: You can make a turnkey image by letting @code{'cold} execute a word
10653: (your turnkey application) that never returns; instead, it exits Gforth
10654: via @code{bye} or @code{throw}.
10655:
10656: @cindex command-line arguments, access
10657: @cindex arguments on the command line, access
10658: You can access the (image-specific) command-line arguments through the
1.26 crook 10659: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1 anton 10660: access to @code{argv}.
10661:
1.26 crook 10662: If @code{'cold} exits normally, Gforth processes the command-line
10663: arguments as files to be loaded and strings to be evaluated. Therefore,
10664: @code{'cold} should remove the arguments it has used in this case.
10665:
10666: doc-'cold
1.1 anton 10667: doc-argc
10668: doc-argv
10669: doc-arg
10670:
10671:
10672: @c ******************************************************************
1.13 pazsan 10673: @node Engine, Binding to System Library, Image Files, Top
1.1 anton 10674: @chapter Engine
10675: @cindex engine
10676: @cindex virtual machine
10677:
1.26 crook 10678: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 10679: may be helpful for finding your way in the Gforth sources.
10680:
10681: The ideas in this section have also been published in the papers
10682: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
10683: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
10684: Ertl, presented at EuroForth '93; the latter is available at
10685: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
10686:
10687: @menu
10688: * Portability::
10689: * Threading::
10690: * Primitives::
10691: * Performance::
10692: @end menu
10693:
10694: @node Portability, Threading, Engine, Engine
10695: @section Portability
10696: @cindex engine portability
10697:
1.26 crook 10698: An important goal of the Gforth Project is availability across a wide
10699: range of personal machines. fig-Forth, and, to a lesser extent, F83,
10700: achieved this goal by manually coding the engine in assembly language
10701: for several then-popular processors. This approach is very
10702: labor-intensive and the results are short-lived due to progress in
10703: computer architecture.
1.1 anton 10704:
10705: @cindex C, using C for the engine
10706: Others have avoided this problem by coding in C, e.g., Mitch Bradley
10707: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
10708: particularly popular for UNIX-based Forths due to the large variety of
10709: architectures of UNIX machines. Unfortunately an implementation in C
10710: does not mix well with the goals of efficiency and with using
10711: traditional techniques: Indirect or direct threading cannot be expressed
10712: in C, and switch threading, the fastest technique available in C, is
10713: significantly slower. Another problem with C is that it is very
10714: cumbersome to express double integer arithmetic.
10715:
10716: @cindex GNU C for the engine
10717: @cindex long long
10718: Fortunately, there is a portable language that does not have these
10719: limitations: GNU C, the version of C processed by the GNU C compiler
10720: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
10721: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
10722: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
10723: threading possible, its @code{long long} type (@pxref{Long Long, ,
10724: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
10725: double numbers@footnote{Unfortunately, long longs are not implemented
10726: properly on all machines (e.g., on alpha-osf1, long longs are only 64
10727: bits, the same size as longs (and pointers), but they should be twice as
1.4 anton 10728: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1 anton 10729: C Manual}). So, we had to implement doubles in C after all. Still, on
10730: most machines we can use long longs and achieve better performance than
10731: with the emulation package.}. GNU C is available for free on all
10732: important (and many unimportant) UNIX machines, VMS, 80386s running
10733: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
10734: on all these machines.
10735:
10736: Writing in a portable language has the reputation of producing code that
10737: is slower than assembly. For our Forth engine we repeatedly looked at
10738: the code produced by the compiler and eliminated most compiler-induced
10739: inefficiencies by appropriate changes in the source code.
10740:
10741: @cindex explicit register declarations
10742: @cindex --enable-force-reg, configuration flag
10743: @cindex -DFORCE_REG
10744: However, register allocation cannot be portably influenced by the
10745: programmer, leading to some inefficiencies on register-starved
10746: machines. We use explicit register declarations (@pxref{Explicit Reg
10747: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
10748: improve the speed on some machines. They are turned on by using the
10749: configuration flag @code{--enable-force-reg} (@code{gcc} switch
10750: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
10751: machine, but also on the compiler version: On some machines some
10752: compiler versions produce incorrect code when certain explicit register
10753: declarations are used. So by default @code{-DFORCE_REG} is not used.
10754:
10755: @node Threading, Primitives, Portability, Engine
10756: @section Threading
10757: @cindex inner interpreter implementation
10758: @cindex threaded code implementation
10759:
10760: @cindex labels as values
10761: GNU C's labels as values extension (available since @code{gcc-2.0},
10762: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 10763: makes it possible to take the address of @i{label} by writing
10764: @code{&&@i{label}}. This address can then be used in a statement like
10765: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 10766: @code{goto x}.
10767:
1.26 crook 10768: @cindex @code{NEXT}, indirect threaded
1.1 anton 10769: @cindex indirect threaded inner interpreter
10770: @cindex inner interpreter, indirect threaded
1.26 crook 10771: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 10772: @example
10773: cfa = *ip++;
10774: ca = *cfa;
10775: goto *ca;
10776: @end example
10777: @cindex instruction pointer
10778: For those unfamiliar with the names: @code{ip} is the Forth instruction
10779: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
10780: execution token and points to the code field of the next word to be
10781: executed; The @code{ca} (code address) fetched from there points to some
10782: executable code, e.g., a primitive or the colon definition handler
10783: @code{docol}.
10784:
1.26 crook 10785: @cindex @code{NEXT}, direct threaded
1.1 anton 10786: @cindex direct threaded inner interpreter
10787: @cindex inner interpreter, direct threaded
10788: Direct threading is even simpler:
10789: @example
10790: ca = *ip++;
10791: goto *ca;
10792: @end example
10793:
10794: Of course we have packaged the whole thing neatly in macros called
1.26 crook 10795: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 10796:
10797: @menu
10798: * Scheduling::
10799: * Direct or Indirect Threaded?::
10800: * DOES>::
10801: @end menu
10802:
10803: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
10804: @subsection Scheduling
10805: @cindex inner interpreter optimization
10806:
10807: There is a little complication: Pipelined and superscalar processors,
10808: i.e., RISC and some modern CISC machines can process independent
10809: instructions while waiting for the results of an instruction. The
10810: compiler usually reorders (schedules) the instructions in a way that
10811: achieves good usage of these delay slots. However, on our first tries
10812: the compiler did not do well on scheduling primitives. E.g., for
10813: @code{+} implemented as
10814: @example
10815: n=sp[0]+sp[1];
10816: sp++;
10817: sp[0]=n;
10818: NEXT;
10819: @end example
1.26 crook 10820: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1 anton 10821: scheduling. After a little thought the problem becomes clear: The
1.21 crook 10822: compiler cannot know that @code{sp} and @code{ip} point to different
10823: addresses (and the version of @code{gcc} we used would not know it even
10824: if it was possible), so it could not move the load of the cfa above the
10825: store to the TOS. Indeed the pointers could be the same, if code on or
10826: very near the top of stack were executed. In the interest of speed we
10827: chose to forbid this probably unused ``feature'' and helped the compiler
1.26 crook 10828: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21 crook 10829: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1 anton 10830: @example
10831: n=sp[0]+sp[1];
10832: sp++;
10833: NEXT_P1;
10834: sp[0]=n;
10835: NEXT_P2;
10836: @end example
10837: This can be scheduled optimally by the compiler.
10838:
10839: This division can be turned off with the switch @code{-DCISC_NEXT}. This
10840: switch is on by default on machines that do not profit from scheduling
10841: (e.g., the 80386), in order to preserve registers.
10842:
10843: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
10844: @subsection Direct or Indirect Threaded?
10845: @cindex threading, direct or indirect?
10846:
10847: @cindex -DDIRECT_THREADED
10848: Both! After packaging the nasty details in macro definitions we
10849: realized that we could switch between direct and indirect threading by
10850: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
10851: defining a few machine-specific macros for the direct-threading case.
10852: On the Forth level we also offer access words that hide the
10853: differences between the threading methods (@pxref{Threading Words}).
10854:
10855: Indirect threading is implemented completely machine-independently.
10856: Direct threading needs routines for creating jumps to the executable
1.21 crook 10857: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
10858: machine-dependent, but they do not amount to many source lines. Therefore,
10859: even porting direct threading to a new machine requires little effort.
1.1 anton 10860:
10861: @cindex --enable-indirect-threaded, configuration flag
10862: @cindex --enable-direct-threaded, configuration flag
10863: The default threading method is machine-dependent. You can enforce a
10864: specific threading method when building Gforth with the configuration
10865: flag @code{--enable-direct-threaded} or
10866: @code{--enable-indirect-threaded}. Note that direct threading is not
10867: supported on all machines.
10868:
10869: @node DOES>, , Direct or Indirect Threaded?, Threading
10870: @subsection DOES>
10871: @cindex @code{DOES>} implementation
10872:
1.26 crook 10873: @cindex @code{dodoes} routine
10874: @cindex @code{DOES>}-code
1.1 anton 10875: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
10876: the chunk of code executed by every word defined by a
10877: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
10878: the Forth code to be executed, i.e. the code after the
1.26 crook 10879: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1 anton 10880:
1.21 crook 10881: In fig-Forth the code field points directly to the @code{dodoes} and the
1.26 crook 10882: @code{DOES>}code address is stored in the cell after the code address (i.e. at
1.29 crook 10883: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1 anton 10884: the Forth-79 and all later standards, because in fig-Forth this address
10885: lies in the body (which is illegal in these standards). However, by
10886: making the code field larger for all words this solution becomes legal
10887: again. We use this approach for the indirect threaded version and for
10888: direct threading on some machines. Leaving a cell unused in most words
10889: is a bit wasteful, but on the machines we are targeting this is hardly a
10890: problem. The other reason for having a code field size of two cells is
10891: to avoid having different image files for direct and indirect threaded
10892: systems (direct threaded systems require two-cell code fields on many
10893: machines).
10894:
1.26 crook 10895: @cindex @code{DOES>}-handler
1.1 anton 10896: The other approach is that the code field points or jumps to the cell
1.26 crook 10897: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
10898: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
10899: @code{DOES>}-code address by computing the code address, i.e., the address of
1.1 anton 10900: the jump to dodoes, and add the length of that jump field. A variant of
10901: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
10902: return address (which can be found in the return register on RISCs) is
1.26 crook 10903: the @code{DOES>}-code address. Since the two cells available in the code field
1.1 anton 10904: are used up by the jump to the code address in direct threading on many
10905: architectures, we use this approach for direct threading on these
10906: architectures. We did not want to add another cell to the code field.
10907:
10908: @node Primitives, Performance, Threading, Engine
10909: @section Primitives
10910: @cindex primitives, implementation
10911: @cindex virtual machine instructions, implementation
10912:
10913: @menu
10914: * Automatic Generation::
10915: * TOS Optimization::
10916: * Produced code::
10917: @end menu
10918:
10919: @node Automatic Generation, TOS Optimization, Primitives, Primitives
10920: @subsection Automatic Generation
10921: @cindex primitives, automatic generation
10922:
10923: @cindex @file{prims2x.fs}
10924: Since the primitives are implemented in a portable language, there is no
10925: longer any need to minimize the number of primitives. On the contrary,
10926: having many primitives has an advantage: speed. In order to reduce the
10927: number of errors in primitives and to make programming them easier, we
10928: provide a tool, the primitive generator (@file{prims2x.fs}), that
10929: automatically generates most (and sometimes all) of the C code for a
10930: primitive from the stack effect notation. The source for a primitive
10931: has the following form:
10932:
10933: @cindex primitive source format
10934: @format
1.29 crook 10935: @i{Forth-name} @i{stack-effect} @i{category} [@i{pronounc.}]
10936: [@code{""}@i{glossary entry}@code{""}]
10937: @i{C code}
1.1 anton 10938: [@code{:}
1.29 crook 10939: @i{Forth code}]
1.1 anton 10940: @end format
10941:
10942: The items in brackets are optional. The category and glossary fields
10943: are there for generating the documentation, the Forth code is there
10944: for manual implementations on machines without GNU C. E.g., the source
10945: for the primitive @code{+} is:
10946: @example
10947: + n1 n2 -- n core plus
10948: n = n1+n2;
10949: @end example
10950:
10951: This looks like a specification, but in fact @code{n = n1+n2} is C
10952: code. Our primitive generation tool extracts a lot of information from
10953: the stack effect notations@footnote{We use a one-stack notation, even
10954: though we have separate data and floating-point stacks; The separate
10955: notation can be generated easily from the unified notation.}: The number
10956: of items popped from and pushed on the stack, their type, and by what
10957: name they are referred to in the C code. It then generates a C code
10958: prelude and postlude for each primitive. The final C code for @code{+}
10959: looks like this:
10960:
10961: @example
10962: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
10963: /* */ /* documentation */
10964: @{
10965: DEF_CA /* definition of variable ca (indirect threading) */
10966: Cell n1; /* definitions of variables */
10967: Cell n2;
10968: Cell n;
10969: n1 = (Cell) sp[1]; /* input */
10970: n2 = (Cell) TOS;
10971: sp += 1; /* stack adjustment */
10972: NAME("+") /* debugging output (with -DDEBUG) */
10973: @{
10974: n = n1+n2; /* C code taken from the source */
10975: @}
10976: NEXT_P1; /* NEXT part 1 */
10977: TOS = (Cell)n; /* output */
10978: NEXT_P2; /* NEXT part 2 */
10979: @}
10980: @end example
10981:
10982: This looks long and inefficient, but the GNU C compiler optimizes quite
10983: well and produces optimal code for @code{+} on, e.g., the R3000 and the
10984: HP RISC machines: Defining the @code{n}s does not produce any code, and
10985: using them as intermediate storage also adds no cost.
10986:
1.26 crook 10987: There are also other optimizations that are not illustrated by this
10988: example: assignments between simple variables are usually for free (copy
1.1 anton 10989: propagation). If one of the stack items is not used by the primitive
10990: (e.g. in @code{drop}), the compiler eliminates the load from the stack
10991: (dead code elimination). On the other hand, there are some things that
10992: the compiler does not do, therefore they are performed by
10993: @file{prims2x.fs}: The compiler does not optimize code away that stores
10994: a stack item to the place where it just came from (e.g., @code{over}).
10995:
10996: While programming a primitive is usually easy, there are a few cases
10997: where the programmer has to take the actions of the generator into
10998: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 10999: fall through to @code{NEXT}.
1.1 anton 11000:
11001: @node TOS Optimization, Produced code, Automatic Generation, Primitives
11002: @subsection TOS Optimization
11003: @cindex TOS optimization for primitives
11004: @cindex primitives, keeping the TOS in a register
11005:
11006: An important optimization for stack machine emulators, e.g., Forth
11007: engines, is keeping one or more of the top stack items in
1.29 crook 11008: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
11009: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 11010: @itemize @bullet
11011: @item
1.29 crook 11012: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 11013: due to fewer loads from and stores to the stack.
1.29 crook 11014: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
11015: @i{y<n}, due to additional moves between registers.
1.1 anton 11016: @end itemize
11017:
11018: @cindex -DUSE_TOS
11019: @cindex -DUSE_NO_TOS
11020: In particular, keeping one item in a register is never a disadvantage,
11021: if there are enough registers. Keeping two items in registers is a
11022: disadvantage for frequent words like @code{?branch}, constants,
11023: variables, literals and @code{i}. Therefore our generator only produces
11024: code that keeps zero or one items in registers. The generated C code
11025: covers both cases; the selection between these alternatives is made at
11026: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
11027: code for @code{+} is just a simple variable name in the one-item case,
11028: otherwise it is a macro that expands into @code{sp[0]}. Note that the
11029: GNU C compiler tries to keep simple variables like @code{TOS} in
11030: registers, and it usually succeeds, if there are enough registers.
11031:
11032: @cindex -DUSE_FTOS
11033: @cindex -DUSE_NO_FTOS
11034: The primitive generator performs the TOS optimization for the
11035: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
11036: operations the benefit of this optimization is even larger:
11037: floating-point operations take quite long on most processors, but can be
11038: performed in parallel with other operations as long as their results are
11039: not used. If the FP-TOS is kept in a register, this works. If
11040: it is kept on the stack, i.e., in memory, the store into memory has to
11041: wait for the result of the floating-point operation, lengthening the
11042: execution time of the primitive considerably.
11043:
11044: The TOS optimization makes the automatic generation of primitives a
11045: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
11046: @code{TOS} is not sufficient. There are some special cases to
11047: consider:
11048: @itemize @bullet
11049: @item In the case of @code{dup ( w -- w w )} the generator must not
11050: eliminate the store to the original location of the item on the stack,
11051: if the TOS optimization is turned on.
11052: @item Primitives with stack effects of the form @code{--}
1.29 crook 11053: @i{out1}...@i{outy} must store the TOS to the stack at the start.
11054: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 11055: must load the TOS from the stack at the end. But for the null stack
11056: effect @code{--} no stores or loads should be generated.
11057: @end itemize
11058:
11059: @node Produced code, , TOS Optimization, Primitives
11060: @subsection Produced code
11061: @cindex primitives, assembly code listing
11062:
11063: @cindex @file{engine.s}
11064: To see what assembly code is produced for the primitives on your machine
11065: with your compiler and your flag settings, type @code{make engine.s} and
11066: look at the resulting file @file{engine.s}.
11067:
11068: @node Performance, , Primitives, Engine
11069: @section Performance
11070: @cindex performance of some Forth interpreters
11071: @cindex engine performance
11072: @cindex benchmarking Forth systems
11073: @cindex Gforth performance
11074:
11075: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
11076: impossible to write a significantly faster engine.
11077:
11078: On register-starved machines like the 386 architecture processors
11079: improvements are possible, because @code{gcc} does not utilize the
11080: registers as well as a human, even with explicit register declarations;
11081: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
11082: and hand-tuned it for the 486; this system is 1.19 times faster on the
11083: Sieve benchmark on a 486DX2/66 than Gforth compiled with
11084: @code{gcc-2.6.3} with @code{-DFORCE_REG}.
11085:
11086: @cindex Win32Forth performance
11087: @cindex NT Forth performance
11088: @cindex eforth performance
11089: @cindex ThisForth performance
11090: @cindex PFE performance
11091: @cindex TILE performance
11092: However, this potential advantage of assembly language implementations
11093: is not necessarily realized in complete Forth systems: We compared
11094: Gforth (direct threaded, compiled with @code{gcc-2.6.3} and
11095: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
11096: 1994) and Eforth (with and without peephole (aka pinhole) optimization
11097: of the threaded code); all these systems were written in assembly
11098: language. We also compared Gforth with three systems written in C:
11099: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
11100: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21 crook 11101: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
11102: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1 anton 11103: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
11104: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
11105: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
11106: 486DX2/66 with similar memory performance under Windows NT. Marcel
11107: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
11108: added the peephole optimizer, ran the benchmarks and reported the
11109: results.
11110:
11111: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
11112: matrix multiplication come from the Stanford integer benchmarks and have
11113: been translated into Forth by Martin Fraeman; we used the versions
11114: included in the TILE Forth package, but with bigger data set sizes; and
11115: a recursive Fibonacci number computation for benchmarking calling
11116: performance. The following table shows the time taken for the benchmarks
11117: scaled by the time taken by Gforth (in other words, it shows the speedup
11118: factor that Gforth achieved over the other systems).
11119:
11120: @example
11121: relative Win32- NT eforth This-
11122: time Gforth Forth Forth eforth +opt PFE Forth TILE
11123: sieve 1.00 1.39 1.14 1.39 0.85 1.58 3.18 8.58
11124: bubble 1.00 1.31 1.41 1.48 0.88 1.50 3.88
11125: matmul 1.00 1.47 1.35 1.46 0.74 1.58 4.09
11126: fib 1.00 1.52 1.34 1.22 0.86 1.74 2.99 4.30
11127: @end example
11128:
1.26 crook 11129: You may be quite surprised by the good performance of Gforth when
11130: compared with systems written in assembly language. One important reason
11131: for the disappointing performance of these other systems is probably
11132: that they are not written optimally for the 486 (e.g., they use the
11133: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
11134: but costly method for relocating the Forth image: like @code{cforth}, it
11135: computes the actual addresses at run time, resulting in two address
11136: computations per @code{NEXT} (@pxref{Image File Background}).
11137:
11138: Only Eforth with the peephole optimizer has a performance that is
11139: comparable to Gforth. The speedups achieved with peephole optimization
11140: of threaded code are quite remarkable. Adding a peephole optimizer to
11141: Gforth should cause similar speedups.
1.1 anton 11142:
11143: The speedup of Gforth over PFE, ThisForth and TILE can be easily
11144: explained with the self-imposed restriction of the latter systems to
11145: standard C, which makes efficient threading impossible (however, the
1.4 anton 11146: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 11147: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
11148: Moreover, current C compilers have a hard time optimizing other aspects
11149: of the ThisForth and the TILE source.
11150:
1.26 crook 11151: The performance of Gforth on 386 architecture processors varies widely
11152: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
11153: allocate any of the virtual machine registers into real machine
11154: registers by itself and would not work correctly with explicit register
11155: declarations, giving a 1.3 times slower engine (on a 486DX2/66 running
11156: the Sieve) than the one measured above.
1.1 anton 11157:
1.26 crook 11158: Note that there have been several releases of Win32Forth since the
11159: release presented here, so the results presented above may have little
1.1 anton 11160: predictive value for the performance of Win32Forth today.
11161:
11162: @cindex @file{Benchres}
11163: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
11164: Maierhofer (presented at EuroForth '95), an indirect threaded version of
11165: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
11166: version of Gforth is 2%@minus{}8% slower on a 486 than the direct
11167: threaded version used here. The paper available at
11168: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
11169: it also contains numbers for some native code systems. You can find a
11170: newer version of these measurements at
11171: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
11172: find numbers for Gforth on various machines in @file{Benchres}.
11173:
1.26 crook 11174: @c ******************************************************************
1.13 pazsan 11175: @node Binding to System Library, Cross Compiler, Engine, Top
1.14 pazsan 11176: @chapter Binding to System Library
1.13 pazsan 11177:
11178: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14 pazsan 11179: @chapter Cross Compiler
1.13 pazsan 11180:
11181: Cross Compiler
11182:
11183: @menu
11184: * Using the Cross Compiler::
11185: * How the Cross Compiler Works::
11186: @end menu
11187:
1.21 crook 11188: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 11189: @section Using the Cross Compiler
1.13 pazsan 11190:
1.21 crook 11191: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 11192: @section How the Cross Compiler Works
1.13 pazsan 11193:
11194: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 11195: @appendix Bugs
1.1 anton 11196: @cindex bug reporting
11197:
1.21 crook 11198: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 11199:
11200: If you find a bug, please send a bug report to
1.33 anton 11201: @email{bug-gforth@@gnu.org}. A bug report should include this
1.21 crook 11202: information:
11203:
11204: @itemize @bullet
11205: @item
11206: The Gforth version used (it is announced at the start of an
11207: interactive Gforth session).
11208: @item
11209: The machine and operating system (on Unix
11210: systems @code{uname -a} will report this information).
11211: @item
11212: The installation options (send the file @file{config.status}).
11213: @item
11214: A complete list of changes (if any) you (or your installer) have made to the
11215: Gforth sources.
11216: @item
11217: A program (or a sequence of keyboard commands) that reproduces the bug.
11218: @item
11219: A description of what you think constitutes the buggy behaviour.
11220: @end itemize
1.1 anton 11221:
11222: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
11223: to Report Bugs, gcc.info, GNU C Manual}.
11224:
11225:
1.21 crook 11226: @node Origin, Forth-related information, Bugs, Top
11227: @appendix Authors and Ancestors of Gforth
1.1 anton 11228:
11229: @section Authors and Contributors
11230: @cindex authors of Gforth
11231: @cindex contributors to Gforth
11232:
11233: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
11234: Ertl. The third major author was Jens Wilke. Lennart Benschop (who was
11235: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
11236: with their continuous feedback. Lennart Benshop contributed
11237: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
11238: support for calling C libraries. Helpful comments also came from Paul
11239: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.12 anton 11240: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
11241: release of Gforth-0.2.1 there were also helpful comments from many
11242: others; thank you all, sorry for not listing you here (but digging
1.23 crook 11243: through my mailbox to extract your names is on my to-do list). Since the
11244: release of Gforth-0.4.0 Neal Crook worked on the manual.
1.1 anton 11245:
11246: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
11247: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 11248: was developed across the Internet, and its authors did not meet
1.20 pazsan 11249: physically for the first 4 years of development.
1.1 anton 11250:
11251: @section Pedigree
1.26 crook 11252: @cindex pedigree of Gforth
1.1 anton 11253:
1.20 pazsan 11254: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1 anton 11255: Dirk Zoller) will cross-fertilize each other. Of course, a significant
11256: part of the design of Gforth was prescribed by ANS Forth.
11257:
1.20 pazsan 11258: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 11259: 32 bit native code version of VolksForth for the Atari ST, written
11260: mostly by Dietrich Weineck.
11261:
11262: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
11263: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
11264: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
11265:
11266: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
11267: Forth-83 standard. !! Pedigree? When?
11268:
11269: A team led by Bill Ragsdale implemented fig-Forth on many processors in
11270: 1979. Robert Selzer and Bill Ragsdale developed the original
11271: implementation of fig-Forth for the 6502 based on microForth.
11272:
11273: The principal architect of microForth was Dean Sanderson. microForth was
11274: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
11275: the 1802, and subsequently implemented on the 8080, the 6800 and the
11276: Z80.
11277:
11278: All earlier Forth systems were custom-made, usually by Charles Moore,
11279: who discovered (as he puts it) Forth during the late 60s. The first full
11280: Forth existed in 1971.
11281:
11282: A part of the information in this section comes from @cite{The Evolution
11283: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
11284: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
11285: Notices 28(3), 1993. You can find more historical and genealogical
11286: information about Forth there.
11287:
1.21 crook 11288: @node Forth-related information, Word Index, Origin, Top
11289: @appendix Other Forth-related information
11290: @cindex Forth-related information
11291:
11292: @menu
11293: * Internet resources::
11294: * Books::
11295: * The Forth Interest Group::
11296: * Conferences::
11297: @end menu
11298:
11299:
11300: @node Internet resources, Books, Forth-related information, Forth-related information
11301: @section Internet resources
1.26 crook 11302: @cindex internet resources
1.21 crook 11303:
11304: @cindex comp.lang.forth
11305: @cindex frequently asked questions
11306: There is an active newsgroup (comp.lang.forth) discussing Forth and
11307: Forth-related issues. A frequently-asked-questions (FAQ) list
11308: is posted to the newsgroup regulary, and archived at these sites:
11309:
11310: @itemize @bullet
11311: @item
11312: @url{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
11313: @item
11314: @url{ftp://ftp.forth.org/pub/Forth/FAQ/}
11315: @end itemize
11316:
11317: The FAQ list should be considered mandatory reading before posting to
11318: the newsgroup.
11319:
11320: Here are some other web sites holding Forth-related material:
11321:
11322: @itemize @bullet
11323: @item
11324: @url{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
11325: @item
11326: @url{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
11327: @item
11328: @url{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
11329: @item
11330: @url{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
11331: Research page, including links to the Journal of Forth Application and
11332: Research (JFAR) and a searchable Forth bibliography.
11333: @end itemize
11334:
11335:
11336: @node Books, The Forth Interest Group, Internet resources, Forth-related information
11337: @section Books
1.26 crook 11338: @cindex books on Forth
1.21 crook 11339:
11340: As the Standard is relatively new, there are not many books out yet. It
11341: is not recommended to learn Forth by using Gforth and a book that is not
11342: written for ANS Forth, as you will not know your mistakes from the
11343: deviations of the book. However, books based on the Forth-83 standard
11344: should be ok, because ANS Forth is primarily an extension of Forth-83.
11345:
11346: @cindex standard document for ANS Forth
11347: @cindex ANS Forth document
11348: The definite reference if you want to write ANS Forth programs is, of
1.26 crook 11349: course, the ANS Forth document. It is available in printed form from the
1.21 crook 11350: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
11351: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
11352: $200. You can also get it from Global Engineering Documents (Tel.: USA
11353: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
11354:
11355: @cite{dpANS6}, the last draft of the standard, which was then submitted
11356: to ANSI for publication is available electronically and for free in some
11357: MS Word format, and it has been converted to HTML
11358: (@url{http://www.taygeta.com/forth/dpans.html}; this is my favourite
11359: format); this HTML version also includes the answers to Requests for
11360: Interpretation (RFIs). Some pointers to these versions can be found
11361: through @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
11362:
1.26 crook 11363: @cindex introductory book on Forth
11364: @cindex book on Forth, introductory
1.21 crook 11365: @cindex Woehr, Jack: @cite{Forth: The New Model}
11366: @cindex @cite{Forth: The new model} (book)
11367: @cite{Forth: The New Model} by Jack Woehr (Prentice-Hall, 1993) is an
11368: introductory book based on a draft version of the standard. It does not
11369: cover the whole standard. It also contains interesting background
11370: information (Jack Woehr was in the ANS Forth Technical Committee). It is
11371: not appropriate for complete newbies, but programmers experienced in
11372: other languages should find it ok.
11373:
11374: @cindex Conklin, Edward K., and Elizabeth Rather: @cite{Forth Programmer's Handbook}
11375: @cindex Rather, Elizabeth and Edward K. Conklin: @cite{Forth Programmer's Handbook}
11376: @cindex @cite{Forth Programmer's Handbook} (book)
11377: @cite{Forth Programmer's Handbook} by Edward K. Conklin, Elizabeth
11378: D. Rather and the technical staff of Forth, Inc. (Forth, Inc., 1997;
11379: ISBN 0-9662156-0-5) contains little introductory material. The majority
11380: of the book is similar to @ref{Words}, but the book covers most of the
11381: standard words and some non-standard words (whereas this manual is
11382: quite incomplete). In addition, the book contains a chapter on
11383: programming style. The major drawback of this book is that it usually
11384: does not identify what is standard and what is specific to the Forth
11385: system described in the book (probably one of Forth, Inc.'s systems).
11386: Fortunately, many of the non-standard programming practices described in
11387: the book work in Gforth, too. Still, this drawback makes the book
11388: hardly more useful than a pre-ANS book.
11389:
11390: @node The Forth Interest Group, Conferences, Books, Forth-related information
11391: @section The Forth Interest Group
11392: @cindex Forth interest group (FIG)
11393:
11394: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26 crook 11395: member-supported organisation. It publishes a regular magazine,
11396: @var{FORTH Dimensions}, and offers other benefits of membership. You can
11397: contact the FIG through their office email address:
11398: @email{office@@forth.org} or by visiting their web site at
11399: @url{http://www.forth.org/}. This web site also includes links to FIG
11400: chapters in other countries and American cities
1.21 crook 11401: (@url{http://www.forth.org/chapters.html}).
11402:
11403: @node Conferences, , The Forth Interest Group, Forth-related information
11404: @section Conferences
11405: @cindex Conferences
11406:
11407: There are several regular conferences related to Forth. They are all
1.26 crook 11408: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
11409: news group:
1.21 crook 11410:
11411: @itemize @bullet
11412: @item
11413: FORML -- the Forth modification laboratory convenes every year near
11414: Monterey, California.
11415: @item
11416: The Rochester Forth Conference -- an annual conference traditionally
11417: held in Rochester, New York.
11418: @item
11419: EuroForth -- this European conference takes place annually.
11420: @end itemize
11421:
11422:
11423: @node Word Index, Concept Index, Forth-related information, Top
1.1 anton 11424: @unnumbered Word Index
11425:
1.26 crook 11426: This index is a list of Forth words that have ``glossary'' entries
11427: within this manual. Each word is listed with its stack effect and
11428: wordset.
1.1 anton 11429:
11430: @printindex fn
11431:
11432: @node Concept Index, , Word Index, Top
11433: @unnumbered Concept and Word Index
11434:
1.26 crook 11435: Not all entries listed in this index are present verbatim in the
11436: text. This index also duplicates, in abbreviated form, all of the words
11437: listed in the Word Index (only the names are listed for the words here).
1.1 anton 11438:
11439: @printindex cp
11440:
11441: @contents
11442: @bye
11443:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>