Annotation of gforth/doc/gforth.ds, revision 1.41
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.36 anton 11: @c Not an improvement IMO - anton
12: @c and anyway, this should be taken up
13: @c with Karl Berry (the texinfo guy) - anton
1.29 crook 14: @comment .. would be useful to have a word that identified all deferred words
15: @comment should semantics stuff in intro be moved to another section
16:
1.28 crook 17:
1.1 anton 18: @comment %**start of header (This is for running Texinfo on a region.)
19: @setfilename gforth.info
20: @settitle Gforth Manual
21: @dircategory GNU programming tools
22: @direntry
23: * Gforth: (gforth). A fast interpreter for the Forth language.
24: @end direntry
25: @comment @setchapternewpage odd
1.29 crook 26: @comment TODO this gets left in by HTML converter
1.12 anton 27: @macro progstyle {}
28: Programming style note:
1.3 anton 29: @end macro
1.1 anton 30: @comment %**end of header (This is for running Texinfo on a region.)
31:
1.29 crook 32:
33: @comment ----------------------------------------------------------
34: @comment macros for beautifying glossary entries
35: @comment if these are used, need to strip them out for HTML converter
36: @comment else they get repeated verbatim in HTML output.
37: @comment .. not working yet.
38:
39: @macro GLOSS-START {}
40: @iftex
41: @ninerm
42: @end iftex
43: @end macro
44:
45: @macro GLOSS-END {}
46: @iftex
47: @rm
48: @end iftex
49: @end macro
50:
51: @comment ----------------------------------------------------------
52:
53:
1.10 anton 54: @include version.texi
55:
1.1 anton 56: @ifinfo
1.11 anton 57: This file documents Gforth @value{VERSION}
1.1 anton 58:
1.26 crook 59: Copyright @copyright{} 1995-1999 Free Software Foundation, Inc.
1.1 anton 60:
61: Permission is granted to make and distribute verbatim copies of
62: this manual provided the copyright notice and this permission notice
63: are preserved on all copies.
64:
65: @ignore
66: Permission is granted to process this file through TeX and print the
67: results, provided the printed document carries a copying permission
68: notice identical to this one except for the removal of this paragraph
69: (this paragraph not being relevant to the printed manual).
70:
71: @end ignore
72: Permission is granted to copy and distribute modified versions of this
73: manual under the conditions for verbatim copying, provided also that the
74: sections entitled "Distribution" and "General Public License" are
75: included exactly as in the original, and provided that the entire
76: resulting derived work is distributed under the terms of a permission
77: notice identical to this one.
78:
79: Permission is granted to copy and distribute translations of this manual
80: into another language, under the above conditions for modified versions,
81: except that the sections entitled "Distribution" and "General Public
82: License" may be included in a translation approved by the author instead
83: of in the original English.
84: @end ifinfo
85:
86: @finalout
87: @titlepage
88: @sp 10
89: @center @titlefont{Gforth Manual}
90: @sp 2
1.11 anton 91: @center for version @value{VERSION}
1.1 anton 92: @sp 2
1.34 anton 93: @center Neal Crook
1.1 anton 94: @center Anton Ertl
1.6 pazsan 95: @center Bernd Paysan
1.5 anton 96: @center Jens Wilke
1.1 anton 97: @sp 3
1.29 crook 98: @center This manual is permanently under construction and was last updated on 04-May-1999
1.1 anton 99:
100: @comment The following two commands start the copyright page.
101: @page
102: @vskip 0pt plus 1filll
1.29 crook 103: Copyright @copyright{} 1995--1999 Free Software Foundation, Inc.
1.1 anton 104:
105: @comment !! Published by ... or You can get a copy of this manual ...
106:
107: Permission is granted to make and distribute verbatim copies of
108: this manual provided the copyright notice and this permission notice
109: are preserved on all copies.
110:
111: Permission is granted to copy and distribute modified versions of this
112: manual under the conditions for verbatim copying, provided also that the
113: sections entitled "Distribution" and "General Public License" are
114: included exactly as in the original, and provided that the entire
115: resulting derived work is distributed under the terms of a permission
116: notice identical to this one.
117:
118: Permission is granted to copy and distribute translations of this manual
119: into another language, under the above conditions for modified versions,
120: except that the sections entitled "Distribution" and "General Public
121: License" may be included in a translation approved by the author instead
122: of in the original English.
123: @end titlepage
124:
125:
126: @node Top, License, (dir), (dir)
127: @ifinfo
128: Gforth is a free implementation of ANS Forth available on many
1.11 anton 129: personal machines. This manual corresponds to version @value{VERSION}.
1.1 anton 130: @end ifinfo
131:
132: @menu
1.21 crook 133: * License:: The GPL
1.26 crook 134: * Goals:: About the Gforth Project
1.29 crook 135: * Gforth Environment:: Starting (and exiting) Gforth
1.21 crook 136: * Introduction:: An introduction to ANS Forth
1.1 anton 137: * Words:: Forth words available in Gforth
1.24 anton 138: * Error messages:: How to interpret them
1.1 anton 139: * Tools:: Programming tools
140: * ANS conformance:: Implementation-defined options etc.
141: * Model:: The abstract machine of Gforth
142: * Integrating Gforth:: Forth as scripting language for applications
143: * Emacs and Gforth:: The Gforth Mode
144: * Image Files:: @code{.fi} files contain compiled code
145: * Engine:: The inner interpreter and the primitives
1.24 anton 146: * Binding to System Library::
1.13 pazsan 147: * Cross Compiler:: The Cross Compiler
1.1 anton 148: * Bugs:: How to report them
149: * Origin:: Authors and ancestors of Gforth
1.21 crook 150: * Forth-related information:: Books and places to look on the WWW
1.1 anton 151: * Word Index:: An item for each Forth word
1.41 ! anton 152: * Name Index:: Forth words, only names listed
1.1 anton 153: * Concept Index:: A menu covering many topics
1.12 anton 154:
1.41 ! anton 155: @detailmenu
! 156: --- The Detailed Node Listing ---
1.12 anton 157:
1.26 crook 158: Goals of Gforth
159:
160: * Gforth Extensions Sinful?::
161:
1.29 crook 162: Gforth Environment
163:
1.32 anton 164: * Invoking Gforth:: Getting in
165: * Leaving Gforth:: Getting out
166: * Command-line editing::
1.29 crook 167: * Upper and lower case::
1.32 anton 168: * Environment variables:: ..that affect how Gforth starts up
169: * Gforth Files:: What gets installed and where
1.29 crook 170:
1.24 anton 171: An Introduction to ANS Forth
172:
173: * Introducing the Text Interpreter::
174: * Stacks and Postfix notation::
175: * Your first definition::
176: * How does that work?::
177: * Forth is written in Forth::
178: * Review - elements of a Forth system::
1.29 crook 179: * Where to go next::
1.24 anton 180: * Exercises::
181:
1.12 anton 182: Forth Words
183:
184: * Notation::
1.21 crook 185: * Comments::
186: * Boolean Flags::
1.12 anton 187: * Arithmetic::
188: * Stack Manipulation::
189: * Memory::
190: * Control Structures::
191: * Defining Words::
1.21 crook 192: * The Text Interpreter::
1.12 anton 193: * Tokens for Words::
1.21 crook 194: * Word Lists::
195: * Environmental Queries::
1.12 anton 196: * Files::
197: * Blocks::
198: * Other I/O::
199: * Programming Tools::
200: * Assembler and Code Words::
201: * Threading Words::
1.26 crook 202: * Locals::
203: * Structures::
204: * Object-oriented Forth::
1.21 crook 205: * Passing Commands to the OS::
206: * Miscellaneous Words::
1.12 anton 207:
208: Arithmetic
209:
210: * Single precision::
211: * Bitwise operations::
1.21 crook 212: * Double precision:: Double-cell integer arithmetic
213: * Numeric comparison::
1.32 anton 214: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 215: * Floating Point::
216:
217: Stack Manipulation
218:
219: * Data stack::
220: * Floating point stack::
221: * Return stack::
222: * Locals stack::
223: * Stack pointer manipulation::
224:
225: Memory
226:
1.32 anton 227: * Memory model::
228: * Dictionary allocation::
229: * Heap Allocation::
230: * Memory Access::
231: * Address arithmetic::
232: * Memory Blocks::
1.12 anton 233:
234: Control Structures
235:
1.41 ! anton 236: * Selection:: IF ... ELSE ... ENDIF
! 237: * Simple Loops:: BEGIN ...
1.32 anton 238: * Counted Loops:: DO
239: * Arbitrary control structures::
240: * Calls and returns::
1.12 anton 241: * Exception Handling::
242:
243: Defining Words
244:
1.32 anton 245: * Simple Defining Words:: Variables, values and constants
246: * Colon Definitions::
247: * User-defined Defining Words::
248: * Supplying names::
249: * Interpretation and Compilation Semantics::
1.12 anton 250:
1.21 crook 251: The Text Interpreter
252:
1.29 crook 253: * Input Sources::
1.21 crook 254: * Number Conversion::
255: * Interpret/Compile states::
256: * Literals::
257: * Interpreter Directives::
258:
1.26 crook 259: Word Lists
260:
261: * Why use word lists?::
262: * Word list examples::
263:
264: Files
265:
266: * Forth source files::
267: * General files::
268: * Search Paths::
269: * Forth Search Paths::
270: * General Search Paths::
271:
272: Other I/O
273:
1.32 anton 274: * Simple numeric output:: Predefined formats
275: * Formatted numeric output:: Formatted (pictured) output
276: * String Formats:: How Forth stores strings in memory
277: * Displaying characters and strings:: Other stuff
278: * Input:: Input
1.26 crook 279:
280: Programming Tools
281:
282: * Debugging:: Simple and quick.
283: * Assertions:: Making your programs self-checking.
284: * Singlestep Debugger:: Executing your program word by word.
285:
286: Locals
287:
288: * Gforth locals::
289: * ANS Forth locals::
290:
291: Gforth locals
292:
293: * Where are locals visible by name?::
294: * How long do locals live?::
295: * Programming Style::
296: * Implementation::
297:
1.12 anton 298: Structures
299:
300: * Why explicit structure support?::
301: * Structure Usage::
302: * Structure Naming Convention::
303: * Structure Implementation::
304: * Structure Glossary::
305:
306: Object-oriented Forth
307:
1.24 anton 308: * Why object-oriented programming?::
309: * Object-Oriented Terminology::
310: * Objects::
311: * OOF::
312: * Mini-OOF::
1.23 crook 313: * Comparison with other object models::
1.12 anton 314:
1.24 anton 315: The @file{objects.fs} model
1.12 anton 316:
317: * Properties of the Objects model::
318: * Basic Objects Usage::
1.41 ! anton 319: * The Objects base class::
1.12 anton 320: * Creating objects::
321: * Object-Oriented Programming Style::
322: * Class Binding::
323: * Method conveniences::
324: * Classes and Scoping::
1.41 ! anton 325: * Dividing classes::
1.12 anton 326: * Object Interfaces::
327: * Objects Implementation::
328: * Objects Glossary::
329:
1.24 anton 330: The @file{oof.fs} model
1.12 anton 331:
332: * Properties of the OOF model::
333: * Basic OOF Usage::
1.23 crook 334: * The OOF base class::
1.12 anton 335: * Class Declaration::
336: * Class Implementation::
337:
1.24 anton 338: The @file{mini-oof.fs} model
1.23 crook 339:
340: * Basic Mini-OOF Usage::
341: * Mini-OOF Example::
342: * Mini-OOF Implementation::
343:
1.12 anton 344: Tools
345:
346: * ANS Report:: Report the words used, sorted by wordset.
347:
348: ANS conformance
349:
350: * The Core Words::
351: * The optional Block word set::
352: * The optional Double Number word set::
353: * The optional Exception word set::
354: * The optional Facility word set::
355: * The optional File-Access word set::
356: * The optional Floating-Point word set::
357: * The optional Locals word set::
358: * The optional Memory-Allocation word set::
359: * The optional Programming-Tools word set::
360: * The optional Search-Order word set::
361:
362: The Core Words
363:
364: * core-idef:: Implementation Defined Options
365: * core-ambcond:: Ambiguous Conditions
366: * core-other:: Other System Documentation
367:
368: The optional Block word set
369:
370: * block-idef:: Implementation Defined Options
371: * block-ambcond:: Ambiguous Conditions
372: * block-other:: Other System Documentation
373:
374: The optional Double Number word set
375:
376: * double-ambcond:: Ambiguous Conditions
377:
378: The optional Exception word set
379:
380: * exception-idef:: Implementation Defined Options
381:
382: The optional Facility word set
383:
384: * facility-idef:: Implementation Defined Options
385: * facility-ambcond:: Ambiguous Conditions
386:
387: The optional File-Access word set
388:
389: * file-idef:: Implementation Defined Options
390: * file-ambcond:: Ambiguous Conditions
391:
392: The optional Floating-Point word set
393:
394: * floating-idef:: Implementation Defined Options
395: * floating-ambcond:: Ambiguous Conditions
396:
397: The optional Locals word set
398:
399: * locals-idef:: Implementation Defined Options
400: * locals-ambcond:: Ambiguous Conditions
401:
402: The optional Memory-Allocation word set
403:
404: * memory-idef:: Implementation Defined Options
405:
406: The optional Programming-Tools word set
407:
408: * programming-idef:: Implementation Defined Options
409: * programming-ambcond:: Ambiguous Conditions
410:
411: The optional Search-Order word set
412:
413: * search-idef:: Implementation Defined Options
414: * search-ambcond:: Ambiguous Conditions
415:
416: Image Files
417:
1.24 anton 418: * Image Licensing Issues:: Distribution terms for images.
419: * Image File Background:: Why have image files?
1.32 anton 420: * Non-Relocatable Image Files:: don't always work.
1.24 anton 421: * Data-Relocatable Image Files:: are better.
1.32 anton 422: * Fully Relocatable Image Files:: better yet.
1.24 anton 423: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 424: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 425: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 426:
427: Fully Relocatable Image Files
428:
1.27 crook 429: * gforthmi:: The normal way
1.12 anton 430: * cross.fs:: The hard way
431:
432: Engine
433:
434: * Portability::
435: * Threading::
436: * Primitives::
437: * Performance::
438:
439: Threading
440:
441: * Scheduling::
442: * Direct or Indirect Threaded?::
443: * DOES>::
444:
445: Primitives
446:
447: * Automatic Generation::
448: * TOS Optimization::
449: * Produced code::
1.13 pazsan 450:
451: Cross Compiler
452:
453: * Using the Cross Compiler::
454: * How the Cross Compiler Works::
455:
1.24 anton 456: Other Forth-related information
1.21 crook 457:
458: * Internet resources::
459: * Books::
460: * The Forth Interest Group::
461: * Conferences::
462:
1.24 anton 463: @end detailmenu
1.1 anton 464: @end menu
465:
1.26 crook 466: @node License, Goals, Top, Top
1.1 anton 467: @unnumbered GNU GENERAL PUBLIC LICENSE
468: @center Version 2, June 1991
469:
470: @display
471: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
472: 675 Mass Ave, Cambridge, MA 02139, USA
473:
474: Everyone is permitted to copy and distribute verbatim copies
475: of this license document, but changing it is not allowed.
476: @end display
477:
478: @unnumberedsec Preamble
479:
480: The licenses for most software are designed to take away your
481: freedom to share and change it. By contrast, the GNU General Public
482: License is intended to guarantee your freedom to share and change free
483: software---to make sure the software is free for all its users. This
484: General Public License applies to most of the Free Software
485: Foundation's software and to any other program whose authors commit to
486: using it. (Some other Free Software Foundation software is covered by
487: the GNU Library General Public License instead.) You can apply it to
488: your programs, too.
489:
490: When we speak of free software, we are referring to freedom, not
491: price. Our General Public Licenses are designed to make sure that you
492: have the freedom to distribute copies of free software (and charge for
493: this service if you wish), that you receive source code or can get it
494: if you want it, that you can change the software or use pieces of it
495: in new free programs; and that you know you can do these things.
496:
497: To protect your rights, we need to make restrictions that forbid
498: anyone to deny you these rights or to ask you to surrender the rights.
499: These restrictions translate to certain responsibilities for you if you
500: distribute copies of the software, or if you modify it.
501:
502: For example, if you distribute copies of such a program, whether
503: gratis or for a fee, you must give the recipients all the rights that
504: you have. You must make sure that they, too, receive or can get the
505: source code. And you must show them these terms so they know their
506: rights.
507:
508: We protect your rights with two steps: (1) copyright the software, and
509: (2) offer you this license which gives you legal permission to copy,
510: distribute and/or modify the software.
511:
512: Also, for each author's protection and ours, we want to make certain
513: that everyone understands that there is no warranty for this free
514: software. If the software is modified by someone else and passed on, we
515: want its recipients to know that what they have is not the original, so
516: that any problems introduced by others will not reflect on the original
517: authors' reputations.
518:
519: Finally, any free program is threatened constantly by software
520: patents. We wish to avoid the danger that redistributors of a free
521: program will individually obtain patent licenses, in effect making the
522: program proprietary. To prevent this, we have made it clear that any
523: patent must be licensed for everyone's free use or not licensed at all.
524:
525: The precise terms and conditions for copying, distribution and
526: modification follow.
527:
528: @iftex
529: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
530: @end iftex
531: @ifinfo
532: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
533: @end ifinfo
534:
535: @enumerate 0
536: @item
537: This License applies to any program or other work which contains
538: a notice placed by the copyright holder saying it may be distributed
539: under the terms of this General Public License. The ``Program'', below,
540: refers to any such program or work, and a ``work based on the Program''
541: means either the Program or any derivative work under copyright law:
542: that is to say, a work containing the Program or a portion of it,
543: either verbatim or with modifications and/or translated into another
544: language. (Hereinafter, translation is included without limitation in
545: the term ``modification''.) Each licensee is addressed as ``you''.
546:
547: Activities other than copying, distribution and modification are not
548: covered by this License; they are outside its scope. The act of
549: running the Program is not restricted, and the output from the Program
550: is covered only if its contents constitute a work based on the
551: Program (independent of having been made by running the Program).
552: Whether that is true depends on what the Program does.
553:
554: @item
555: You may copy and distribute verbatim copies of the Program's
556: source code as you receive it, in any medium, provided that you
557: conspicuously and appropriately publish on each copy an appropriate
558: copyright notice and disclaimer of warranty; keep intact all the
559: notices that refer to this License and to the absence of any warranty;
560: and give any other recipients of the Program a copy of this License
561: along with the Program.
562:
563: You may charge a fee for the physical act of transferring a copy, and
564: you may at your option offer warranty protection in exchange for a fee.
565:
566: @item
567: You may modify your copy or copies of the Program or any portion
568: of it, thus forming a work based on the Program, and copy and
569: distribute such modifications or work under the terms of Section 1
570: above, provided that you also meet all of these conditions:
571:
572: @enumerate a
573: @item
574: You must cause the modified files to carry prominent notices
575: stating that you changed the files and the date of any change.
576:
577: @item
578: You must cause any work that you distribute or publish, that in
579: whole or in part contains or is derived from the Program or any
580: part thereof, to be licensed as a whole at no charge to all third
581: parties under the terms of this License.
582:
583: @item
584: If the modified program normally reads commands interactively
585: when run, you must cause it, when started running for such
586: interactive use in the most ordinary way, to print or display an
587: announcement including an appropriate copyright notice and a
588: notice that there is no warranty (or else, saying that you provide
589: a warranty) and that users may redistribute the program under
590: these conditions, and telling the user how to view a copy of this
591: License. (Exception: if the Program itself is interactive but
592: does not normally print such an announcement, your work based on
593: the Program is not required to print an announcement.)
594: @end enumerate
595:
596: These requirements apply to the modified work as a whole. If
597: identifiable sections of that work are not derived from the Program,
598: and can be reasonably considered independent and separate works in
599: themselves, then this License, and its terms, do not apply to those
600: sections when you distribute them as separate works. But when you
601: distribute the same sections as part of a whole which is a work based
602: on the Program, the distribution of the whole must be on the terms of
603: this License, whose permissions for other licensees extend to the
604: entire whole, and thus to each and every part regardless of who wrote it.
605:
606: Thus, it is not the intent of this section to claim rights or contest
607: your rights to work written entirely by you; rather, the intent is to
608: exercise the right to control the distribution of derivative or
609: collective works based on the Program.
610:
611: In addition, mere aggregation of another work not based on the Program
612: with the Program (or with a work based on the Program) on a volume of
613: a storage or distribution medium does not bring the other work under
614: the scope of this License.
615:
616: @item
617: You may copy and distribute the Program (or a work based on it,
618: under Section 2) in object code or executable form under the terms of
619: Sections 1 and 2 above provided that you also do one of the following:
620:
621: @enumerate a
622: @item
623: Accompany it with the complete corresponding machine-readable
624: source code, which must be distributed under the terms of Sections
625: 1 and 2 above on a medium customarily used for software interchange; or,
626:
627: @item
628: Accompany it with a written offer, valid for at least three
629: years, to give any third party, for a charge no more than your
630: cost of physically performing source distribution, a complete
631: machine-readable copy of the corresponding source code, to be
632: distributed under the terms of Sections 1 and 2 above on a medium
633: customarily used for software interchange; or,
634:
635: @item
636: Accompany it with the information you received as to the offer
637: to distribute corresponding source code. (This alternative is
638: allowed only for noncommercial distribution and only if you
639: received the program in object code or executable form with such
640: an offer, in accord with Subsection b above.)
641: @end enumerate
642:
643: The source code for a work means the preferred form of the work for
644: making modifications to it. For an executable work, complete source
645: code means all the source code for all modules it contains, plus any
646: associated interface definition files, plus the scripts used to
647: control compilation and installation of the executable. However, as a
648: special exception, the source code distributed need not include
649: anything that is normally distributed (in either source or binary
650: form) with the major components (compiler, kernel, and so on) of the
651: operating system on which the executable runs, unless that component
652: itself accompanies the executable.
653:
654: If distribution of executable or object code is made by offering
655: access to copy from a designated place, then offering equivalent
656: access to copy the source code from the same place counts as
657: distribution of the source code, even though third parties are not
658: compelled to copy the source along with the object code.
659:
660: @item
661: You may not copy, modify, sublicense, or distribute the Program
662: except as expressly provided under this License. Any attempt
663: otherwise to copy, modify, sublicense or distribute the Program is
664: void, and will automatically terminate your rights under this License.
665: However, parties who have received copies, or rights, from you under
666: this License will not have their licenses terminated so long as such
667: parties remain in full compliance.
668:
669: @item
670: You are not required to accept this License, since you have not
671: signed it. However, nothing else grants you permission to modify or
672: distribute the Program or its derivative works. These actions are
673: prohibited by law if you do not accept this License. Therefore, by
674: modifying or distributing the Program (or any work based on the
675: Program), you indicate your acceptance of this License to do so, and
676: all its terms and conditions for copying, distributing or modifying
677: the Program or works based on it.
678:
679: @item
680: Each time you redistribute the Program (or any work based on the
681: Program), the recipient automatically receives a license from the
682: original licensor to copy, distribute or modify the Program subject to
683: these terms and conditions. You may not impose any further
684: restrictions on the recipients' exercise of the rights granted herein.
685: You are not responsible for enforcing compliance by third parties to
686: this License.
687:
688: @item
689: If, as a consequence of a court judgment or allegation of patent
690: infringement or for any other reason (not limited to patent issues),
691: conditions are imposed on you (whether by court order, agreement or
692: otherwise) that contradict the conditions of this License, they do not
693: excuse you from the conditions of this License. If you cannot
694: distribute so as to satisfy simultaneously your obligations under this
695: License and any other pertinent obligations, then as a consequence you
696: may not distribute the Program at all. For example, if a patent
697: license would not permit royalty-free redistribution of the Program by
698: all those who receive copies directly or indirectly through you, then
699: the only way you could satisfy both it and this License would be to
700: refrain entirely from distribution of the Program.
701:
702: If any portion of this section is held invalid or unenforceable under
703: any particular circumstance, the balance of the section is intended to
704: apply and the section as a whole is intended to apply in other
705: circumstances.
706:
707: It is not the purpose of this section to induce you to infringe any
708: patents or other property right claims or to contest validity of any
709: such claims; this section has the sole purpose of protecting the
710: integrity of the free software distribution system, which is
711: implemented by public license practices. Many people have made
712: generous contributions to the wide range of software distributed
713: through that system in reliance on consistent application of that
714: system; it is up to the author/donor to decide if he or she is willing
715: to distribute software through any other system and a licensee cannot
716: impose that choice.
717:
718: This section is intended to make thoroughly clear what is believed to
719: be a consequence of the rest of this License.
720:
721: @item
722: If the distribution and/or use of the Program is restricted in
723: certain countries either by patents or by copyrighted interfaces, the
724: original copyright holder who places the Program under this License
725: may add an explicit geographical distribution limitation excluding
726: those countries, so that distribution is permitted only in or among
727: countries not thus excluded. In such case, this License incorporates
728: the limitation as if written in the body of this License.
729:
730: @item
731: The Free Software Foundation may publish revised and/or new versions
732: of the General Public License from time to time. Such new versions will
733: be similar in spirit to the present version, but may differ in detail to
734: address new problems or concerns.
735:
736: Each version is given a distinguishing version number. If the Program
737: specifies a version number of this License which applies to it and ``any
738: later version'', you have the option of following the terms and conditions
739: either of that version or of any later version published by the Free
740: Software Foundation. If the Program does not specify a version number of
741: this License, you may choose any version ever published by the Free Software
742: Foundation.
743:
744: @item
745: If you wish to incorporate parts of the Program into other free
746: programs whose distribution conditions are different, write to the author
747: to ask for permission. For software which is copyrighted by the Free
748: Software Foundation, write to the Free Software Foundation; we sometimes
749: make exceptions for this. Our decision will be guided by the two goals
750: of preserving the free status of all derivatives of our free software and
751: of promoting the sharing and reuse of software generally.
752:
753: @iftex
754: @heading NO WARRANTY
755: @end iftex
756: @ifinfo
757: @center NO WARRANTY
758: @end ifinfo
759:
760: @item
761: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
762: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
763: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
764: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
765: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
766: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
767: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
768: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
769: REPAIR OR CORRECTION.
770:
771: @item
772: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
773: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
774: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
775: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
776: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
777: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
778: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
779: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
780: POSSIBILITY OF SUCH DAMAGES.
781: @end enumerate
782:
783: @iftex
784: @heading END OF TERMS AND CONDITIONS
785: @end iftex
786: @ifinfo
787: @center END OF TERMS AND CONDITIONS
788: @end ifinfo
789:
790: @page
791: @unnumberedsec How to Apply These Terms to Your New Programs
792:
793: If you develop a new program, and you want it to be of the greatest
794: possible use to the public, the best way to achieve this is to make it
795: free software which everyone can redistribute and change under these terms.
796:
797: To do so, attach the following notices to the program. It is safest
798: to attach them to the start of each source file to most effectively
799: convey the exclusion of warranty; and each file should have at least
800: the ``copyright'' line and a pointer to where the full notice is found.
801:
802: @smallexample
803: @var{one line to give the program's name and a brief idea of what it does.}
804: Copyright (C) 19@var{yy} @var{name of author}
805:
806: This program is free software; you can redistribute it and/or modify
807: it under the terms of the GNU General Public License as published by
808: the Free Software Foundation; either version 2 of the License, or
809: (at your option) any later version.
810:
811: This program is distributed in the hope that it will be useful,
812: but WITHOUT ANY WARRANTY; without even the implied warranty of
813: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
814: GNU General Public License for more details.
815:
816: You should have received a copy of the GNU General Public License
817: along with this program; if not, write to the Free Software
818: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
819: @end smallexample
820:
821: Also add information on how to contact you by electronic and paper mail.
822:
823: If the program is interactive, make it output a short notice like this
824: when it starts in an interactive mode:
825:
826: @smallexample
827: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
828: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
829: type `show w'.
830: This is free software, and you are welcome to redistribute it
831: under certain conditions; type `show c' for details.
832: @end smallexample
833:
834: The hypothetical commands @samp{show w} and @samp{show c} should show
835: the appropriate parts of the General Public License. Of course, the
836: commands you use may be called something other than @samp{show w} and
837: @samp{show c}; they could even be mouse-clicks or menu items---whatever
838: suits your program.
839:
840: You should also get your employer (if you work as a programmer) or your
841: school, if any, to sign a ``copyright disclaimer'' for the program, if
842: necessary. Here is a sample; alter the names:
843:
844: @smallexample
845: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
846: `Gnomovision' (which makes passes at compilers) written by James Hacker.
847:
848: @var{signature of Ty Coon}, 1 April 1989
849: Ty Coon, President of Vice
850: @end smallexample
851:
852: This General Public License does not permit incorporating your program into
853: proprietary programs. If your program is a subroutine library, you may
854: consider it more useful to permit linking proprietary applications with the
855: library. If this is what you want to do, use the GNU Library General
856: Public License instead of this License.
857:
858: @iftex
859: @unnumbered Preface
860: @cindex Preface
1.21 crook 861: This manual documents Gforth. Some introductory material is provided for
862: readers who are unfamiliar with Forth or who are migrating to Gforth
863: from other Forth compilers. However, this manual is primarily a
864: reference manual.
1.1 anton 865: @end iftex
866:
1.28 crook 867: @comment TODO much more blurb here.
1.26 crook 868:
869: @c ******************************************************************
1.29 crook 870: @node Goals, Gforth Environment, License, Top
1.26 crook 871: @comment node-name, next, previous, up
872: @chapter Goals of Gforth
873: @cindex goals of the Gforth project
874: The goal of the Gforth Project is to develop a standard model for
875: ANS Forth. This can be split into several subgoals:
876:
877: @itemize @bullet
878: @item
879: Gforth should conform to the ANS Forth Standard.
880: @item
881: It should be a model, i.e. it should define all the
882: implementation-dependent things.
883: @item
884: It should become standard, i.e. widely accepted and used. This goal
885: is the most difficult one.
886: @end itemize
887:
888: To achieve these goals Gforth should be
889: @itemize @bullet
890: @item
891: Similar to previous models (fig-Forth, F83)
892: @item
893: Powerful. It should provide for all the things that are considered
894: necessary today and even some that are not yet considered necessary.
895: @item
896: Efficient. It should not get the reputation of being exceptionally
897: slow.
898: @item
899: Free.
900: @item
901: Available on many machines/easy to port.
902: @end itemize
903:
904: Have we achieved these goals? Gforth conforms to the ANS Forth
905: standard. It may be considered a model, but we have not yet documented
906: which parts of the model are stable and which parts we are likely to
907: change. It certainly has not yet become a de facto standard, but it
908: appears to be quite popular. It has some similarities to and some
909: differences from previous models. It has some powerful features, but not
910: yet everything that we envisioned. We certainly have achieved our
911: execution speed goals (@pxref{Performance}). It is free and available
912: on many machines.
913:
914: @menu
915: * Gforth Extensions Sinful?::
916: @end menu
917:
918: @node Gforth Extensions Sinful?, , Goals, Goals
919: @comment node-name, next, previous, up
920: @section Is it a Sin to use Gforth Extensions?
921: @cindex Gforth extensions
922:
923: If you've been paying attention, you will have realised that there is an
924: ANS (American National Standard) for Forth. As you read through the rest
1.29 crook 925: of this manual, you will see documentation for @i{Standard} words, and
926: documentation for some appealing Gforth @i{extensions}. You might ask
927: yourself the question: @i{``Given that there is a standard, would I be
1.26 crook 928: committing a sin to use (non-Standard) Gforth extensions?''}
929:
930: The answer to that question is somewhat pragmatic and somewhat
931: philosophical. Consider these points:
932:
933: @itemize @bullet
934: @item
935: A number of the Gforth extensions can be implemented in ANS Forth using
936: files provided in the @file{compat/} directory. These are mentioned in
937: the text in passing.
938: @item
939: Forth has a rich historical precedent for programmers taking advantage
940: of implementation-dependent features of their tools (for example,
941: relying on a knowledge of the dictionary structure). Sometimes these
942: techniques are necessary to extract every last bit of performance from
943: the hardware, sometimes they are just a programming shorthand.
944: @item
945: The best way to break the rules is to know what the rules are. To learn
946: the rules, there is no substitute for studying the text of the Standard
947: itself. In particular, Appendix A of the Standard (@var{Rationale})
948: provides a valuable insight into the thought processes of the technical
949: committee.
950: @item
951: The best reason to break a rule is because you have to; because it's
952: more productive to do that, because it makes your code run fast enough
953: or because you can see no Standard way to achieve what you want to
954: achieve.
955: @end itemize
956:
957: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
958: analyse your program and determine what non-Standard definitions it
959: relies upon.
960:
1.29 crook 961:
1.26 crook 962: @c ******************************************************************
1.29 crook 963: @node Gforth Environment, Introduction, Goals, Top
964: @chapter Gforth Environment
965: @cindex Gforth environment
1.21 crook 966:
1.29 crook 967: Note: ultimately, the gforth man page will be auto-generated from the
968: material in this chapter.
1.21 crook 969:
970: @menu
1.29 crook 971: * Invoking Gforth:: Getting in
972: * Leaving Gforth:: Getting out
973: * Command-line editing::
974: * Upper and lower case::
975: * Environment variables:: ..that affect how Gforth starts up
976: * Gforth Files:: What gets installed and where
1.21 crook 977: @end menu
978:
1.30 anton 979: @xref{Image Files} for related information about the creation of images.
1.29 crook 980:
1.21 crook 981: @comment ----------------------------------------------
1.29 crook 982: @node Invoking Gforth, Leaving Gforth, ,Gforth Environment
983: @section Invoking Gforth
984: @cindex invoking Gforth
985: @cindex running Gforth
986: @cindex command-line options
987: @cindex options on the command line
988: @cindex flags on the command line
1.21 crook 989:
1.30 anton 990: Gforth is made up of two parts; an executable ``engine'' (named
991: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
992: will usually just say @code{gforth} -- this automatically loads the
993: default image file @file{gforth.fi}. In many other cases the default
994: Gforth image will be invoked like this:
1.21 crook 995: @example
1.30 anton 996: gforth [file | -e forth-code] ...
1.21 crook 997: @end example
1.29 crook 998: @noindent
999: This interprets the contents of the files and the Forth code in the order they
1000: are given.
1.21 crook 1001:
1.30 anton 1002: In addition to the @file{gforth} engine, there is also an engine called
1003: @file{gforth-fast}, which is faster, but gives less informative error
1004: messages (@pxref{Error messages}).
1005:
1.29 crook 1006: In general, the command line looks like this:
1.21 crook 1007:
1008: @example
1.30 anton 1009: gforth[-fast] [engine options] [image options]
1.21 crook 1010: @end example
1011:
1.30 anton 1012: The engine options must come before the rest of the command
1.29 crook 1013: line. They are:
1.26 crook 1014:
1.29 crook 1015: @table @code
1016: @cindex -i, command-line option
1017: @cindex --image-file, command-line option
1018: @item --image-file @i{file}
1019: @itemx -i @i{file}
1020: Loads the Forth image @i{file} instead of the default
1021: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 1022:
1.39 anton 1023: @cindex --appl-image, command-line option
1024: @item --appl-image @i{file}
1025: Loads the image @i{file} and leaves all further command-line arguments
1026: to the image (instead of processing them as options). This is useful
1027: for building executable application images on Unix, built with
1028: @code{gforthmi --application ...}.
1029:
1.29 crook 1030: @cindex --path, command-line option
1031: @cindex -p, command-line option
1032: @item --path @i{path}
1033: @itemx -p @i{path}
1034: Uses @i{path} for searching the image file and Forth source code files
1035: instead of the default in the environment variable @code{GFORTHPATH} or
1036: the path specified at installation time (e.g.,
1037: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
1038: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 1039:
1.29 crook 1040: @cindex --dictionary-size, command-line option
1041: @cindex -m, command-line option
1042: @cindex @i{size} parameters for command-line options
1043: @cindex size of the dictionary and the stacks
1044: @item --dictionary-size @i{size}
1045: @itemx -m @i{size}
1046: Allocate @i{size} space for the Forth dictionary space instead of
1047: using the default specified in the image (typically 256K). The
1048: @i{size} specification for this and subsequent options consists of
1049: an integer and a unit (e.g.,
1050: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
1051: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
1052: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
1053: @code{e} is used.
1.21 crook 1054:
1.29 crook 1055: @cindex --data-stack-size, command-line option
1056: @cindex -d, command-line option
1057: @item --data-stack-size @i{size}
1058: @itemx -d @i{size}
1059: Allocate @i{size} space for the data stack instead of using the
1060: default specified in the image (typically 16K).
1.21 crook 1061:
1.29 crook 1062: @cindex --return-stack-size, command-line option
1063: @cindex -r, command-line option
1064: @item --return-stack-size @i{size}
1065: @itemx -r @i{size}
1066: Allocate @i{size} space for the return stack instead of using the
1067: default specified in the image (typically 15K).
1.21 crook 1068:
1.29 crook 1069: @cindex --fp-stack-size, command-line option
1070: @cindex -f, command-line option
1071: @item --fp-stack-size @i{size}
1072: @itemx -f @i{size}
1073: Allocate @i{size} space for the floating point stack instead of
1074: using the default specified in the image (typically 15.5K). In this case
1075: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 1076:
1.29 crook 1077: @cindex --locals-stack-size, command-line option
1078: @cindex -l, command-line option
1079: @item --locals-stack-size @i{size}
1080: @itemx -l @i{size}
1081: Allocate @i{size} space for the locals stack instead of using the
1082: default specified in the image (typically 14.5K).
1.21 crook 1083:
1.29 crook 1084: @cindex -h, command-line option
1085: @cindex --help, command-line option
1086: @item --help
1087: @itemx -h
1088: Print a message about the command-line options
1.21 crook 1089:
1.29 crook 1090: @cindex -v, command-line option
1091: @cindex --version, command-line option
1092: @item --version
1093: @itemx -v
1094: Print version and exit
1.21 crook 1095:
1.29 crook 1096: @cindex --debug, command-line option
1097: @item --debug
1098: Print some information useful for debugging on startup.
1.21 crook 1099:
1.29 crook 1100: @cindex --offset-image, command-line option
1101: @item --offset-image
1102: Start the dictionary at a slightly different position than would be used
1103: otherwise (useful for creating data-relocatable images,
1104: @pxref{Data-Relocatable Image Files}).
1.21 crook 1105:
1.29 crook 1106: @cindex --no-offset-im, command-line option
1107: @item --no-offset-im
1108: Start the dictionary at the normal position.
1.21 crook 1109:
1.29 crook 1110: @cindex --clear-dictionary, command-line option
1111: @item --clear-dictionary
1112: Initialize all bytes in the dictionary to 0 before loading the image
1113: (@pxref{Data-Relocatable Image Files}).
1114:
1115: @cindex --die-on-signal, command-line-option
1116: @item --die-on-signal
1117: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
1118: or the segmentation violation SIGSEGV) by translating it into a Forth
1119: @code{THROW}. With this option, Gforth exits if it receives such a
1120: signal. This option is useful when the engine and/or the image might be
1121: severely broken (such that it causes another signal before recovering
1122: from the first); this option avoids endless loops in such cases.
1123: @end table
1124:
1125: @cindex loading files at startup
1126: @cindex executing code on startup
1127: @cindex batch processing with Gforth
1128: As explained above, the image-specific command-line arguments for the
1129: default image @file{gforth.fi} consist of a sequence of filenames and
1130: @code{-e @var{forth-code}} options that are interpreted in the sequence
1131: in which they are given. The @code{-e @var{forth-code}} or
1132: @code{--evaluate @var{forth-code}} option evaluates the Forth
1133: code. This option takes only one argument; if you want to evaluate more
1134: Forth words, you have to quote them or use @code{-e} several times. To exit
1135: after processing the command line (instead of entering interactive mode)
1136: append @code{-e bye} to the command line.
1137:
1138: @cindex versions, invoking other versions of Gforth
1139: If you have several versions of Gforth installed, @code{gforth} will
1140: invoke the version that was installed last. @code{gforth-@i{version}}
1141: invokes a specific version. You may want to use the option
1142: @code{--path}, if your environment contains the variable
1143: @code{GFORTHPATH}.
1144:
1145: Not yet implemented:
1146: On startup the system first executes the system initialization file
1147: (unless the option @code{--no-init-file} is given; note that the system
1148: resulting from using this option may not be ANS Forth conformant). Then
1149: the user initialization file @file{.gforth.fs} is executed, unless the
1150: option @code{--no-rc} is given; this file is first searched in @file{.},
1151: then in @file{~}, then in the normal path (see above).
1.21 crook 1152:
1153:
1154:
1.29 crook 1155: @comment ----------------------------------------------
1156: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
1157: @section Leaving Gforth
1158: @cindex Gforth - leaving
1159: @cindex leaving Gforth
1.21 crook 1160:
1.30 anton 1161: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
1162: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
1163: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1164: data are discarded. @xref{Image Files} for ways of saving the state of
1165: the system before leaving Gforth.
1.21 crook 1166:
1.29 crook 1167: doc-bye
1.21 crook 1168:
1.29 crook 1169: @comment ----------------------------------------------
1170: @node Command-line editing, Upper and lower case,Leaving Gforth,Gforth Environment
1171: @section Command-line editing
1172: @cindex command-line editing
1.21 crook 1173:
1.29 crook 1174: Gforth maintains a history file that records every line that you type to
1175: the text interpreter. This file is preserved between sessions, and is
1176: used to provide a command-line recall facility; if you type ctrl-P
1177: repeatedly you can recall successively older commands from this (or
1178: previous) session(s). The full list of command-line editing facilities is:
1.21 crook 1179:
1.30 anton 1180: @comment use @table? - anton
1.21 crook 1181: @itemize @bullet
1182: @item
1.30 anton 1183: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
1.29 crook 1184: commands from the history buffer.
1185: @item
1.30 anton 1186: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
1.29 crook 1187: from the history buffer.
1188: @item
1.30 anton 1189: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
1.29 crook 1190: @item
1.30 anton 1191: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
1.29 crook 1192: @item
1.30 anton 1193: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
1.29 crook 1194: closing up the line.
1195: @item
1.30 anton 1196: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
1.29 crook 1197: @item
1.30 anton 1198: @kbd{Ctrl-a} to move the cursor to the start of the line.
1.21 crook 1199: @item
1.30 anton 1200: @kbd{Ctrl-e} to move the cursor to the end of the line.
1.21 crook 1201: @item
1.30 anton 1202: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
1.29 crook 1203: line.
1.21 crook 1204: @item
1.30 anton 1205: @key{TAB} to step through all possible full-word completions of the word
1.29 crook 1206: currently being typed.
1.21 crook 1207: @item
1.30 anton 1208: @kbd{Ctrl-d} at the start of the line to terminate Gforth (gracefully,
1209: using @code{bye}).
1.21 crook 1210: @end itemize
1211:
1.29 crook 1212: When editing, displayable characters are inserted to the left of the
1213: cursor position; the line is always in ``insert'' (as opposed to
1214: ``overstrike'') mode.
1215:
1216: @cindex history file
1217: @cindex @file{.gforth-history}
1218: On Unix systems, the history file is @file{~/.gforth-history} by
1219: default@footnote{i.e. it is stored in the user's home directory.}. You
1220: can find out the name and location of your history file using:
1221:
1222: @example
1223: history-file type \ Unix-class systems
1.21 crook 1224:
1.29 crook 1225: history-file type \ Other systems
1226: history-dir type
1.21 crook 1227: @end example
1228:
1.29 crook 1229: If you enter long definitions by hand, you can use a text editor to
1230: paste them out of the history file into a Forth source file for reuse at
1231: a later time.
1232:
1233: Gforth never trims the size of the history file, so you should do this
1234: periodically, if necessary.
1235:
1236: @comment this is all defined in history.fs
1237:
1238:
1239:
1240: @comment ----------------------------------------------
1241: @node Upper and lower case, Environment variables,Command-line editing,Gforth Environment
1242: @section Upper and lower case
1243: @cindex case-sensitivity
1244: @cindex upper and lower case
1245:
1246: Gforth is case-insensitive, so you can enter definitions and invoke
1247: Standard words using upper, lower or mixed case (however,
1248: @pxref{core-idef, Implementation-defined options, Implementation-defined
1249: options}).
1250:
1.30 anton 1251: ANS Forth only @i{requires} implementations to recognise Standard words
1252: when they are typed entirely in upper case. Therefore, a Standard
1253: program must use upper case for all Standard words. You can use whatever
1254: case you like for words that you define, but in a standard program you
1255: have to use the words in the same case that you defined them.
1256:
1257: Gforth supports case sensitivity through @code{table}s (case-sensitive
1258: wordlists, @pxref{Word Lists}).
1259:
1260: Two people have asked how to convert Gforth to case sensitivity; while
1261: we think this is a bad idea, you can change all wordlists into tables
1262: like this:
1.29 crook 1263:
1.30 anton 1264: @example
1265: ' table-find forth-wordlist wordlist-map @ !
1266: @end example
1267:
1268: Note that you now have to type the predefined words in the same case
1269: that we defined them, which are varying. You may want to convert them
1270: to your favourite case before doing this operation (I won't explain how,
1271: because if you are even contemplating to do this, you'd better have
1272: enough knowledge of Forth systems to know this already).
1.29 crook 1273:
1274: @comment ----------------------------------------------
1275: @node Environment variables, Gforth Files, Upper and lower case,Gforth Environment
1276: @section Environment variables
1277: @cindex environment variables
1.21 crook 1278:
1.29 crook 1279: Gforth uses these environment variables:
1.21 crook 1280:
1.29 crook 1281: @itemize @bullet
1282: @item
1283: @cindex GFORTHHIST - environment variable
1284: GFORTHHIST - (Unix systems only) specifies the directory in which to
1285: open/create the history file, @file{.gforth-history}. Default:
1286: @code{$HOME}.
1.21 crook 1287:
1.29 crook 1288: @item
1289: @cindex GFORTHPATH - environment variable
1290: GFORTHPATH - specifies the path used when searching for the gforth image file and
1291: for Forth source-code files.
1.21 crook 1292:
1.29 crook 1293: @item
1294: @cindex GFORTH - environment variable
1295: GFORTH - used by @file{gforthmi} @xref{gforthmi}.
1.26 crook 1296:
1.29 crook 1297: @item
1298: @cindex GFORTHD - environment variable
1299: GFORTHD - used by @file{gforthmi} @xref{gforthmi}.
1.21 crook 1300:
1.29 crook 1301: @item
1302: @cindex TMP, TEMP - environment variable
1303: TMP, TEMP - (non-Unix systems only) used as a potential location for the
1304: history file.
1305: @end itemize
1.21 crook 1306:
1.29 crook 1307: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1308: @comment mentioning these.
1.21 crook 1309:
1.29 crook 1310: All the Gforth environment variables default to sensible values if they
1311: are not set.
1.21 crook 1312:
1313:
1.29 crook 1314: @comment ----------------------------------------------
1315: @node Gforth Files, ,Environment variables,Gforth Environment
1316: @section Gforth files
1317: @cindex Gforth files
1.21 crook 1318:
1.30 anton 1319: When you Gforth on a Unix system in the default places, it installs
1320: files in these locations:
1.21 crook 1321:
1.26 crook 1322: @itemize @bullet
1323: @item
1.29 crook 1324: @file{/usr/local/bin/gforth}
1325: @item
1326: @file{/usr/local/bin/gforthmi}
1327: @item
1328: @file{/usr/local/man/man1/gforth.1} - man page.
1329: @item
1330: @file{/usr/local/info} - the Info version of this manual.
1331: @item
1.30 anton 1332: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1.29 crook 1333: @item
1334: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1.26 crook 1335: @item
1.30 anton 1336: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1.26 crook 1337: @item
1.30 anton 1338: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1.26 crook 1339: @end itemize
1.21 crook 1340:
1.30 anton 1341: You can select different places for installation by using
1342: @code{configure} options (listed with @code{configure --help}).
1.21 crook 1343:
1.29 crook 1344: @c ******************************************************************
1345: @node Introduction, Words, Gforth Environment, Top
1346: @comment node-name, next, previous, up
1347: @chapter An Introduction to ANS Forth
1348: @cindex Forth - an introduction
1.21 crook 1349:
1.29 crook 1350: The primary purpose of this manual is to document Gforth. However, since
1351: Forth is not a widely-known language and there is a lack of up-to-date
1352: teaching material, it seems worthwhile to provide some introductory
1353: material. @xref{Forth-related information} for other sources of Forth-related
1354: information.
1.21 crook 1355:
1.29 crook 1356: The examples in this section should work on any ANS Forth; the
1357: output shown was produced using Gforth. Each example attempts to
1358: reproduce the exact output that Gforth produces. If you try out the
1359: examples (and you should), what you should type is shown @kbd{like this}
1360: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 1361: that, where the example shows @key{RET} it means that you should
1.29 crook 1362: press the ``carriage return'' key. Unfortunately, some output formats for
1363: this manual cannot show the difference between @kbd{this} and
1364: @code{this} which will make trying out the examples harder (but not
1365: impossible).
1.21 crook 1366:
1.29 crook 1367: Forth is an unusual language. It provides an interactive development
1368: environment which includes both an interpreter and compiler. Forth
1369: programming style encourages you to break a problem down into many
1370: @cindex factoring
1371: small fragments (@dfn{factoring}), and then to develop and test each
1372: fragment interactively. Forth advocates assert that breaking the
1373: edit-compile-test cycle used by conventional programming languages can
1374: lead to great productivity improvements.
1.21 crook 1375:
1.29 crook 1376: @menu
1377: * Introducing the Text Interpreter::
1378: * Stacks and Postfix notation::
1379: * Your first definition::
1380: * How does that work?::
1381: * Forth is written in Forth::
1382: * Review - elements of a Forth system::
1383: * Where to go next::
1384: * Exercises::
1385: @end menu
1.21 crook 1386:
1.29 crook 1387: @comment ----------------------------------------------
1388: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
1389: @section Introducing the Text Interpreter
1390: @cindex text interpreter
1391: @cindex outer interpreter
1.21 crook 1392:
1.30 anton 1393: @c IMO this is too detailed and the pace is too slow for
1394: @c an introduction. If you know German, take a look at
1395: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
1396: @c to see how I do it - anton
1397:
1.29 crook 1398: When you invoke the Forth image, you will see a startup banner printed
1399: and nothing else (if you have Gforth installed on your system, try
1.30 anton 1400: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 1401: its command line interpreter, which is called the @dfn{Text Interpreter}
1402: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.30 anton 1403: about the text interpreter as you read through this chapter, but
1404: @pxref{The Text Interpreter} for more detail).
1.21 crook 1405:
1.29 crook 1406: Although it's not obvious, Forth is actually waiting for your
1.30 anton 1407: input. Type a number and press the @key{RET} key:
1.21 crook 1408:
1.26 crook 1409: @example
1.30 anton 1410: @kbd{45@key{RET}} ok
1.26 crook 1411: @end example
1.21 crook 1412:
1.29 crook 1413: Rather than give you a prompt to invite you to input something, the text
1414: interpreter prints a status message @i{after} it has processed a line
1415: of input. The status message in this case (``@code{ ok}'' followed by
1416: carriage-return) indicates that the text interpreter was able to process
1417: all of your input successfully. Now type something illegal:
1418:
1419: @example
1.30 anton 1420: @kbd{qwer341@key{RET}}
1.29 crook 1421: :1: Undefined word
1422: qwer341
1423: ^^^^^^^
1424: $400D2BA8 Bounce
1425: $400DBDA8 no.extensions
1426: @end example
1.23 crook 1427:
1.29 crook 1428: The exact text, other than the ``Undefined word'' may differ slightly on
1429: your system, but the effect is the same; when the text interpreter
1430: detects an error, it discards any remaining text on a line, resets
1.30 anton 1431: certain internal state and prints an error message. @xref{Error
1432: messages} for a detailed description of error messages.
1.23 crook 1433:
1.29 crook 1434: The text interpreter waits for you to press carriage-return, and then
1435: processes your input line. Starting at the beginning of the line, it
1436: breaks the line into groups of characters separated by spaces. For each
1437: group of characters in turn, it makes two attempts to do something:
1.23 crook 1438:
1.29 crook 1439: @itemize @bullet
1440: @item
1441: It tries to treat it as a command. It does this by searching a @dfn{name
1442: dictionary}. If the group of characters matches an entry in the name
1443: dictionary, the name dictionary provides the text interpreter with
1444: information that allows the text interpreter perform some actions. In
1445: Forth jargon, we say that the group
1446: @cindex word
1447: @cindex definition
1448: @cindex execution token
1449: @cindex xt
1450: of characters names a @dfn{word}, that the dictionary search returns an
1451: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
1452: word, and that the text interpreter executes the xt. Often, the terms
1453: @dfn{word} and @dfn{definition} are used interchangeably.
1454: @item
1455: If the text interpreter fails to find a match in the name dictionary, it
1456: tries to treat the group of characters as a number in the current number
1457: base (when you start up Forth, the current number base is base 10). If
1458: the group of characters legitimately represents a number, the text
1459: interpreter pushes the number onto a stack (we'll learn more about that
1460: in the next section).
1461: @end itemize
1.23 crook 1462:
1.29 crook 1463: If the text interpreter is unable to do either of these things with any
1464: group of characters, it discards the group of characters and the rest of
1465: the line, then prints an error message. If the text interpreter reaches
1466: the end of the line without error, it prints the status message ``@code{ ok}''
1467: followed by carriage-return.
1.21 crook 1468:
1.29 crook 1469: This is the simplest command we can give to the text interpreter:
1.23 crook 1470:
1471: @example
1.30 anton 1472: @key{RET} ok
1.23 crook 1473: @end example
1.21 crook 1474:
1.29 crook 1475: The text interpreter did everything we asked it to do (nothing) without
1476: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
1477: command:
1.21 crook 1478:
1.23 crook 1479: @example
1.30 anton 1480: @kbd{12 dup fred dup@key{RET}}
1.29 crook 1481: :1: Undefined word
1482: 12 dup fred dup
1483: ^^^^
1484: $400D2BA8 Bounce
1485: $400DBDA8 no.extensions
1.23 crook 1486: @end example
1.21 crook 1487:
1.29 crook 1488: When you press the carriage-return key, the text interpreter starts to
1489: work its way along the line:
1.21 crook 1490:
1.29 crook 1491: @itemize @bullet
1492: @item
1493: When it gets to the space after the @code{2}, it takes the group of
1494: characters @code{12} and looks them up in the name
1495: dictionary@footnote{We can't tell if it found them or not, but assume
1496: for now that it did not}. There is no match for this group of characters
1497: in the name dictionary, so it tries to treat them as a number. It is
1498: able to do this successfully, so it puts the number, 12, ``on the stack''
1499: (whatever that means).
1500: @item
1501: The text interpreter resumes scanning the line and gets the next group
1502: of characters, @code{dup}. It looks it up in the name dictionary and
1503: (you'll have to take my word for this) finds it, and executes the word
1504: @code{dup} (whatever that means).
1505: @item
1506: Once again, the text interpreter resumes scanning the line and gets the
1507: group of characters @code{fred}. It looks them up in the name
1508: dictionary, but can't find them. It tries to treat them as a number, but
1509: they don't represent any legal number.
1510: @end itemize
1.21 crook 1511:
1.29 crook 1512: At this point, the text interpreter gives up and prints an error
1513: message. The error message shows exactly how far the text interpreter
1514: got in processing the line. In particular, it shows that the text
1515: interpreter made no attempt to do anything with the final character
1516: group, @code{dup}, even though we have good reason to believe that the
1517: text interpreter would have no problem looking that word up and
1518: executing it a second time.
1.21 crook 1519:
1520:
1.29 crook 1521: @comment ----------------------------------------------
1522: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
1523: @section Stacks, postfix notation and parameter passing
1524: @cindex text interpreter
1525: @cindex outer interpreter
1.21 crook 1526:
1.29 crook 1527: In procedural programming languages (like C and Pascal), the
1528: building-block of programs is the @dfn{function} or @dfn{procedure}. These
1529: functions or procedures are called with @dfn{explicit parameters}. For
1530: example, in C we might write:
1.21 crook 1531:
1.23 crook 1532: @example
1.29 crook 1533: total = total + new_volume(length,height,depth);
1.23 crook 1534: @end example
1.21 crook 1535:
1.23 crook 1536: @noindent
1.29 crook 1537: where new_volume is a function-call to another piece of code, and total,
1538: length, height and depth are all variables. length, height and depth are
1539: parameters to the function-call.
1.21 crook 1540:
1.29 crook 1541: In Forth, the equivalent of the function or procedure is the
1542: @dfn{definition} and parameters are implicitly passed between
1543: definitions using a shared stack that is visible to the
1544: programmer. Although Forth does support variables, the existence of the
1545: stack means that they are used far less often than in most other
1546: programming languages. When the text interpreter encounters a number, it
1547: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 1548: actual number is implementation-dependent ...) and the particular stack
1.29 crook 1549: used for any operation is implied unambiguously by the operation being
1550: performed. The stack used for all integer operations is called the @dfn{data
1551: stack} and, since this is the stack used most commonly, references to
1552: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 1553:
1.29 crook 1554: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 1555:
1.23 crook 1556: @example
1.30 anton 1557: @kbd{1 2 3@key{RET}} ok
1.23 crook 1558: @end example
1.21 crook 1559:
1.29 crook 1560: Then this instructs the text interpreter to placed three numbers on the
1561: (data) stack. An analogy for the behaviour of the stack is to take a
1562: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
1563: the table. The 3 was the last card onto the pile (``last-in'') and if
1564: you take a card off the pile then, unless you're prepared to fiddle a
1565: bit, the card that you take off will be the 3 (``first-out''). The
1566: number that will be first-out of the stack is called the @dfn{top of
1567: stack}, which
1568: @cindex TOS definition
1569: is often abbreviated to @dfn{TOS}.
1.21 crook 1570:
1.29 crook 1571: To understand how parameters are passed in Forth, consider the
1572: behaviour of the definition @code{+} (pronounced ``plus''). You will not
1573: be surprised to learn that this definition performs addition. More
1574: precisely, it adds two number together and produces a result. Where does
1575: it get the two numbers from? It takes the top two numbers off the
1576: stack. Where does it place the result? On the stack. You can act-out the
1577: behaviour of @code{+} with your playing cards like this:
1.21 crook 1578:
1579: @itemize @bullet
1580: @item
1.29 crook 1581: Pick up two cards from the stack on the table
1.21 crook 1582: @item
1.29 crook 1583: Stare at them intently and ask yourself ``what @i{is} the sum of these two
1584: numbers''
1.21 crook 1585: @item
1.29 crook 1586: Decide that the answer is 5
1.21 crook 1587: @item
1.29 crook 1588: Shuffle the two cards back into the pack and find a 5
1.21 crook 1589: @item
1.29 crook 1590: Put a 5 on the remaining ace that's on the table.
1.21 crook 1591: @end itemize
1592:
1.29 crook 1593: If you don't have a pack of cards handy but you do have Forth running,
1594: you can use the definition @code{.s} to show the current state of the stack,
1595: without affecting the stack. Type:
1.21 crook 1596:
1597: @example
1.30 anton 1598: @kbd{clearstack 1 2 3@key{RET}} ok
1599: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 1600: @end example
1601:
1.29 crook 1602: The text interpreter looks up the word @code{clearstack} and executes
1603: it; it tidies up the stack and removes any entries that may have been
1604: left on it by earlier examples. The text interpreter pushes each of the
1605: three numbers in turn onto the stack. Finally, the text interpreter
1606: looks up the word @code{.s} and executes it. The effect of executing
1607: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
1608: followed by a list of all the items on the stack; the item on the far
1609: right-hand side is the TOS.
1.21 crook 1610:
1.29 crook 1611: You can now type:
1.21 crook 1612:
1.29 crook 1613: @example
1.30 anton 1614: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 1615: @end example
1.21 crook 1616:
1.29 crook 1617: @noindent
1618: which is correct; there are now 2 items on the stack and the result of
1619: the addition is 5.
1.23 crook 1620:
1.29 crook 1621: If you're playing with cards, try doing a second addition: pick up the
1622: two cards, work out that their sum is 6, shuffle them into the pack,
1623: look for a 6 and place that on the table. You now have just one item on
1624: the stack. What happens if you try to do a third addition? Pick up the
1625: first card, pick up the second card -- ah! There is no second card. This
1626: is called a @dfn{stack underflow} and consitutes an error. If you try to
1627: do the same thing with Forth it will report an error (probably a Stack
1628: Underflow or an Invalid Memory Address error).
1.23 crook 1629:
1.29 crook 1630: The opposite situation to a stack underflow is a @dfn{stack overflow},
1631: which simply accepts that there is a finite amount of storage space
1632: reserved for the stack. To stretch the playing card analogy, if you had
1633: enough packs of cards and you piled the cards up on the table, you would
1634: eventually be unable to add another card; you'd hit the ceiling. Gforth
1635: allows you to set the maximum size of the stacks. In general, the only
1636: time that you will get a stack overflow is because a definition has a
1637: bug in it and is generating data on the stack uncontrollably.
1.23 crook 1638:
1.29 crook 1639: There's one final use for the playing card analogy. If you model your
1640: stack using a pack of playing cards, the maximum number of items on
1641: your stack will be 52 (I assume you didn't use the Joker). The maximum
1642: @i{value} of any item on the stack is 13 (the King). In fact, the only
1643: possible numbers are positive integer numbers 1 through 13; you can't
1644: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
1645: think about some of the cards, you can accommodate different
1646: numbers. For example, you could think of the Jack as representing 0,
1647: the Queen as representing -1 and the King as representing -2. Your
1648: *range* remains unchanged (you can still only represent a total of 13
1649: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 1650:
1.29 crook 1651: In that analogy, the limit was the amount of information that a single
1652: stack entry could hold, and Forth has a similar limit. In Forth, the
1653: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
1654: implementation dependent and affects the maximum value that a stack
1655: entry can hold. A Standard Forth provides a cell size of at least
1656: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 1657:
1.29 crook 1658: Forth does not do any type checking for you, so you are free to
1659: manipulate and combine stack items in any way you wish. A convenient way
1660: of treating stack items is as 2's complement signed integers, and that
1661: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 1662:
1.29 crook 1663: @example
1.30 anton 1664: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 1665: @end example
1.21 crook 1666:
1.29 crook 1667: If you use numbers and definitions like @code{+} in order to turn Forth
1668: into a great big pocket calculator, you will realise that it's rather
1669: different from a normal calculator. Rather than typing 2 + 3 = you had
1670: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
1671: result). The terminology used to describe this difference is to say that
1672: your calculator uses @dfn{Infix Notation} (parameters and operators are
1673: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
1674: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 1675:
1.29 crook 1676: Whilst postfix notation might look confusing to begin with, it has
1677: several important advantages:
1.21 crook 1678:
1.23 crook 1679: @itemize @bullet
1680: @item
1.29 crook 1681: it is unambiguous
1.23 crook 1682: @item
1.29 crook 1683: it is more concise
1.23 crook 1684: @item
1.29 crook 1685: it fits naturally with a stack-based system
1.23 crook 1686: @end itemize
1.21 crook 1687:
1.29 crook 1688: To examine these claims in more detail, consider these sums:
1.21 crook 1689:
1.29 crook 1690: @example
1691: 6 + 5 * 4 =
1692: 4 * 5 + 6 =
1693: @end example
1.21 crook 1694:
1.29 crook 1695: If you're just learning maths or your maths is very rusty, you will
1696: probably come up with the answer 44 for the first and 26 for the
1697: second. If you are a bit of a whizz at maths you will remember the
1698: @i{convention} that multiplication takes precendence over addition, and
1699: you'd come up with the answer 26 both times. To explain the answer 26
1700: to someone who got the answer 44, you'd probably rewrite the first sum
1701: like this:
1.21 crook 1702:
1.29 crook 1703: @example
1704: 6 + (5 * 4) =
1705: @end example
1.21 crook 1706:
1.29 crook 1707: If what you really wanted was to perform the addition before the
1708: multiplication, you would have to use parentheses to force it.
1.21 crook 1709:
1.29 crook 1710: If you did the first two sums on a pocket calculator you would probably
1711: get the right answers, unless you were very cautious and entered them using
1712: these keystroke sequences:
1.21 crook 1713:
1.29 crook 1714: 6 + 5 = * 4 =
1715: 4 * 5 = + 6 =
1.21 crook 1716:
1.29 crook 1717: Postfix notation is unambiguous because the order that the operators
1718: are applied is always explicit; that also means that parentheses are
1719: never required. The operators are @i{active} (the act of quoting the
1720: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 1721:
1.29 crook 1722: The sum 6 + 5 * 4 can be written (in postfix notation) in two
1723: equivalent ways:
1.26 crook 1724:
1725: @example
1.29 crook 1726: 6 5 4 * + or:
1727: 5 4 * 6 +
1.26 crook 1728: @end example
1.23 crook 1729:
1.29 crook 1730: An important thing that you should notice about this notation is that
1731: the @i{order} of the numbers does not change; if you want to subtract
1732: 2 from 10 you type @code{10 2 -}.
1.1 anton 1733:
1.29 crook 1734: The reason that Forth uses postfix notation is very simple to explain: it
1735: makes the implementation extremely simple, and it follows naturally from
1736: using the stack as a mechanism for passing parameters. Another way of
1737: thinking about this is to realise that all Forth definitions are
1738: @i{active}; they execute as they are encountered by the text
1739: interpreter. The result of this is that the syntax of Forth is trivially
1740: simple.
1.1 anton 1741:
1742:
1743:
1.29 crook 1744: @comment ----------------------------------------------
1745: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
1746: @section Your first Forth definition
1747: @cindex first definition
1.1 anton 1748:
1.29 crook 1749: Until now, the examples we've seen have been trivial; we've just been
1750: using Forth as a bigger-than-pocket calculator. Also, each calculation
1751: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
1752: again@footnote{That's not quite true. If you press the up-arrow key on
1753: your keyboard you should be able to scroll back to any earlier command,
1754: edit it and re-enter it.} In this section we'll see how to add new
1755: words to Forth's vocabulary.
1.1 anton 1756:
1.29 crook 1757: The easiest way to create a new word is to use a @dfn{colon
1758: definition}. We'll define a few and try them out before worrying too
1759: much about how they work. Try typing in these examples; be careful to
1760: copy the spaces accurately:
1.1 anton 1761:
1.29 crook 1762: @example
1763: : add-two 2 + . ;
1764: : greet ." Hello and welcome" ;
1765: : demo 5 add-two ;
1766: @end example
1.1 anton 1767:
1.29 crook 1768: @noindent
1769: Now try them out:
1.1 anton 1770:
1.29 crook 1771: @example
1.30 anton 1772: @kbd{greet@key{RET}} Hello and welcome ok
1773: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
1774: @kbd{4 add-two@key{RET}} 6 ok
1775: @kbd{demo@key{RET}} 7 ok
1776: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 1777: @end example
1.1 anton 1778:
1.29 crook 1779: The first new thing that we've introduced here is the pair of words
1780: @code{:} and @code{;}. These are used to start and terminate a new
1781: definition, respectively. The first word after the @code{:} is the name
1782: for the new definition.
1.1 anton 1783:
1.29 crook 1784: As you can see from the examples, a definition is built up of words that
1785: have already been defined; Forth makes no distinction between
1786: definitions that existed when you started the system up, and those that
1787: you define yourself.
1.1 anton 1788:
1.29 crook 1789: The examples also introduce the words @code{.} (dot), @code{."}
1790: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
1791: the stack and displays it. It's like @code{.s} except that it only
1792: displays the top item of the stack and it is destructive; after it has
1793: executed, the number is no longer on the stack. There is always one
1794: space printed after the number, and no spaces before it. Dot-quote
1795: defines a string (a sequence of characters) that will be printed when
1796: the word is executed. The string can contain any printable characters
1797: except @code{"}. A @code{"} has a special function; it is not a Forth
1798: word but it acts as a delimiter (the way that delimiters work is
1799: described in the next section). Finally, @code{dup} duplicates the value
1800: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 1801:
1.29 crook 1802: We already know that the text interpreter searches through the
1803: dictionary to locate names. If you've followed the examples earlier, you
1804: will already have a definition called @code{add-two}. Lets try modifying
1805: it by typing in a new definition:
1.1 anton 1806:
1.29 crook 1807: @example
1.30 anton 1808: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 1809: @end example
1.5 anton 1810:
1.29 crook 1811: Forth recognised that we were defining a word that already exists, and
1812: printed a message to warn us of that fact. Let's try out the new
1813: definition:
1.5 anton 1814:
1.29 crook 1815: @example
1.30 anton 1816: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 1817: @end example
1.1 anton 1818:
1.29 crook 1819: @noindent
1820: All that we've actually done here, though, is to create a new
1821: definition, with a particular name. The fact that there was already a
1822: definition with the same name did not make any difference to the way
1823: that the new definition was created (except that Forth printed a warning
1824: message). The old definition of add-two still exists (try @code{demo}
1825: again to see that this is true). Any new definition will use the new
1826: definition of @code{add-two}, but old definitions continue to use the
1827: version that already existed at the time that they were @code{compiled}.
1.1 anton 1828:
1.29 crook 1829: Before you go on to the next section, try defining and redefining some
1830: words of your own.
1.1 anton 1831:
1.29 crook 1832: @comment ----------------------------------------------
1833: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
1834: @section How does that work?
1835: @cindex parsing words
1.1 anton 1836:
1.30 anton 1837: @c That's pretty deep (IMO way too deep) for an introduction. - anton
1838:
1839: @c Is it a good idea to talk about the interpretation semantics of a
1840: @c number? We don't have an xt to go along with it. - anton
1841:
1842: @c Now that I have eliminated execution semantics, I wonder if it would not
1843: @c be better to keep them (or add run-time semantics), to make it easier to
1844: @c explain what compilation semantics usually does. - anton
1845:
1.29 crook 1846: Now we're going to take another look at the definition of @code{add-two}
1847: from the previous section. From our knowledge of the way that the text
1848: interpreter works, we would have expected this result when we tried to
1849: define @code{add-two}:
1.21 crook 1850:
1.29 crook 1851: @example
1.30 anton 1852: @kbd{: add-two 2 + . " ;@key{RET}}
1.29 crook 1853: ^^^^^^^
1854: Error: Undefined word
1855: @end example
1.28 crook 1856:
1.29 crook 1857: The reason that this didn't happen is bound up in the way that @code{:}
1858: works. The word @code{:} does two special things. The first special
1859: thing that it does prevents the text interpreter from ever seeing the
1860: characters @code{add-two}. The text interpreter uses a variable called
1861: @cindex modifying >IN
1862: @code{>IN} (pronounced ''to-in'') to keep track of where it is in the
1863: input line. When it encounters the word @code{:} it behaves in exactly
1864: the same way as it does for any other word; it looks it up in the name
1865: dictionary, finds its xt and executes it. When @code{:} executes, it
1866: looks at the input buffer, finds the word @code{add-two} and advances the
1867: value of @code{>IN} to point past it. It then does some other stuff
1868: associated with creating the new definition (including creating an entry
1869: for @code{add-two} in the name dictionary). When the execution of @code{:}
1870: completes, control returns to the text interpreter, which is oblivious
1871: to the fact that it has been tricked into ignoring part of the input
1872: line.
1.21 crook 1873:
1.29 crook 1874: @cindex parsing words
1875: Words like @code{:} -- words that advance the value of @code{>IN} and so
1876: prevent the text interpreter from acting on the whole of the input line
1877: -- are called @dfn{parsing words}.
1.21 crook 1878:
1.29 crook 1879: @cindex @code{state} - effect on the text interpreter
1880: @cindex text interpreter - effect of state
1881: The second special thing that @code{:} does is change the value of a
1882: variable called @code{state}, which affects the way that the text
1883: interpreter behaves. When Gforth starts up, @code{state} has the value
1884: 0, and the text interpreter is said to be @dfn{interpreting}. During a
1885: colon definition (started with @code{:}), @code{state} is set to -1 and
1886: the text interpreter is said to be @dfn{compiling}. The word @code{;}
1887: ends the definition -- one of the things that it does is to change the
1888: value of @code{state} back to 0.
1.21 crook 1889:
1.29 crook 1890: We have already seen how the text interpreter behaves when it is
1891: interpreting; it looks for each character sequence in the dictionary,
1892: finds its xt and executes it, or it converts it to a number and pushes
1893: it onto the stack, or it fails to do either and generates an error.
1.21 crook 1894:
1.29 crook 1895: When the text interpreter is compiling, its behaviour is slightly
1896: different; it still looks for each character sequence in the dictionary
1.30 anton 1897: and finds it, or converts it to a number, or fails to do either and
1898: generates an error. But instead of the execution token of a word it
1899: finds and executes the compilation token. For most words executing the
1900: compilation token results in laying down (@dfn{compiling}) the execution
1901: token, i.e., some magic to make that xt or number get executed or pushed
1902: at a later time; at the time that @code{add-two} is
1903: @dfn{executed}. Therefore, when you execute @code{add-two} its
1904: @dfn{run-time effect} is exactly the same as if you had typed @code{2 +
1905: .} outside of a definition, and pressed carriage-return.
1.28 crook 1906:
1.30 anton 1907: In Forth, every word or number can be described in terms of two
1.29 crook 1908: properties:
1.28 crook 1909:
1910: @itemize @bullet
1911: @item
1.30 anton 1912: Its @dfn{interpretation semantics}, represented by the execution token.
1.28 crook 1913: @item
1.30 anton 1914: Its @dfn{compilation semantics}, represented by the compilation token.
1.29 crook 1915: @end itemize
1916:
1.30 anton 1917: The value of @code{state} determines whether the text interpreter will
1918: use the compilation or interpretation semantics of a word or number that
1919: it encounters.
1.29 crook 1920:
1921: @itemize @bullet
1.28 crook 1922: @item
1.29 crook 1923: @cindex interpretation semantics
1924: When the text interpreter encounters a word or number in @dfn{interpret}
1925: state, it performs the @dfn{interpretation semantics} of the word or
1926: number.
1.28 crook 1927: @item
1.29 crook 1928: @cindex compilation semantics
1929: When the text interpreter encounters a word or number in @dfn{compile}
1930: state, it performs the @dfn{compilation semantics} of the word or
1931: number.
1932: @end itemize
1933:
1934: @noindent
1935: Numbers are always treated in a fixed way:
1936:
1937: @itemize @bullet
1.28 crook 1938: @item
1.30 anton 1939: When the number is @dfn{interpreted}, its behaviour is to push the number onto the stack.
1.28 crook 1940: @item
1.30 anton 1941: When the number is @dfn{compiled}, a piece of code is appended to the
1942: current definition that pushes the number when it runs. (In other words,
1943: the compilation semantics of a number are to postpone its interpretation
1944: semantics until the run-time of the definition that it is being compiled
1945: into.)
1.29 crook 1946: @end itemize
1947:
1948: The behaviour of a word is not so regular, but most have @i{default
1.30 anton 1949: compilation semantics} which means that they behave like this:
1.29 crook 1950:
1951: @itemize @bullet
1.28 crook 1952: @item
1.30 anton 1953: The @dfn{interpretation semantics} of the word are to do something useful.
1954: @item
1.29 crook 1955: The @dfn{compilation semantics} of the word are to append its
1.30 anton 1956: @dfn{interpretation semantics} to the current definition (so that its
1957: run-time behaviour is to do something useful).
1.28 crook 1958: @end itemize
1959:
1.30 anton 1960: @cindex immediate words
1.29 crook 1961: The actual behaviour of any particular word depends upon the way in
1962: which it was defined. When the text interpreter finds the word in the
1963: name dictionary, it not only retrieves the xt for the word, it also
1964: retrieves some flags: the @dfn{compile-only} flag and the @dfn{immediate
1965: flag}. The compile-only flag indicates that the word has no
1.30 anton 1966: interpretation semantics (the run-time behaviour for the default
1967: compilation semantics is not affected by this flag, however); any
1968: attempt to interpret a word that has the compile-only flag set will
1969: generate an error (for example, @code{IF} has no interpretation
1970: semantics). The immediate flag changes the compilation semantics of the
1971: word; if it is set, the compilation semantics are equal to the
1972: interpretation semantics (again ignoring the compile-only flag). it. In
1973: other words, these so-called @dfn{immediate} words behave like this:
1.29 crook 1974:
1975: @itemize @bullet
1976: @item
1.30 anton 1977: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 1978: @item
1.30 anton 1979: The @dfn{compilation semantics} of the word are to do something useful
1980: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 1981: @end itemize
1.28 crook 1982:
1.29 crook 1983: This example shows the difference between an immediate and a
1984: non-immediate word:
1.28 crook 1985:
1.29 crook 1986: @example
1987: : show-state state @@ . ;
1988: : show-state-now show-state ; immediate
1989: : word1 show-state ;
1990: : word2 show-state-now ;
1.28 crook 1991: @end example
1.23 crook 1992:
1.29 crook 1993: The word @code{immediate} after the definition of @code{show-state-now}
1994: makes that word an immediate word. These definitions introduce a new
1995: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
1996: variable, and leaves it on the stack. Therefore, the behaviour of
1997: @code{show-state} is to print a number that represents the current value
1998: of @code{state}.
1.28 crook 1999:
1.29 crook 2000: When you execute @code{word1}, it prints the number 0, indicating that
2001: the system is interpreting. When the text interpreter compiled the
2002: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 2003: compilation semantics are to append its interpretation semantics to the
1.29 crook 2004: current definition. When you execute @code{word1}, it performs the
1.30 anton 2005: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 2006: (and therefore @code{show-state}) are executed, the system is
2007: interpreting.
1.28 crook 2008:
1.30 anton 2009: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 2010: you should have seen the number -1 printed, followed by ``@code{
2011: ok}''. When the text interpreter compiled the definition of
2012: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 2013: whose compilation semantics are therefore to perform its interpretation
1.29 crook 2014: semantics. It is executed straight away (even before the text
2015: interpreter has moved on to process another group of characters; the
2016: @code{;} in this example). The effect of executing it are to display the
2017: value of @code{state} @i{at the time that the definition of}
2018: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
2019: system is compiling at this time. If you execute @code{word2} it does
2020: nothing at all.
1.28 crook 2021:
1.29 crook 2022: @cindex @code{."}, how it works
2023: Before leaving the subject of immediate words, consider the behaviour of
2024: @code{."} in the definition of @code{greet}, in the previous
2025: section. This word is both a parsing word and an immediate word. Notice
2026: that there is a space between @code{."} and the start of the text
2027: @code{Hello and welcome}, but that there is no space between the last
2028: letter of @code{welcome} and the @code{"} character. The reason for this
2029: is that @code{."} is a Forth word; it must have a space after it so that
2030: the text interpreter can identify it. The @code{"} is not a Forth word;
2031: it is a @dfn{delimiter}. The examples earlier show that, when the string
2032: is displayed, there is neither a space before the @code{H} nor after the
2033: @code{e}. Since @code{."} is an immediate word, it executes at the time
2034: that @code{greet} is defined. When it executes, its behaviour is to
2035: search forward in the input line looking for the delimiter. When it
2036: finds the delimiter, it updates @code{>IN} to point past the
2037: delimiter. It also compiles some magic code into the definition of
2038: @code{greet}; the xt of a run-time routine that prints a text string. It
2039: compiles the string @code{Hello and welcome} into memory so that it is
2040: available to be printed later. When the text interpreter gains control,
2041: the next word it finds in the input stream is @code{;} and so it
2042: terminates the definition of @code{greet}.
1.28 crook 2043:
2044:
2045: @comment ----------------------------------------------
1.29 crook 2046: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
2047: @section Forth is written in Forth
2048: @cindex structure of Forth programs
2049:
2050: When you start up a Forth compiler, a large number of definitions
2051: already exist. In Forth, you develop a new application using bottom-up
2052: programming techniques to create new definitions that are defined in
2053: terms of existing definitions. As you create each definition you can
2054: test and debug it interactively.
2055:
2056: If you have tried out the examples in this section, you will probably
2057: have typed them in by hand; when you leave Gforth, your definitions will
2058: be lost. You can avoid this by using a text editor to enter Forth source
2059: code into a file, and then loading code from the file using
2060: @code{include} (@xref{Forth source files}). A Forth source file is
2061: processed by the text interpreter, just as though you had typed it in by
2062: hand@footnote{Actually, there are some subtle differences -- see
2063: @ref{The Text Interpreter}.}.
2064:
2065: Gforth also supports the traditional Forth alternative to using text
2066: files for program entry (@xref{Blocks}).
1.28 crook 2067:
1.29 crook 2068: In common with many, if not most, Forth compilers, most of Gforth is
2069: actually written in Forth. All of the @file{.fs} files in the
2070: installation directory@footnote{For example,
1.30 anton 2071: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 2072: study to see examples of Forth programming.
1.28 crook 2073:
1.29 crook 2074: Gforth maintains a history file that records every line that you type to
2075: the text interpreter. This file is preserved between sessions, and is
2076: used to provide a command-line recall facility. If you enter long
2077: definitions by hand, you can use a text editor to paste them out of the
2078: history file into a Forth source file for reuse at a later time
2079: (@pxref{Command-line editing} for more information).
1.28 crook 2080:
2081:
2082: @comment ----------------------------------------------
1.29 crook 2083: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
2084: @section Review - elements of a Forth system
2085: @cindex elements of a Forth system
1.28 crook 2086:
1.29 crook 2087: To summarise this chapter:
1.28 crook 2088:
2089: @itemize @bullet
2090: @item
1.29 crook 2091: Forth programs use @dfn{factoring} to break a problem down into small
2092: fragments called @dfn{words} or @dfn{definitions}.
2093: @item
2094: Forth program development is an interactive process.
2095: @item
2096: The main command loop that accepts input, and controls both
2097: interpretation and compilation, is called the @dfn{text interpreter}
2098: (also known as the @dfn{outer interpreter}).
2099: @item
2100: Forth has a very simple syntax, consisting of words and numbers
2101: separated by spaces or carriage-return characters. Any additional syntax
2102: is imposed by @dfn{parsing words}.
2103: @item
2104: Forth uses a stack to pass parameters between words. As a result, it
2105: uses postfix notation.
2106: @item
2107: To use a word that has previously been defined, the text interpreter
2108: searches for the word in the @dfn{name dictionary}.
2109: @item
1.30 anton 2110: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 2111: @item
1.29 crook 2112: The text interpreter uses the value of @code{state} to select between
2113: the use of the @dfn{interpretation semantics} and the @dfn{compilation
2114: semantics} of a word that it encounters.
1.28 crook 2115: @item
1.30 anton 2116: The relationship between the @dfn{interpretation semantics} and
2117: @dfn{compilation semantics} for a word
1.29 crook 2118: depend upon the way in which the word was defined (for example, whether
2119: it is an @dfn{immediate} word).
1.28 crook 2120: @item
1.29 crook 2121: Forth definitions can be implemented in Forth (called @dfn{high-level
2122: definitions}) or in some other way (usually a lower-level language and
2123: as a result often called @dfn{low-level definitions}, @dfn{code
2124: definitions} or @dfn{primitives}).
1.28 crook 2125: @item
1.29 crook 2126: Many Forth systems are implemented mainly in Forth.
1.28 crook 2127: @end itemize
2128:
2129:
1.29 crook 2130: @comment ----------------------------------------------
2131: @node Where to go next,Exercises,Review - elements of a Forth system, Introduction
2132: @section Where To Go Next
2133: @cindex where to go next
1.28 crook 2134:
1.29 crook 2135: Amazing as it may seem, if you have read (and understood) this far, you
2136: know almost all the fundamentals about the inner workings of a Forth
2137: system. You certainly know enough to be able to read and understand the
2138: rest of this manual and the ANS Forth document, to learn more about the
2139: facilities that Forth in general and Gforth in particular provide. Even
2140: scarier, you know almost enough to implement your own Forth system.
1.30 anton 2141: However, that's not a good idea just yet... better to try writing some
1.29 crook 2142: programs in Gforth.
1.28 crook 2143:
1.29 crook 2144: Forth has such a rich vocabulary that it can be hard to know where to
2145: start in learning it. This section suggests a few sets of words that are
2146: enough to write small but useful programs. Use the word index in this
2147: document to learn more about each word, then try it out and try to write
2148: small definitions using it. Start by experimenting with these words:
1.28 crook 2149:
2150: @itemize @bullet
2151: @item
1.29 crook 2152: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
2153: @item
2154: Comparison: @code{MIN MAX =}
2155: @item
2156: Logic: @code{AND OR XOR NOT}
2157: @item
2158: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 2159: @item
1.29 crook 2160: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 2161: @item
1.29 crook 2162: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 2163: @item
1.29 crook 2164: Defining words: @code{: ; CREATE}
1.28 crook 2165: @item
1.29 crook 2166: Memory allocation words: @code{ALLOT ,}
1.28 crook 2167: @item
1.29 crook 2168: Tools: @code{SEE WORDS .S MARKER}
2169: @end itemize
2170:
2171: When you have mastered those, go on to:
2172:
2173: @itemize @bullet
1.28 crook 2174: @item
1.29 crook 2175: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 2176: @item
1.29 crook 2177: Memory access: @code{@@ !}
1.28 crook 2178: @end itemize
1.23 crook 2179:
1.29 crook 2180: When you have mastered these, there's nothing for it but to read through
2181: the whole of this manual and find out what you've missed.
2182:
2183: @comment ----------------------------------------------
2184: @node Exercises, ,Where to go next, Introduction
2185: @section Exercises
2186: @cindex exercises
2187:
2188: TODO: provide a set of programming excercises linked into the stuff done
2189: already and into other sections of the manual. Provide solutions to all
2190: the exercises in a .fs file in the distribution.
2191:
2192: @c Get some inspiration from Starting Forth and Kelly&Spies.
2193:
2194: @c excercises:
2195: @c 1. take inches and convert to feet and inches.
2196: @c 2. take temperature and convert from fahrenheight to celcius;
2197: @c may need to care about symmetric vs floored??
2198: @c 3. take input line and do character substitution
2199: @c to encipher or decipher
2200: @c 4. as above but work on a file for in and out
2201: @c 5. take input line and convert to pig-latin
2202: @c
2203: @c thing of sets of things to exercise then come up with
2204: @c problems that need those things.
2205:
2206:
1.26 crook 2207: @c ******************************************************************
1.29 crook 2208: @node Words, Error messages, Introduction, Top
1.1 anton 2209: @chapter Forth Words
1.26 crook 2210: @cindex words
1.1 anton 2211:
2212: @menu
2213: * Notation::
1.21 crook 2214: * Comments::
2215: * Boolean Flags::
1.1 anton 2216: * Arithmetic::
2217: * Stack Manipulation::
1.5 anton 2218: * Memory::
1.1 anton 2219: * Control Structures::
2220: * Defining Words::
1.21 crook 2221: * The Text Interpreter::
1.12 anton 2222: * Tokens for Words::
1.21 crook 2223: * Word Lists::
2224: * Environmental Queries::
1.12 anton 2225: * Files::
2226: * Blocks::
2227: * Other I/O::
2228: * Programming Tools::
2229: * Assembler and Code Words::
2230: * Threading Words::
1.26 crook 2231: * Locals::
2232: * Structures::
2233: * Object-oriented Forth::
1.21 crook 2234: * Passing Commands to the OS::
2235: * Miscellaneous Words::
1.1 anton 2236: @end menu
2237:
1.21 crook 2238: @node Notation, Comments, Words, Words
1.1 anton 2239: @section Notation
2240: @cindex notation of glossary entries
2241: @cindex format of glossary entries
2242: @cindex glossary notation format
2243: @cindex word glossary entry format
2244:
2245: The Forth words are described in this section in the glossary notation
2246: that has become a de-facto standard for Forth texts, i.e.,
2247:
2248: @format
1.29 crook 2249: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 2250: @end format
1.29 crook 2251: @i{Description}
1.1 anton 2252:
2253: @table @var
2254: @item word
1.28 crook 2255: The name of the word.
1.1 anton 2256:
2257: @item Stack effect
2258: @cindex stack effect
1.29 crook 2259: The stack effect is written in the notation @code{@i{before} --
2260: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 2261: stack entries before and after the execution of the word. The rest of
2262: the stack is not touched by the word. The top of stack is rightmost,
2263: i.e., a stack sequence is written as it is typed in. Note that Gforth
2264: uses a separate floating point stack, but a unified stack
1.29 crook 2265: notation. Also, return stack effects are not shown in @i{stack
2266: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 2267: the type and/or the function of the item. See below for a discussion of
2268: the types.
2269:
2270: All words have two stack effects: A compile-time stack effect and a
2271: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 2272: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 2273: this standard behaviour, or the word does other unusual things at
2274: compile time, both stack effects are shown; otherwise only the run-time
2275: stack effect is shown.
2276:
2277: @cindex pronounciation of words
2278: @item pronunciation
2279: How the word is pronounced.
2280:
2281: @cindex wordset
2282: @item wordset
1.21 crook 2283: The ANS Forth standard is divided into several word sets. A standard
2284: system need not support all of them. Therefore, in theory, the fewer
2285: word sets your program uses the more portable it will be. However, we
2286: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 2287: all word sets. Words that are not defined in ANS Forth have
1.21 crook 2288: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 2289: describes words that will work in future releases of Gforth;
2290: @code{gforth-internal} words are more volatile. Environmental query
2291: strings are also displayed like words; you can recognize them by the
1.21 crook 2292: @code{environment} in the word set field.
1.1 anton 2293:
2294: @item Description
2295: A description of the behaviour of the word.
2296: @end table
2297:
2298: @cindex types of stack items
2299: @cindex stack item types
2300: The type of a stack item is specified by the character(s) the name
2301: starts with:
2302:
2303: @table @code
2304: @item f
2305: @cindex @code{f}, stack item type
2306: Boolean flags, i.e. @code{false} or @code{true}.
2307: @item c
2308: @cindex @code{c}, stack item type
2309: Char
2310: @item w
2311: @cindex @code{w}, stack item type
2312: Cell, can contain an integer or an address
2313: @item n
2314: @cindex @code{n}, stack item type
2315: signed integer
2316: @item u
2317: @cindex @code{u}, stack item type
2318: unsigned integer
2319: @item d
2320: @cindex @code{d}, stack item type
2321: double sized signed integer
2322: @item ud
2323: @cindex @code{ud}, stack item type
2324: double sized unsigned integer
2325: @item r
2326: @cindex @code{r}, stack item type
2327: Float (on the FP stack)
1.21 crook 2328: @item a-
1.1 anton 2329: @cindex @code{a_}, stack item type
2330: Cell-aligned address
1.21 crook 2331: @item c-
1.1 anton 2332: @cindex @code{c_}, stack item type
2333: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 2334: @item f-
1.1 anton 2335: @cindex @code{f_}, stack item type
2336: Float-aligned address
1.21 crook 2337: @item df-
1.1 anton 2338: @cindex @code{df_}, stack item type
2339: Address aligned for IEEE double precision float
1.21 crook 2340: @item sf-
1.1 anton 2341: @cindex @code{sf_}, stack item type
2342: Address aligned for IEEE single precision float
2343: @item xt
2344: @cindex @code{xt}, stack item type
2345: Execution token, same size as Cell
2346: @item wid
2347: @cindex @code{wid}, stack item type
1.21 crook 2348: Word list ID, same size as Cell
1.1 anton 2349: @item f83name
2350: @cindex @code{f83name}, stack item type
2351: Pointer to a name structure
2352: @item "
2353: @cindex @code{"}, stack item type
1.12 anton 2354: string in the input stream (not on the stack). The terminating character
2355: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 2356: quotes.
2357: @end table
2358:
1.21 crook 2359: @node Comments, Boolean Flags, Notation, Words
2360: @section Comments
1.26 crook 2361: @cindex comments
1.21 crook 2362:
1.29 crook 2363: Forth supports two styles of comment; the traditional @i{in-line} comment,
2364: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 2365:
1.23 crook 2366: doc-(
1.21 crook 2367: doc-\
1.23 crook 2368: doc-\G
1.21 crook 2369:
2370: @node Boolean Flags, Arithmetic, Comments, Words
2371: @section Boolean Flags
1.26 crook 2372: @cindex Boolean flags
1.21 crook 2373:
2374: A Boolean flag is cell-sized. A cell with all bits clear represents the
2375: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 2376: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 2377: a cell that has @i{any} bit set as @code{true}.
1.21 crook 2378:
2379: doc-true
2380: doc-false
1.29 crook 2381: doc-on
2382: doc-off
1.21 crook 2383:
2384: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 2385: @section Arithmetic
2386: @cindex arithmetic words
2387:
2388: @cindex division with potentially negative operands
2389: Forth arithmetic is not checked, i.e., you will not hear about integer
2390: overflow on addition or multiplication, you may hear about division by
2391: zero if you are lucky. The operator is written after the operands, but
2392: the operands are still in the original order. I.e., the infix @code{2-1}
2393: corresponds to @code{2 1 -}. Forth offers a variety of division
2394: operators. If you perform division with potentially negative operands,
2395: you do not want to use @code{/} or @code{/mod} with its undefined
2396: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
2397: former, @pxref{Mixed precision}).
1.26 crook 2398: @comment TODO discuss the different division forms and the std approach
1.1 anton 2399:
2400: @menu
2401: * Single precision::
2402: * Bitwise operations::
1.21 crook 2403: * Double precision:: Double-cell integer arithmetic
2404: * Numeric comparison::
1.29 crook 2405: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 2406: * Floating Point::
2407: @end menu
2408:
2409: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
2410: @subsection Single precision
2411: @cindex single precision arithmetic words
2412:
1.21 crook 2413: By default, numbers in Forth are single-precision integers that are 1
1.26 crook 2414: cell in size. They can be signed or unsigned, depending upon how you
1.21 crook 2415: treat them. @xref{Number Conversion} for the rules used by the text
2416: interpreter for recognising single-precision integers.
2417:
1.1 anton 2418: doc-+
1.21 crook 2419: doc-1+
1.1 anton 2420: doc--
1.21 crook 2421: doc-1-
1.1 anton 2422: doc-*
2423: doc-/
2424: doc-mod
2425: doc-/mod
2426: doc-negate
2427: doc-abs
2428: doc-min
2429: doc-max
1.21 crook 2430: doc-d>s
1.27 crook 2431: doc-floored
1.1 anton 2432:
1.21 crook 2433: @node Bitwise operations, Double precision, Single precision, Arithmetic
1.1 anton 2434: @subsection Bitwise operations
2435: @cindex bitwise operation words
2436:
2437: doc-and
2438: doc-or
2439: doc-xor
2440: doc-invert
1.21 crook 2441: doc-lshift
2442: doc-rshift
1.1 anton 2443: doc-2*
1.21 crook 2444: doc-d2*
1.1 anton 2445: doc-2/
1.21 crook 2446: doc-d2/
2447:
2448: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
2449: @subsection Double precision
2450: @cindex double precision arithmetic words
2451:
2452: @xref{Number Conversion} for the rules used by the text interpreter for
2453: recognising double-precision integers.
2454:
2455: A double precision number is represented by a cell pair, with the most
1.31 anton 2456: significant cell at the TOS. It is trivial to convert an unsigned
1.26 crook 2457: single to an (unsigned) double; simply push a @code{0} onto the
2458: TOS. Since numbers are represented by Gforth using 2's complement
2459: arithmetic, converting a signed single to a (signed) double requires
1.31 anton 2460: sign-extension across the most significant cell. This can be achieved
1.26 crook 2461: using @code{s>d}. The moral of the story is that you cannot convert a
2462: number without knowing whether it represents an unsigned or a
2463: signed number.
1.21 crook 2464:
2465: doc-s>d
2466: doc-d+
2467: doc-d-
2468: doc-dnegate
2469: doc-dabs
2470: doc-dmin
2471: doc-dmax
2472:
2473: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
2474: @subsection Numeric comparison
2475: @cindex numeric comparison words
2476:
1.28 crook 2477: doc-<
2478: doc-<=
2479: doc-<>
2480: doc-=
2481: doc->
2482: doc->=
2483:
1.21 crook 2484: doc-0<
1.23 crook 2485: doc-0<=
1.21 crook 2486: doc-0<>
2487: doc-0=
1.23 crook 2488: doc-0>
2489: doc-0>=
1.28 crook 2490:
2491: doc-u<
2492: doc-u<=
1.31 anton 2493: @c TODO why u<> and u= ... they are the same as <> and =
2494: @c commented them out because they are unnecessary
2495: @c doc-u<>
2496: @c doc-u=
1.28 crook 2497: doc-u>
2498: doc-u>=
2499:
2500: doc-within
2501:
2502: doc-d<
2503: doc-d<=
2504: doc-d<>
2505: doc-d=
2506: doc-d>
2507: doc-d>=
1.23 crook 2508:
1.21 crook 2509: doc-d0<
1.23 crook 2510: doc-d0<=
2511: doc-d0<>
1.21 crook 2512: doc-d0=
1.23 crook 2513: doc-d0>
2514: doc-d0>=
2515:
1.21 crook 2516: doc-du<
1.28 crook 2517: doc-du<=
1.31 anton 2518: @c doc-du<>
2519: @c doc-du=
1.28 crook 2520: doc-du>
2521: doc-du>=
1.1 anton 2522:
1.21 crook 2523: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 2524: @subsection Mixed precision
2525: @cindex mixed precision arithmetic words
2526:
2527: doc-m+
2528: doc-*/
2529: doc-*/mod
2530: doc-m*
2531: doc-um*
2532: doc-m*/
2533: doc-um/mod
2534: doc-fm/mod
2535: doc-sm/rem
2536:
1.21 crook 2537: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 2538: @subsection Floating Point
2539: @cindex floating point arithmetic words
2540:
1.21 crook 2541: @xref{Number Conversion} for the rules used by the text interpreter for
2542: recognising floating-point numbers.
1.1 anton 2543:
1.32 anton 2544: Gforth has a separate floating point
1.26 crook 2545: stack, but the documentation uses the unified notation.
1.1 anton 2546:
2547: @cindex floating-point arithmetic, pitfalls
2548: Floating point numbers have a number of unpleasant surprises for the
2549: unwary (e.g., floating point addition is not associative) and even a few
2550: for the wary. You should not use them unless you know what you are doing
2551: or you don't care that the results you get are totally bogus. If you
2552: want to learn about the problems of floating point numbers (and how to
2553: avoid them), you might start with @cite{David Goldberg, What Every
2554: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
1.17 anton 2555: Computing Surveys 23(1):5@minus{}48, March 1991}
2556: (@url{http://www.validgh.com/goldberg/paper.ps}).
1.1 anton 2557:
1.21 crook 2558: doc-d>f
2559: doc-f>d
1.1 anton 2560: doc-f+
2561: doc-f-
2562: doc-f*
2563: doc-f/
2564: doc-fnegate
2565: doc-fabs
2566: doc-fmax
2567: doc-fmin
2568: doc-floor
2569: doc-fround
2570: doc-f**
2571: doc-fsqrt
2572: doc-fexp
2573: doc-fexpm1
2574: doc-fln
2575: doc-flnp1
2576: doc-flog
2577: doc-falog
1.32 anton 2578: doc-f2*
2579: doc-f2/
2580: doc-1/f
2581: doc-precision
2582: doc-set-precision
2583:
2584: @cindex angles in trigonometric operations
2585: @cindex trigonometric operations
2586: Angles in floating point operations are given in radians (a full circle
2587: has 2 pi radians).
2588:
1.1 anton 2589: doc-fsin
2590: doc-fcos
2591: doc-fsincos
2592: doc-ftan
2593: doc-fasin
2594: doc-facos
2595: doc-fatan
2596: doc-fatan2
2597: doc-fsinh
2598: doc-fcosh
2599: doc-ftanh
2600: doc-fasinh
2601: doc-facosh
2602: doc-fatanh
1.21 crook 2603: doc-pi
1.28 crook 2604:
1.32 anton 2605: @cindex equality of floats
2606: @cindex floating-point comparisons
1.31 anton 2607: One particular problem with floating-point arithmetic is that comparison
2608: for equality often fails when you would expect it to succeed. For this
2609: reason approximate equality is often preferred (but you still have to
2610: know what you are doing). The comparison words are:
2611:
2612: doc-f~rel
2613: doc-f~abs
2614: doc-f=
2615: doc-f~
2616: doc-f<>
2617:
2618: doc-f<
2619: doc-f<=
2620: doc-f>
2621: doc-f>=
2622:
1.21 crook 2623: doc-f0<
1.28 crook 2624: doc-f0<=
2625: doc-f0<>
1.21 crook 2626: doc-f0=
1.28 crook 2627: doc-f0>
2628: doc-f0>=
2629:
1.1 anton 2630:
2631: @node Stack Manipulation, Memory, Arithmetic, Words
2632: @section Stack Manipulation
2633: @cindex stack manipulation words
2634:
2635: @cindex floating-point stack in the standard
1.21 crook 2636: Gforth maintains a number of separate stacks:
2637:
1.29 crook 2638: @cindex data stack
2639: @cindex parameter stack
1.21 crook 2640: @itemize @bullet
2641: @item
1.29 crook 2642: A data stack (also known as the @dfn{parameter stack}) -- for
2643: characters, cells, addresses, and double cells.
1.21 crook 2644:
1.29 crook 2645: @cindex floating-point stack
1.21 crook 2646: @item
2647: A floating point stack -- for floating point numbers.
2648:
1.29 crook 2649: @cindex return stack
1.21 crook 2650: @item
2651: A return stack -- for storing the return addresses of colon
1.32 anton 2652: definitions and other (non-FP) data.
1.21 crook 2653:
1.29 crook 2654: @cindex locals stack
1.21 crook 2655: @item
2656: A locals stack for storing local variables.
2657: @end itemize
2658:
1.1 anton 2659: @menu
2660: * Data stack::
2661: * Floating point stack::
2662: * Return stack::
2663: * Locals stack::
2664: * Stack pointer manipulation::
2665: @end menu
2666:
2667: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
2668: @subsection Data stack
2669: @cindex data stack manipulation words
2670: @cindex stack manipulations words, data stack
2671:
2672: doc-drop
2673: doc-nip
2674: doc-dup
2675: doc-over
2676: doc-tuck
2677: doc-swap
1.21 crook 2678: doc-pick
1.1 anton 2679: doc-rot
2680: doc--rot
2681: doc-?dup
2682: doc-roll
2683: doc-2drop
2684: doc-2nip
2685: doc-2dup
2686: doc-2over
2687: doc-2tuck
2688: doc-2swap
2689: doc-2rot
2690:
2691: @node Floating point stack, Return stack, Data stack, Stack Manipulation
2692: @subsection Floating point stack
2693: @cindex floating-point stack manipulation words
2694: @cindex stack manipulation words, floating-point stack
2695:
1.32 anton 2696: Whilst every sane Forth has a separate floating-point stack, it is not
2697: strictly required; an ANS Forth system could theoretically keep
2698: floating-point numbers on the data stack. As an additional difficulty,
2699: you don't know how many cells a floating-point number takes. It is
2700: reportedly possible to write words in a way that they work also for a
2701: unified stack model, but we do not recommend trying it. Instead, just
2702: say that your program has an environmental dependency on a separate
2703: floating-point stack.
2704:
2705: doc-floating-stack
2706:
1.1 anton 2707: doc-fdrop
2708: doc-fnip
2709: doc-fdup
2710: doc-fover
2711: doc-ftuck
2712: doc-fswap
1.21 crook 2713: doc-fpick
1.1 anton 2714: doc-frot
2715:
2716: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
2717: @subsection Return stack
2718: @cindex return stack manipulation words
2719: @cindex stack manipulation words, return stack
2720:
1.32 anton 2721: @cindex return stack and locals
2722: @cindex locals and return stack
2723: A Forth system is allowed to keep local variables on the
2724: return stack. This is reasonable, as local variables usually eliminate
2725: the need to use the return stack explicitly. So, if you want to produce
2726: a standard compliant program and you are using local variables in a
2727: word, forget about return stack manipulations in that word (refer to the
2728: standard document for the exact rules).
2729:
1.1 anton 2730: doc->r
2731: doc-r>
2732: doc-r@
2733: doc-rdrop
2734: doc-2>r
2735: doc-2r>
2736: doc-2r@
2737: doc-2rdrop
2738:
2739: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
2740: @subsection Locals stack
2741:
1.26 crook 2742: @comment TODO
1.21 crook 2743:
1.1 anton 2744: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
2745: @subsection Stack pointer manipulation
2746: @cindex stack pointer manipulation words
2747:
1.21 crook 2748: doc-sp0
1.1 anton 2749: doc-sp@
2750: doc-sp!
1.21 crook 2751: doc-fp0
1.1 anton 2752: doc-fp@
2753: doc-fp!
1.21 crook 2754: doc-rp0
1.1 anton 2755: doc-rp@
2756: doc-rp!
1.21 crook 2757: doc-lp0
1.1 anton 2758: doc-lp@
2759: doc-lp!
2760:
2761: @node Memory, Control Structures, Stack Manipulation, Words
2762: @section Memory
1.26 crook 2763: @cindex memory words
1.1 anton 2764:
1.32 anton 2765: @menu
2766: * Memory model::
2767: * Dictionary allocation::
2768: * Heap Allocation::
2769: * Memory Access::
2770: * Address arithmetic::
2771: * Memory Blocks::
2772: @end menu
2773:
2774: @node Memory model, Dictionary allocation, Memory, Memory
2775: @subsection ANS Forth and Gforth memory models
2776:
2777: @c The ANS Forth description is a mess (e.g., is the heap part of
2778: @c the dictionary?), so let's not stick to closely with it.
2779:
2780: ANS Forth considers a Forth system as consisting of several memories, of
2781: which only @dfn{data space} is managed and accessible with the memory
2782: words. Memory not necessarily in data space includes the stacks, the
2783: code (called code space) and the headers (called name space). In Gforth
2784: everything is in data space, but the code for the primitives is usually
2785: read-only.
2786:
2787: Data space is divided into a number of areas: The (data space portion of
2788: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
2789: refer to the search data structure embodied in word lists and headers,
2790: because it is used for looking up names, just as you would in a
2791: conventional dictionary.}, the heap, and a number of system-allocated
2792: buffers.
2793:
2794: In ANS Forth data space is also divided into contiguous regions. You
2795: can only use address arithmetic within a contiguous region, not between
2796: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 2797: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 2798: allocation}).
2799:
2800: Gforth provides one big address space, and address arithmetic can be
2801: performed between any addresses. However, in the dictionary headers or
2802: code are interleaved with data, so almost the only contiguous data space
2803: regions there are those described by ANS Forth as contiguous; but you
2804: can be sure that the dictionary is allocated towards increasing
2805: addresses even between contiguous regions. The memory order of
2806: allocations in the heap is platform-dependent (and possibly different
2807: from one run to the next).
2808:
2809: @subsubsection ANS Forth dictionary details
2810:
2811: @c !! I have deleted some of the stuff this section refers to - anton
1.27 crook 2812:
1.32 anton 2813: This section is just informative, you can skip it if you are in a hurry.
1.27 crook 2814:
1.29 crook 2815: When you create a colon definition, the text interpreter compiles the
1.32 anton 2816: code for the definition into the code space and compiles the name
2817: of the definition into the header space, together with other
1.27 crook 2818: information about the definition (such as its execution token).
2819:
2820: When you create a variable, the execution of @code{variable} will
1.32 anton 2821: compile some code, assign one cell in data space, and compile the name
2822: of the variable into the header space.
1.27 crook 2823:
2824: @cindex memory regions - relationship between them
2825: ANS Forth does not specify the relationship between the three memory
2826: regions, and specifies that a Standard program must not access code or
2827: data space directly -- it may only access data space directly. In
2828: addition, the Standard defines what relationships you may and may not
2829: rely on when allocating regions in data space. These constraints are
2830: simply a reflection of the many diverse techniques that are used to
2831: implement Forth systems; understanding and following the requirements of
2832: the Standard allows you to write portable programs -- programs that run
2833: in the same way on any of these diverse systems. Another way of looking
2834: at this is to say that ANS Forth was designed to permit compliant Forth
2835: systems to be implemented in many diverse ways.
2836:
2837: @cindex memory regions - how they are assigned
1.29 crook 2838: Here are some examples of ways in which name, code and data spaces
2839: might be assigned in different Forth implementations:
1.27 crook 2840:
2841: @itemize @bullet
2842: @item
2843: For a Forth system that runs from RAM under a general-purpose operating
2844: system, it can be convenient to interleave name, code and data spaces in
2845: a single contiguous memory region. This organisation can be
2846: memory-efficient (for example, because the relationship between the name
1.32 anton 2847: dictionary entry and the associated code space entry can be
1.27 crook 2848: implicit, rather than requiring an explicit memory pointer to reference
1.32 anton 2849: from the header space and the code space). This is the
1.27 crook 2850: organisation used by Gforth, as this example@footnote{The addresses
2851: in the example have been truncated to fit it onto the page, and the
2852: addresses and data shown will not match the output from your system} shows:
2853: @example
2854: hex
2855: variable fred 123456 fred !
2856: variable jim abcd jim !
2857: : foo + / - ;
2858: ' fred 10 - 50 dump
2859: ..80: 5C 46 0E 40 84 66 72 65 - 64 20 20 20 20 20 20 20 \F.@.fred
2860: ..90: D0 9B 04 08 00 00 00 00 - 56 34 12 00 80 46 0E 40 ........V4...F.@
2861: ..A0: 83 6A 69 6D 20 20 20 20 - D0 9B 04 08 00 00 00 00 .jim ........
2862: ..B0: CD AB 00 00 9C 46 0E 40 - 83 66 6F 6F 20 20 20 20 .....F.@.foo
2863: ..C0: 80 9B 04 08 00 00 00 00 - E4 2E 05 08 0C 2F 05 08 ............./..
2864: @end example
2865:
2866: @item
2867: For a high-performance system running on a modern RISC processor with a
2868: modified Harvard architecture (one that has a unified main memory but
2869: separate instruction and data caches), it is desirable to separate
2870: processor instructions from processor data. This encourages a high cache
1.32 anton 2871: density and therefore a high cache hit rate. The Forth code space
1.27 crook 2872: is not necessarily made up entirely of processor instructions; its
2873: nature is dependent upon the Forth implementation.
2874:
2875: @item
2876: A Forth compiler that runs on a segmented 8086 processor could be
2877: designed to interleave the name, code and data spaces within a single
2878: 64Kbyte segment. A more common implementation choice is to use a
2879: separate 64Kbyte segment for each region, which provides more memory
2880: overall but provides an address map in which only the data space is
2881: accessible.
2882:
2883: @item
2884: Microprocessors exist that run Forth (or many of the primitives required
2885: to implement the Forth virtual machine efficiently) directly. On these
2886: processors, the relationship between name, code and data spaces may be
1.32 anton 2887: imposed as a side-effect of the architecture of the processor.
1.27 crook 2888:
2889: @item
2890: A Forth compiler that executes from ROM on an embedded system needs its
2891: data space separated from the name and code spaces so that the data
2892: space can be mapped to a RAM area.
2893:
2894: @item
2895: A Forth compiler that runs on an embedded system may have a requirement
2896: for a small memory footprint. On such a system it can be useful to
1.32 anton 2897: separate the header space from the data and code spaces; once the
2898: application has been compiled, the header space is no longer
1.27 crook 2899: required@footnote{more strictly speaking, most applications can be
1.32 anton 2900: designed so that this is the case}. The header space can be deleted
1.29 crook 2901: entirely, or could be stored in memory on a remote @i{host} system for
1.27 crook 2902: debug and development purposes. In the latter case, the compiler running
1.29 crook 2903: on the @i{target} system could implement a protocol across a
1.32 anton 2904: communication link that would allow it to interrogate the header space.
1.27 crook 2905: @end itemize
2906:
1.1 anton 2907:
1.32 anton 2908: @node Dictionary allocation, Heap Allocation, Memory model, Memory
2909: @subsection Dictionary allocation
1.27 crook 2910: @cindex reserving data space
2911: @cindex data space - reserving some
2912:
1.32 anton 2913: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
2914: you want to deallocate X, you also deallocate everything
2915: allocated after X.
2916:
2917: The allocations using the words below are contiguous and grow the region
2918: towards increasing addresses. Other words that allocate dictionary
2919: memory of any kind (i.e., defining words including @code{:noname}) end
2920: the contiguous region and start a new one.
2921:
2922: In ANS Forth only @code{create}d words are guaranteed to produce an
2923: address that is the start of the following contiguous region. In
2924: particular, the cell allocated by @code{variable} is not guaranteed to
2925: be contiguous with following @code{allot}ed memory.
2926:
2927: You can deallocate memory by using @code{allot} with a negative argument
2928: (with some restrictions, see @code{allot}). For larger deallocations use
2929: @code{marker}.
1.27 crook 2930:
1.29 crook 2931:
1.27 crook 2932: doc-here
2933: doc-unused
2934: doc-allot
2935: doc-c,
1.29 crook 2936: doc-f,
1.27 crook 2937: doc-,
2938: doc-2,
1.29 crook 2939: @cindex user space
2940: doc-udp
2941: doc-uallot
1.27 crook 2942:
1.32 anton 2943: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
2944: course you should allocate memory in an aligned way, too. I.e., before
2945: allocating allocating a cell, @code{here} must be cell-aligned, etc.
2946: The words below align @code{here} if it is not already. Basically it is
2947: only already aligned for a type, if the last allocation was a multiple
2948: of the size of this type and if @code{here} was aligned for this type
2949: before.
2950:
2951: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
2952: ANS Forth (@code{maxalign}ed in Gforth).
2953:
2954: doc-align
2955: doc-falign
2956: doc-sfalign
2957: doc-dfalign
2958: doc-maxalign
2959: doc-cfalign
2960:
2961:
2962: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
2963: @subsection Heap allocation
2964: @cindex heap allocation
2965: @cindex dynamic allocation of memory
2966: @cindex memory-allocation word set
2967:
2968: Heap allocation supports deallocation of allocated memory in any
2969: order. Dictionary allocation is not affected by it (i.e., it does not
2970: end a contiguous region). In Gforth, these words are implemented using
2971: the standard C library calls malloc(), free() and resize().
2972:
2973: doc-allocate
2974: doc-free
2975: doc-resize
2976:
1.27 crook 2977:
1.32 anton 2978: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 2979: @subsection Memory Access
2980: @cindex memory access words
2981:
2982: doc-@
2983: doc-!
2984: doc-+!
2985: doc-c@
2986: doc-c!
2987: doc-2@
2988: doc-2!
2989: doc-f@
2990: doc-f!
2991: doc-sf@
2992: doc-sf!
2993: doc-df@
2994: doc-df!
2995:
1.32 anton 2996: @node Address arithmetic, Memory Blocks, Memory Access, Memory
2997: @subsection Address arithmetic
1.1 anton 2998: @cindex address arithmetic words
2999:
1.32 anton 3000: Address arithmetic is the foundation on which data structures like
3001: arrays, records (@pxref{Structures}) and objects (@pxref{Object-oriented
3002: Forth}) are built.
3003:
1.1 anton 3004: ANS Forth does not specify the sizes of the data types. Instead, it
3005: offers a number of words for computing sizes and doing address
1.29 crook 3006: arithmetic. Address arithmetic is performed in terms of address units
3007: (aus); on most systems the address unit is one byte. Note that a
3008: character may have more than one au, so @code{chars} is no noop (on
3009: systems where it is a noop, it compiles to nothing).
1.1 anton 3010:
3011: @cindex alignment of addresses for types
3012: ANS Forth also defines words for aligning addresses for specific
3013: types. Many computers require that accesses to specific data types
3014: must only occur at specific addresses; e.g., that cells may only be
3015: accessed at addresses divisible by 4. Even if a machine allows unaligned
3016: accesses, it can usually perform aligned accesses faster.
3017:
3018: For the performance-conscious: alignment operations are usually only
3019: necessary during the definition of a data structure, not during the
3020: (more frequent) accesses to it.
3021:
3022: ANS Forth defines no words for character-aligning addresses. This is not
3023: an oversight, but reflects the fact that addresses that are not
3024: char-aligned have no use in the standard and therefore will not be
3025: created.
3026:
3027: @cindex @code{CREATE} and alignment
1.29 crook 3028: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 3029: are cell-aligned; in addition, Gforth guarantees that these addresses
3030: are aligned for all purposes.
3031:
1.26 crook 3032: Note that the ANS Forth word @code{char} has nothing to do with address
3033: arithmetic.
1.1 anton 3034:
3035: doc-chars
3036: doc-char+
3037: doc-cells
3038: doc-cell+
3039: doc-cell
3040: doc-aligned
3041: doc-floats
3042: doc-float+
3043: doc-float
3044: doc-faligned
3045: doc-sfloats
3046: doc-sfloat+
3047: doc-sfaligned
3048: doc-dfloats
3049: doc-dfloat+
3050: doc-dfaligned
3051: doc-maxaligned
3052: doc-cfaligned
3053: doc-address-unit-bits
3054:
1.32 anton 3055: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 3056: @subsection Memory Blocks
3057: @cindex memory block words
1.27 crook 3058: @cindex character strings - moving and copying
3059:
3060: Memory blocks often represent character strings; @xref{String Formats}
3061: for ways of storing character strings in memory. @xref{Displaying
3062: characters and strings} for other string-processing words.
1.1 anton 3063:
1.32 anton 3064: Some of these words work on address units. Others work on character
3065: units (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
3066: address. Choose the correct operation depending upon your data type.
1.21 crook 3067:
3068: When copying characters between overlapping memory regions, choose
3069: carefully between @code{cmove} and @code{cmove>}.
3070:
1.29 crook 3071: You can only use any of these words @i{portably} to access data space.
1.21 crook 3072:
1.27 crook 3073: @comment TODO - think the naming of the arguments is wrong for move
1.29 crook 3074: @comment well, really it seems to be the Standard that's wrong; it
3075: @comment describes MOVE as a word that requires a CELL-aligned source
3076: @comment and destination address but a xtranfer count that need not
3077: @comment be a multiple of CELL.
1.1 anton 3078: doc-move
3079: doc-erase
3080: doc-cmove
3081: doc-cmove>
3082: doc-fill
3083: doc-blank
1.21 crook 3084: doc-compare
3085: doc-search
1.27 crook 3086: doc--trailing
3087: doc-/string
3088:
3089: @comment TODO examples
3090:
1.1 anton 3091:
1.26 crook 3092: @node Control Structures, Defining Words, Memory, Words
1.1 anton 3093: @section Control Structures
3094: @cindex control structures
3095:
1.33 anton 3096: Control structures in Forth cannot be used interpretively, only in a
3097: colon definition@footnote{To be precise, they have no interpretation
3098: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
3099: not like this limitation, but have not seen a satisfying way around it
3100: yet, although many schemes have been proposed.
1.1 anton 3101:
3102: @menu
1.33 anton 3103: * Selection:: IF ... ELSE ... ENDIF
3104: * Simple Loops:: BEGIN ...
1.29 crook 3105: * Counted Loops:: DO
3106: * Arbitrary control structures::
3107: * Calls and returns::
1.1 anton 3108: * Exception Handling::
3109: @end menu
3110:
3111: @node Selection, Simple Loops, Control Structures, Control Structures
3112: @subsection Selection
3113: @cindex selection control structures
3114: @cindex control structures for selection
3115:
1.33 anton 3116: @c what's the purpose of all these @i? Maybe we should define a macro
3117: @c so we can produce logical markup. - anton
3118:
1.1 anton 3119: @cindex @code{IF} control structure
3120: @example
1.29 crook 3121: @i{flag}
1.1 anton 3122: IF
1.29 crook 3123: @i{code}
1.1 anton 3124: ENDIF
3125: @end example
1.21 crook 3126: @noindent
1.33 anton 3127:
3128: @var{code} is executed if @var{flag} is non-zero (that's truth as far as
3129: @code{IF} etc. are concerned).
3130:
1.1 anton 3131: @example
1.29 crook 3132: @i{flag}
1.1 anton 3133: IF
1.29 crook 3134: @i{code1}
1.1 anton 3135: ELSE
1.29 crook 3136: @i{code2}
1.1 anton 3137: ENDIF
3138: @end example
3139:
1.33 anton 3140: If @var{flag} is true, perform @var{code1}, otherwise @var{code2}.
3141:
1.1 anton 3142: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
3143: standard, and @code{ENDIF} is not, although it is quite popular. We
3144: recommend using @code{ENDIF}, because it is less confusing for people
3145: who also know other languages (and is not prone to reinforcing negative
3146: prejudices against Forth in these people). Adding @code{ENDIF} to a
3147: system that only supplies @code{THEN} is simple:
3148: @example
1.21 crook 3149: : ENDIF POSTPONE THEN ; immediate
1.1 anton 3150: @end example
3151:
3152: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
3153: (adv.)} has the following meanings:
3154: @quotation
3155: ... 2b: following next after in order ... 3d: as a necessary consequence
3156: (if you were there, then you saw them).
3157: @end quotation
3158: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
3159: and many other programming languages has the meaning 3d.]
3160:
1.21 crook 3161: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 3162: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 3163: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 3164: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
3165: @file{compat/control.fs}.
3166:
3167: @cindex @code{CASE} control structure
3168: @example
1.29 crook 3169: @i{n}
1.1 anton 3170: CASE
1.29 crook 3171: @i{n1} OF @i{code1} ENDOF
3172: @i{n2} OF @i{code2} ENDOF
1.1 anton 3173: @dots{}
3174: ENDCASE
3175: @end example
3176:
1.29 crook 3177: Executes the first @i{codei}, where the @i{ni} is equal to
3178: @i{n}. A default case can be added by simply writing the code after
3179: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
1.1 anton 3180: but must not consume it.
3181:
3182: @node Simple Loops, Counted Loops, Selection, Control Structures
3183: @subsection Simple Loops
3184: @cindex simple loops
3185: @cindex loops without count
3186:
3187: @cindex @code{WHILE} loop
3188: @example
3189: BEGIN
1.29 crook 3190: @i{code1}
3191: @i{flag}
1.1 anton 3192: WHILE
1.29 crook 3193: @i{code2}
1.1 anton 3194: REPEAT
3195: @end example
3196:
1.29 crook 3197: @i{code1} is executed and @i{flag} is computed. If it is true,
3198: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 3199: false, execution continues after the @code{REPEAT}.
3200:
3201: @cindex @code{UNTIL} loop
3202: @example
3203: BEGIN
1.29 crook 3204: @i{code}
3205: @i{flag}
1.1 anton 3206: UNTIL
3207: @end example
3208:
1.29 crook 3209: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 3210:
3211: @cindex endless loop
3212: @cindex loops, endless
3213: @example
3214: BEGIN
1.29 crook 3215: @i{code}
1.1 anton 3216: AGAIN
3217: @end example
3218:
3219: This is an endless loop.
3220:
3221: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
3222: @subsection Counted Loops
3223: @cindex counted loops
3224: @cindex loops, counted
3225: @cindex @code{DO} loops
3226:
3227: The basic counted loop is:
3228: @example
1.29 crook 3229: @i{limit} @i{start}
1.1 anton 3230: ?DO
1.29 crook 3231: @i{body}
1.1 anton 3232: LOOP
3233: @end example
3234:
1.29 crook 3235: This performs one iteration for every integer, starting from @i{start}
3236: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 3237: accessed with @code{i}. For example, the loop:
1.1 anton 3238: @example
3239: 10 0 ?DO
3240: i .
3241: LOOP
3242: @end example
1.21 crook 3243: @noindent
3244: prints @code{0 1 2 3 4 5 6 7 8 9}
3245:
1.1 anton 3246: The index of the innermost loop can be accessed with @code{i}, the index
3247: of the next loop with @code{j}, and the index of the third loop with
3248: @code{k}.
3249:
3250: doc-i
3251: doc-j
3252: doc-k
3253:
3254: The loop control data are kept on the return stack, so there are some
1.21 crook 3255: restrictions on mixing return stack accesses and counted loop words. In
3256: particuler, if you put values on the return stack outside the loop, you
3257: cannot read them inside the loop@footnote{well, not in a way that is
3258: portable.}. If you put values on the return stack within a loop, you
3259: have to remove them before the end of the loop and before accessing the
3260: index of the loop.
1.1 anton 3261:
3262: There are several variations on the counted loop:
3263:
1.21 crook 3264: @itemize @bullet
3265: @item
3266: @code{LEAVE} leaves the innermost counted loop immediately; execution
3267: continues after the associated @code{LOOP} or @code{NEXT}. For example:
3268:
3269: @example
3270: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
3271: @end example
3272: prints @code{0 1 2 3}
3273:
1.1 anton 3274:
1.21 crook 3275: @item
3276: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
3277: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
3278: return stack so @code{EXIT} can get to its return address. For example:
3279:
3280: @example
3281: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
3282: @end example
3283: prints @code{0 1 2 3}
3284:
3285:
3286: @item
1.29 crook 3287: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 3288: (and @code{LOOP} iterates until they become equal by wrap-around
3289: arithmetic). This behaviour is usually not what you want. Therefore,
3290: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 3291: @code{?DO}), which do not enter the loop if @i{start} is greater than
3292: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 3293: unsigned loop parameters.
3294:
1.21 crook 3295: @item
3296: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
3297: the loop, independent of the loop parameters. Do not use @code{DO}, even
3298: if you know that the loop is entered in any case. Such knowledge tends
3299: to become invalid during maintenance of a program, and then the
3300: @code{DO} will make trouble.
3301:
3302: @item
1.29 crook 3303: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
3304: index by @i{n} instead of by 1. The loop is terminated when the border
3305: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 3306:
1.21 crook 3307: @example
3308: 4 0 +DO i . 2 +LOOP
3309: @end example
3310: @noindent
3311: prints @code{0 2}
3312:
3313: @example
3314: 4 1 +DO i . 2 +LOOP
3315: @end example
3316: @noindent
3317: prints @code{1 3}
1.1 anton 3318:
3319:
3320: @cindex negative increment for counted loops
3321: @cindex counted loops with negative increment
1.29 crook 3322: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 3323:
1.21 crook 3324: @example
3325: -1 0 ?DO i . -1 +LOOP
3326: @end example
3327: @noindent
3328: prints @code{0 -1}
1.1 anton 3329:
1.21 crook 3330: @example
3331: 0 0 ?DO i . -1 +LOOP
3332: @end example
3333: prints nothing.
1.1 anton 3334:
1.29 crook 3335: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
3336: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
3337: index by @i{u} each iteration. The loop is terminated when the border
3338: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 3339: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
3340:
1.21 crook 3341: @example
3342: -2 0 -DO i . 1 -LOOP
3343: @end example
3344: @noindent
3345: prints @code{0 -1}
1.1 anton 3346:
1.21 crook 3347: @example
3348: -1 0 -DO i . 1 -LOOP
3349: @end example
3350: @noindent
3351: prints @code{0}
3352:
3353: @example
3354: 0 0 -DO i . 1 -LOOP
3355: @end example
3356: @noindent
3357: prints nothing.
1.1 anton 3358:
1.21 crook 3359: @end itemize
1.1 anton 3360:
3361: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 3362: @code{-LOOP} are not defined in ANS Forth. However, an implementation
3363: for these words that uses only standard words is provided in
3364: @file{compat/loops.fs}.
1.1 anton 3365:
3366:
3367: @cindex @code{FOR} loops
1.26 crook 3368: Another counted loop is:
1.1 anton 3369: @example
1.29 crook 3370: @i{n}
1.1 anton 3371: FOR
1.29 crook 3372: @i{body}
1.1 anton 3373: NEXT
3374: @end example
3375: This is the preferred loop of native code compiler writers who are too
1.26 crook 3376: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 3377: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
3378: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 3379: Forth systems may behave differently, even if they support @code{FOR}
3380: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 3381:
3382: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
3383: @subsection Arbitrary control structures
3384: @cindex control structures, user-defined
3385:
3386: @cindex control-flow stack
3387: ANS Forth permits and supports using control structures in a non-nested
3388: way. Information about incomplete control structures is stored on the
3389: control-flow stack. This stack may be implemented on the Forth data
3390: stack, and this is what we have done in Gforth.
3391:
3392: @cindex @code{orig}, control-flow stack item
3393: @cindex @code{dest}, control-flow stack item
3394: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
3395: entry represents a backward branch target. A few words are the basis for
3396: building any control structure possible (except control structures that
3397: need storage, like calls, coroutines, and backtracking).
3398:
3399: doc-if
3400: doc-ahead
3401: doc-then
3402: doc-begin
3403: doc-until
3404: doc-again
3405: doc-cs-pick
3406: doc-cs-roll
3407:
1.21 crook 3408: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
3409: manipulate the control-flow stack in a portable way. Without them, you
3410: would need to know how many stack items are occupied by a control-flow
3411: entry (many systems use one cell. In Gforth they currently take three,
3412: but this may change in the future).
3413:
1.1 anton 3414: Some standard control structure words are built from these words:
3415:
3416: doc-else
3417: doc-while
3418: doc-repeat
3419:
3420: Gforth adds some more control-structure words:
3421:
3422: doc-endif
3423: doc-?dup-if
3424: doc-?dup-0=-if
3425:
3426: Counted loop words constitute a separate group of words:
3427:
3428: doc-?do
3429: doc-+do
3430: doc-u+do
3431: doc--do
3432: doc-u-do
3433: doc-do
3434: doc-for
3435: doc-loop
3436: doc-+loop
3437: doc--loop
3438: doc-next
3439: doc-leave
3440: doc-?leave
3441: doc-unloop
3442: doc-done
3443:
1.21 crook 3444: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
3445: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 3446: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
3447: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
3448: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
3449: resolved (by using one of the loop-ending words or @code{DONE}).
3450:
1.26 crook 3451: Another group of control structure words are:
1.1 anton 3452:
3453: doc-case
3454: doc-endcase
3455: doc-of
3456: doc-endof
3457:
1.21 crook 3458: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
3459: @code{CS-ROLL}.
1.1 anton 3460:
3461: @subsubsection Programming Style
3462:
3463: In order to ensure readability we recommend that you do not create
3464: arbitrary control structures directly, but define new control structure
3465: words for the control structure you want and use these words in your
1.26 crook 3466: program. For example, instead of writing:
1.1 anton 3467:
3468: @example
1.26 crook 3469: BEGIN
1.1 anton 3470: ...
1.26 crook 3471: IF [ 1 CS-ROLL ]
1.1 anton 3472: ...
1.26 crook 3473: AGAIN THEN
1.1 anton 3474: @end example
3475:
1.21 crook 3476: @noindent
1.1 anton 3477: we recommend defining control structure words, e.g.,
3478:
3479: @example
1.26 crook 3480: : WHILE ( DEST -- ORIG DEST )
3481: POSTPONE IF
3482: 1 CS-ROLL ; immediate
3483:
3484: : REPEAT ( orig dest -- )
3485: POSTPONE AGAIN
3486: POSTPONE THEN ; immediate
1.1 anton 3487: @end example
3488:
1.21 crook 3489: @noindent
1.1 anton 3490: and then using these to create the control structure:
3491:
3492: @example
1.26 crook 3493: BEGIN
1.1 anton 3494: ...
1.26 crook 3495: WHILE
1.1 anton 3496: ...
1.26 crook 3497: REPEAT
1.1 anton 3498: @end example
3499:
3500: That's much easier to read, isn't it? Of course, @code{REPEAT} and
3501: @code{WHILE} are predefined, so in this example it would not be
3502: necessary to define them.
3503:
3504: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
3505: @subsection Calls and returns
3506: @cindex calling a definition
3507: @cindex returning from a definition
3508:
1.3 anton 3509: @cindex recursive definitions
3510: A definition can be called simply be writing the name of the definition
1.26 crook 3511: to be called. Normally a definition is invisible during its own
1.3 anton 3512: definition. If you want to write a directly recursive definition, you
1.26 crook 3513: can use @code{recursive} to make the current definition visible, or
3514: @code{recurse} to call the current definition directly.
1.3 anton 3515:
3516: doc-recursive
3517: doc-recurse
3518:
1.21 crook 3519: @comment TODO add example of the two recursion methods
1.12 anton 3520: @quotation
3521: @progstyle
3522: I prefer using @code{recursive} to @code{recurse}, because calling the
3523: definition by name is more descriptive (if the name is well-chosen) than
3524: the somewhat cryptic @code{recurse}. E.g., in a quicksort
3525: implementation, it is much better to read (and think) ``now sort the
3526: partitions'' than to read ``now do a recursive call''.
3527: @end quotation
1.3 anton 3528:
1.29 crook 3529: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 3530:
3531: @example
1.28 crook 3532: Defer foo
1.3 anton 3533:
3534: : bar ( ... -- ... )
3535: ... foo ... ;
3536:
3537: :noname ( ... -- ... )
3538: ... bar ... ;
3539: IS foo
3540: @end example
3541:
1.33 anton 3542: Deferred words are discussed in more detail in @ref{Simple
3543: Defining Words}.
3544:
1.26 crook 3545: The current definition returns control to the calling definition when
1.33 anton 3546: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 3547:
3548: doc-exit
3549: doc-;s
3550:
3551: @node Exception Handling, , Calls and returns, Control Structures
3552: @subsection Exception Handling
1.26 crook 3553: @cindex exceptions
1.1 anton 3554:
1.26 crook 3555: If your program detects a fatal error condition, the simplest action
3556: that it can take is to @code{quit}. This resets the return stack and
3557: restarts the text interpreter, but does not print any error message.
1.21 crook 3558:
1.26 crook 3559: The next stage in severity is to execute @code{abort}, which has the
3560: same effect as @code{quit}, with the addition that it resets the data
3561: stack.
1.1 anton 3562:
1.26 crook 3563: A slightly more sophisticated approach is use use @code{abort"}, which
3564: compiles a string to be used as an error message and does a conditional
3565: @code{abort} at run-time. For example:
1.1 anton 3566:
1.26 crook 3567: @example
1.30 anton 3568: @kbd{: checker abort" That flag was true" ." A false flag" ;@key{RET}} ok
3569: @kbd{0 checker@key{RET}} A false flag ok
3570: @kbd{1 checker@key{RET}}
1.26 crook 3571: :1: That flag was true
3572: 1 checker
3573: ^^^^^^^
3574: $400D1648 throw
3575: $400E4660
3576: @end example
1.1 anton 3577:
1.26 crook 3578: These simple techniques allow a program to react to a fatal error
3579: condition, but they are not exactly user-friendly. The ANS Forth
3580: Exception word set provides the pair of words @code{throw} and
3581: @code{catch}, which can be used to provide sophisticated error-handling.
1.1 anton 3582:
1.26 crook 3583: @code{catch} has a similar behaviour to @code{execute}, in that it takes
1.29 crook 3584: an @i{xt} as a parameter and starts execution of the xt. However,
1.26 crook 3585: before passing control to the xt, @code{catch} pushes an
1.29 crook 3586: @dfn{exception frame} onto the @dfn{exception stack}. This exception
1.26 crook 3587: frame is used to restore the system to a known state if a detected error
3588: occurs during the execution of the xt. A typical way to use @code{catch}
3589: would be:
1.1 anton 3590:
1.26 crook 3591: @example
3592: ... ['] foo catch IF ...
3593: @end example
1.1 anton 3594:
1.33 anton 3595: @c TOS is undefined. - anton
1.26 crook 3596: Whilst @code{foo} executes, it can call other words to any level of
3597: nesting, as usual. If @code{foo} (and all the words that it calls)
1.33 anton 3598: execute successfully, control will ultimately pass to the word following
3599: the @code{catch}, and there will be a 0 at TOS. However, if any word
3600: detects an error, it can terminate the execution of @code{foo} by
3601: pushing a non-zero error code onto the stack and then performing a
3602: @code{throw}. The execution of @code{throw} will pass control to the
3603: word following the @code{catch}, but this time the TOS will hold the
3604: error code. Therefore, the @code{IF} in the example can be used to
3605: determine whether @code{foo} executed successfully.
1.1 anton 3606:
1.26 crook 3607: This simple example shows how you can use @code{throw} and @code{catch}
3608: to ``take over'' exception handling from the system:
1.1 anton 3609: @example
1.26 crook 3610: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
1.1 anton 3611: @end example
3612:
1.26 crook 3613: The next example is more sophisticated and shows a multi-level
3614: @code{throw} and @code{catch}. To understand this example, start at the
3615: definition of @code{top-level} and work backwards:
3616:
1.1 anton 3617: @example
1.26 crook 3618: : lowest-level ( -- c )
3619: key dup 27 = if
3620: 1 throw \ ESCAPE key pressed
3621: else
3622: ." lowest-level successfull" CR
3623: then
3624: ;
3625:
3626: : lower-level ( -- c )
3627: lowest-level
3628: \ at this level consider a CTRL-U to be a fatal error
3629: dup 21 = if \ CTRL-U
3630: 2 throw
3631: else
3632: ." lower-level successfull" CR
3633: then
3634: ;
3635:
3636: : low-level ( -- c )
3637: ['] lower-level catch
3638: ?dup if
3639: \ error occurred - do we recognise it?
3640: dup 1 = if
3641: \ ESCAPE key pressed.. pretend it was an E
3642: [char] E
3643: else throw \ propogate the error upwards
3644: then
3645: then
3646: ." low-level successfull" CR
3647: ;
3648:
3649: : top-level ( -- )
3650: CR ['] low-level catch \ CATCH is used like EXECUTE
3651: ?dup if \ error occurred..
3652: ." Error " . ." occurred - contact your supplier"
3653: else
3654: ." The '" emit ." ' key was pressed" CR
3655: then
3656: ;
1.1 anton 3657: @end example
3658:
1.26 crook 3659: The ANS Forth document assigns @code{throw} codes thus:
1.1 anton 3660:
1.26 crook 3661: @itemize @bullet
3662: @item
3663: codes in the range -1 -- -255 are reserved to be assigned by the
3664: Standard. Assignments for codes in the range -1 -- -58 are currently
3665: documented in the Standard. In particular, @code{-1 throw} is equivalent
3666: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
3667: @item
3668: codes in the range -256 -- -4095 are reserved to be assigned by the system.
3669: @item
3670: all other codes may be assigned by programs.
3671: @end itemize
1.1 anton 3672:
1.26 crook 3673: Gforth provides the word @code{exception} as a mechanism for assigning
3674: system throw codes to applications. This allows multiple applications to
3675: co-exist in memory without any clash of @code{throw} codes. A definition
3676: of @code{exception} in ANS Forth is provided in
3677: @file{compat/exception.fs}.
1.1 anton 3678:
1.26 crook 3679: doc-quit
3680: doc-abort
3681: doc-abort"
1.1 anton 3682:
1.26 crook 3683: doc-catch
1.29 crook 3684: doc-throw
3685: doc---exception-exception
3686:
3687:
3688: @c -------------------------------------------------------------
3689: @node Defining Words, The Text Interpreter, Control Structures, Words
3690: @section Defining Words
3691: @cindex defining words
3692:
3693: @menu
3694: * Simple Defining Words:: Variables, values and constants
3695: * Colon Definitions::
3696: * User-defined Defining Words::
3697: * Supplying names::
3698: * Interpretation and Compilation Semantics::
3699: @end menu
3700:
3701: @node Simple Defining Words, Colon Definitions, Defining Words, Defining Words
3702: @subsection Simple Defining Words
3703: @cindex simple defining words
3704: @cindex defining words, simple
3705:
1.33 anton 3706: @c split this section?
3707:
1.29 crook 3708: Defining words are used to create new entries in the dictionary. The
3709: simplest defining word is @code{CREATE}. @code{CREATE} is used like
3710: this:
3711:
3712: @example
3713: CREATE new-word1
3714: @end example
3715:
3716: @code{CREATE} is a parsing word that generates a dictionary entry for
3717: @code{new-word1}. When @code{new-word1} is executed, all that it does is
3718: leave an address on the stack. The address represents the value of
3719: the data space pointer (@code{HERE}) at the time that @code{new-word1}
3720: was defined. Therefore, @code{CREATE} is a way of associating a name
3721: with the address of a region of memory.
3722:
1.34 anton 3723: doc-create
3724:
1.29 crook 3725: By extending this example to reserve some memory in data space, we end
3726: up with a @i{variable}. Here are two different ways to do it:
3727:
3728: @example
3729: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
3730: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
3731: @end example
3732:
3733: The variable can be examined and modified using @code{@@} (``fetch'') and
3734: @code{!} (``store'') like this:
3735:
3736: @example
3737: new-word2 @@ . \ get address, fetch from it and display
3738: 1234 new-word2 ! \ new value, get address, store to it
3739: @end example
3740:
3741: As a final refinement, the whole code sequence can be wrapped up in a
3742: defining word (pre-empting the subject of the next section), making it
3743: easier to create new variables:
3744:
3745: @example
1.33 anton 3746: : myvariable ( "name" -- a-addr ) CREATE 0 , ;
1.29 crook 3747:
3748: myvariable foo
3749: myvariable joe
3750:
3751: 45 3 * foo ! \ set foo to 135
3752: 1234 joe ! \ set joe to 1234
3753: 3 joe +! \ increment joe by 3.. to 1237
3754: @end example
3755:
3756: Not surprisingly, there is no need to define @code{myvariable}, since
3757: Forth already has a definition @code{Variable}. It behaves in exactly
1.33 anton 3758: the same way as @code{myvariable}. Forth also provides @code{2Variable}
3759: and @code{fvariable} for double and floating-point variables,
3760: respectively.
1.29 crook 3761:
1.34 anton 3762: doc-variable
3763: doc-2variable
3764: doc-fvariable
3765:
1.29 crook 3766: @cindex arrays
3767: A similar mechanism can be used to create arrays. For example, an
3768: 80-character text input buffer:
3769:
3770: @example
3771: CREATE text-buf 80 chars allot
3772:
3773: text-buf 0 chars c@@ \ the 1st character (offset 0)
3774: text-buf 3 chars c@@ \ the 4th character (offset 3)
3775: @end example
3776:
3777: You can build arbitrarily complex data structures by allocating
3778: appropriate areas of memory. @xref{Structures} for further discussions
3779: of this, and to learn about some Gforth tools that make it easier.
3780:
3781: @cindex user variables
3782: @cindex user space
3783: The defining word @code{User} behaves in the same way as @code{Variable}.
3784: The difference is that it reserves space in @i{user (data) space} rather
3785: than normal data space. In a Forth system that has a multi-tasker, each
3786: task has its own set of user variables.
3787:
1.34 anton 3788: doc-user
3789:
1.29 crook 3790: @comment TODO is that stuff about user variables strictly correct? Is it
3791: @comment just terminal tasks that have user variables?
3792: @comment should document tasker.fs (with some examples) elsewhere
3793: @comment in this manual, then expand on user space and user variables.
3794:
3795: After @code{CREATE} and @code{Variable}s, the next defining word to
3796: consider is @code{Constant}. @code{Constant} allows you to declare a
3797: fixed value and refer to it by name. For example:
3798:
3799: @example
3800: 12 Constant INCHES-PER-FOOT
3801: 3E+08 fconstant SPEED-O-LIGHT
3802: @end example
3803:
3804: A @code{Variable} can be both read and written, so its run-time
3805: behaviour is to supply an address through which its current value can be
3806: manipulated. In contrast, the value of a @code{Constant} cannot be
3807: changed once it has been declared@footnote{Well, often it can be -- but
3808: not in a Standard, portable way. It's safer to use a @code{Value} (read
3809: on).} so it's not necessary to supply the address -- it is more
3810: efficient to return the value of the constant directly. That's exactly
3811: what happens; the run-time effect of a constant is to put its value on
3812: the top of the stack (@ref{User-defined Defining Words} describes one
3813: way of implementing @code{Constant}).
3814:
3815: Gforth also provides @code{2Constant} and @code{fconstant} for defining
3816: double and floating-point constants, respectively.
3817:
1.34 anton 3818: doc-constant
3819: doc-2constant
3820: doc-fconstant
3821:
3822: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.29 crook 3823: Constants in Forth behave differently from their equivalents in other
3824: programming languages. In other languages, a constant (such as an EQU in
3825: assembler or a #define in C) only exists at compile-time; in the
3826: executable program the constant has been translated into an absolute
3827: number and, unless you are using a symbolic debugger, it's impossible to
3828: know what abstract thing that number represents. In Forth a constant has
1.32 anton 3829: an entry in the header space and remains there after the code that
1.29 crook 3830: uses it has been defined. In fact, it must remain in the dictionary
3831: since it has run-time duties to perform. For example:
3832:
3833: @example
3834: 12 Constant INCHES-PER-FOOT
3835: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
3836: @end example
3837:
3838: @cindex in-lining of constants
3839: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
3840: associated with the constant @code{INCHES-PER-FOOT}. If you use
3841: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
3842: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
3843: attempt to optimise constants by in-lining them where they are used. You
3844: can force Gforth to in-line a constant like this:
3845:
3846: @example
3847: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
3848: @end example
3849:
3850: If you use @code{see} to decompile @i{this} version of
3851: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.33 anton 3852: longer present. @xref{Interpret/Compile states} and @ref{Literals} on
3853: how this works.
1.29 crook 3854:
3855: In-lining constants in this way might improve execution time
3856: fractionally, and can ensure that a constant is now only referenced at
3857: compile-time. However, the definition of the constant still remains in
3858: the dictionary. Some Forth compilers provide a mechanism for controlling
3859: a second dictionary for holding transient words such that this second
3860: dictionary can be deleted later in order to recover memory
3861: space. However, there is no standard way of doing this.
3862:
3863: One aspect of constants and variables that can sometimes be confusing is
3864: that they have different stack effects; one returns its value whilst the
3865: other returns the address of its value. The defining word @code{Value}
3866: provides an alternative to @code{Variable}, and has the same stack
3867: effect as a constant. A @code{Value} needs an additional word, @code{TO}
3868: to allow its value to be changed. Here are some examples:
3869:
3870: @example
3871: 12 Value APPLES \ a Value is initialised when it is declared.. like a
3872: \ constant but unlike a variable
3873: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
3874: APPLES \ puts 34 on the top of the stack.
3875: @end example
3876:
1.34 anton 3877: doc-value
3878: doc-to
3879:
1.29 crook 3880: The defining word @code{Defer} allows you to define a word by name
3881: without defining its behaviour; the definition of its behaviour is
3882: deferred. Here are two situation where this can be useful:
3883:
3884: @itemize @bullet
3885: @item
3886: Where you want to allow the behaviour of a word to be altered later, and
3887: for all precompiled references to the word to change when its behaviour
3888: is changed.
3889: @item
3890: For mutual recursion; @xref{Calls and returns}.
3891: @end itemize
3892:
3893: In the following example, @code{foo} always invokes the version of
3894: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
3895: always invokes the version that prints ``@code{Hello}''. There is no way
3896: of getting @code{foo} to use the later version without re-ordering the
3897: source code and recompilng it.
3898:
3899: @example
3900: : greet ." Good morning" ;
3901: : foo ... greet ... ;
3902: : greet ." Hello" ;
3903: : bar ... greet ... ;
3904: @end example
3905:
3906: This problem can be solved by defining @code{greet} as a @code{Defer}red
3907: word. The behaviour of a @code{Defer}red word can be defined and
3908: redefined at any time by using @code{IS} to associate the xt of a
3909: previously-defined word with it. The previous example becomes:
3910:
3911: @example
3912: Defer greet
3913: : foo ... greet ... ;
3914: : bar ... greet ... ;
3915: : greet1 ." Good morning" ;
3916: : greet2 ." Hello" ;
1.35 anton 3917: ' greet2 <IS> greet \ make greet behave like greet2
3918: @end example
3919:
3920: One thing to note is that @code{<IS>} consumes it's name when it is
3921: executed. If you want to specify the name at compile time, use
3922: @code{[IS]}:
3923:
3924: @example
3925: : set-greet ( xt -- )
3926: [IS] greet ;
3927:
3928: ' greet1 set-greet
1.29 crook 3929: @end example
3930:
3931: A deferred word can only inherit default semantics from the xt (because
3932: that is all that an xt can represent -- @pxref{Tokens for Words} for
3933: more discussion of this). However, the semantics of the deferred word
3934: itself can be modified at the time that it is defined. For example:
3935:
3936: @example
3937: : bar .... ; compile-only
3938: Defer fred immediate
3939: Defer jim
3940:
1.35 anton 3941: ' bar <IS> jim \ jim has default semantics
3942: ' bar <IS> fred \ fred is immediate
1.29 crook 3943: @end example
1.1 anton 3944:
1.34 anton 3945: doc-defer
1.35 anton 3946: doc-<is>
3947: doc-[is]
3948: @comment TODO document these: what's defers [is]
1.34 anton 3949: doc-what's
3950: doc-defers
3951:
3952: Definitions in ANS Forth for @code{defer}, @code{<is>} and
3953: @code{[is]} are provided in @file{compat/defer.fs}.
3954:
1.29 crook 3955: The defining word @code{Alias} allows you to define a word by name that
3956: has the same behaviour as some other word. Here are two situation where
3957: this can be useful:
1.1 anton 3958:
1.29 crook 3959: @itemize @bullet
3960: @item
3961: When you want access to a word's definition from a different word list
3962: (for an example of this, see the definition of the @code{Root} word list
3963: in the Gforth source).
3964: @item
3965: When you want to create a synonym; a definition that can be known by
3966: either of two names (for example, @code{THEN} and @code{ENDIF} are
3967: aliases).
3968: @end itemize
1.1 anton 3969:
1.29 crook 3970: The word whose behaviour the alias is to inherit is represented by an
1.34 anton 3971: xt. Therefore, the alias only inherits default semantics from its
1.29 crook 3972: ancestor. The semantics of the alias itself can be modified at the time
3973: that it is defined. For example:
1.1 anton 3974:
1.29 crook 3975: @example
3976: : foo ... ; immediate
1.1 anton 3977:
1.29 crook 3978: ' foo Alias bar \ bar is not an immediate word
3979: ' foo Alias fooby immediate \ fooby is an immediate word
3980: @end example
1.26 crook 3981:
1.34 anton 3982: @c "combined words" is an undefined term
3983: Words that are aliases have the same xt, different headers in the
3984: dictionary, and consequently different name tokens (@pxref{Tokens for
3985: Words}) and possibly different immediate flags. An alias can only have
3986: default or immediate compilation semantics; you can define aliases for
3987: combined words with @code{interpret/compile:}.
1.27 crook 3988:
1.33 anton 3989: @c distribute this to the appropriate paragraphs? - anton
1.29 crook 3990: doc-alias
1.1 anton 3991:
1.26 crook 3992: @node Colon Definitions, User-defined Defining Words, Simple Defining Words, Defining Words
3993: @subsection Colon Definitions
3994: @cindex colon definitions
1.1 anton 3995:
1.26 crook 3996: @example
3997: : name ( ... -- ... )
3998: word1 word2 word3 ;
3999: @end example
1.1 anton 4000:
1.29 crook 4001: @noindent
4002: Creates a word called @code{name} that, upon execution, executes
1.26 crook 4003: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.1 anton 4004:
1.29 crook 4005: The explanation above is somewhat superficial. @xref{Your first
4006: definition} for simple examples of colon definitions, then
4007: @xref{Interpretation and Compilation Semantics} for an in-depth
4008: discussion of some of the issues involved.
1.26 crook 4009:
4010: doc-:
4011: doc-;
1.1 anton 4012:
1.26 crook 4013: @node User-defined Defining Words, Supplying names, Colon Definitions, Defining Words
4014: @subsection User-defined Defining Words
4015: @cindex user-defined defining words
4016: @cindex defining words, user-defined
1.1 anton 4017:
1.29 crook 4018: You can create a new defining word by wrapping defining-time code around
4019: an existing defining word and putting the sequence in a colon
4020: definition. For example, suppose that you have a word @code{stats} that
4021: gathers statistics about colon definitions given the @i{xt} of the
4022: definition, and you want every colon definition in your application to
4023: make a call to @code{stats}. You can define and use a new version of
4024: @code{:} like this:
4025:
4026: @example
4027: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
4028: ... ; \ other code
4029:
4030: : my: : lastxt postpone literal ['] stats compile, ;
4031:
4032: my: foo + - ;
4033: @end example
4034:
4035: When @code{foo} is defined using @code{my:} these steps occur:
4036:
4037: @itemize @bullet
4038: @item
4039: @code{my:} is executed.
4040: @item
4041: The @code{:} within the definition (the one between @code{my:} and
4042: @code{lastxt}) is executed, and does just what it always does; it parses
4043: the input stream for a name, builds a dictionary header for the name
4044: @code{foo} and switches @code{state} from interpret to compile.
4045: @item
4046: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
4047: being defined -- @code{foo} -- onto the stack.
4048: @item
4049: The code that was produced by @code{postpone literal} is executed; this
4050: causes the value on the stack to be compiled as a literal in the code
4051: area of @code{foo}.
4052: @item
4053: The code @code{['] stats} compiles a literal into the definition of
4054: @code{my:}. When @code{compile,} is executed, that literal -- the
4055: execution token for @code{stats} -- is layed down in the code area of
4056: @code{foo} , following the literal@footnote{Strictly speaking, the
4057: mechanism that @code{compile,} uses to convert an @i{xt} into something
4058: in the code area is implementation-dependent. A threaded implementation
4059: might spit out the execution token directly whilst another
4060: implementation might spit out a native code sequence.}.
4061: @item
4062: At this point, the execution of @code{my:} is complete, and control
4063: returns to the text interpreter. The text interpreter is in compile
4064: state, so subsequent text @code{+ -} is compiled into the definition of
4065: @code{foo} and the @code{;} terminates the definition as always.
4066: @end itemize
4067:
4068: You can use @code{see} to decompile a word that was defined using
4069: @code{my:} and see how it is different from a normal @code{:}
4070: definition. For example:
4071:
4072: @example
4073: : bar + - ; \ like foo but using : rather than my:
4074: see bar
4075: : bar
4076: + - ;
4077: see foo
4078: : foo
4079: 107645672 stats + - ;
4080:
4081: \ use ' stats . to show that 107645672 is the xt for stats
4082: @end example
4083:
4084:
1.33 anton 4085: @c a deferred word is not neccessary for these examples. - anton
1.29 crook 4086: Rather than edit your application's source code to change every @code{:}
4087: to a @code{my:}, use a deferred word:
4088:
4089: @example
4090: : real: : ; \ retain access to the original
4091: defer : \ redefine as a deferred word
4092: ' my: IS : \ use special version of :
4093: \
4094: \ load application here
4095: \
4096: ' real: IS : \ go back to the original
4097: @end example
4098:
4099: You can use techniques like this to make new defining words in terms of
4100: @i{any} existing defining word.
1.1 anton 4101:
4102:
1.29 crook 4103: @cindex defining defining words
1.26 crook 4104: @cindex @code{CREATE} ... @code{DOES>}
4105: If you want the words defined with your defining words to behave
4106: differently from words defined with standard defining words, you can
4107: write your defining word like this:
1.1 anton 4108:
4109: @example
1.26 crook 4110: : def-word ( "name" -- )
1.29 crook 4111: CREATE @i{code1}
1.26 crook 4112: DOES> ( ... -- ... )
1.29 crook 4113: @i{code2} ;
1.26 crook 4114:
4115: def-word name
1.1 anton 4116: @end example
4117:
1.29 crook 4118: @cindex child words
4119: This fragment defines a @dfn{defining word} @code{def-word} and then
4120: executes it. When @code{def-word} executes, it @code{CREATE}s a new
4121: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
4122: is not executed at this time. The word @code{name} is sometimes called a
4123: @dfn{child} of @code{def-word}.
4124:
4125: When you execute @code{name}, the address of the body of @code{name} is
4126: put on the data stack and @i{code2} is executed (the address of the body
4127: of @code{name} is the address @code{HERE} returns immediately after the
4128: @code{CREATE}).
4129:
4130: @cindex atavism in child words
1.33 anton 4131: You can use @code{def-word} to define a set of child words that behave
1.29 crook 4132: differently, though atavistically; they all have a common run-time
4133: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
4134: builds a data area in the body of the child word. The structure of the
4135: data is common to all children of @code{def-word}, but the data values
4136: are specific -- and private -- to each child word. When a child word is
4137: executed, the address of its private data area is passed as a parameter
4138: on TOS to be used and manipulated@footnote{It is legitimate both to read
4139: and write to this data area.} by @i{code2}.
4140:
4141: The two fragments of code that make up the defining words act (are
4142: executed) at two completely separate times:
1.1 anton 4143:
1.29 crook 4144: @itemize @bullet
4145: @item
4146: At @i{define time}, the defining word executes @i{code1} to generate a
4147: child word
4148: @item
4149: At @i{child execution time}, when a child word is invoked, @i{code2}
4150: is executed, using parameters (data) that are private and specific to
4151: the child word.
4152: @end itemize
4153:
4154: @c NAC I think this is a really bad example, because it diminishes
4155: @c rather than emphasising the fact that some important stuff happens
4156: @c at define time, and other important stuff happens at child-invocation
4157: @c time, and that those two times are potentially very different.
1.33 anton 4158:
4159: @c Well, IMO CREATE-DOES> is usually presented with much ado, making
4160: @c people think that it's hard to understand, and making those people who
4161: @c understand it easily think that it's hyped. I prefer presenting it in a
4162: @c diminished way and only emphasize the special issues later. - anton
4163:
4164: In other words, if you make the following definitions:
4165: @example
4166: : def-word1 ( "name" -- )
4167: CREATE @i{code1} ;
4168:
4169: : action1 ( ... -- ... )
4170: @i{code2} ;
4171:
4172: def-word1 name1
4173: @end example
4174:
4175: Using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 4176:
1.29 crook 4177: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 4178:
1.1 anton 4179: @example
1.29 crook 4180: : CONSTANT ( w "name" -- )
4181: CREATE ,
1.26 crook 4182: DOES> ( -- w )
4183: @@ ;
1.1 anton 4184: @end example
4185:
1.29 crook 4186: @comment There is a beautiful description of how this works and what
4187: @comment it does in the Forthwrite 100th edition.. as well as an elegant
4188: @comment commentary on the Counting Fruits problem.
4189:
4190: When you create a constant with @code{5 CONSTANT five}, a set of
4191: define-time actions take place; first a new word @code{five} is created,
4192: then the value 5 is laid down in the body of @code{five} with
4193: @code{,}. When @code{five} is invoked, the address of the body is put on
4194: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
4195: no code of its own; it simply contains a data field and a pointer to the
4196: code that follows @code{DOES>} in its defining word. That makes words
4197: created in this way very compact.
4198:
4199: The final example in this section is intended to remind you that space
4200: reserved in @code{CREATE}d words is @i{data} space and therefore can be
4201: both read and written by a Standard program@footnote{Exercise: use this
4202: example as a starting point for your own implementation of @code{Value}
4203: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
4204: @code{[']}.}:
4205:
4206: @example
4207: : foo ( "name" -- )
4208: CREATE -1 ,
4209: DOES> ( -- )
1.33 anton 4210: @@ . ;
1.29 crook 4211:
4212: foo first-word
4213: foo second-word
4214:
4215: 123 ' first-word >BODY !
4216: @end example
4217:
4218: If @code{first-word} had been a @code{CREATE}d word, we could simply
4219: have executed it to get the address of its data field. However, since it
4220: was defined to have @code{DOES>} actions, its execution semantics are to
4221: perform those @code{DOES>} actions. To get the address of its data field
4222: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
4223: translate the xt into the address of the data field. When you execute
4224: @code{first-word}, it will display @code{123}. When you execute
4225: @code{second-word} it will display @code{-1}.
1.26 crook 4226:
4227: @cindex stack effect of @code{DOES>}-parts
4228: @cindex @code{DOES>}-parts, stack effect
1.29 crook 4229: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 4230: the stack effect of the defined words, not the stack effect of the
4231: following code (the following code expects the address of the body on
4232: the top of stack, which is not reflected in the stack comment). This is
4233: the convention that I use and recommend (it clashes a bit with using
4234: locals declarations for stack effect specification, though).
1.1 anton 4235:
1.26 crook 4236: @subsubsection Applications of @code{CREATE..DOES>}
4237: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 4238:
1.26 crook 4239: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 4240:
1.26 crook 4241: @cindex factoring similar colon definitions
4242: When you see a sequence of code occurring several times, and you can
4243: identify a meaning, you will factor it out as a colon definition. When
4244: you see similar colon definitions, you can factor them using
4245: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
4246: that look very similar:
1.1 anton 4247: @example
1.26 crook 4248: : ori, ( reg-target reg-source n -- )
4249: 0 asm-reg-reg-imm ;
4250: : andi, ( reg-target reg-source n -- )
4251: 1 asm-reg-reg-imm ;
1.1 anton 4252: @end example
4253:
1.26 crook 4254: @noindent
4255: This could be factored with:
4256: @example
4257: : reg-reg-imm ( op-code -- )
4258: CREATE ,
4259: DOES> ( reg-target reg-source n -- )
4260: @@ asm-reg-reg-imm ;
4261:
4262: 0 reg-reg-imm ori,
4263: 1 reg-reg-imm andi,
4264: @end example
1.1 anton 4265:
1.26 crook 4266: @cindex currying
4267: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
4268: supply a part of the parameters for a word (known as @dfn{currying} in
4269: the functional language community). E.g., @code{+} needs two
4270: parameters. Creating versions of @code{+} with one parameter fixed can
4271: be done like this:
1.1 anton 4272: @example
1.26 crook 4273: : curry+ ( n1 -- )
4274: CREATE ,
4275: DOES> ( n2 -- n1+n2 )
4276: @@ + ;
4277:
4278: 3 curry+ 3+
4279: -2 curry+ 2-
1.1 anton 4280: @end example
4281:
1.26 crook 4282: @subsubsection The gory details of @code{CREATE..DOES>}
4283: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 4284:
1.26 crook 4285: doc-does>
1.1 anton 4286:
1.26 crook 4287: @cindex @code{DOES>} in a separate definition
4288: This means that you need not use @code{CREATE} and @code{DOES>} in the
4289: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 4290: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 4291: @example
4292: : does1
4293: DOES> ( ... -- ... )
4294: ... ;
1.1 anton 4295:
1.26 crook 4296: : does2
4297: DOES> ( ... -- ... )
4298: ... ;
1.1 anton 4299:
1.26 crook 4300: : def-word ( ... -- ... )
4301: create ...
4302: IF
4303: does1
4304: ELSE
4305: does2
4306: ENDIF ;
4307: @end example
1.1 anton 4308:
1.26 crook 4309: In this example, the selection of whether to use @code{does1} or
4310: @code{does2} is made at compile-time; at the time that the child word is
1.29 crook 4311: @code{CREATE}d.
1.1 anton 4312:
1.26 crook 4313: @cindex @code{DOES>} in interpretation state
4314: In a standard program you can apply a @code{DOES>}-part only if the last
4315: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
4316: will override the behaviour of the last word defined in any case. In a
4317: standard program, you can use @code{DOES>} only in a colon
4318: definition. In Gforth, you can also use it in interpretation state, in a
4319: kind of one-shot mode; for example:
1.1 anton 4320: @example
1.26 crook 4321: CREATE name ( ... -- ... )
1.29 crook 4322: @i{initialization}
1.26 crook 4323: DOES>
1.29 crook 4324: @i{code} ;
1.1 anton 4325: @end example
4326:
1.26 crook 4327: @noindent
4328: is equivalent to the standard:
1.1 anton 4329: @example
1.26 crook 4330: :noname
4331: DOES>
1.29 crook 4332: @i{code} ;
1.26 crook 4333: CREATE name EXECUTE ( ... -- ... )
1.29 crook 4334: @i{initialization}
1.1 anton 4335: @end example
4336:
1.26 crook 4337: You can get the address of the body of a word with:
4338:
4339: doc->body
1.1 anton 4340:
1.26 crook 4341: @node Supplying names, Interpretation and Compilation Semantics, User-defined Defining Words, Defining Words
1.29 crook 4342: @subsection Supplying the name of a defined word
1.26 crook 4343: @cindex names for defined words
4344: @cindex defining words, name parameter
1.1 anton 4345:
1.26 crook 4346: @cindex defining words, name given in a string
1.29 crook 4347: By default, a defining word takes the name for the defined word from the
1.26 crook 4348: input stream. Sometimes you want to supply the name from a string. You
4349: can do this with:
1.1 anton 4350:
1.26 crook 4351: doc-nextname
1.1 anton 4352:
1.26 crook 4353: For example:
1.1 anton 4354:
1.26 crook 4355: @example
4356: s" foo" nextname create
4357: @end example
4358: @noindent
4359: is equivalent to:
4360: @example
4361: create foo
4362: @end example
1.1 anton 4363:
1.26 crook 4364: @cindex defining words without name
1.29 crook 4365: Sometimes you want to define an @dfn{anonymous word}; a word without a
1.26 crook 4366: name. You can do this with:
1.1 anton 4367:
1.26 crook 4368: doc-:noname
1.1 anton 4369:
1.26 crook 4370: This leaves the execution token for the word on the stack after the
4371: closing @code{;}. Here's an example in which a deferred word is
4372: initialised with an @code{xt} from an anonymous colon definition:
4373: @example
4374: Defer deferred
4375: :noname ( ... -- ... )
4376: ... ;
4377: IS deferred
4378: @end example
1.1 anton 4379:
1.29 crook 4380: @noindent
1.26 crook 4381: Gforth provides an alternative way of doing this, using two separate
4382: words:
1.1 anton 4383:
1.26 crook 4384: doc-noname
4385: @cindex execution token of last defined word
4386: doc-lastxt
1.1 anton 4387:
1.29 crook 4388: @noindent
1.26 crook 4389: The previous example can be rewritten using @code{noname} and
4390: @code{lastxt}:
1.1 anton 4391:
1.26 crook 4392: @example
4393: Defer deferred
4394: noname : ( ... -- ... )
4395: ... ;
4396: lastxt IS deferred
4397: @end example
1.1 anton 4398:
1.29 crook 4399: @noindent
1.33 anton 4400: @code{noname} and @code{nextname} work with any defining word, not just
4401: @code{:}.
4402:
1.26 crook 4403: @code{lastxt} also works when the last word was not defined as
1.29 crook 4404: @code{noname}. It also has the useful property that is is valid as soon
4405: as the header for a definition has been build. Thus:
4406:
4407: @example
4408: lastxt . : foo [ lastxt . ] ; ' foo .
4409: @end example
4410:
4411: @noindent
4412: prints 3 numbers; the last two are the same.
1.1 anton 4413:
4414:
1.26 crook 4415: @node Interpretation and Compilation Semantics, , Supplying names, Defining Words
4416: @subsection Interpretation and Compilation Semantics
4417: @cindex semantics, interpretation and compilation
1.1 anton 4418:
1.26 crook 4419: @cindex interpretation semantics
4420: The @dfn{interpretation semantics} of a word are what the text
4421: interpreter does when it encounters the word in interpret state. It also
4422: appears in some other contexts, e.g., the execution token returned by
1.29 crook 4423: @code{' @i{word}} identifies the interpretation semantics of
4424: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
4425: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 4426:
1.26 crook 4427: @cindex compilation semantics
4428: The @dfn{compilation semantics} of a word are what the text interpreter
4429: does when it encounters the word in compile state. It also appears in
1.29 crook 4430: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
1.26 crook 4431: standard terminology, ``appends to the current definition''.} the
1.29 crook 4432: compilation semantics of @i{word}.
1.1 anton 4433:
1.26 crook 4434: @cindex execution semantics
4435: The standard also talks about @dfn{execution semantics}. They are used
4436: only for defining the interpretation and compilation semantics of many
4437: words. By default, the interpretation semantics of a word are to
4438: @code{execute} its execution semantics, and the compilation semantics of
4439: a word are to @code{compile,} its execution semantics.@footnote{In
4440: standard terminology: The default interpretation semantics are its
4441: execution semantics; the default compilation semantics are to append its
4442: execution semantics to the execution semantics of the current
4443: definition.}
4444:
4445: @comment TODO expand, make it co-operate with new sections on text interpreter.
4446:
4447: @cindex immediate words
4448: @cindex compile-only words
4449: You can change the semantics of the most-recently defined word:
4450:
4451: doc-immediate
4452: doc-compile-only
4453: doc-restrict
4454:
4455: Note that ticking (@code{'}) a compile-only word gives an error
4456: (``Interpreting a compile-only word'').
1.1 anton 4457:
1.26 crook 4458: Gforth also allows you to define words with arbitrary combinations of
4459: interpretation and compilation semantics.
1.1 anton 4460:
1.26 crook 4461: doc-interpret/compile:
1.1 anton 4462:
1.26 crook 4463: This feature was introduced for implementing @code{TO} and @code{S"}. I
4464: recommend that you do not define such words, as cute as they may be:
4465: they make it hard to get at both parts of the word in some contexts.
4466: E.g., assume you want to get an execution token for the compilation
4467: part. Instead, define two words, one that embodies the interpretation
4468: part, and one that embodies the compilation part. Once you have done
4469: that, you can define a combined word with @code{interpret/compile:} for
4470: the convenience of your users.
1.1 anton 4471:
1.26 crook 4472: You might try to use this feature to provide an optimizing
4473: implementation of the default compilation semantics of a word. For
4474: example, by defining:
1.1 anton 4475: @example
1.26 crook 4476: :noname
4477: foo bar ;
4478: :noname
4479: POSTPONE foo POSTPONE bar ;
1.29 crook 4480: interpret/compile: opti-foobar
1.1 anton 4481: @end example
1.26 crook 4482:
1.23 crook 4483: @noindent
1.26 crook 4484: as an optimizing version of:
4485:
1.1 anton 4486: @example
1.26 crook 4487: : foobar
4488: foo bar ;
1.1 anton 4489: @end example
4490:
1.26 crook 4491: Unfortunately, this does not work correctly with @code{[compile]},
4492: because @code{[compile]} assumes that the compilation semantics of all
4493: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 4494: opti-foobar} would compile compilation semantics, whereas
4495: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 4496:
1.26 crook 4497: @cindex state-smart words (are a bad idea)
1.29 crook 4498: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 4499: by @code{interpret/compile:} (words are state-smart if they check
4500: @code{STATE} during execution). E.g., they would try to code
4501: @code{foobar} like this:
1.1 anton 4502:
1.26 crook 4503: @example
4504: : foobar
4505: STATE @@
4506: IF ( compilation state )
4507: POSTPONE foo POSTPONE bar
4508: ELSE
4509: foo bar
4510: ENDIF ; immediate
4511: @end example
1.1 anton 4512:
1.26 crook 4513: Although this works if @code{foobar} is only processed by the text
4514: interpreter, it does not work in other contexts (like @code{'} or
4515: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
4516: for a state-smart word, not for the interpretation semantics of the
4517: original @code{foobar}; when you execute this execution token (directly
4518: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
4519: state, the result will not be what you expected (i.e., it will not
4520: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
4521: write them@footnote{For a more detailed discussion of this topic, see
4522: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
4523: Ertl; presented at EuroForth '98 and available from
1.33 anton 4524: @url{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz}}!
1.1 anton 4525:
1.26 crook 4526: @cindex defining words with arbitrary semantics combinations
4527: It is also possible to write defining words that define words with
4528: arbitrary combinations of interpretation and compilation semantics. In
4529: general, they look like this:
1.1 anton 4530:
1.26 crook 4531: @example
4532: : def-word
4533: create-interpret/compile
1.29 crook 4534: @i{code1}
1.26 crook 4535: interpretation>
1.29 crook 4536: @i{code2}
1.26 crook 4537: <interpretation
4538: compilation>
1.29 crook 4539: @i{code3}
1.26 crook 4540: <compilation ;
4541: @end example
1.1 anton 4542:
1.29 crook 4543: For a @i{word} defined with @code{def-word}, the interpretation
4544: semantics are to push the address of the body of @i{word} and perform
4545: @i{code2}, and the compilation semantics are to push the address of
4546: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 4547: can also be defined like this (except that the defined constants don't
4548: behave correctly when @code{[compile]}d):
1.1 anton 4549:
1.26 crook 4550: @example
4551: : constant ( n "name" -- )
4552: create-interpret/compile
4553: ,
4554: interpretation> ( -- n )
4555: @@
4556: <interpretation
4557: compilation> ( compilation. -- ; run-time. -- n )
4558: @@ postpone literal
4559: <compilation ;
4560: @end example
1.1 anton 4561:
1.26 crook 4562: doc-create-interpret/compile
4563: doc-interpretation>
4564: doc-<interpretation
4565: doc-compilation>
4566: doc-<compilation
1.1 anton 4567:
1.29 crook 4568: Words defined with @code{interpret/compile:} and
1.26 crook 4569: @code{create-interpret/compile} have an extended header structure that
4570: differs from other words; however, unless you try to access them with
4571: plain address arithmetic, you should not notice this. Words for
4572: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 4573: @code{'} @i{word} @code{>body} also gives you the body of a word created
4574: with @code{create-interpret/compile}.
1.1 anton 4575:
1.27 crook 4576: doc-postpone
1.29 crook 4577: @comment TODO -- expand glossary text for POSTPONE
1.27 crook 4578:
1.26 crook 4579: @c ----------------------------------------------------------
4580: @node The Text Interpreter, Tokens for Words, Defining Words, Words
4581: @section The Text Interpreter
4582: @cindex interpreter - outer
4583: @cindex text interpreter
4584: @cindex outer interpreter
1.1 anton 4585:
1.34 anton 4586: @c Should we really describe all these ugly details? IMO the text
4587: @c interpreter should be much cleaner, but that may not be possible within
4588: @c ANS Forth. - anton
4589:
1.29 crook 4590: The text interpreter@footnote{This is an expanded version of the
4591: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 4592: that processes input from the current input device. It is also called
4593: the outer interpreter, in contrast to the inner interpreter
4594: (@pxref{Engine}) which executes the compiled Forth code on interpretive
4595: implementations.
1.27 crook 4596:
1.29 crook 4597: @cindex interpret state
4598: @cindex compile state
4599: The text interpreter operates in one of two states: @dfn{interpret
4600: state} and @dfn{compile state}. The current state is defined by the
4601: aptly-named variable, @code{state}.
4602:
4603: This section starts by describing how the text interpreter behaves when
4604: it is in interpret state, processing input from the user input device --
4605: the keyboard. This is the mode that a Forth system is in after it starts
4606: up.
4607:
4608: @cindex input buffer
4609: @cindex terminal input buffer
4610: The text interpreter works from an area of memory called the @dfn{input
4611: buffer}@footnote{When the text interpreter is processing input from the
4612: keyboard, this area of memory is called the @dfn{terminal input buffer}
4613: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
4614: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 4615: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 4616: leading spaces (called @dfn{delimiters}) then parses a string (a
4617: sequence of non-space characters) until it reaches either a space
4618: character or the end of the buffer. Having parsed a string, it makes two
4619: attempts to process it:
1.27 crook 4620:
1.29 crook 4621: @cindex dictionary
1.27 crook 4622: @itemize @bullet
4623: @item
1.29 crook 4624: It looks for the string in a @dfn{dictionary} of definitions. If the
4625: string is found, the string names a @dfn{definition} (also known as a
4626: @dfn{word}) and the dictionary search returns information that allows
4627: the text interpreter to perform the word's @dfn{interpretation
4628: semantics}. In most cases, this simply means that the word will be
4629: executed.
1.27 crook 4630: @item
4631: If the string is not found in the dictionary, the text interpreter
1.29 crook 4632: attempts to treat it as a number, using the rules described in
4633: @ref{Number Conversion}. If the string represents a legal number in the
4634: current radix, the number is pushed onto a parameter stack (the data
4635: stack for integers, the floating-point stack for floating-point
4636: numbers).
4637: @end itemize
4638:
4639: If both attempts fail, or if the word is found in the dictionary but has
4640: no interpretation semantics@footnote{This happens if the word was
4641: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
4642: remainder of the input buffer, issues an error message and waits for
4643: more input. If one of the attempts succeeds, the text interpreter
4644: repeats the parsing process until the whole of the input buffer has been
4645: processed, at which point it prints the status message ``@code{ ok}''
4646: and waits for more input.
4647:
4648: @cindex parse area
4649: The text interpreter keeps track of its position in the input buffer by
4650: updating a variable called @code{>IN} (pronounced ``to-in''). The value
4651: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
4652: of the input buffer. The region from offset @code{>IN @@} to the end of
4653: the input buffer is called the @dfn{parse area}@footnote{In other words,
4654: the text interpreter processes the contents of the input buffer by
4655: parsing strings from the parse area until the parse area is empty.}.
4656: This example shows how @code{>IN} changes as the text interpreter parses
4657: the input buffer:
4658:
4659: @example
4660: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
4661: CR ." ->" TYPE ." <-" ; IMMEDIATE
4662:
4663: 1 2 3 remaining + remaining .
4664:
4665: : foo 1 2 3 remaining SWAP remaining ;
4666: @end example
4667:
4668: @noindent
4669: The result is:
4670:
4671: @example
4672: ->+ remaining .<-
4673: ->.<-5 ok
4674:
4675: ->SWAP remaining ;-<
4676: ->;<- ok
4677: @end example
4678:
4679: @cindex parsing words
4680: The value of @code{>IN} can also be modified by a word in the input
4681: buffer that is executed by the text interpreter. This means that a word
4682: can ``trick'' the text interpreter into either skipping a section of the
4683: input buffer@footnote{This is how parsing words work.} or into parsing a
4684: section twice. For example:
1.27 crook 4685:
1.29 crook 4686: @example
4687: : lat ." <<lat>>" ;
4688: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
4689: @end example
4690:
4691: @noindent
4692: When @code{flat} is executed, this output is produced@footnote{Exercise
4693: for the reader: what would happen if the @code{3} were replaced with
4694: @code{4}?}:
4695:
4696: @example
4697: <<flat>><<lat>>
4698: @end example
4699:
4700: @noindent
4701: Two important notes about the behaviour of the text interpreter:
1.27 crook 4702:
4703: @itemize @bullet
4704: @item
4705: It processes each input string to completion before parsing additional
1.29 crook 4706: characters from the input buffer.
4707: @item
4708: It treats the input buffer as a read-only region (and so must your code).
4709: @end itemize
4710:
4711: @noindent
4712: When the text interpreter is in compile state, its behaviour changes in
4713: these ways:
4714:
4715: @itemize @bullet
4716: @item
4717: If a parsed string is found in the dictionary, the text interpreter will
4718: perform the word's @dfn{compilation semantics}. In most cases, this
4719: simply means that the execution semantics of the word will be appended
4720: to the current definition.
1.27 crook 4721: @item
1.29 crook 4722: When a number is encountered, it is compiled into the current definition
4723: (as a literal) rather than being pushed onto a parameter stack.
4724: @item
4725: If an error occurs, @code{state} is modified to put the text interpreter
4726: back into interpret state.
4727: @item
4728: Each time a line is entered from the keyboard, Gforth prints
4729: ``@code{ compiled}'' rather than `` @code{ok}''.
4730: @end itemize
4731:
4732: @cindex text interpreter - input sources
4733: When the text interpreter is using an input device other than the
4734: keyboard, its behaviour changes in these ways:
4735:
4736: @itemize @bullet
4737: @item
4738: When the parse area is empty, the text interpreter attempts to refill
4739: the input buffer from the input source. When the input source is
4740: exhausted, the input source is set back to the user input device.
4741: @item
4742: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
4743: time the parse area is emptied.
4744: @item
4745: If an error occurs, the input source is set back to the user input
4746: device.
1.27 crook 4747: @end itemize
1.21 crook 4748:
1.29 crook 4749: @ref{Input Sources} describes this in more detail.
4750:
1.26 crook 4751: doc->in
1.27 crook 4752: doc-source
4753:
1.26 crook 4754: doc-tib
4755: doc-#tib
1.1 anton 4756:
1.26 crook 4757: @menu
1.29 crook 4758: * Input Sources::
1.26 crook 4759: * Number Conversion::
4760: * Interpret/Compile states::
4761: * Literals::
4762: * Interpreter Directives::
4763: @end menu
1.1 anton 4764:
1.29 crook 4765: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
4766: @subsection Input Sources
4767: @cindex input sources
4768: @cindex text interpreter - input sources
4769:
4770: By default, the text interpreter accepts input from the user input
4771: device (the keyboard) when Forth starts up. The text interpreter can
4772: process input from any of these sources:
4773:
4774: @itemize @bullet
4775: @item
4776: The user input device -- the keyboard.
4777: @item
4778: A file, using the words described in @ref{Forth source files}.
4779: @item
4780: A block, using the words described in @ref{Blocks}.
4781: @item
4782: A text string, using @code{evaluate}.
4783: @end itemize
4784:
4785: A program can identify the current input device from the values of
4786: @code{source-id} and @code{blk}.
4787:
4788: doc-source-id
4789: doc-blk
4790:
4791: doc-save-input
4792: doc-restore-input
4793:
4794: doc-evaluate
1.1 anton 4795:
1.29 crook 4796:
4797: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 4798: @subsection Number Conversion
4799: @cindex number conversion
4800: @cindex double-cell numbers, input format
4801: @cindex input format for double-cell numbers
4802: @cindex single-cell numbers, input format
4803: @cindex input format for single-cell numbers
4804: @cindex floating-point numbers, input format
4805: @cindex input format for floating-point numbers
1.1 anton 4806:
1.29 crook 4807: This section describes the rules that the text interpreter uses when it
4808: tries to convert a string into a number.
1.1 anton 4809:
1.26 crook 4810: Let <digit> represent any character that is a legal digit in the current
1.29 crook 4811: number base@footnote{For example, 0-9 when the number base is decimal or
4812: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 4813:
1.26 crook 4814: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 4815:
1.29 crook 4816: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
4817: in the braces (@i{a} or @i{b} or neither).
1.1 anton 4818:
1.26 crook 4819: Let * represent any number of instances of the previous character
4820: (including none).
1.1 anton 4821:
1.26 crook 4822: Let any other character represent itself.
1.1 anton 4823:
1.29 crook 4824: @noindent
1.26 crook 4825: Now, the conversion rules are:
1.21 crook 4826:
1.26 crook 4827: @itemize @bullet
4828: @item
4829: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 4830: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 4831: @item
4832: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 4833: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 4834: arithmetic. Examples are -45 -5681 -0
4835: @item
4836: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 4837: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
4838: (all three of these represent the same number).
1.26 crook 4839: @item
4840: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 4841: double-precision (double-cell-sized) negative integer, and is
1.26 crook 4842: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 4843: -34.65 (all three of these represent the same number).
1.26 crook 4844: @item
1.29 crook 4845: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
4846: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 4847: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 4848: number) +12.E-4
1.26 crook 4849: @end itemize
1.1 anton 4850:
1.26 crook 4851: By default, the number base used for integer number conversion is given
1.35 anton 4852: by the contents of the variable @code{base}. Note that a lot of
4853: confusion can result from unexpected values of @code{base}. If you
4854: change @code{base} anywhere, make sure to save the old value and restore
4855: it afterwards. In general I recommend keeping @code{base} decimal, and
4856: using the prefixes described below for the popular non-decimal bases.
1.1 anton 4857:
1.29 crook 4858: doc-dpl
1.26 crook 4859: doc-base
4860: doc-hex
4861: doc-decimal
1.1 anton 4862:
1.26 crook 4863: @cindex '-prefix for character strings
4864: @cindex &-prefix for decimal numbers
4865: @cindex %-prefix for binary numbers
4866: @cindex $-prefix for hexadecimal numbers
1.35 anton 4867: Gforth allows you to override the value of @code{base} by using a
1.29 crook 4868: prefix@footnote{Some Forth implementations provide a similar scheme by
4869: implementing @code{$} etc. as parsing words that process the subsequent
4870: number in the input stream and push it onto the stack. For example, see
4871: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
4872: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
4873: is required between the prefix and the number.} before the first digit
4874: of an (integer) number. Four prefixes are supported:
1.1 anton 4875:
1.26 crook 4876: @itemize @bullet
4877: @item
1.35 anton 4878: @code{&} -- decimal
1.26 crook 4879: @item
1.35 anton 4880: @code{%} -- binary
1.26 crook 4881: @item
1.35 anton 4882: @code{$} -- hexadecimal
1.26 crook 4883: @item
1.35 anton 4884: @code{'} -- base @code{max-char+1}
1.26 crook 4885: @end itemize
1.1 anton 4886:
1.26 crook 4887: Here are some examples, with the equivalent decimal number shown after
4888: in braces:
1.1 anton 4889:
1.26 crook 4890: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
4891: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
4892: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
4893: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 4894:
1.26 crook 4895: @cindex number conversion - traps for the unwary
1.29 crook 4896: @noindent
1.26 crook 4897: Number conversion has a number of traps for the unwary:
1.1 anton 4898:
1.26 crook 4899: @itemize @bullet
4900: @item
4901: You cannot determine the current number base using the code sequence
1.35 anton 4902: @code{base @@ .} -- the number base is always 10 in the current number
4903: base. Instead, use something like @code{base @@ dec.}
1.26 crook 4904: @item
4905: If the number base is set to a value greater than 14 (for example,
4906: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
4907: it to be intepreted as either a single-precision integer or a
4908: floating-point number (Gforth treats it as an integer). The ambiguity
4909: can be resolved by explicitly stating the sign of the mantissa and/or
4910: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
4911: ambiguity arises; either representation will be treated as a
4912: floating-point number.
4913: @item
1.29 crook 4914: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 4915: It is used to specify file types.
4916: @item
4917: ANS Forth requires the @code{.} of a double-precision number to
4918: be the final character in the string. Allowing the @code{.} to be
4919: anywhere after the first digit is a Gforth extension.
4920: @item
4921: The number conversion process does not check for overflow.
4922: @item
4923: In Gforth, number conversion to floating-point numbers always use base
1.35 anton 4924: 10, irrespective of the value of @code{base}. In ANS Forth,
1.26 crook 4925: conversion to floating-point numbers whilst the value of
1.35 anton 4926: @code{base} is not 10 is an ambiguous condition.
1.26 crook 4927: @end itemize
1.1 anton 4928:
1.29 crook 4929: @ref{Input} describes words that you can use to read numbers into your
4930: programs.
1.1 anton 4931:
1.26 crook 4932: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
4933: @subsection Interpret/Compile states
4934: @cindex Interpret/Compile states
1.1 anton 4935:
1.29 crook 4936: A standard program is not permitted to change @code{state}
4937: explicitly. However, it can change @code{state} implicitly, using the
4938: words @code{[} and @code{]}. When @code{[} is executed it switches
4939: @code{state} to interpret state, and therefore the text interpreter
4940: starts interpreting. When @code{]} is executed it switches @code{state}
4941: to compile state and therefore the text interpreter starts
4942: compiling. The most common usage for these words is to compile literals,
4943: as shown in @ref{Literals}. However, they give you the freedom to switch
1.35 anton 4944: modes at will.
4945:
4946: @c This is a bad example: It's non-standard, and it's not necessary.
4947: @c However, I can't think of a good example for switching into compile
4948: @c state when there is no current word (@code{state}-smart words are not a
4949: @c good reason). So maybe we should use an example for switching into
4950: @c interpret @code{state} in a colon def. - anton
4951:
4952: Here is an example of building a jump-table of execution
1.29 crook 4953: tokens:
4954:
4955: @example
4956: : AA ." this is A" ;
4957: : BB ." this is B" ;
4958: : CC ." this is C" ;
4959:
4960: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
4961: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
4962: cells table + @ execute ;
4963: @end example
4964:
4965: @noindent
4966: Now @code{0 go} will display ``@code{this is A}''. The table can be
4967: built far more neatly@footnote{The source code is neater.. what is
4968: compiled in memory in each case is identical.} like this:
4969:
4970: @example
4971: create table ] aa bb cc [
4972: @end example
4973:
4974: The problem with this code is that it is not portable; it will only work
4975: on systems where code space and data space co-incide. The reason is that
4976: both tables @i{compile} execution tokens -- into code space. The
4977: Standard only allows data space to be assigned for a @code{CREATE}d
4978: word. In addition, the Standard only allows @code{@@} to access data
4979: space, whilst this example is using it to access code space. The only
4980: portable, Standard way to build this table is to build it in data space,
4981: like this:
4982:
4983: @example
4984: create table ' aa , ' bb , ' cc ,
4985: @end example
4986:
4987: @noindent
4988: A similar technique can be used to build a table of constants:
4989:
4990: @example
4991: create primes 1 , 3 , 5 , 7 , 11 ,
4992: @end example
1.1 anton 4993:
1.26 crook 4994: doc-state
4995: doc-[
4996: doc-]
1.1 anton 4997:
1.26 crook 4998: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
4999: @subsection Literals
5000: @cindex Literals
1.21 crook 5001:
1.29 crook 5002: Often, you want to use a number within a colon definition. When you do
5003: this, the text interpreter automatically compiles the number as a
5004: @i{literal}. A literal is a number whose run-time effect is to be pushed
5005: onto the stack. If you had to do some maths to generate the number, you
5006: might write it like this:
5007:
5008: @example
5009: : HOUR-TO-SEC ( n1 -- n2 )
5010: 60 * \ to minutes
5011: 60 * ; \ to seconds
5012: @end example
5013:
5014: It is very clear what this definition is doing, but it's inefficient
5015: since it is performing 2 multiples at run-time. An alternative would be
5016: to write:
5017:
5018: @example
5019: : HOUR-TO-SEC ( n1 -- n2 )
5020: 3600 * ; \ to seconds
5021: @end example
5022:
5023: Which does the same thing, and has the advantage of using a single
5024: multiply. Ideally, we'd like the efficiency of the second with the
5025: readability of the first.
5026:
5027: @code{Literal} allows us to achieve that. It takes a number from the
5028: stack and lays it down in the current definition just as though the
5029: number had been typed directly into the definition. Our first attempt
5030: might look like this:
5031:
5032: @example
5033: 60 \ mins per hour
5034: 60 * \ seconds per minute
5035: : HOUR-TO-SEC ( n1 -- n2 )
5036: Literal * ; \ to seconds
5037: @end example
5038:
5039: But this produces the error message @code{unstructured}. What happened?
5040: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
5041: @i{colon-sys} is implementation-defined. In other words, once we start a
5042: colon definition we can't portably access anything that was on the stack
5043: before the definition began@footnote{@cite{Two Problems in ANS Forth},
5044: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
5045: some situations where you might want to access stack items above
5046: colon-sys, and provides a solution to the problem.}. The correct way of
5047: solving this problem in this instance is to use @code{[ ]} like this:
5048:
5049: @example
5050: : HOUR-TO-SEC ( n1 -- n2 )
5051: [ 60 \ minutes per hour
5052: 60 * ] \ seconds per minute
5053: LITERAL * ; \ to seconds
5054: @end example
1.23 crook 5055:
1.26 crook 5056: doc-literal
5057: doc-]L
5058: doc-2literal
5059: doc-fliteral
1.1 anton 5060:
1.29 crook 5061: @node Interpreter Directives, , Literals, The Text Interpreter
1.26 crook 5062: @subsection Interpreter Directives
5063: @cindex interpreter directives
1.1 anton 5064:
1.29 crook 5065: These words are usually used in interpret state; typically to control
5066: which parts of a source file are processed by the text
1.26 crook 5067: interpreter. There are only a few ANS Forth Standard words, but Gforth
5068: supplements these with a rich set of immediate control structure words
5069: to compensate for the fact that the non-immediate versions can only be
1.29 crook 5070: used in compile state (@pxref{Control Structures}). Typical usages:
5071:
5072: @example
5073: FALSE Constant ASSEMBLER
5074: .
5075: .
5076: ASSEMBLER [IF]
5077: : ASSEMBLER-FEATURE
5078: ...
5079: ;
5080: [ENDIF]
5081: .
5082: .
5083: : SEE
5084: ... \ general-purpose SEE code
5085: [ ASSEMBLER [IF] ]
5086: ... \ assembler-specific SEE code
5087: [ [ENDIF] ]
5088: ;
5089: @end example
1.1 anton 5090:
1.26 crook 5091: doc-[IF]
5092: doc-[ELSE]
5093: doc-[THEN]
5094: doc-[ENDIF]
1.1 anton 5095:
1.26 crook 5096: doc-[IFDEF]
5097: doc-[IFUNDEF]
1.1 anton 5098:
1.26 crook 5099: doc-[?DO]
5100: doc-[DO]
5101: doc-[FOR]
5102: doc-[LOOP]
5103: doc-[+LOOP]
5104: doc-[NEXT]
1.1 anton 5105:
1.26 crook 5106: doc-[BEGIN]
5107: doc-[UNTIL]
5108: doc-[AGAIN]
5109: doc-[WHILE]
5110: doc-[REPEAT]
1.1 anton 5111:
1.27 crook 5112:
5113:
1.26 crook 5114: @c -------------------------------------------------------------
5115: @node Tokens for Words, Word Lists, The Text Interpreter, Words
5116: @section Tokens for Words
5117: @cindex tokens for words
1.1 anton 5118:
1.28 crook 5119: This section describes the creation and use of tokens that represent
1.29 crook 5120: words.
5121:
1.32 anton 5122: Named words have information stored in their header space entries to
1.29 crook 5123: indicate any non-default semantics (@pxref{Interpretation and
5124: Compilation Semantics}). The semantics can be modified, using
5125: @code{immediate} and/or @code{compile-only}, at the time that the words
1.32 anton 5126: are defined. Unnamed words have (by definition) no header space
1.29 crook 5127: entry, and therefore must have default semantics.
1.21 crook 5128:
1.26 crook 5129: Named words have interpretation and compilation semantics. Unnamed words
5130: just have execution semantics.
1.21 crook 5131:
1.29 crook 5132: @cindex xt
5133: @cindex execution token
5134: The execution semantics of an unnamed word are represented by an
5135: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
5136: the execution token of the last word defined can be produced with
5137: @code{lastxt}.
5138:
5139: The interpretation semantics of a named word are also represented by an
5140: execution token. You can produce the execution token using @code{'} or
5141: @code{[']}. A simple example shows the difference between the two:
1.21 crook 5142:
1.29 crook 5143: @example
5144: : greet ( -- ) ." Hello" ;
1.36 anton 5145: : foo ( -- xt ) ['] greet execute ; \ ['] parses greet at compile-time
5146: : bar ( -- ) ' execute ; \ ' parses at run-time
1.1 anton 5147:
1.29 crook 5148: \ the next four lines all do the same thing
1.36 anton 5149: foo
5150: bar greet
1.29 crook 5151: greet
5152: ' greet EXECUTE
5153: @end example
1.1 anton 5154:
1.29 crook 5155: An execution token occupies one cell.
1.26 crook 5156: @cindex code field address
5157: @cindex CFA
1.29 crook 5158: In Gforth, the abstract data type @i{execution token} is implemented
1.26 crook 5159: as a code field address (CFA).
5160: @comment TODO note that the standard does not say what it represents..
5161: @comment and you cannot necessarily compile it in all Forths (eg native
5162: @comment compilers?).
1.1 anton 5163:
1.29 crook 5164: For literals, use @code{'} in interpreted code and @code{[']} in
5165: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
5166: unusually by complaining about compile-only words. To get the execution
5167: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
5168: or @code{[COMP'] @i{name} DROP}.
1.1 anton 5169:
1.26 crook 5170: @cindex compilation token
1.29 crook 5171: The compilation semantics of a named word are represented by a
5172: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
5173: @i{xt} is an execution token. The compilation semantics represented by
5174: the compilation token can be performed with @code{execute}, which
5175: consumes the whole compilation token, with an additional stack effect
5176: determined by the represented compilation semantics.
5177:
5178: At present, the @i{w} part of a compilation token is an execution token,
5179: and the @i{xt} part represents either @code{execute} or
5180: @code{compile,}@footnote{Depending upon the compilation semantics of the
5181: word. If the word has default compilation semantics, the @i{xt} will
1.36 anton 5182: represent @code{compile,}. Otherwise (e.g., for immediate words), the
5183: @i{xt} will represent @code{execute}.}. However, don't rely on that
5184: knowledge, unless necessary; future versions of Gforth may introduce
5185: unusual compilation tokens (e.g., a compilation token that represents
5186: the compilation semantics of a literal).
1.1 anton 5187:
1.26 crook 5188: You can compile the compilation semantics with @code{postpone,}. I.e.,
1.29 crook 5189: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
5190: @i{word}}.
1.21 crook 5191:
1.26 crook 5192: @cindex name token
5193: @cindex name field address
5194: @cindex NFA
1.29 crook 5195: Named words are also represented by the @dfn{name token}, (@i{nt}). In
5196: Gforth, the abstract data type @emph{name token} is implemented as a
5197: name field address (NFA).
5198:
5199: doc-execute
5200: doc-compile,
5201: doc-[']
5202: doc-'
5203: doc-[comp']
5204: doc-comp'
5205: doc-postpone,
1.1 anton 5206:
1.26 crook 5207: doc-find-name
5208: doc-name>int
5209: doc-name?int
5210: doc-name>comp
5211: doc-name>string
1.1 anton 5212:
1.26 crook 5213: @c -------------------------------------------------------------
5214: @node Word Lists, Environmental Queries, Tokens for Words, Words
5215: @section Word Lists
5216: @cindex word lists
1.32 anton 5217: @cindex header space
1.1 anton 5218:
1.36 anton 5219: A wordlist is a list of named words; you can add new words and look up
5220: words by name (and you can remove words in a restricted way with
5221: markers). Every named (and @code{reveal}ed) word is in one wordlist.
5222:
5223: @cindex search order stack
5224: The text interpreter searches the wordlists present in the search order
5225: (a stack of wordlists), from the top to the bottom. Within each
5226: wordlist, the search starts conceptually at the newest word; i.e., if
5227: two words in a wordlist have the same name, the newer word is found.
1.1 anton 5228:
1.26 crook 5229: @cindex compilation word list
1.36 anton 5230: New words are added to the @dfn{compilation wordlist} (aka current
5231: wordlist).
1.1 anton 5232:
1.36 anton 5233: @cindex wid
5234: A word list is identified by a cell-sized word list identifier (@i{wid})
5235: in much the same way as a file is identified by a file handle. The
5236: numerical value of the wid has no (portable) meaning, and might change
5237: from session to session.
1.1 anton 5238:
1.29 crook 5239: The ANS Forth ``Search order'' word set is intended to provide a set of
5240: low-level tools that allow various different schemes to be
1.26 crook 5241: implemented. Gforth provides @code{vocabulary}, a traditional Forth
5242: word. @file{compat/vocabulary.fs} provides an implementation in ANS
5243: Standard Forth.
1.1 anton 5244:
1.27 crook 5245: @comment TODO: locals section refers to here, saying that every word list (aka
5246: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.1 anton 5247:
1.27 crook 5248: @comment the thisone- prefix is used to pick out the true definition of a
5249: @comment word from the source files, rather than some alias.
1.26 crook 5250: doc-forth-wordlist
5251: doc-definitions
5252: doc-get-current
5253: doc-set-current
5254: doc-get-order
1.27 crook 5255: doc---thisone-set-order
1.26 crook 5256: doc-wordlist
1.30 anton 5257: doc-table
1.36 anton 5258: doc-push-order
5259: doc-previous
1.26 crook 5260: doc-also
1.27 crook 5261: doc---thisone-forth
1.26 crook 5262: doc-only
1.27 crook 5263: doc---thisone-order
1.15 anton 5264:
1.26 crook 5265: doc-find
5266: doc-search-wordlist
1.15 anton 5267:
1.26 crook 5268: doc-words
5269: doc-vlist
1.1 anton 5270:
1.26 crook 5271: doc-mappedwordlist
5272: doc-root
5273: doc-vocabulary
5274: doc-seal
5275: doc-vocs
5276: doc-current
5277: doc-context
1.1 anton 5278:
1.26 crook 5279: @menu
5280: * Why use word lists?::
5281: * Word list examples::
5282: @end menu
5283:
5284: @node Why use word lists?, Word list examples, Word Lists, Word Lists
5285: @subsection Why use word lists?
5286: @cindex word lists - why use them?
5287:
1.29 crook 5288: Here are some reasons for using multiple word lists:
1.26 crook 5289:
5290: @itemize @bullet
5291: @item
1.32 anton 5292: To improve compilation speed by reducing the number of header space
1.26 crook 5293: entries that must be searched. This is achieved by creating a new
5294: word list that contains all of the definitions that are used in the
5295: definition of a Forth system but which would not usually be used by
5296: programs running on that system. That word list would be on the search
5297: list when the Forth system was compiled but would be removed from the
5298: search list for normal operation. This can be a useful technique for
5299: low-performance systems (for example, 8-bit processors in embedded
5300: systems) but is unlikely to be necessary in high-performance desktop
5301: systems.
5302: @item
5303: To prevent a set of words from being used outside the context in which
5304: they are valid. Two classic examples of this are an integrated editor
5305: (all of the edit commands are defined in a separate word list; the
5306: search order is set to the editor word list when the editor is invoked;
5307: the old search order is restored when the editor is terminated) and an
5308: integrated assembler (the op-codes for the machine are defined in a
5309: separate word list which is used when a @code{CODE} word is defined).
5310: @item
5311: To prevent a name-space clash between multiple definitions with the same
5312: name. For example, when building a cross-compiler you might have a word
5313: @code{IF} that generates conditional code for your target system. By
5314: placing this definition in a different word list you can control whether
5315: the host system's @code{IF} or the target system's @code{IF} get used in
5316: any particular context by controlling the order of the word lists on the
5317: search order stack.
5318: @end itemize
1.1 anton 5319:
1.26 crook 5320: @node Word list examples, ,Why use word lists?, Word Lists
5321: @subsection Word list examples
5322: @cindex word lists - examples
1.1 anton 5323:
1.26 crook 5324: Here is an example of creating and using a new wordlist using ANS
5325: Forth Standard words:
1.1 anton 5326:
5327: @example
1.26 crook 5328: wordlist constant my-new-words-wordlist
5329: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
1.21 crook 5330:
1.26 crook 5331: \ add it to the search order
5332: also my-new-words
1.21 crook 5333:
1.26 crook 5334: \ alternatively, add it to the search order and make it
5335: \ the compilation word list
5336: also my-new-words definitions
5337: \ type "order" to see the problem
1.21 crook 5338: @end example
5339:
1.26 crook 5340: The problem with this example is that @code{order} has no way to
5341: associate the name @code{my-new-words} with the wid of the word list (in
5342: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
5343: that has no associated name). There is no Standard way of associating a
5344: name with a wid.
5345:
5346: In Gforth, this example can be re-coded using @code{vocabulary}, which
5347: associates a name with a wid:
1.21 crook 5348:
1.26 crook 5349: @example
5350: vocabulary my-new-words
1.21 crook 5351:
1.26 crook 5352: \ add it to the search order
5353: my-new-words
1.21 crook 5354:
1.26 crook 5355: \ alternatively, add it to the search order and make it
5356: \ the compilation word list
5357: my-new-words definitions
5358: \ type "order" to see that the problem is solved
5359: @end example
1.23 crook 5360:
1.26 crook 5361: @c -------------------------------------------------------------
5362: @node Environmental Queries, Files, Word Lists, Words
5363: @section Environmental Queries
5364: @cindex environmental queries
1.21 crook 5365:
1.26 crook 5366: ANS Forth introduced the idea of ``environmental queries'' as a way
5367: for a program running on a system to determine certain characteristics of the system.
5368: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 5369:
1.32 anton 5370: The Standard requires that the header space used for environmental queries
5371: be distinct from the header space used for definitions.
1.21 crook 5372:
1.26 crook 5373: Typically, environmental queries are supported by creating a set of
1.29 crook 5374: definitions in a word list that is @i{only} used during environmental
1.26 crook 5375: queries; that is what Gforth does. There is no Standard way of adding
5376: definitions to the set of recognised environmental queries, but any
5377: implementation that supports the loading of optional word sets must have
5378: some mechanism for doing this (after loading the word set, the
5379: associated environmental query string must return @code{true}). In
5380: Gforth, the word list used to honour environmental queries can be
5381: manipulated just like any other word list.
1.21 crook 5382:
1.26 crook 5383: doc-environment?
5384: doc-environment-wordlist
1.21 crook 5385:
1.26 crook 5386: doc-gforth
5387: doc-os-class
1.21 crook 5388:
1.26 crook 5389: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
5390: returning two items on the stack, querying it using @code{environment?}
5391: will return an additional item; the @code{true} flag that shows that the
5392: string was recognised.
1.21 crook 5393:
1.26 crook 5394: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 5395:
1.26 crook 5396: Here are some examples of using environmental queries:
1.21 crook 5397:
1.26 crook 5398: @example
5399: s" address-unit-bits" environment? 0=
5400: [IF]
5401: cr .( environmental attribute address-units-bits unknown... ) cr
5402: [THEN]
1.21 crook 5403:
1.26 crook 5404: s" block" environment? [IF] DROP include block.fs [THEN]
1.21 crook 5405:
1.26 crook 5406: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
1.21 crook 5407:
1.26 crook 5408: s" gforth" environment? [IF] .( Gforth version ) TYPE
5409: [ELSE] .( Not Gforth..) [THEN]
5410: @end example
1.21 crook 5411:
5412:
1.26 crook 5413: Here is an example of adding a definition to the environment word list:
1.21 crook 5414:
1.26 crook 5415: @example
5416: get-current environment-wordlist set-current
5417: true constant block
5418: true constant block-ext
5419: set-current
5420: @end example
1.21 crook 5421:
1.26 crook 5422: You can see what definitions are in the environment word list like this:
1.21 crook 5423:
1.26 crook 5424: @example
5425: get-order 1+ environment-wordlist swap set-order words previous
5426: @end example
1.21 crook 5427:
5428:
1.26 crook 5429: @c -------------------------------------------------------------
5430: @node Files, Blocks, Environmental Queries, Words
5431: @section Files
1.28 crook 5432: @cindex files
5433: @cindex I/O - file-handling
1.21 crook 5434:
1.26 crook 5435: Gforth provides facilities for accessing files that are stored in the
5436: host operating system's file-system. Files that are processed by Gforth
5437: can be divided into two categories:
1.21 crook 5438:
1.23 crook 5439: @itemize @bullet
5440: @item
1.29 crook 5441: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 5442: @item
1.29 crook 5443: Files that are processed by some other program (@dfn{general files}).
1.26 crook 5444: @end itemize
5445:
5446: @menu
5447: * Forth source files::
5448: * General files::
5449: * Search Paths::
5450: * Forth Search Paths::
5451: * General Search Paths::
5452: @end menu
5453:
1.21 crook 5454:
1.26 crook 5455: @c -------------------------------------------------------------
5456: @node Forth source files, General files, Files, Files
5457: @subsection Forth source files
5458: @cindex including files
5459: @cindex Forth source files
1.21 crook 5460:
1.26 crook 5461: The simplest way to interpret the contents of a file is to use one of
5462: these two formats:
1.21 crook 5463:
1.26 crook 5464: @example
5465: include mysource.fs
5466: s" mysource.fs" included
5467: @end example
1.21 crook 5468:
1.26 crook 5469: Sometimes you want to include a file only if it is not included already
5470: (by, say, another source file). In that case, you can use one of these
5471: fomats:
1.21 crook 5472:
1.26 crook 5473: @example
5474: require mysource.fs
5475: needs mysource.fs
5476: s" mysource.fs" required
5477: @end example
1.21 crook 5478:
1.26 crook 5479: @cindex stack effect of included files
5480: @cindex including files, stack effect
5481: I recommend that you write your source files such that interpreting them
5482: does not change the stack. This allows using these files with
5483: @code{required} and friends without complications. For example:
1.21 crook 5484:
1.26 crook 5485: @example
5486: 1 require foo.fs drop
5487: @end example
1.21 crook 5488:
1.26 crook 5489: doc-include-file
5490: doc-included
1.28 crook 5491: doc-included?
1.26 crook 5492: doc-include
5493: doc-required
5494: doc-require
5495: doc-needs
1.28 crook 5496: doc-init-included-files
1.21 crook 5497:
1.26 crook 5498: A definition in ANS Forth for @code{required} is provided in
5499: @file{compat/required.fs}.
1.21 crook 5500:
1.26 crook 5501: @c -------------------------------------------------------------
5502: @node General files, Search Paths, Forth source files, Files
5503: @subsection General files
5504: @cindex general files
5505: @cindex file-handling
1.21 crook 5506:
1.26 crook 5507: Files are opened/created by name and type. The following types are
5508: recognised:
1.1 anton 5509:
1.26 crook 5510: doc-r/o
5511: doc-r/w
5512: doc-w/o
5513: doc-bin
1.1 anton 5514:
1.26 crook 5515: When a file is opened/created, it returns a file identifier,
1.29 crook 5516: @i{wfileid} that is used for all other file commands. All file
5517: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 5518: successful operation and an implementation-defined non-zero value in the
5519: case of an error.
1.21 crook 5520:
1.26 crook 5521: doc-open-file
5522: doc-create-file
1.21 crook 5523:
1.26 crook 5524: doc-close-file
5525: doc-delete-file
5526: doc-rename-file
5527: doc-read-file
5528: doc-read-line
5529: doc-write-file
5530: doc-write-line
5531: doc-emit-file
5532: doc-flush-file
1.21 crook 5533:
1.26 crook 5534: doc-file-status
5535: doc-file-position
5536: doc-reposition-file
5537: doc-file-size
5538: doc-resize-file
1.21 crook 5539:
1.26 crook 5540: @c ---------------------------------------------------------
5541: @node Search Paths, Forth Search Paths, General files, Files
5542: @subsection Search Paths
5543: @cindex path for @code{included}
5544: @cindex file search path
5545: @cindex @code{include} search path
5546: @cindex search path for files
1.21 crook 5547:
1.26 crook 5548: If you specify an absolute filename (i.e., a filename starting with
5549: @file{/} or @file{~}, or with @file{:} in the second position (as in
5550: @samp{C:...})) for @code{included} and friends, that file is included
5551: just as you would expect.
1.21 crook 5552:
1.26 crook 5553: For relative filenames, Gforth uses a search path similar to Forth's
5554: search order (@pxref{Word Lists}). It tries to find the given filename
5555: in the directories present in the path, and includes the first one it
5556: finds. There are separate search paths for Forth source files and
5557: general files.
1.21 crook 5558:
1.26 crook 5559: If the search path contains the directory @file{.} (as it should), this
5560: refers to the directory that the present file was @code{included}
5561: from. This allows files to include other files relative to their own
5562: position (irrespective of the current working directory or the absolute
5563: position). This feature is essential for libraries consisting of
5564: several files, where a file may include other files from the library.
5565: It corresponds to @code{#include "..."} in C. If the current input
5566: source is not a file, @file{.} refers to the directory of the innermost
5567: file being included, or, if there is no file being included, to the
5568: current working directory.
1.21 crook 5569:
1.26 crook 5570: Use @file{~+} to refer to the current working directory (as in the
5571: @code{bash}).
1.1 anton 5572:
1.26 crook 5573: If the filename starts with @file{./}, the search path is not searched
5574: (just as with absolute filenames), and the @file{.} has the same meaning
5575: as described above.
1.1 anton 5576:
1.26 crook 5577: @c ---------------------------------------------------------
5578: @node Forth Search Paths, General Search Paths, Search Paths, Files
5579: @subsubsection Forth Search Paths
1.28 crook 5580: @cindex search path control - Forth
1.5 anton 5581:
1.26 crook 5582: The search path is initialized when you start Gforth (@pxref{Invoking
5583: Gforth}). You can display it and change it using these words:
1.5 anton 5584:
1.26 crook 5585: doc-.fpath
5586: doc-fpath+
5587: doc-fpath=
5588: doc-open-fpath-file
1.5 anton 5589:
1.26 crook 5590: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 5591:
1.26 crook 5592: @example
5593: fpath= /usr/lib/forth/|./
5594: require timer.fs
5595: @end example
1.5 anton 5596:
1.26 crook 5597: @c ---------------------------------------------------------
5598: @node General Search Paths, , Forth Search Paths, Files
5599: @subsubsection General Search Paths
5600: @cindex search path control - for user applications
1.5 anton 5601:
1.26 crook 5602: Your application may need to search files in several directories, like
5603: @code{included} does. To facilitate this, Gforth allows you to define
5604: and use your own search paths, by providing generic equivalents of the
5605: Forth search path words:
1.5 anton 5606:
1.26 crook 5607: doc-.path
5608: doc-path+
5609: doc-path=
5610: doc-open-path-file
1.5 anton 5611:
1.26 crook 5612: Here's an example of creating a search path:
1.5 anton 5613:
1.26 crook 5614: @example
5615: \ Make a buffer for the path:
5616: create mypath 100 chars , \ maximum length (is checked)
5617: 0 , \ real len
5618: 100 chars allot \ space for path
5619: @end example
1.5 anton 5620:
1.26 crook 5621: @c -------------------------------------------------------------
5622: @node Blocks, Other I/O, Files, Words
5623: @section Blocks
1.28 crook 5624: @cindex I/O - blocks
5625: @cindex blocks
5626:
5627: When you run Gforth on a modern desk-top computer, it runs under the
5628: control of an operating system which provides certain services. One of
5629: these services is @var{file services}, which allows Forth source code
5630: and data to be stored in files and read into Gforth (@pxref{Files}).
5631:
5632: Traditionally, Forth has been an important programming language on
5633: systems where it has interfaced directly to the underlying hardware with
5634: no intervening operating system. Forth provides a mechanism, called
1.29 crook 5635: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 5636:
5637: A block is a 1024-byte data area, which can be used to hold data or
5638: Forth source code. No structure is imposed on the contents of the
5639: block. A block is identified by its number; blocks are numbered
5640: contiguously from 1 to an implementation-defined maximum.
5641:
5642: A typical system that used blocks but no operating system might use a
5643: single floppy-disk drive for mass storage, with the disks formatted to
5644: provide 256-byte sectors. Blocks would be implemented by assigning the
5645: first four sectors of the disk to block 1, the second four sectors to
5646: block 2 and so on, up to the limit of the capacity of the disk. The disk
5647: would not contain any file system information, just the set of blocks.
5648:
1.29 crook 5649: @cindex blocks file
1.28 crook 5650: On systems that do provide file services, blocks are typically
1.29 crook 5651: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 5652: file}. The size of the blocks file will be an exact multiple of 1024
5653: bytes, corresponding to the number of blocks it contains. This is the
5654: mechanism that Gforth uses.
5655:
1.29 crook 5656: @cindex @file{blocks.fb}
1.28 crook 5657: Only 1 blocks file can be open at a time. If you use block words without
5658: having specified a blocks file, Gforth defaults to the blocks file
5659: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
5660: locate a blocks file (@pxref{Forth Search Paths}).
5661:
1.29 crook 5662: @cindex block buffers
1.28 crook 5663: When you read and write blocks under program control, Gforth uses a
1.29 crook 5664: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 5665: not used when you use @code{load} to interpret the contents of a block.
5666:
5667: The behaviour of the block buffers is directly analagous to that of a
5668: cache. Each block buffer has three states:
5669:
5670: @itemize @bullet
5671: @item
5672: Unassigned
5673: @item
5674: Assigned-clean
5675: @item
5676: Assigned-dirty
5677: @end itemize
5678:
1.29 crook 5679: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 5680: block, the block (specified by its block number) must be assigned to a
5681: block buffer.
5682:
5683: The assignment of a block to a block buffer is performed by @code{block}
5684: or @code{buffer}. Use @code{block} when you wish to modify the existing
5685: contents of a block. Use @code{buffer} when you don't care about the
5686: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 5687: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 5688: with the particular block is already stored in a block buffer due to an
5689: earlier @code{block} command, @code{buffer} will return that block
5690: buffer and the existing contents of the block will be
5691: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 5692: block buffer for the block.}.
1.28 crook 5693:
5694: Once a block has been assigned to a block buffer, the block buffer state
1.29 crook 5695: becomes @i{assigned-clean}. Data can now be manipulated within the
1.28 crook 5696: block buffer.
5697:
5698: When the contents of a block buffer is changed it is necessary,
5699: @i{before calling} @code{block} @i{or} @code{buffer} @i{again}, to
5700: either abandon the changes (by doing nothing) or commit the changes,
5701: using @code{update}. Using @code{update} does not change the blocks
1.29 crook 5702: file; it simply changes a block buffer's state to @i{assigned-dirty}.
1.28 crook 5703:
1.29 crook 5704: The word @code{flush} causes all @i{assigned-dirty} blocks to be
1.28 crook 5705: written back to the blocks file on disk. Leaving Gforth using @code{bye}
5706: also causes a @code{flush} to be performed.
5707:
1.29 crook 5708: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 5709: algorithm to assign a block buffer to a block. That means that any
5710: particular block can only be assigned to one specific block buffer,
1.29 crook 5711: called (for the particular operation) the @i{victim buffer}. If the
5712: victim buffer is @i{unassigned} or @i{assigned-clean} it can be
5713: allocated to the new block immediately. If it is @i{assigned-dirty}
1.28 crook 5714: its current contents must be written out to disk before it can be
5715: allocated to the new block.
5716:
5717: Although no structure is imposed on the contents of a block, it is
5718: traditional to display the contents as 16 lines each of 64 characters. A
5719: block provides a single, continuous stream of input (for example, it
5720: acts as a single parse area) -- there are no end-of-line characters
5721: within a block, and no end-of-file character at the end of a
5722: block. There are two consequences of this:
1.26 crook 5723:
1.28 crook 5724: @itemize @bullet
5725: @item
5726: The last character of one line wraps straight into the first character
5727: of the following line
5728: @item
5729: The word @code{\} -- comment to end of line -- requires special
5730: treatment; in the context of a block it causes all characters until the
5731: end of the current 64-character ``line'' to be ignored.
5732: @end itemize
5733:
5734: In Gforth, when you use @code{block} with a non-existent block number,
5735: the current block file will be extended to the appropriate size and the
5736: block buffer will be initialised with spaces.
5737:
1.29 crook 5738: Gforth doesn't encourage the use of blocks; the mechanism is only
5739: provided for backward compatibility -- ANS Forth requires blocks to be
5740: available when files are.
1.28 crook 5741:
5742: Common techniques that are used when working with blocks include:
5743:
5744: @itemize @bullet
5745: @item
5746: A screen editor that allows you to edit blocks without leaving the Forth
5747: environment.
5748: @item
5749: Shadow screens; where every code block has an associated block
5750: containing comments (for example: code in odd block numbers, comments in
5751: even block numbers). Typically, the block editor provides a convenient
5752: mechanism to toggle between code and comments.
5753: @item
5754: Load blocks; a single block (typically block 1) contains a number of
5755: @code{thru} commands which @code{load} the whole of the application.
5756: @end itemize
1.26 crook 5757:
1.29 crook 5758: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
5759: integrated into a Forth programming environment.
1.26 crook 5760:
5761: @comment TODO what about errors on open-blocks?
5762: doc-open-blocks
5763: doc-use
5764: doc-get-block-fid
5765: doc-block-position
1.28 crook 5766:
5767: doc-scr
5768: doc-list
5769:
5770: doc---block-block
5771: doc-buffer
5772:
1.26 crook 5773: doc-update
1.28 crook 5774: doc-updated?
1.26 crook 5775: doc-save-buffers
5776: doc-empty-buffers
5777: doc-empty-buffer
5778: doc-flush
1.28 crook 5779:
1.26 crook 5780: doc-load
5781: doc-thru
5782: doc-+load
5783: doc-+thru
1.35 anton 5784: xdoc--gforth--->
1.26 crook 5785: doc-block-included
5786:
5787: @c -------------------------------------------------------------
5788: @node Other I/O, Programming Tools, Blocks, Words
5789: @section Other I/O
1.28 crook 5790: @cindex I/O - keyboard and display
1.26 crook 5791:
5792: @menu
5793: * Simple numeric output:: Predefined formats
5794: * Formatted numeric output:: Formatted (pictured) output
5795: * String Formats:: How Forth stores strings in memory
5796: * Displaying characters and strings:: Other stuff
5797: * Input:: Input
5798: @end menu
5799:
5800: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
5801: @subsection Simple numeric output
1.28 crook 5802: @cindex numeric output - simple/free-format
1.5 anton 5803:
1.26 crook 5804: The simplest output functions are those that display numbers from the
5805: data or floating-point stacks. Floating-point output is always displayed
5806: using base 10. Numbers displayed from the data stack use the value stored
5807: in @code{base}.
1.5 anton 5808:
1.26 crook 5809: doc-.
5810: doc-dec.
5811: doc-hex.
5812: doc-u.
5813: doc-.r
5814: doc-u.r
5815: doc-d.
5816: doc-ud.
5817: doc-d.r
5818: doc-ud.r
5819: doc-f.
5820: doc-fe.
5821: doc-fs.
1.5 anton 5822:
1.26 crook 5823: Examples of printing the number 1234.5678E23 in the different floating-point output
5824: formats are shown below:
1.5 anton 5825:
5826: @example
1.26 crook 5827: f. 123456779999999000000000000.
5828: fe. 123.456779999999E24
5829: fs. 1.23456779999999E26
1.5 anton 5830: @end example
5831:
5832:
1.26 crook 5833: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
5834: @subsection Formatted numeric output
1.28 crook 5835: @cindex formatted numeric output
1.26 crook 5836: @cindex pictured numeric output
1.28 crook 5837: @cindex numeric output - formatted
1.26 crook 5838:
1.29 crook 5839: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 5840: output} for formatted printing of integers. In this technique, digits
5841: are extracted from the number (using the current output radix defined by
5842: @code{base}), converted to ASCII codes and appended to a string that is
5843: built in a scratch-pad area of memory (@pxref{core-idef,
5844: Implementation-defined options, Implementation-defined
5845: options}). Arbitrary characters can be appended to the string during the
5846: extraction process. The completed string is specified by an address
5847: and length and can be manipulated (@code{TYPE}ed, copied, modified)
5848: under program control.
1.5 anton 5849:
1.26 crook 5850: All of the words described in the previous section for simple numeric
5851: output are implemented in Gforth using pictured numeric output.
1.5 anton 5852:
1.26 crook 5853: Three important things to remember about Pictured Numeric Output:
1.5 anton 5854:
1.26 crook 5855: @itemize @bullet
5856: @item
1.28 crook 5857: It always operates on double-precision numbers; to display a
5858: single-precision number, convert it first (@pxref{Double precision} for
5859: ways of doing this).
1.26 crook 5860: @item
1.28 crook 5861: It always treats the double-precision number as though it were
5862: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 5863: @item
5864: The string is built up from right to left; least significant digit first.
5865: @end itemize
1.5 anton 5866:
1.26 crook 5867: doc-<#
5868: doc-#
5869: doc-#s
5870: doc-hold
5871: doc-sign
5872: doc-#>
1.5 anton 5873:
1.26 crook 5874: doc-represent
1.5 anton 5875:
1.26 crook 5876: Here are some examples of using pictured numeric output:
1.5 anton 5877:
5878: @example
1.26 crook 5879: : my-u. ( u -- )
5880: \ Simplest use of pns.. behaves like Standard u.
5881: 0 \ convert to unsigned double
5882: <# \ start conversion
5883: #s \ convert all digits
5884: #> \ complete conversion
5885: TYPE SPACE ; \ display, with trailing space
1.5 anton 5886:
1.26 crook 5887: : cents-only ( u -- )
5888: 0 \ convert to unsigned double
5889: <# \ start conversion
5890: # # \ convert two least-significant digits
5891: #> \ complete conversion, discard other digits
5892: TYPE SPACE ; \ display, with trailing space
1.5 anton 5893:
1.26 crook 5894: : dollars-and-cents ( u -- )
5895: 0 \ convert to unsigned double
5896: <# \ start conversion
5897: # # \ convert two least-significant digits
5898: [char] . hold \ insert decimal point
5899: #s \ convert remaining digits
5900: [char] $ hold \ append currency symbol
5901: #> \ complete conversion
5902: TYPE SPACE ; \ display, with trailing space
1.5 anton 5903:
1.26 crook 5904: : my-. ( n -- )
5905: \ handling negatives.. behaves like Standard .
5906: s>d \ convert to signed double
5907: swap over dabs \ leave sign byte followed by unsigned double
5908: <# \ start conversion
5909: #s \ convert all digits
5910: rot sign \ get at sign byte, append "-" if needed
5911: #> \ complete conversion
5912: TYPE SPACE ; \ display, with trailing space
1.5 anton 5913:
1.26 crook 5914: : account. ( n -- )
5915: \ accountants don't like minus signs, they use braces
5916: \ for negative numbers
5917: s>d \ convert to signed double
5918: swap over dabs \ leave sign byte followed by unsigned double
5919: <# \ start conversion
5920: 2 pick \ get copy of sign byte
5921: 0< IF [char] ) hold THEN \ right-most character of output
5922: #s \ convert all digits
5923: rot \ get at sign byte
5924: 0< IF [char] ( hold THEN
5925: #> \ complete conversion
5926: TYPE SPACE ; \ display, with trailing space
1.5 anton 5927: @end example
5928:
1.26 crook 5929: Here are some examples of using these words:
1.5 anton 5930:
5931: @example
1.26 crook 5932: 1 my-u. 1
5933: hex -1 my-u. decimal FFFFFFFF
5934: 1 cents-only 01
5935: 1234 cents-only 34
5936: 2 dollars-and-cents $0.02
5937: 1234 dollars-and-cents $12.34
5938: 123 my-. 123
5939: -123 my. -123
5940: 123 account. 123
5941: -456 account. (456)
1.5 anton 5942: @end example
5943:
5944:
1.26 crook 5945: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
5946: @subsection String Formats
1.27 crook 5947: @cindex strings - see character strings
5948: @cindex character strings - formats
1.28 crook 5949: @cindex I/O - see character strings
1.26 crook 5950:
1.27 crook 5951: Forth commonly uses two different methods for representing character
5952: strings:
1.26 crook 5953:
5954: @itemize @bullet
5955: @item
5956: @cindex address of counted string
1.29 crook 5957: As a @dfn{counted string}, represented by a @i{c-addr}. The char
5958: addressed by @i{c-addr} contains a character-count, @i{n}, of the
5959: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 5960: memory.
5961: @item
1.29 crook 5962: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
5963: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 5964: first byte of the string.
5965: @end itemize
5966:
5967: ANS Forth encourages the use of the second format when representing
5968: strings on the stack, whilst conceeding that the counted string format
5969: remains useful as a way of storing strings in memory.
5970:
5971: doc-count
5972:
5973: @xref{Memory Blocks} for words that move, copy and search
5974: for strings. @xref{Displaying characters and strings,} for words that
5975: display characters and strings.
5976:
5977:
5978: @node Displaying characters and strings, Input, String Formats, Other I/O
5979: @subsection Displaying characters and strings
1.27 crook 5980: @cindex characters - compiling and displaying
5981: @cindex character strings - compiling and displaying
1.26 crook 5982:
5983: This section starts with a glossary of Forth words and ends with a set
5984: of examples.
5985:
5986: doc-bl
5987: doc-space
5988: doc-spaces
5989: doc-emit
5990: doc-toupper
5991: doc-."
5992: doc-.(
5993: doc-type
5994: doc-cr
1.27 crook 5995: @cindex cursor control
1.26 crook 5996: doc-at-xy
5997: doc-page
5998: doc-s"
5999: doc-c"
6000: doc-char
6001: doc-[char]
6002: doc-sliteral
6003:
6004: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 6005:
6006: @example
1.26 crook 6007: .( text-1)
6008: : my-word
6009: ." text-2" cr
6010: .( text-3)
6011: ;
6012:
6013: ." text-4"
6014:
6015: : my-char
6016: [char] ALPHABET emit
6017: char emit
6018: ;
1.5 anton 6019: @end example
6020:
1.26 crook 6021: When you load this code into Gforth, the following output is generated:
1.5 anton 6022:
1.26 crook 6023: @example
1.30 anton 6024: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 6025: @end example
1.5 anton 6026:
1.26 crook 6027: @itemize @bullet
6028: @item
6029: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
6030: is an immediate word; it behaves in the same way whether it is used inside
6031: or outside a colon definition.
6032: @item
6033: Message @code{text-4} is displayed because of Gforth's added interpretation
6034: semantics for @code{."}.
6035: @item
1.29 crook 6036: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 6037: performs the compilation semantics for @code{."} within the definition of
6038: @code{my-word}.
6039: @end itemize
1.5 anton 6040:
1.26 crook 6041: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 6042:
1.26 crook 6043: @example
1.30 anton 6044: @kbd{my-word @key{RET}} text-2
1.26 crook 6045: ok
1.30 anton 6046: @kbd{my-char fred @key{RET}} Af ok
6047: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 6048: @end example
1.5 anton 6049:
6050: @itemize @bullet
6051: @item
1.26 crook 6052: Message @code{text-2} is displayed because of the run-time behaviour of
6053: @code{."}.
6054: @item
6055: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
6056: on the stack at run-time. @code{emit} always displays the character
6057: when @code{my-char} is executed.
6058: @item
6059: @code{char} parses a string at run-time and the second @code{emit} displays
6060: the first character of the string.
1.5 anton 6061: @item
1.26 crook 6062: If you type @code{see my-char} you can see that @code{[char]} discarded
6063: the text ``LPHABET'' and only compiled the display code for ``A'' into the
6064: definition of @code{my-char}.
1.5 anton 6065: @end itemize
6066:
6067:
6068:
1.26 crook 6069: @node Input, , Displaying characters and strings, Other I/O
6070: @subsection Input
6071: @cindex input
1.28 crook 6072: @cindex I/O - see input
6073: @cindex parsing a string
1.5 anton 6074:
1.27 crook 6075: @xref{String Formats} for ways of storing character strings in memory.
1.5 anton 6076:
1.27 crook 6077: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 6078: @comment then index them
1.27 crook 6079:
6080: doc-key
6081: doc-key?
1.26 crook 6082: doc->number
6083: doc->float
6084: doc-accept
1.27 crook 6085: doc-pad
6086: doc-parse
6087: doc-word
6088: doc-sword
6089: doc-refill
6090: @comment obsolescent words..
6091: doc-convert
1.26 crook 6092: doc-query
6093: doc-expect
1.27 crook 6094: doc-span
1.5 anton 6095:
6096:
6097: @c -------------------------------------------------------------
1.26 crook 6098: @node Programming Tools, Assembler and Code Words, Other I/O, Words
6099: @section Programming Tools
6100: @cindex programming tools
1.12 anton 6101:
6102: @menu
1.26 crook 6103: * Debugging:: Simple and quick.
6104: * Assertions:: Making your programs self-checking.
6105: * Singlestep Debugger:: Executing your program word by word.
1.5 anton 6106: @end menu
6107:
1.26 crook 6108: @node Debugging, Assertions, Programming Tools, Programming Tools
6109: @subsection Debugging
6110: @cindex debugging
1.5 anton 6111:
1.26 crook 6112: Languages with a slow edit/compile/link/test development loop tend to
6113: require sophisticated tracing/stepping debuggers to facilate
6114: productive debugging.
1.5 anton 6115:
1.26 crook 6116: A much better (faster) way in fast-compiling languages is to add
6117: printing code at well-selected places, let the program run, look at
6118: the output, see where things went wrong, add more printing code, etc.,
6119: until the bug is found.
1.5 anton 6120:
1.26 crook 6121: The simple debugging aids provided in @file{debugs.fs}
6122: are meant to support this style of debugging. In addition, there are
6123: words for non-destructively inspecting the stack and memory:
1.5 anton 6124:
1.26 crook 6125: doc-.s
6126: doc-f.s
1.5 anton 6127:
1.29 crook 6128: There is a word @code{.r} but it does @i{not} display the return
1.26 crook 6129: stack! It is used for formatted numeric output.
1.5 anton 6130:
1.26 crook 6131: doc-depth
6132: doc-fdepth
6133: doc-clearstack
6134: doc-?
6135: doc-dump
1.5 anton 6136:
1.26 crook 6137: The word @code{~~} prints debugging information (by default the source
6138: location and the stack contents). It is easy to insert. If you use Emacs
6139: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
6140: query-replace them with nothing). The deferred words
6141: @code{printdebugdata} and @code{printdebugline} control the output of
6142: @code{~~}. The default source location output format works well with
6143: Emacs' compilation mode, so you can step through the program at the
6144: source level using @kbd{C-x `} (the advantage over a stepping debugger
6145: is that you can step in any direction and you know where the crash has
6146: happened or where the strange data has occurred).
1.5 anton 6147:
1.26 crook 6148: The default actions of @code{~~} clobber the contents of the pictured
6149: numeric output string, so you should not use @code{~~}, e.g., between
6150: @code{<#} and @code{#>}.
1.5 anton 6151:
1.26 crook 6152: doc-~~
6153: doc-printdebugdata
6154: doc-printdebugline
1.5 anton 6155:
1.26 crook 6156: doc-see
6157: doc-marker
1.5 anton 6158:
1.26 crook 6159: Here's an example of using @code{marker} at the start of a source file
6160: that you are debugging; it ensures that you only ever have one copy of
6161: the file's definitions compiled at any time:
1.5 anton 6162:
1.26 crook 6163: @example
6164: [IFDEF] my-code
6165: my-code
6166: [ENDIF]
1.5 anton 6167:
1.26 crook 6168: marker my-code
1.28 crook 6169: init-included-files
1.5 anton 6170:
1.26 crook 6171: \ .. definitions start here
6172: \ .
6173: \ .
6174: \ end
6175: @end example
1.5 anton 6176:
6177:
6178:
1.26 crook 6179: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
6180: @subsection Assertions
6181: @cindex assertions
1.5 anton 6182:
1.26 crook 6183: It is a good idea to make your programs self-checking, especially if you
6184: make an assumption that may become invalid during maintenance (for
6185: example, that a certain field of a data structure is never zero). Gforth
1.29 crook 6186: supports @dfn{assertions} for this purpose. They are used like this:
1.23 crook 6187:
1.26 crook 6188: @example
1.29 crook 6189: assert( @i{flag} )
1.26 crook 6190: @end example
1.23 crook 6191:
1.26 crook 6192: The code between @code{assert(} and @code{)} should compute a flag, that
6193: should be true if everything is alright and false otherwise. It should
6194: not change anything else on the stack. The overall stack effect of the
6195: assertion is @code{( -- )}. E.g.
1.23 crook 6196:
1.26 crook 6197: @example
6198: assert( 1 1 + 2 = ) \ what we learn in school
6199: assert( dup 0<> ) \ assert that the top of stack is not zero
6200: assert( false ) \ this code should not be reached
6201: @end example
1.23 crook 6202:
1.26 crook 6203: The need for assertions is different at different times. During
6204: debugging, we want more checking, in production we sometimes care more
6205: for speed. Therefore, assertions can be turned off, i.e., the assertion
6206: becomes a comment. Depending on the importance of an assertion and the
6207: time it takes to check it, you may want to turn off some assertions and
6208: keep others turned on. Gforth provides several levels of assertions for
6209: this purpose:
1.23 crook 6210:
1.26 crook 6211: doc-assert0(
6212: doc-assert1(
6213: doc-assert2(
6214: doc-assert3(
6215: doc-assert(
6216: doc-)
1.23 crook 6217:
1.26 crook 6218: The variable @code{assert-level} specifies the highest assertions that
6219: are turned on. I.e., at the default @code{assert-level} of one,
6220: @code{assert0(} and @code{assert1(} assertions perform checking, while
6221: @code{assert2(} and @code{assert3(} assertions are treated as comments.
6222:
6223: The value of @code{assert-level} is evaluated at compile-time, not at
6224: run-time. Therefore you cannot turn assertions on or off at run-time;
6225: you have to set the @code{assert-level} appropriately before compiling a
6226: piece of code. You can compile different pieces of code at different
6227: @code{assert-level}s (e.g., a trusted library at level 1 and
6228: newly-written code at level 3).
1.23 crook 6229:
1.26 crook 6230: doc-assert-level
1.23 crook 6231:
1.26 crook 6232: If an assertion fails, a message compatible with Emacs' compilation mode
6233: is produced and the execution is aborted (currently with @code{ABORT"}.
6234: If there is interest, we will introduce a special throw code. But if you
6235: intend to @code{catch} a specific condition, using @code{throw} is
6236: probably more appropriate than an assertion).
1.23 crook 6237:
1.26 crook 6238: Definitions in ANS Forth for these assertion words are provided
6239: in @file{compat/assert.fs}.
1.23 crook 6240:
6241:
1.26 crook 6242: @node Singlestep Debugger, , Assertions, Programming Tools
6243: @subsection Singlestep Debugger
6244: @cindex singlestep Debugger
6245: @cindex debugging Singlestep
6246: @cindex @code{dbg}
6247: @cindex @code{BREAK:}
6248: @cindex @code{BREAK"}
1.23 crook 6249:
1.26 crook 6250: When you create a new word there's often the need to check whether it
6251: behaves correctly or not. You can do this by typing @code{dbg
6252: badword}. A debug session might look like this:
1.23 crook 6253:
1.26 crook 6254: @example
6255: : badword 0 DO i . LOOP ; ok
6256: 2 dbg badword
6257: : badword
6258: Scanning code...
1.23 crook 6259:
1.26 crook 6260: Nesting debugger ready!
1.23 crook 6261:
1.26 crook 6262: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
6263: 400D4740 8049F68 DO -> [ 0 ]
6264: 400D4744 804A0C8 i -> [ 1 ] 00000
6265: 400D4748 400C5E60 . -> 0 [ 0 ]
6266: 400D474C 8049D0C LOOP -> [ 0 ]
6267: 400D4744 804A0C8 i -> [ 1 ] 00001
6268: 400D4748 400C5E60 . -> 1 [ 0 ]
6269: 400D474C 8049D0C LOOP -> [ 0 ]
6270: 400D4758 804B384 ; -> ok
6271: @end example
1.23 crook 6272:
1.26 crook 6273: Each line displayed is one step. You always have to hit return to
6274: execute the next word that is displayed. If you don't want to execute
6275: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
6276: an overview what keys are available:
1.23 crook 6277:
1.26 crook 6278: @table @i
1.23 crook 6279:
1.30 anton 6280: @item @key{RET}
1.26 crook 6281: Next; Execute the next word.
1.23 crook 6282:
1.26 crook 6283: @item n
6284: Nest; Single step through next word.
1.5 anton 6285:
1.26 crook 6286: @item u
6287: Unnest; Stop debugging and execute rest of word. If we got to this word
6288: with nest, continue debugging with the calling word.
1.5 anton 6289:
1.26 crook 6290: @item d
6291: Done; Stop debugging and execute rest.
1.5 anton 6292:
1.26 crook 6293: @item s
6294: Stop; Abort immediately.
1.5 anton 6295:
1.26 crook 6296: @end table
1.5 anton 6297:
1.26 crook 6298: Debugging large application with this mechanism is very difficult, because
6299: you have to nest very deeply into the program before the interesting part
6300: begins. This takes a lot of time.
1.5 anton 6301:
1.26 crook 6302: To do it more directly put a @code{BREAK:} command into your source code.
6303: When program execution reaches @code{BREAK:} the single step debugger is
6304: invoked and you have all the features described above.
1.23 crook 6305:
1.26 crook 6306: If you have more than one part to debug it is useful to know where the
6307: program has stopped at the moment. You can do this by the
6308: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
6309: string is typed out when the ``breakpoint'' is reached.
6310:
6311: doc-dbg
6312: doc-BREAK:
6313: doc-BREAK"
6314:
6315:
6316: @c -------------------------------------------------------------
6317: @node Assembler and Code Words, Threading Words, Programming Tools, Words
6318: @section Assembler and Code Words
6319: @cindex assembler
6320: @cindex code words
1.5 anton 6321:
1.26 crook 6322: Gforth provides some words for defining primitives (words written in
1.29 crook 6323: machine code), and for defining the machine-code equivalent of
1.26 crook 6324: @code{DOES>}-based defining words. However, the machine-independent
6325: nature of Gforth poses a few problems: First of all, Gforth runs on
6326: several architectures, so it can provide no standard assembler. What's
6327: worse is that the register allocation not only depends on the processor,
6328: but also on the @code{gcc} version and options used.
1.5 anton 6329:
1.29 crook 6330: The words that Gforth offers encapsulate some system dependences (e.g.,
6331: the header structure), so a system-independent assembler may be used in
1.26 crook 6332: Gforth. If you do not have an assembler, you can compile machine code
1.29 crook 6333: directly with @code{,} and @code{c,}@footnote{This isn't portable,
6334: because these words emit stuff in @i{data} space; it works because
6335: Gforth has unified code/data spaces. Assembler isn't likely to be
6336: portable anyway.}.
1.5 anton 6337:
1.26 crook 6338: doc-assembler
6339: doc-code
6340: doc-end-code
6341: doc-;code
6342: doc-flush-icache
1.5 anton 6343:
1.26 crook 6344: If @code{flush-icache} does not work correctly, @code{code} words
6345: etc. will not work (reliably), either.
1.5 anton 6346:
1.29 crook 6347: The typical usage of these @code{code} words can be shown most easily by
6348: analogy to the equivalent high-level defining words:
6349:
6350: @example
6351: : foo code foo
6352: <high-level Forth words> <assembler>
6353: ; end-code
6354:
6355: : bar : bar
6356: <high-level Forth words> <high-level Forth words>
6357: CREATE CREATE
6358: <high-level Forth words> <high-level Forth words>
6359: DOES> ;code
6360: <high-level Forth words> <assembler>
6361: ; end-code
6362: @end example
6363:
1.26 crook 6364: @code{flush-icache} is always present. The other words are rarely used
6365: and reside in @code{code.fs}, which is usually not loaded. You can load
6366: it with @code{require code.fs}.
1.5 anton 6367:
1.26 crook 6368: @cindex registers of the inner interpreter
6369: In the assembly code you will want to refer to the inner interpreter's
6370: registers (e.g., the data stack pointer) and you may want to use other
6371: registers for temporary storage. Unfortunately, the register allocation
6372: is installation-dependent.
1.5 anton 6373:
1.26 crook 6374: The easiest solution is to use explicit register declarations
6375: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
6376: GNU C Manual}) for all of the inner interpreter's registers: You have to
6377: compile Gforth with @code{-DFORCE_REG} (configure option
6378: @code{--enable-force-reg}) and the appropriate declarations must be
6379: present in the @code{machine.h} file (see @code{mips.h} for an example;
6380: you can find a full list of all declarable register symbols with
6381: @code{grep register engine.c}). If you give explicit registers to all
6382: variables that are declared at the beginning of @code{engine()}, you
6383: should be able to use the other caller-saved registers for temporary
6384: storage. Alternatively, you can use the @code{gcc} option
6385: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
6386: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
6387: (however, this restriction on register allocation may slow Gforth
6388: significantly).
1.5 anton 6389:
1.26 crook 6390: If this solution is not viable (e.g., because @code{gcc} does not allow
6391: you to explicitly declare all the registers you need), you have to find
6392: out by looking at the code where the inner interpreter's registers
6393: reside and which registers can be used for temporary storage. You can
6394: get an assembly listing of the engine's code with @code{make engine.s}.
1.5 anton 6395:
1.26 crook 6396: In any case, it is good practice to abstract your assembly code from the
6397: actual register allocation. E.g., if the data stack pointer resides in
6398: register @code{$17}, create an alias for this register called @code{sp},
6399: and use that in your assembly code.
1.5 anton 6400:
1.26 crook 6401: @cindex code words, portable
6402: Another option for implementing normal and defining words efficiently
6403: is to add the desired functionality to the source of Gforth. For normal
6404: words you just have to edit @file{primitives} (@pxref{Automatic
6405: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
6406: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
6407: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5 anton 6408:
6409:
1.26 crook 6410: @c -------------------------------------------------------------
6411: @node Threading Words, Locals, Assembler and Code Words, Words
6412: @section Threading Words
6413: @cindex threading words
1.5 anton 6414:
1.26 crook 6415: @cindex code address
6416: These words provide access to code addresses and other threading stuff
6417: in Gforth (and, possibly, other interpretive Forths). It more or less
6418: abstracts away the differences between direct and indirect threading
6419: (and, for direct threading, the machine dependences). However, at
6420: present this wordset is still incomplete. It is also pretty low-level;
6421: some day it will hopefully be made unnecessary by an internals wordset
6422: that abstracts implementation details away completely.
1.5 anton 6423:
1.26 crook 6424: doc-threading-method
6425: doc->code-address
6426: doc->does-code
6427: doc-code-address!
6428: doc-does-code!
6429: doc-does-handler!
6430: doc-/does-handler
1.5 anton 6431:
1.26 crook 6432: The code addresses produced by various defining words are produced by
6433: the following words:
1.5 anton 6434:
1.26 crook 6435: doc-docol:
6436: doc-docon:
6437: doc-dovar:
6438: doc-douser:
6439: doc-dodefer:
6440: doc-dofield:
1.5 anton 6441:
1.26 crook 6442: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
6443: with @code{>does-code}. If the word was defined in that way, the value
6444: returned is non-zero and identifies the @code{DOES>} used by the
6445: defining word.
6446: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5 anton 6447:
1.26 crook 6448: @c -------------------------------------------------------------
6449: @node Locals, Structures, Threading Words, Words
6450: @section Locals
6451: @cindex locals
1.5 anton 6452:
1.26 crook 6453: Local variables can make Forth programming more enjoyable and Forth
6454: programs easier to read. Unfortunately, the locals of ANS Forth are
6455: laden with restrictions. Therefore, we provide not only the ANS Forth
6456: locals wordset, but also our own, more powerful locals wordset (we
6457: implemented the ANS Forth locals wordset through our locals wordset).
1.5 anton 6458:
1.26 crook 6459: The ideas in this section have also been published in the paper
6460: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
6461: at EuroForth '94; it is available at
6462: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
1.5 anton 6463:
1.26 crook 6464: @menu
6465: * Gforth locals::
6466: * ANS Forth locals::
6467: @end menu
1.5 anton 6468:
1.26 crook 6469: @node Gforth locals, ANS Forth locals, Locals, Locals
6470: @subsection Gforth locals
6471: @cindex Gforth locals
6472: @cindex locals, Gforth style
1.5 anton 6473:
1.26 crook 6474: Locals can be defined with
1.5 anton 6475:
6476: @example
1.26 crook 6477: @{ local1 local2 ... -- comment @}
6478: @end example
6479: or
6480: @example
6481: @{ local1 local2 ... @}
1.5 anton 6482: @end example
6483:
1.26 crook 6484: E.g.,
1.5 anton 6485: @example
1.26 crook 6486: : max @{ n1 n2 -- n3 @}
6487: n1 n2 > if
6488: n1
6489: else
6490: n2
6491: endif ;
1.5 anton 6492: @end example
6493:
1.26 crook 6494: The similarity of locals definitions with stack comments is intended. A
6495: locals definition often replaces the stack comment of a word. The order
6496: of the locals corresponds to the order in a stack comment and everything
6497: after the @code{--} is really a comment.
1.5 anton 6498:
1.26 crook 6499: This similarity has one disadvantage: It is too easy to confuse locals
6500: declarations with stack comments, causing bugs and making them hard to
6501: find. However, this problem can be avoided by appropriate coding
6502: conventions: Do not use both notations in the same program. If you do,
6503: they should be distinguished using additional means, e.g. by position.
6504:
6505: @cindex types of locals
6506: @cindex locals types
6507: The name of the local may be preceded by a type specifier, e.g.,
6508: @code{F:} for a floating point value:
6509:
6510: @example
6511: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
6512: \ complex multiplication
6513: Ar Br f* Ai Bi f* f-
6514: Ar Bi f* Ai Br f* f+ ;
6515: @end example
6516:
6517: @cindex flavours of locals
6518: @cindex locals flavours
6519: @cindex value-flavoured locals
6520: @cindex variable-flavoured locals
6521: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
6522: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
6523: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
6524: with @code{W:}, @code{D:} etc.) produces its value and can be changed
6525: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
6526: produces its address (which becomes invalid when the variable's scope is
6527: left). E.g., the standard word @code{emit} can be defined in terms of
6528: @code{type} like this:
1.5 anton 6529:
6530: @example
1.26 crook 6531: : emit @{ C^ char* -- @}
6532: char* 1 type ;
1.5 anton 6533: @end example
6534:
1.26 crook 6535: @cindex default type of locals
6536: @cindex locals, default type
6537: A local without type specifier is a @code{W:} local. Both flavours of
6538: locals are initialized with values from the data or FP stack.
1.5 anton 6539:
1.26 crook 6540: Currently there is no way to define locals with user-defined data
6541: structures, but we are working on it.
1.5 anton 6542:
1.26 crook 6543: Gforth allows defining locals everywhere in a colon definition. This
6544: poses the following questions:
1.5 anton 6545:
1.26 crook 6546: @menu
6547: * Where are locals visible by name?::
6548: * How long do locals live?::
6549: * Programming Style::
6550: * Implementation::
6551: @end menu
1.5 anton 6552:
1.26 crook 6553: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
6554: @subsubsection Where are locals visible by name?
6555: @cindex locals visibility
6556: @cindex visibility of locals
6557: @cindex scope of locals
1.5 anton 6558:
1.26 crook 6559: Basically, the answer is that locals are visible where you would expect
6560: it in block-structured languages, and sometimes a little longer. If you
6561: want to restrict the scope of a local, enclose its definition in
6562: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 6563:
1.26 crook 6564: doc-scope
6565: doc-endscope
1.5 anton 6566:
1.26 crook 6567: These words behave like control structure words, so you can use them
6568: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
6569: arbitrary ways.
1.5 anton 6570:
1.26 crook 6571: If you want a more exact answer to the visibility question, here's the
6572: basic principle: A local is visible in all places that can only be
6573: reached through the definition of the local@footnote{In compiler
6574: construction terminology, all places dominated by the definition of the
6575: local.}. In other words, it is not visible in places that can be reached
6576: without going through the definition of the local. E.g., locals defined
6577: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
6578: defined in @code{BEGIN}...@code{UNTIL} are visible after the
6579: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5 anton 6580:
1.26 crook 6581: The reasoning behind this solution is: We want to have the locals
6582: visible as long as it is meaningful. The user can always make the
6583: visibility shorter by using explicit scoping. In a place that can
6584: only be reached through the definition of a local, the meaning of a
6585: local name is clear. In other places it is not: How is the local
6586: initialized at the control flow path that does not contain the
6587: definition? Which local is meant, if the same name is defined twice in
6588: two independent control flow paths?
1.5 anton 6589:
1.26 crook 6590: This should be enough detail for nearly all users, so you can skip the
6591: rest of this section. If you really must know all the gory details and
6592: options, read on.
1.5 anton 6593:
1.26 crook 6594: In order to implement this rule, the compiler has to know which places
6595: are unreachable. It knows this automatically after @code{AHEAD},
6596: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
6597: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
6598: compiler that the control flow never reaches that place. If
6599: @code{UNREACHABLE} is not used where it could, the only consequence is
6600: that the visibility of some locals is more limited than the rule above
6601: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
6602: lie to the compiler), buggy code will be produced.
1.5 anton 6603:
1.26 crook 6604: doc-unreachable
1.5 anton 6605:
1.26 crook 6606: Another problem with this rule is that at @code{BEGIN}, the compiler
6607: does not know which locals will be visible on the incoming
6608: back-edge. All problems discussed in the following are due to this
6609: ignorance of the compiler (we discuss the problems using @code{BEGIN}
6610: loops as examples; the discussion also applies to @code{?DO} and other
6611: loops). Perhaps the most insidious example is:
1.5 anton 6612: @example
1.26 crook 6613: AHEAD
6614: BEGIN
6615: x
6616: [ 1 CS-ROLL ] THEN
6617: @{ x @}
6618: ...
6619: UNTIL
6620: @end example
1.5 anton 6621:
1.26 crook 6622: This should be legal according to the visibility rule. The use of
6623: @code{x} can only be reached through the definition; but that appears
6624: textually below the use.
1.5 anton 6625:
1.26 crook 6626: From this example it is clear that the visibility rules cannot be fully
6627: implemented without major headaches. Our implementation treats common
6628: cases as advertised and the exceptions are treated in a safe way: The
6629: compiler makes a reasonable guess about the locals visible after a
6630: @code{BEGIN}; if it is too pessimistic, the
6631: user will get a spurious error about the local not being defined; if the
6632: compiler is too optimistic, it will notice this later and issue a
6633: warning. In the case above the compiler would complain about @code{x}
6634: being undefined at its use. You can see from the obscure examples in
6635: this section that it takes quite unusual control structures to get the
6636: compiler into trouble, and even then it will often do fine.
1.5 anton 6637:
1.26 crook 6638: If the @code{BEGIN} is reachable from above, the most optimistic guess
6639: is that all locals visible before the @code{BEGIN} will also be
6640: visible after the @code{BEGIN}. This guess is valid for all loops that
6641: are entered only through the @code{BEGIN}, in particular, for normal
6642: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
6643: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
6644: compiler. When the branch to the @code{BEGIN} is finally generated by
6645: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
6646: warns the user if it was too optimistic:
6647: @example
6648: IF
6649: @{ x @}
6650: BEGIN
6651: \ x ?
6652: [ 1 cs-roll ] THEN
6653: ...
6654: UNTIL
1.5 anton 6655: @end example
6656:
1.26 crook 6657: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
6658: optimistically assumes that it lives until the @code{THEN}. It notices
6659: this difference when it compiles the @code{UNTIL} and issues a
6660: warning. The user can avoid the warning, and make sure that @code{x}
6661: is not used in the wrong area by using explicit scoping:
6662: @example
6663: IF
6664: SCOPE
6665: @{ x @}
6666: ENDSCOPE
6667: BEGIN
6668: [ 1 cs-roll ] THEN
6669: ...
6670: UNTIL
6671: @end example
1.5 anton 6672:
1.26 crook 6673: Since the guess is optimistic, there will be no spurious error messages
6674: about undefined locals.
1.5 anton 6675:
1.26 crook 6676: If the @code{BEGIN} is not reachable from above (e.g., after
6677: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
6678: optimistic guess, as the locals visible after the @code{BEGIN} may be
6679: defined later. Therefore, the compiler assumes that no locals are
6680: visible after the @code{BEGIN}. However, the user can use
6681: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
6682: visible at the BEGIN as at the point where the top control-flow stack
6683: item was created.
1.5 anton 6684:
1.26 crook 6685: doc-assume-live
1.5 anton 6686:
1.26 crook 6687: E.g.,
1.5 anton 6688: @example
1.26 crook 6689: @{ x @}
6690: AHEAD
6691: ASSUME-LIVE
6692: BEGIN
6693: x
6694: [ 1 CS-ROLL ] THEN
6695: ...
6696: UNTIL
1.5 anton 6697: @end example
6698:
1.26 crook 6699: Other cases where the locals are defined before the @code{BEGIN} can be
6700: handled by inserting an appropriate @code{CS-ROLL} before the
6701: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
6702: behind the @code{ASSUME-LIVE}).
1.5 anton 6703:
1.26 crook 6704: Cases where locals are defined after the @code{BEGIN} (but should be
6705: visible immediately after the @code{BEGIN}) can only be handled by
6706: rearranging the loop. E.g., the ``most insidious'' example above can be
6707: arranged into:
1.5 anton 6708: @example
1.26 crook 6709: BEGIN
6710: @{ x @}
6711: ... 0=
6712: WHILE
6713: x
6714: REPEAT
1.5 anton 6715: @end example
6716:
1.26 crook 6717: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
6718: @subsubsection How long do locals live?
6719: @cindex locals lifetime
6720: @cindex lifetime of locals
1.5 anton 6721:
1.26 crook 6722: The right answer for the lifetime question would be: A local lives at
6723: least as long as it can be accessed. For a value-flavoured local this
6724: means: until the end of its visibility. However, a variable-flavoured
6725: local could be accessed through its address far beyond its visibility
6726: scope. Ultimately, this would mean that such locals would have to be
6727: garbage collected. Since this entails un-Forth-like implementation
6728: complexities, I adopted the same cowardly solution as some other
6729: languages (e.g., C): The local lives only as long as it is visible;
6730: afterwards its address is invalid (and programs that access it
6731: afterwards are erroneous).
1.5 anton 6732:
1.26 crook 6733: @node Programming Style, Implementation, How long do locals live?, Gforth locals
6734: @subsubsection Programming Style
6735: @cindex locals programming style
6736: @cindex programming style, locals
1.5 anton 6737:
1.26 crook 6738: The freedom to define locals anywhere has the potential to change
6739: programming styles dramatically. In particular, the need to use the
6740: return stack for intermediate storage vanishes. Moreover, all stack
6741: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
6742: determined arguments) can be eliminated: If the stack items are in the
6743: wrong order, just write a locals definition for all of them; then
6744: write the items in the order you want.
1.5 anton 6745:
1.26 crook 6746: This seems a little far-fetched and eliminating stack manipulations is
6747: unlikely to become a conscious programming objective. Still, the number
6748: of stack manipulations will be reduced dramatically if local variables
6749: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
6750: a traditional implementation of @code{max}).
1.5 anton 6751:
1.26 crook 6752: This shows one potential benefit of locals: making Forth programs more
6753: readable. Of course, this benefit will only be realized if the
6754: programmers continue to honour the principle of factoring instead of
6755: using the added latitude to make the words longer.
1.5 anton 6756:
1.26 crook 6757: @cindex single-assignment style for locals
6758: Using @code{TO} can and should be avoided. Without @code{TO},
6759: every value-flavoured local has only a single assignment and many
6760: advantages of functional languages apply to Forth. I.e., programs are
6761: easier to analyse, to optimize and to read: It is clear from the
6762: definition what the local stands for, it does not turn into something
6763: different later.
1.5 anton 6764:
1.26 crook 6765: E.g., a definition using @code{TO} might look like this:
1.5 anton 6766: @example
1.26 crook 6767: : strcmp @{ addr1 u1 addr2 u2 -- n @}
6768: u1 u2 min 0
6769: ?do
6770: addr1 c@@ addr2 c@@ -
6771: ?dup-if
6772: unloop exit
6773: then
6774: addr1 char+ TO addr1
6775: addr2 char+ TO addr2
6776: loop
6777: u1 u2 - ;
1.5 anton 6778: @end example
1.26 crook 6779: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
6780: every loop iteration. @code{strcmp} is a typical example of the
6781: readability problems of using @code{TO}. When you start reading
6782: @code{strcmp}, you think that @code{addr1} refers to the start of the
6783: string. Only near the end of the loop you realize that it is something
6784: else.
1.5 anton 6785:
1.26 crook 6786: This can be avoided by defining two locals at the start of the loop that
6787: are initialized with the right value for the current iteration.
1.5 anton 6788: @example
1.26 crook 6789: : strcmp @{ addr1 u1 addr2 u2 -- n @}
6790: addr1 addr2
6791: u1 u2 min 0
6792: ?do @{ s1 s2 @}
6793: s1 c@@ s2 c@@ -
6794: ?dup-if
6795: unloop exit
6796: then
6797: s1 char+ s2 char+
6798: loop
6799: 2drop
6800: u1 u2 - ;
1.5 anton 6801: @end example
1.26 crook 6802: Here it is clear from the start that @code{s1} has a different value
6803: in every loop iteration.
1.5 anton 6804:
1.26 crook 6805: @node Implementation, , Programming Style, Gforth locals
6806: @subsubsection Implementation
6807: @cindex locals implementation
6808: @cindex implementation of locals
1.5 anton 6809:
1.26 crook 6810: @cindex locals stack
6811: Gforth uses an extra locals stack. The most compelling reason for
6812: this is that the return stack is not float-aligned; using an extra stack
6813: also eliminates the problems and restrictions of using the return stack
6814: as locals stack. Like the other stacks, the locals stack grows toward
6815: lower addresses. A few primitives allow an efficient implementation:
1.5 anton 6816:
1.26 crook 6817: doc-@local#
6818: doc-f@local#
6819: doc-laddr#
6820: doc-lp+!#
6821: doc-lp!
6822: doc->l
6823: doc-f>l
1.5 anton 6824:
1.26 crook 6825: In addition to these primitives, some specializations of these
6826: primitives for commonly occurring inline arguments are provided for
6827: efficiency reasons, e.g., @code{@@local0} as specialization of
6828: @code{@@local#} for the inline argument 0. The following compiling words
6829: compile the right specialized version, or the general version, as
6830: appropriate:
1.6 pazsan 6831:
1.26 crook 6832: doc-compile-@local
6833: doc-compile-f@local
6834: doc-compile-lp+!
1.12 anton 6835:
1.26 crook 6836: Combinations of conditional branches and @code{lp+!#} like
6837: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
6838: is taken) are provided for efficiency and correctness in loops.
1.6 pazsan 6839:
1.26 crook 6840: A special area in the dictionary space is reserved for keeping the
6841: local variable names. @code{@{} switches the dictionary pointer to this
6842: area and @code{@}} switches it back and generates the locals
6843: initializing code. @code{W:} etc.@ are normal defining words. This
6844: special area is cleared at the start of every colon definition.
1.6 pazsan 6845:
1.26 crook 6846: @cindex word list for defining locals
6847: A special feature of Gforth's dictionary is used to implement the
6848: definition of locals without type specifiers: every word list (aka
6849: vocabulary) has its own methods for searching
6850: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
6851: with a special search method: When it is searched for a word, it
6852: actually creates that word using @code{W:}. @code{@{} changes the search
6853: order to first search the word list containing @code{@}}, @code{W:} etc.,
6854: and then the word list for defining locals without type specifiers.
1.12 anton 6855:
1.26 crook 6856: The lifetime rules support a stack discipline within a colon
6857: definition: The lifetime of a local is either nested with other locals
6858: lifetimes or it does not overlap them.
1.6 pazsan 6859:
1.26 crook 6860: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
6861: pointer manipulation is generated. Between control structure words
6862: locals definitions can push locals onto the locals stack. @code{AGAIN}
6863: is the simplest of the other three control flow words. It has to
6864: restore the locals stack depth of the corresponding @code{BEGIN}
6865: before branching. The code looks like this:
6866: @format
6867: @code{lp+!#} current-locals-size @minus{} dest-locals-size
6868: @code{branch} <begin>
6869: @end format
1.6 pazsan 6870:
1.26 crook 6871: @code{UNTIL} is a little more complicated: If it branches back, it
6872: must adjust the stack just like @code{AGAIN}. But if it falls through,
6873: the locals stack must not be changed. The compiler generates the
6874: following code:
6875: @format
6876: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
6877: @end format
6878: The locals stack pointer is only adjusted if the branch is taken.
1.6 pazsan 6879:
1.26 crook 6880: @code{THEN} can produce somewhat inefficient code:
6881: @format
6882: @code{lp+!#} current-locals-size @minus{} orig-locals-size
6883: <orig target>:
6884: @code{lp+!#} orig-locals-size @minus{} new-locals-size
6885: @end format
6886: The second @code{lp+!#} adjusts the locals stack pointer from the
1.29 crook 6887: level at the @i{orig} point to the level after the @code{THEN}. The
1.26 crook 6888: first @code{lp+!#} adjusts the locals stack pointer from the current
6889: level to the level at the orig point, so the complete effect is an
6890: adjustment from the current level to the right level after the
6891: @code{THEN}.
1.6 pazsan 6892:
1.26 crook 6893: @cindex locals information on the control-flow stack
6894: @cindex control-flow stack items, locals information
6895: In a conventional Forth implementation a dest control-flow stack entry
6896: is just the target address and an orig entry is just the address to be
6897: patched. Our locals implementation adds a word list to every orig or dest
6898: item. It is the list of locals visible (or assumed visible) at the point
6899: described by the entry. Our implementation also adds a tag to identify
6900: the kind of entry, in particular to differentiate between live and dead
6901: (reachable and unreachable) orig entries.
1.6 pazsan 6902:
1.26 crook 6903: A few unusual operations have to be performed on locals word lists:
1.6 pazsan 6904:
1.26 crook 6905: doc-common-list
6906: doc-sub-list?
6907: doc-list-size
1.6 pazsan 6908:
1.26 crook 6909: Several features of our locals word list implementation make these
6910: operations easy to implement: The locals word lists are organised as
6911: linked lists; the tails of these lists are shared, if the lists
6912: contain some of the same locals; and the address of a name is greater
6913: than the address of the names behind it in the list.
1.6 pazsan 6914:
1.26 crook 6915: Another important implementation detail is the variable
6916: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
6917: determine if they can be reached directly or only through the branch
6918: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
6919: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
6920: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6 pazsan 6921:
1.26 crook 6922: Counted loops are similar to other loops in most respects, but
6923: @code{LEAVE} requires special attention: It performs basically the same
6924: service as @code{AHEAD}, but it does not create a control-flow stack
6925: entry. Therefore the information has to be stored elsewhere;
6926: traditionally, the information was stored in the target fields of the
6927: branches created by the @code{LEAVE}s, by organizing these fields into a
6928: linked list. Unfortunately, this clever trick does not provide enough
6929: space for storing our extended control flow information. Therefore, we
6930: introduce another stack, the leave stack. It contains the control-flow
6931: stack entries for all unresolved @code{LEAVE}s.
1.6 pazsan 6932:
1.26 crook 6933: Local names are kept until the end of the colon definition, even if
6934: they are no longer visible in any control-flow path. In a few cases
6935: this may lead to increased space needs for the locals name area, but
6936: usually less than reclaiming this space would cost in code size.
1.6 pazsan 6937:
6938:
1.26 crook 6939: @node ANS Forth locals, , Gforth locals, Locals
6940: @subsection ANS Forth locals
6941: @cindex locals, ANS Forth style
1.6 pazsan 6942:
1.26 crook 6943: The ANS Forth locals wordset does not define a syntax for locals, but
6944: words that make it possible to define various syntaxes. One of the
6945: possible syntaxes is a subset of the syntax we used in the Gforth locals
6946: wordset, i.e.:
1.6 pazsan 6947:
6948: @example
1.26 crook 6949: @{ local1 local2 ... -- comment @}
1.6 pazsan 6950: @end example
1.23 crook 6951: @noindent
1.26 crook 6952: or
1.6 pazsan 6953: @example
1.26 crook 6954: @{ local1 local2 ... @}
1.6 pazsan 6955: @end example
6956:
1.26 crook 6957: The order of the locals corresponds to the order in a stack comment. The
6958: restrictions are:
1.6 pazsan 6959:
6960: @itemize @bullet
6961: @item
1.26 crook 6962: Locals can only be cell-sized values (no type specifiers are allowed).
1.6 pazsan 6963: @item
1.26 crook 6964: Locals can be defined only outside control structures.
1.6 pazsan 6965: @item
1.26 crook 6966: Locals can interfere with explicit usage of the return stack. For the
6967: exact (and long) rules, see the standard. If you don't use return stack
6968: accessing words in a definition using locals, you will be all right. The
6969: purpose of this rule is to make locals implementation on the return
6970: stack easier.
1.6 pazsan 6971: @item
1.26 crook 6972: The whole definition must be in one line.
6973: @end itemize
1.6 pazsan 6974:
1.26 crook 6975: Locals defined in this way behave like @code{VALUE}s (@xref{Simple
6976: Defining Words}). I.e., they are initialized from the stack. Using their
6977: name produces their value. Their value can be changed using @code{TO}.
1.6 pazsan 6978:
1.26 crook 6979: Since this syntax is supported by Gforth directly, you need not do
6980: anything to use it. If you want to port a program using this syntax to
6981: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
6982: syntax on the other system.
1.6 pazsan 6983:
1.26 crook 6984: Note that a syntax shown in the standard, section A.13 looks
6985: similar, but is quite different in having the order of locals
6986: reversed. Beware!
1.6 pazsan 6987:
1.26 crook 6988: The ANS Forth locals wordset itself consists of a word:
1.6 pazsan 6989:
1.26 crook 6990: doc-(local)
1.6 pazsan 6991:
1.26 crook 6992: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
6993: awful that we strongly recommend not to use it. We have implemented this
6994: syntax to make porting to Gforth easy, but do not document it here. The
6995: problem with this syntax is that the locals are defined in an order
6996: reversed with respect to the standard stack comment notation, making
6997: programs harder to read, and easier to misread and miswrite. The only
6998: merit of this syntax is that it is easy to implement using the ANS Forth
6999: locals wordset.
1.7 pazsan 7000:
7001:
1.26 crook 7002: @c ----------------------------------------------------------
7003: @node Structures, Object-oriented Forth, Locals, Words
7004: @section Structures
7005: @cindex structures
7006: @cindex records
1.7 pazsan 7007:
1.26 crook 7008: This section presents the structure package that comes with Gforth. A
7009: version of the package implemented in ANS Forth is available in
7010: @file{compat/struct.fs}. This package was inspired by a posting on
7011: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
7012: possibly John Hayes). A version of this section has been published in
7013: ???. Marcel Hendrix provided helpful comments.
1.7 pazsan 7014:
1.26 crook 7015: @menu
7016: * Why explicit structure support?::
7017: * Structure Usage::
7018: * Structure Naming Convention::
7019: * Structure Implementation::
7020: * Structure Glossary::
7021: @end menu
1.7 pazsan 7022:
1.26 crook 7023: @node Why explicit structure support?, Structure Usage, Structures, Structures
7024: @subsection Why explicit structure support?
1.7 pazsan 7025:
1.26 crook 7026: @cindex address arithmetic for structures
7027: @cindex structures using address arithmetic
7028: If we want to use a structure containing several fields, we could simply
7029: reserve memory for it, and access the fields using address arithmetic
1.32 anton 7030: (@pxref{Address arithmetic}). As an example, consider a structure with
1.26 crook 7031: the following fields
1.7 pazsan 7032:
1.26 crook 7033: @table @code
7034: @item a
7035: is a float
7036: @item b
7037: is a cell
7038: @item c
7039: is a float
7040: @end table
1.7 pazsan 7041:
1.26 crook 7042: Given the (float-aligned) base address of the structure we get the
7043: address of the field
1.13 pazsan 7044:
1.26 crook 7045: @table @code
7046: @item a
7047: without doing anything further.
7048: @item b
7049: with @code{float+}
7050: @item c
7051: with @code{float+ cell+ faligned}
7052: @end table
1.13 pazsan 7053:
1.26 crook 7054: It is easy to see that this can become quite tiring.
1.13 pazsan 7055:
1.26 crook 7056: Moreover, it is not very readable, because seeing a
7057: @code{cell+} tells us neither which kind of structure is
7058: accessed nor what field is accessed; we have to somehow infer the kind
7059: of structure, and then look up in the documentation, which field of
7060: that structure corresponds to that offset.
1.13 pazsan 7061:
1.26 crook 7062: Finally, this kind of address arithmetic also causes maintenance
7063: troubles: If you add or delete a field somewhere in the middle of the
7064: structure, you have to find and change all computations for the fields
7065: afterwards.
1.13 pazsan 7066:
1.26 crook 7067: So, instead of using @code{cell+} and friends directly, how
7068: about storing the offsets in constants:
1.13 pazsan 7069:
7070: @example
1.26 crook 7071: 0 constant a-offset
7072: 0 float+ constant b-offset
7073: 0 float+ cell+ faligned c-offset
1.13 pazsan 7074: @end example
7075:
1.26 crook 7076: Now we can get the address of field @code{x} with @code{x-offset
7077: +}. This is much better in all respects. Of course, you still
7078: have to change all later offset definitions if you add a field. You can
7079: fix this by declaring the offsets in the following way:
1.13 pazsan 7080:
7081: @example
1.26 crook 7082: 0 constant a-offset
7083: a-offset float+ constant b-offset
7084: b-offset cell+ faligned constant c-offset
1.13 pazsan 7085: @end example
7086:
1.26 crook 7087: Since we always use the offsets with @code{+}, we could use a defining
7088: word @code{cfield} that includes the @code{+} in the action of the
7089: defined word:
1.8 pazsan 7090:
7091: @example
1.26 crook 7092: : cfield ( n "name" -- )
7093: create ,
7094: does> ( name execution: addr1 -- addr2 )
7095: @@ + ;
1.13 pazsan 7096:
1.26 crook 7097: 0 cfield a
7098: 0 a float+ cfield b
7099: 0 b cell+ faligned cfield c
1.13 pazsan 7100: @end example
7101:
1.26 crook 7102: Instead of @code{x-offset +}, we now simply write @code{x}.
7103:
7104: The structure field words now can be used quite nicely. However,
7105: their definition is still a bit cumbersome: We have to repeat the
7106: name, the information about size and alignment is distributed before
7107: and after the field definitions etc. The structure package presented
7108: here addresses these problems.
7109:
7110: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
7111: @subsection Structure Usage
7112: @cindex structure usage
1.13 pazsan 7113:
1.26 crook 7114: @cindex @code{field} usage
7115: @cindex @code{struct} usage
7116: @cindex @code{end-struct} usage
7117: You can define a structure for a (data-less) linked list with:
1.13 pazsan 7118: @example
1.26 crook 7119: struct
7120: cell% field list-next
7121: end-struct list%
1.13 pazsan 7122: @end example
7123:
1.26 crook 7124: With the address of the list node on the stack, you can compute the
7125: address of the field that contains the address of the next node with
7126: @code{list-next}. E.g., you can determine the length of a list
7127: with:
1.13 pazsan 7128:
7129: @example
1.26 crook 7130: : list-length ( list -- n )
7131: \ "list" is a pointer to the first element of a linked list
7132: \ "n" is the length of the list
7133: 0 BEGIN ( list1 n1 )
7134: over
7135: WHILE ( list1 n1 )
7136: 1+ swap list-next @@ swap
7137: REPEAT
7138: nip ;
1.13 pazsan 7139: @end example
7140:
1.26 crook 7141: You can reserve memory for a list node in the dictionary with
7142: @code{list% %allot}, which leaves the address of the list node on the
7143: stack. For the equivalent allocation on the heap you can use @code{list%
7144: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
7145: use @code{list% %allocate}). You can get the the size of a list
7146: node with @code{list% %size} and its alignment with @code{list%
7147: %alignment}.
1.13 pazsan 7148:
1.26 crook 7149: Note that in ANS Forth the body of a @code{create}d word is
7150: @code{aligned} but not necessarily @code{faligned};
7151: therefore, if you do a:
1.13 pazsan 7152: @example
1.26 crook 7153: create @emph{name} foo% %allot
1.8 pazsan 7154: @end example
7155:
1.26 crook 7156: @noindent
7157: then the memory alloted for @code{foo%} is
7158: guaranteed to start at the body of @code{@emph{name}} only if
7159: @code{foo%} contains only character, cell and double fields.
1.20 pazsan 7160:
1.26 crook 7161: @cindex strcutures containing structures
7162: You can include a structure @code{foo%} as a field of
7163: another structure, like this:
1.20 pazsan 7164: @example
1.26 crook 7165: struct
7166: ...
7167: foo% field ...
7168: ...
7169: end-struct ...
1.20 pazsan 7170: @end example
7171:
1.26 crook 7172: @cindex structure extension
7173: @cindex extended records
7174: Instead of starting with an empty structure, you can extend an
7175: existing structure. E.g., a plain linked list without data, as defined
7176: above, is hardly useful; You can extend it to a linked list of integers,
7177: like this:@footnote{This feature is also known as @emph{extended
7178: records}. It is the main innovation in the Oberon language; in other
7179: words, adding this feature to Modula-2 led Wirth to create a new
7180: language, write a new compiler etc. Adding this feature to Forth just
7181: required a few lines of code.}
1.20 pazsan 7182:
7183: @example
1.26 crook 7184: list%
7185: cell% field intlist-int
7186: end-struct intlist%
1.20 pazsan 7187: @end example
7188:
1.26 crook 7189: @code{intlist%} is a structure with two fields:
7190: @code{list-next} and @code{intlist-int}.
1.20 pazsan 7191:
1.26 crook 7192: @cindex structures containing arrays
7193: You can specify an array type containing @emph{n} elements of
7194: type @code{foo%} like this:
1.20 pazsan 7195:
7196: @example
1.26 crook 7197: foo% @emph{n} *
1.20 pazsan 7198: @end example
7199:
1.26 crook 7200: You can use this array type in any place where you can use a normal
7201: type, e.g., when defining a @code{field}, or with
7202: @code{%allot}.
1.20 pazsan 7203:
1.26 crook 7204: @cindex first field optimization
7205: The first field is at the base address of a structure and the word
7206: for this field (e.g., @code{list-next}) actually does not change
7207: the address on the stack. You may be tempted to leave it away in the
7208: interest of run-time and space efficiency. This is not necessary,
7209: because the structure package optimizes this case and compiling such
7210: words does not generate any code. So, in the interest of readability
7211: and maintainability you should include the word for the field when
7212: accessing the field.
1.20 pazsan 7213:
1.26 crook 7214: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
7215: @subsection Structure Naming Convention
7216: @cindex structure naming convention
1.20 pazsan 7217:
1.26 crook 7218: The field names that come to (my) mind are often quite generic, and,
7219: if used, would cause frequent name clashes. E.g., many structures
7220: probably contain a @code{counter} field. The structure names
7221: that come to (my) mind are often also the logical choice for the names
7222: of words that create such a structure.
1.20 pazsan 7223:
1.26 crook 7224: Therefore, I have adopted the following naming conventions:
1.20 pazsan 7225:
1.26 crook 7226: @itemize @bullet
7227: @cindex field naming convention
7228: @item
7229: The names of fields are of the form
7230: @code{@emph{struct}-@emph{field}}, where
7231: @code{@emph{struct}} is the basic name of the structure, and
7232: @code{@emph{field}} is the basic name of the field. You can
7233: think of field words as converting the (address of the)
7234: structure into the (address of the) field.
1.20 pazsan 7235:
1.26 crook 7236: @cindex structure naming convention
7237: @item
7238: The names of structures are of the form
7239: @code{@emph{struct}%}, where
7240: @code{@emph{struct}} is the basic name of the structure.
7241: @end itemize
1.20 pazsan 7242:
1.26 crook 7243: This naming convention does not work that well for fields of extended
7244: structures; e.g., the integer list structure has a field
7245: @code{intlist-int}, but has @code{list-next}, not
7246: @code{intlist-next}.
1.20 pazsan 7247:
1.26 crook 7248: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
7249: @subsection Structure Implementation
7250: @cindex structure implementation
7251: @cindex implementation of structures
1.20 pazsan 7252:
1.26 crook 7253: The central idea in the implementation is to pass the data about the
7254: structure being built on the stack, not in some global
7255: variable. Everything else falls into place naturally once this design
7256: decision is made.
1.20 pazsan 7257:
1.26 crook 7258: The type description on the stack is of the form @emph{align
7259: size}. Keeping the size on the top-of-stack makes dealing with arrays
7260: very simple.
1.20 pazsan 7261:
1.26 crook 7262: @code{field} is a defining word that uses @code{Create}
7263: and @code{DOES>}. The body of the field contains the offset
7264: of the field, and the normal @code{DOES>} action is simply:
1.20 pazsan 7265:
7266: @example
1.26 crook 7267: @ +
1.20 pazsan 7268: @end example
7269:
1.23 crook 7270: @noindent
1.26 crook 7271: i.e., add the offset to the address, giving the stack effect
1.29 crook 7272: @i{addr1 -- addr2} for a field.
1.20 pazsan 7273:
1.26 crook 7274: @cindex first field optimization, implementation
7275: This simple structure is slightly complicated by the optimization
7276: for fields with offset 0, which requires a different
7277: @code{DOES>}-part (because we cannot rely on there being
7278: something on the stack if such a field is invoked during
7279: compilation). Therefore, we put the different @code{DOES>}-parts
7280: in separate words, and decide which one to invoke based on the
7281: offset. For a zero offset, the field is basically a noop; it is
7282: immediate, and therefore no code is generated when it is compiled.
1.20 pazsan 7283:
1.26 crook 7284: @node Structure Glossary, , Structure Implementation, Structures
7285: @subsection Structure Glossary
7286: @cindex structure glossary
1.20 pazsan 7287:
1.26 crook 7288: doc-%align
7289: doc-%alignment
7290: doc-%alloc
7291: doc-%allocate
7292: doc-%allot
7293: doc-cell%
7294: doc-char%
7295: doc-dfloat%
7296: doc-double%
7297: doc-end-struct
7298: doc-field
7299: doc-float%
7300: doc-naligned
7301: doc-sfloat%
7302: doc-%size
7303: doc-struct
1.23 crook 7304:
1.26 crook 7305: @c -------------------------------------------------------------
7306: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
7307: @section Object-oriented Forth
1.20 pazsan 7308:
1.26 crook 7309: Gforth comes with three packages for object-oriented programming:
7310: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
7311: is preloaded, so you have to @code{include} them before use. The most
7312: important differences between these packages (and others) are discussed
7313: in @ref{Comparison with other object models}. All packages are written
7314: in ANS Forth and can be used with any other ANS Forth.
1.20 pazsan 7315:
1.26 crook 7316: @menu
7317: * Why object-oriented programming?::
7318: * Object-Oriented Terminology::
7319: * Objects::
7320: * OOF::
7321: * Mini-OOF::
7322: * Comparison with other object models::
7323: @end menu
1.20 pazsan 7324:
1.23 crook 7325:
1.26 crook 7326: @node Why object-oriented programming?, Object-Oriented Terminology, , Object-oriented Forth
7327: @subsubsection Why object-oriented programming?
7328: @cindex object-oriented programming motivation
7329: @cindex motivation for object-oriented programming
1.23 crook 7330:
1.26 crook 7331: Often we have to deal with several data structures (@emph{objects}),
7332: that have to be treated similarly in some respects, but differently in
7333: others. Graphical objects are the textbook example: circles, triangles,
7334: dinosaurs, icons, and others, and we may want to add more during program
7335: development. We want to apply some operations to any graphical object,
7336: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
7337: has to do something different for every kind of object.
7338: @comment TODO add some other operations eg perimeter, area
7339: @comment and tie in to concrete examples later..
1.23 crook 7340:
1.26 crook 7341: We could implement @code{draw} as a big @code{CASE}
7342: control structure that executes the appropriate code depending on the
7343: kind of object to be drawn. This would be not be very elegant, and,
7344: moreover, we would have to change @code{draw} every time we add
7345: a new kind of graphical object (say, a spaceship).
1.23 crook 7346:
1.26 crook 7347: What we would rather do is: When defining spaceships, we would tell
7348: the system: ``Here's how you @code{draw} a spaceship; you figure
7349: out the rest''.
1.23 crook 7350:
1.26 crook 7351: This is the problem that all systems solve that (rightfully) call
7352: themselves object-oriented; the object-oriented packages presented here
7353: solve this problem (and not much else).
7354: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23 crook 7355:
1.26 crook 7356: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
7357: @subsubsection Object-Oriented Terminology
7358: @cindex object-oriented terminology
7359: @cindex terminology for object-oriented programming
1.23 crook 7360:
1.26 crook 7361: This section is mainly for reference, so you don't have to understand
7362: all of it right away. The terminology is mainly Smalltalk-inspired. In
7363: short:
1.23 crook 7364:
1.26 crook 7365: @table @emph
7366: @cindex class
7367: @item class
7368: a data structure definition with some extras.
1.23 crook 7369:
1.26 crook 7370: @cindex object
7371: @item object
7372: an instance of the data structure described by the class definition.
1.23 crook 7373:
1.26 crook 7374: @cindex instance variables
7375: @item instance variables
7376: fields of the data structure.
1.23 crook 7377:
1.26 crook 7378: @cindex selector
7379: @cindex method selector
7380: @cindex virtual function
7381: @item selector
7382: (or @emph{method selector}) a word (e.g.,
7383: @code{draw}) that performs an operation on a variety of data
7384: structures (classes). A selector describes @emph{what} operation to
7385: perform. In C++ terminology: a (pure) virtual function.
1.23 crook 7386:
1.26 crook 7387: @cindex method
7388: @item method
7389: the concrete definition that performs the operation
7390: described by the selector for a specific class. A method specifies
7391: @emph{how} the operation is performed for a specific class.
1.23 crook 7392:
1.26 crook 7393: @cindex selector invocation
7394: @cindex message send
7395: @cindex invoking a selector
7396: @item selector invocation
7397: a call of a selector. One argument of the call (the TOS (top-of-stack))
7398: is used for determining which method is used. In Smalltalk terminology:
7399: a message (consisting of the selector and the other arguments) is sent
7400: to the object.
1.1 anton 7401:
1.26 crook 7402: @cindex receiving object
7403: @item receiving object
7404: the object used for determining the method executed by a selector
7405: invocation. In the @file{objects.fs} model, it is the object that is on
7406: the TOS when the selector is invoked. (@emph{Receiving} comes from
7407: the Smalltalk @emph{message} terminology.)
1.1 anton 7408:
1.26 crook 7409: @cindex child class
7410: @cindex parent class
7411: @cindex inheritance
7412: @item child class
7413: a class that has (@emph{inherits}) all properties (instance variables,
7414: selectors, methods) from a @emph{parent class}. In Smalltalk
7415: terminology: The subclass inherits from the superclass. In C++
7416: terminology: The derived class inherits from the base class.
1.1 anton 7417:
1.26 crook 7418: @end table
1.21 crook 7419:
1.26 crook 7420: @c If you wonder about the message sending terminology, it comes from
7421: @c a time when each object had it's own task and objects communicated via
7422: @c message passing; eventually the Smalltalk developers realized that
7423: @c they can do most things through simple (indirect) calls. They kept the
7424: @c terminology.
1.1 anton 7425:
7426:
1.26 crook 7427: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
7428: @subsection The @file{objects.fs} model
7429: @cindex objects
7430: @cindex object-oriented programming
1.1 anton 7431:
1.26 crook 7432: @cindex @file{objects.fs}
7433: @cindex @file{oof.fs}
1.1 anton 7434:
1.37 anton 7435: This section describes the @file{objects.fs} package. This material also
7436: has been published in @cite{Yet Another Forth Objects Package} by Anton
7437: Ertl and appeared in Forth Dimensions 19(2), pages 37--43
7438: (@url{http://www.complang.tuwien.ac.at/forth/objects/objects.html}).
1.26 crook 7439: @c McKewan's and Zsoter's packages
1.1 anton 7440:
1.26 crook 7441: This section assumes that you have read @ref{Structures}.
1.1 anton 7442:
1.26 crook 7443: The techniques on which this model is based have been used to implement
7444: the parser generator, Gray, and have also been used in Gforth for
7445: implementing the various flavours of word lists (hashed or not,
7446: case-sensitive or not, special-purpose word lists for locals etc.).
1.1 anton 7447:
7448:
1.26 crook 7449: @menu
7450: * Properties of the Objects model::
7451: * Basic Objects Usage::
1.37 anton 7452: * The Objects base class::
1.26 crook 7453: * Creating objects::
7454: * Object-Oriented Programming Style::
7455: * Class Binding::
7456: * Method conveniences::
7457: * Classes and Scoping::
1.37 anton 7458: * Dividing classes::
1.26 crook 7459: * Object Interfaces::
7460: * Objects Implementation::
7461: * Objects Glossary::
7462: @end menu
1.1 anton 7463:
1.26 crook 7464: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
7465: and Bernd Paysan helped me with the related works section.
1.1 anton 7466:
1.26 crook 7467: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
7468: @subsubsection Properties of the @file{objects.fs} model
7469: @cindex @file{objects.fs} properties
1.1 anton 7470:
1.26 crook 7471: @itemize @bullet
7472: @item
7473: It is straightforward to pass objects on the stack. Passing
7474: selectors on the stack is a little less convenient, but possible.
1.1 anton 7475:
1.26 crook 7476: @item
7477: Objects are just data structures in memory, and are referenced by their
7478: address. You can create words for objects with normal defining words
7479: like @code{constant}. Likewise, there is no difference between instance
7480: variables that contain objects and those that contain other data.
1.1 anton 7481:
1.26 crook 7482: @item
7483: Late binding is efficient and easy to use.
1.21 crook 7484:
1.26 crook 7485: @item
7486: It avoids parsing, and thus avoids problems with state-smartness
7487: and reduced extensibility; for convenience there are a few parsing
7488: words, but they have non-parsing counterparts. There are also a few
7489: defining words that parse. This is hard to avoid, because all standard
7490: defining words parse (except @code{:noname}); however, such
7491: words are not as bad as many other parsing words, because they are not
7492: state-smart.
1.21 crook 7493:
1.26 crook 7494: @item
7495: It does not try to incorporate everything. It does a few things and does
7496: them well (IMO). In particular, this model was not designed to support
7497: information hiding (although it has features that may help); you can use
7498: a separate package for achieving this.
1.21 crook 7499:
1.26 crook 7500: @item
7501: It is layered; you don't have to learn and use all features to use this
7502: model. Only a few features are necessary (@xref{Basic Objects Usage},
7503: @xref{The Objects base class}, @xref{Creating objects}.), the others
7504: are optional and independent of each other.
1.21 crook 7505:
1.26 crook 7506: @item
7507: An implementation in ANS Forth is available.
1.21 crook 7508:
1.26 crook 7509: @end itemize
1.21 crook 7510:
7511:
1.26 crook 7512: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
7513: @subsubsection Basic @file{objects.fs} Usage
7514: @cindex basic objects usage
7515: @cindex objects, basic usage
1.21 crook 7516:
1.26 crook 7517: You can define a class for graphical objects like this:
1.21 crook 7518:
1.26 crook 7519: @cindex @code{class} usage
7520: @cindex @code{end-class} usage
7521: @cindex @code{selector} usage
7522: @example
7523: object class \ "object" is the parent class
7524: selector draw ( x y graphical -- )
7525: end-class graphical
7526: @end example
1.21 crook 7527:
1.26 crook 7528: This code defines a class @code{graphical} with an
7529: operation @code{draw}. We can perform the operation
7530: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 7531:
1.26 crook 7532: @example
7533: 100 100 t-rex draw
7534: @end example
1.21 crook 7535:
1.26 crook 7536: @noindent
7537: where @code{t-rex} is a word (say, a constant) that produces a
7538: graphical object.
1.21 crook 7539:
1.29 crook 7540: @comment TODO add a 2nd operation eg perimeter.. and use for
1.26 crook 7541: @comment a concrete example
1.21 crook 7542:
1.26 crook 7543: @cindex abstract class
7544: How do we create a graphical object? With the present definitions,
7545: we cannot create a useful graphical object. The class
7546: @code{graphical} describes graphical objects in general, but not
7547: any concrete graphical object type (C++ users would call it an
7548: @emph{abstract class}); e.g., there is no method for the selector
7549: @code{draw} in the class @code{graphical}.
1.21 crook 7550:
1.26 crook 7551: For concrete graphical objects, we define child classes of the
7552: class @code{graphical}, e.g.:
1.21 crook 7553:
1.26 crook 7554: @cindex @code{overrides} usage
7555: @cindex @code{field} usage in class definition
7556: @example
7557: graphical class \ "graphical" is the parent class
7558: cell% field circle-radius
1.21 crook 7559:
1.26 crook 7560: :noname ( x y circle -- )
7561: circle-radius @@ draw-circle ;
7562: overrides draw
1.21 crook 7563:
1.26 crook 7564: :noname ( n-radius circle -- )
7565: circle-radius ! ;
7566: overrides construct
1.21 crook 7567:
1.26 crook 7568: end-class circle
1.21 crook 7569: @end example
7570:
1.26 crook 7571: Here we define a class @code{circle} as a child of @code{graphical},
7572: with field @code{circle-radius} (which behaves just like a field
7573: (@pxref{Structures}); it defines (using @code{overrides}) new methods
7574: for the selectors @code{draw} and @code{construct} (@code{construct} is
7575: defined in @code{object}, the parent class of @code{graphical}).
1.21 crook 7576:
1.26 crook 7577: Now we can create a circle on the heap (i.e.,
7578: @code{allocate}d memory) with:
1.21 crook 7579:
1.26 crook 7580: @cindex @code{heap-new} usage
1.21 crook 7581: @example
1.26 crook 7582: 50 circle heap-new constant my-circle
7583: @end example
1.21 crook 7584:
1.26 crook 7585: @noindent
7586: @code{heap-new} invokes @code{construct}, thus
7587: initializing the field @code{circle-radius} with 50. We can draw
7588: this new circle at (100,100) with:
1.21 crook 7589:
1.26 crook 7590: @example
7591: 100 100 my-circle draw
1.21 crook 7592: @end example
7593:
1.26 crook 7594: @cindex selector invocation, restrictions
7595: @cindex class definition, restrictions
7596: Note: You can only invoke a selector if the object on the TOS
7597: (the receiving object) belongs to the class where the selector was
7598: defined or one of its descendents; e.g., you can invoke
7599: @code{draw} only for objects belonging to @code{graphical}
7600: or its descendents (e.g., @code{circle}). Immediately before
7601: @code{end-class}, the search order has to be the same as
7602: immediately after @code{class}.
1.21 crook 7603:
1.26 crook 7604: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
7605: @subsubsection The @file{object.fs} base class
7606: @cindex @code{object} class
1.21 crook 7607:
1.26 crook 7608: When you define a class, you have to specify a parent class. So how do
7609: you start defining classes? There is one class available from the start:
7610: @code{object}. It is ancestor for all classes and so is the
7611: only class that has no parent. It has two selectors: @code{construct}
7612: and @code{print}.
1.21 crook 7613:
1.26 crook 7614: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
7615: @subsubsection Creating objects
7616: @cindex creating objects
7617: @cindex object creation
7618: @cindex object allocation options
1.21 crook 7619:
1.26 crook 7620: @cindex @code{heap-new} discussion
7621: @cindex @code{dict-new} discussion
7622: @cindex @code{construct} discussion
7623: You can create and initialize an object of a class on the heap with
7624: @code{heap-new} ( ... class -- object ) and in the dictionary
7625: (allocation with @code{allot}) with @code{dict-new} (
7626: ... class -- object ). Both words invoke @code{construct}, which
7627: consumes the stack items indicated by "..." above.
1.21 crook 7628:
1.26 crook 7629: @cindex @code{init-object} discussion
7630: @cindex @code{class-inst-size} discussion
7631: If you want to allocate memory for an object yourself, you can get its
7632: alignment and size with @code{class-inst-size 2@@} ( class --
7633: align size ). Once you have memory for an object, you can initialize
7634: it with @code{init-object} ( ... class object -- );
7635: @code{construct} does only a part of the necessary work.
1.21 crook 7636:
1.26 crook 7637: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
7638: @subsubsection Object-Oriented Programming Style
7639: @cindex object-oriented programming style
1.21 crook 7640:
1.26 crook 7641: This section is not exhaustive.
1.1 anton 7642:
1.26 crook 7643: @cindex stack effects of selectors
7644: @cindex selectors and stack effects
7645: In general, it is a good idea to ensure that all methods for the
7646: same selector have the same stack effect: when you invoke a selector,
7647: you often have no idea which method will be invoked, so, unless all
7648: methods have the same stack effect, you will not know the stack effect
7649: of the selector invocation.
1.21 crook 7650:
1.26 crook 7651: One exception to this rule is methods for the selector
7652: @code{construct}. We know which method is invoked, because we
7653: specify the class to be constructed at the same place. Actually, I
7654: defined @code{construct} as a selector only to give the users a
7655: convenient way to specify initialization. The way it is used, a
7656: mechanism different from selector invocation would be more natural
7657: (but probably would take more code and more space to explain).
1.21 crook 7658:
1.26 crook 7659: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
7660: @subsubsection Class Binding
7661: @cindex class binding
7662: @cindex early binding
1.21 crook 7663:
1.26 crook 7664: @cindex late binding
7665: Normal selector invocations determine the method at run-time depending
7666: on the class of the receiving object. This run-time selection is called
1.29 crook 7667: @i{late binding}.
1.21 crook 7668:
1.26 crook 7669: Sometimes it's preferable to invoke a different method. For example,
7670: you might want to use the simple method for @code{print}ing
7671: @code{object}s instead of the possibly long-winded @code{print} method
7672: of the receiver class. You can achieve this by replacing the invocation
7673: of @code{print} with:
1.21 crook 7674:
1.26 crook 7675: @cindex @code{[bind]} usage
7676: @example
7677: [bind] object print
1.21 crook 7678: @end example
7679:
1.26 crook 7680: @noindent
7681: in compiled code or:
1.21 crook 7682:
1.26 crook 7683: @cindex @code{bind} usage
1.21 crook 7684: @example
1.26 crook 7685: bind object print
1.21 crook 7686: @end example
7687:
1.26 crook 7688: @cindex class binding, alternative to
7689: @noindent
7690: in interpreted code. Alternatively, you can define the method with a
7691: name (e.g., @code{print-object}), and then invoke it through the
7692: name. Class binding is just a (often more convenient) way to achieve
7693: the same effect; it avoids name clutter and allows you to invoke
7694: methods directly without naming them first.
7695:
7696: @cindex superclass binding
7697: @cindex parent class binding
7698: A frequent use of class binding is this: When we define a method
7699: for a selector, we often want the method to do what the selector does
7700: in the parent class, and a little more. There is a special word for
7701: this purpose: @code{[parent]}; @code{[parent]
7702: @emph{selector}} is equivalent to @code{[bind] @emph{parent
7703: selector}}, where @code{@emph{parent}} is the parent
7704: class of the current class. E.g., a method definition might look like:
1.21 crook 7705:
1.26 crook 7706: @cindex @code{[parent]} usage
1.21 crook 7707: @example
1.26 crook 7708: :noname
7709: dup [parent] foo \ do parent's foo on the receiving object
7710: ... \ do some more
7711: ; overrides foo
1.21 crook 7712: @end example
7713:
1.26 crook 7714: @cindex class binding as optimization
7715: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
7716: March 1997), Andrew McKewan presents class binding as an optimization
7717: technique. I recommend not using it for this purpose unless you are in
7718: an emergency. Late binding is pretty fast with this model anyway, so the
7719: benefit of using class binding is small; the cost of using class binding
7720: where it is not appropriate is reduced maintainability.
1.21 crook 7721:
1.26 crook 7722: While we are at programming style questions: You should bind
7723: selectors only to ancestor classes of the receiving object. E.g., say,
7724: you know that the receiving object is of class @code{foo} or its
7725: descendents; then you should bind only to @code{foo} and its
7726: ancestors.
1.21 crook 7727:
1.26 crook 7728: @node Method conveniences, Classes and Scoping, Class Binding, Objects
7729: @subsubsection Method conveniences
7730: @cindex method conveniences
1.1 anton 7731:
1.26 crook 7732: In a method you usually access the receiving object pretty often. If
7733: you define the method as a plain colon definition (e.g., with
7734: @code{:noname}), you may have to do a lot of stack
7735: gymnastics. To avoid this, you can define the method with @code{m:
7736: ... ;m}. E.g., you could define the method for
7737: @code{draw}ing a @code{circle} with
1.20 pazsan 7738:
1.26 crook 7739: @cindex @code{this} usage
7740: @cindex @code{m:} usage
7741: @cindex @code{;m} usage
7742: @example
7743: m: ( x y circle -- )
7744: ( x y ) this circle-radius @@ draw-circle ;m
7745: @end example
1.20 pazsan 7746:
1.26 crook 7747: @cindex @code{exit} in @code{m: ... ;m}
7748: @cindex @code{exitm} discussion
7749: @cindex @code{catch} in @code{m: ... ;m}
7750: When this method is executed, the receiver object is removed from the
7751: stack; you can access it with @code{this} (admittedly, in this
7752: example the use of @code{m: ... ;m} offers no advantage). Note
7753: that I specify the stack effect for the whole method (i.e. including
7754: the receiver object), not just for the code between @code{m:}
7755: and @code{;m}. You cannot use @code{exit} in
7756: @code{m:...;m}; instead, use
7757: @code{exitm}.@footnote{Moreover, for any word that calls
7758: @code{catch} and was defined before loading
7759: @code{objects.fs}, you have to redefine it like I redefined
7760: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20 pazsan 7761:
1.26 crook 7762: @cindex @code{inst-var} usage
7763: You will frequently use sequences of the form @code{this
7764: @emph{field}} (in the example above: @code{this
7765: circle-radius}). If you use the field only in this way, you can
7766: define it with @code{inst-var} and eliminate the
7767: @code{this} before the field name. E.g., the @code{circle}
7768: class above could also be defined with:
1.20 pazsan 7769:
1.26 crook 7770: @example
7771: graphical class
7772: cell% inst-var radius
1.20 pazsan 7773:
1.26 crook 7774: m: ( x y circle -- )
7775: radius @@ draw-circle ;m
7776: overrides draw
1.20 pazsan 7777:
1.26 crook 7778: m: ( n-radius circle -- )
7779: radius ! ;m
7780: overrides construct
1.12 anton 7781:
1.26 crook 7782: end-class circle
7783: @end example
1.12 anton 7784:
1.26 crook 7785: @code{radius} can only be used in @code{circle} and its
7786: descendent classes and inside @code{m:...;m}.
1.12 anton 7787:
1.26 crook 7788: @cindex @code{inst-value} usage
7789: You can also define fields with @code{inst-value}, which is
7790: to @code{inst-var} what @code{value} is to
7791: @code{variable}. You can change the value of such a field with
7792: @code{[to-inst]}. E.g., we could also define the class
7793: @code{circle} like this:
1.12 anton 7794:
1.26 crook 7795: @example
7796: graphical class
7797: inst-value radius
1.12 anton 7798:
1.26 crook 7799: m: ( x y circle -- )
7800: radius draw-circle ;m
7801: overrides draw
1.12 anton 7802:
1.26 crook 7803: m: ( n-radius circle -- )
7804: [to-inst] radius ;m
7805: overrides construct
1.21 crook 7806:
1.26 crook 7807: end-class circle
1.12 anton 7808: @end example
7809:
1.38 anton 7810: Finally, you can define named methods with @code{:m}. One use of this
7811: feature is the definition of words that occur only in one class and are
7812: not intended to be overridden, but which still need method context
7813: (e.g., for accessing @code{inst-var}s). Another use is for methods that
7814: would be bound frequently, if defined anonymously.
7815:
1.12 anton 7816:
1.37 anton 7817: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
1.26 crook 7818: @subsubsection Classes and Scoping
7819: @cindex classes and scoping
7820: @cindex scoping and classes
1.12 anton 7821:
1.26 crook 7822: Inheritance is frequent, unlike structure extension. This exacerbates
7823: the problem with the field name convention (@pxref{Structure Naming
7824: Convention}): One always has to remember in which class the field was
7825: originally defined; changing a part of the class structure would require
7826: changes for renaming in otherwise unaffected code.
1.12 anton 7827:
1.26 crook 7828: @cindex @code{inst-var} visibility
7829: @cindex @code{inst-value} visibility
7830: To solve this problem, I added a scoping mechanism (which was not in my
7831: original charter): A field defined with @code{inst-var} (or
7832: @code{inst-value}) is visible only in the class where it is defined and in
7833: the descendent classes of this class. Using such fields only makes
7834: sense in @code{m:}-defined methods in these classes anyway.
1.12 anton 7835:
1.26 crook 7836: This scoping mechanism allows us to use the unadorned field name,
7837: because name clashes with unrelated words become much less likely.
1.12 anton 7838:
1.26 crook 7839: @cindex @code{protected} discussion
7840: @cindex @code{private} discussion
7841: Once we have this mechanism, we can also use it for controlling the
7842: visibility of other words: All words defined after
7843: @code{protected} are visible only in the current class and its
7844: descendents. @code{public} restores the compilation
7845: (i.e. @code{current}) word list that was in effect before. If you
7846: have several @code{protected}s without an intervening
7847: @code{public} or @code{set-current}, @code{public}
7848: will restore the compilation word list in effect before the first of
7849: these @code{protected}s.
1.12 anton 7850:
1.37 anton 7851: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
7852: @subsubsection Dividing classes
7853: @cindex Dividing classes
7854: @cindex @code{methods}...@code{end-methods}
7855:
7856: You may want to do the definition of methods separate from the
7857: definition of the class, its selectors, fields, and instance variables,
7858: i.e., separate the implementation from the definition. You can do this
7859: in the following way:
7860:
7861: @example
7862: graphical class
7863: inst-value radius
7864: end-class circle
7865:
7866: ... \ do some other stuff
7867:
7868: circle methods \ now we are ready
7869:
7870: m: ( x y circle -- )
7871: radius draw-circle ;m
7872: overrides draw
7873:
7874: m: ( n-radius circle -- )
7875: [to-inst] radius ;m
7876: overrides construct
7877:
7878: end-methods
7879: @end example
7880:
7881: You can use several @code{methods}...@code{end-methods} sections. The
7882: only things you can do to the class in these sections are: defining
7883: methods, and overriding the class's selectors. You must not define new
7884: selectors or fields.
7885:
7886: Note that you often have to override a selector before using it. In
7887: particular, you usually have to override @code{construct} with a new
7888: method before you can invoke @code{heap-new} and friends. E.g., you
7889: must not create a circle before the @code{overrides construct} sequence
7890: in the example above.
7891:
7892: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
1.26 crook 7893: @subsubsection Object Interfaces
7894: @cindex object interfaces
7895: @cindex interfaces for objects
1.12 anton 7896:
1.26 crook 7897: In this model you can only call selectors defined in the class of the
7898: receiving objects or in one of its ancestors. If you call a selector
7899: with a receiving object that is not in one of these classes, the
7900: result is undefined; if you are lucky, the program crashes
7901: immediately.
1.12 anton 7902:
1.26 crook 7903: @cindex selectors common to hardly-related classes
7904: Now consider the case when you want to have a selector (or several)
7905: available in two classes: You would have to add the selector to a
7906: common ancestor class, in the worst case to @code{object}. You
7907: may not want to do this, e.g., because someone else is responsible for
7908: this ancestor class.
1.12 anton 7909:
1.26 crook 7910: The solution for this problem is interfaces. An interface is a
7911: collection of selectors. If a class implements an interface, the
7912: selectors become available to the class and its descendents. A class
7913: can implement an unlimited number of interfaces. For the problem
7914: discussed above, we would define an interface for the selector(s), and
7915: both classes would implement the interface.
1.12 anton 7916:
1.26 crook 7917: As an example, consider an interface @code{storage} for
7918: writing objects to disk and getting them back, and a class
7919: @code{foo} that implements it. The code would look like this:
1.12 anton 7920:
1.26 crook 7921: @cindex @code{interface} usage
7922: @cindex @code{end-interface} usage
7923: @cindex @code{implementation} usage
7924: @example
7925: interface
7926: selector write ( file object -- )
7927: selector read1 ( file object -- )
7928: end-interface storage
1.12 anton 7929:
1.26 crook 7930: bar class
7931: storage implementation
1.12 anton 7932:
1.26 crook 7933: ... overrides write
1.37 anton 7934: ... overrides read1
1.26 crook 7935: ...
7936: end-class foo
1.12 anton 7937: @end example
7938:
1.26 crook 7939: @noindent
1.29 crook 7940: (I would add a word @code{read} @i{( file -- object )} that uses
1.26 crook 7941: @code{read1} internally, but that's beyond the point illustrated
7942: here.)
1.12 anton 7943:
1.26 crook 7944: Note that you cannot use @code{protected} in an interface; and
7945: of course you cannot define fields.
1.12 anton 7946:
1.26 crook 7947: In the Neon model, all selectors are available for all classes;
7948: therefore it does not need interfaces. The price you pay in this model
7949: is slower late binding, and therefore, added complexity to avoid late
7950: binding.
1.12 anton 7951:
1.26 crook 7952: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
7953: @subsubsection @file{objects.fs} Implementation
7954: @cindex @file{objects.fs} implementation
1.12 anton 7955:
1.26 crook 7956: @cindex @code{object-map} discussion
7957: An object is a piece of memory, like one of the data structures
7958: described with @code{struct...end-struct}. It has a field
7959: @code{object-map} that points to the method map for the object's
7960: class.
1.12 anton 7961:
1.26 crook 7962: @cindex method map
7963: @cindex virtual function table
7964: The @emph{method map}@footnote{This is Self terminology; in C++
7965: terminology: virtual function table.} is an array that contains the
1.29 crook 7966: execution tokens (@i{xt}s) of the methods for the object's class. Each
1.26 crook 7967: selector contains an offset into a method map.
1.12 anton 7968:
1.26 crook 7969: @cindex @code{selector} implementation, class
7970: @code{selector} is a defining word that uses
7971: @code{CREATE} and @code{DOES>}. The body of the
7972: selector contains the offset; the @code{does>} action for a
7973: class selector is, basically:
1.21 crook 7974:
1.26 crook 7975: @example
7976: ( object addr ) @@ over object-map @@ + @@ execute
7977: @end example
1.12 anton 7978:
1.26 crook 7979: Since @code{object-map} is the first field of the object, it
7980: does not generate any code. As you can see, calling a selector has a
7981: small, constant cost.
1.12 anton 7982:
1.26 crook 7983: @cindex @code{current-interface} discussion
7984: @cindex class implementation and representation
7985: A class is basically a @code{struct} combined with a method
7986: map. During the class definition the alignment and size of the class
7987: are passed on the stack, just as with @code{struct}s, so
7988: @code{field} can also be used for defining class
7989: fields. However, passing more items on the stack would be
7990: inconvenient, so @code{class} builds a data structure in memory,
7991: which is accessed through the variable
7992: @code{current-interface}. After its definition is complete, the
7993: class is represented on the stack by a pointer (e.g., as parameter for
7994: a child class definition).
1.1 anton 7995:
1.26 crook 7996: A new class starts off with the alignment and size of its parent,
7997: and a copy of the parent's method map. Defining new fields extends the
7998: size and alignment; likewise, defining new selectors extends the
1.29 crook 7999: method map. @code{overrides} just stores a new @i{xt} in the method
1.26 crook 8000: map at the offset given by the selector.
1.20 pazsan 8001:
1.26 crook 8002: @cindex class binding, implementation
1.29 crook 8003: Class binding just gets the @i{xt} at the offset given by the selector
1.26 crook 8004: from the class's method map and @code{compile,}s (in the case of
8005: @code{[bind]}) it.
1.21 crook 8006:
1.26 crook 8007: @cindex @code{this} implementation
8008: @cindex @code{catch} and @code{this}
8009: @cindex @code{this} and @code{catch}
8010: I implemented @code{this} as a @code{value}. At the
8011: start of an @code{m:...;m} method the old @code{this} is
8012: stored to the return stack and restored at the end; and the object on
8013: the TOS is stored @code{TO this}. This technique has one
8014: disadvantage: If the user does not leave the method via
8015: @code{;m}, but via @code{throw} or @code{exit},
8016: @code{this} is not restored (and @code{exit} may
8017: crash). To deal with the @code{throw} problem, I have redefined
8018: @code{catch} to save and restore @code{this}; the same
8019: should be done with any word that can catch an exception. As for
8020: @code{exit}, I simply forbid it (as a replacement, there is
8021: @code{exitm}).
1.21 crook 8022:
1.26 crook 8023: @cindex @code{inst-var} implementation
8024: @code{inst-var} is just the same as @code{field}, with
8025: a different @code{DOES>} action:
8026: @example
8027: @@ this +
8028: @end example
8029: Similar for @code{inst-value}.
1.21 crook 8030:
1.26 crook 8031: @cindex class scoping implementation
8032: Each class also has a word list that contains the words defined with
8033: @code{inst-var} and @code{inst-value}, and its protected
8034: words. It also has a pointer to its parent. @code{class} pushes
8035: the word lists of the class and all its ancestors onto the search order stack,
8036: and @code{end-class} drops them.
1.21 crook 8037:
1.26 crook 8038: @cindex interface implementation
8039: An interface is like a class without fields, parent and protected
8040: words; i.e., it just has a method map. If a class implements an
8041: interface, its method map contains a pointer to the method map of the
8042: interface. The positive offsets in the map are reserved for class
8043: methods, therefore interface map pointers have negative
8044: offsets. Interfaces have offsets that are unique throughout the
8045: system, unlike class selectors, whose offsets are only unique for the
8046: classes where the selector is available (invokable).
1.21 crook 8047:
1.26 crook 8048: This structure means that interface selectors have to perform one
8049: indirection more than class selectors to find their method. Their body
8050: contains the interface map pointer offset in the class method map, and
8051: the method offset in the interface method map. The
8052: @code{does>} action for an interface selector is, basically:
1.21 crook 8053:
8054: @example
1.26 crook 8055: ( object selector-body )
8056: 2dup selector-interface @@ ( object selector-body object interface-offset )
8057: swap object-map @@ + @@ ( object selector-body map )
8058: swap selector-offset @@ + @@ execute
1.21 crook 8059: @end example
8060:
1.26 crook 8061: where @code{object-map} and @code{selector-offset} are
8062: first fields and generate no code.
8063:
8064: As a concrete example, consider the following code:
1.21 crook 8065:
1.26 crook 8066: @example
8067: interface
8068: selector if1sel1
8069: selector if1sel2
8070: end-interface if1
1.21 crook 8071:
1.26 crook 8072: object class
8073: if1 implementation
8074: selector cl1sel1
8075: cell% inst-var cl1iv1
1.21 crook 8076:
1.26 crook 8077: ' m1 overrides construct
8078: ' m2 overrides if1sel1
8079: ' m3 overrides if1sel2
8080: ' m4 overrides cl1sel2
8081: end-class cl1
1.21 crook 8082:
1.26 crook 8083: create obj1 object dict-new drop
8084: create obj2 cl1 dict-new drop
8085: @end example
1.21 crook 8086:
1.26 crook 8087: The data structure created by this code (including the data structure
8088: for @code{object}) is shown in the <a
8089: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.29 crook 8090: @comment TODO add this diagram..
1.21 crook 8091:
1.26 crook 8092: @node Objects Glossary, , Objects Implementation, Objects
8093: @subsubsection @file{objects.fs} Glossary
8094: @cindex @file{objects.fs} Glossary
1.21 crook 8095:
1.26 crook 8096: doc---objects-bind
8097: doc---objects-<bind>
8098: doc---objects-bind'
8099: doc---objects-[bind]
8100: doc---objects-class
8101: doc---objects-class->map
8102: doc---objects-class-inst-size
8103: doc---objects-class-override!
8104: doc---objects-construct
8105: doc---objects-current'
8106: doc---objects-[current]
8107: doc---objects-current-interface
8108: doc---objects-dict-new
8109: doc---objects-drop-order
8110: doc---objects-end-class
8111: doc---objects-end-class-noname
8112: doc---objects-end-interface
8113: doc---objects-end-interface-noname
1.37 anton 8114: doc---objects-end-methods
1.26 crook 8115: doc---objects-exitm
8116: doc---objects-heap-new
8117: doc---objects-implementation
8118: doc---objects-init-object
8119: doc---objects-inst-value
8120: doc---objects-inst-var
8121: doc---objects-interface
1.38 anton 8122: doc---objects-m:
8123: doc---objects-:m
1.26 crook 8124: doc---objects-;m
8125: doc---objects-method
1.37 anton 8126: doc---objects-methods
1.26 crook 8127: doc---objects-object
8128: doc---objects-overrides
8129: doc---objects-[parent]
8130: doc---objects-print
8131: doc---objects-protected
8132: doc---objects-public
8133: doc---objects-push-order
8134: doc---objects-selector
8135: doc---objects-this
8136: doc---objects-<to-inst>
8137: doc---objects-[to-inst]
8138: doc---objects-to-this
8139: doc---objects-xt-new
1.21 crook 8140:
1.26 crook 8141: @c -------------------------------------------------------------
8142: @node OOF, Mini-OOF, Objects, Object-oriented Forth
8143: @subsection The @file{oof.fs} model
8144: @cindex oof
8145: @cindex object-oriented programming
1.21 crook 8146:
1.26 crook 8147: @cindex @file{objects.fs}
8148: @cindex @file{oof.fs}
1.21 crook 8149:
1.26 crook 8150: This section describes the @file{oof.fs} package.
1.21 crook 8151:
1.26 crook 8152: The package described in this section has been used in bigFORTH since 1991, and
8153: used for two large applications: a chromatographic system used to
8154: create new medicaments, and a graphic user interface library (MINOS).
1.21 crook 8155:
1.26 crook 8156: You can find a description (in German) of @file{oof.fs} in @cite{Object
8157: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
8158: 10(2), 1994.
1.21 crook 8159:
1.26 crook 8160: @menu
8161: * Properties of the OOF model::
8162: * Basic OOF Usage::
8163: * The OOF base class::
8164: * Class Declaration::
8165: * Class Implementation::
8166: @end menu
1.21 crook 8167:
1.26 crook 8168: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
8169: @subsubsection Properties of the @file{oof.fs} model
8170: @cindex @file{oof.fs} properties
1.21 crook 8171:
1.26 crook 8172: @itemize @bullet
8173: @item
8174: This model combines object oriented programming with information
8175: hiding. It helps you writing large application, where scoping is
8176: necessary, because it provides class-oriented scoping.
1.21 crook 8177:
1.26 crook 8178: @item
8179: Named objects, object pointers, and object arrays can be created,
8180: selector invocation uses the ``object selector'' syntax. Selector invocation
8181: to objects and/or selectors on the stack is a bit less convenient, but
8182: possible.
1.21 crook 8183:
1.26 crook 8184: @item
8185: Selector invocation and instance variable usage of the active object is
8186: straightforward, since both make use of the active object.
1.21 crook 8187:
1.26 crook 8188: @item
8189: Late binding is efficient and easy to use.
1.21 crook 8190:
1.26 crook 8191: @item
8192: State-smart objects parse selectors. However, extensibility is provided
8193: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21 crook 8194:
8195: @item
1.26 crook 8196: An implementation in ANS Forth is available.
8197:
1.21 crook 8198: @end itemize
8199:
8200:
1.26 crook 8201: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
8202: @subsubsection Basic @file{oof.fs} Usage
8203: @cindex @file{oof.fs} usage
8204:
8205: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21 crook 8206:
1.26 crook 8207: You can define a class for graphical objects like this:
1.21 crook 8208:
1.26 crook 8209: @cindex @code{class} usage
8210: @cindex @code{class;} usage
8211: @cindex @code{method} usage
8212: @example
8213: object class graphical \ "object" is the parent class
8214: method draw ( x y graphical -- )
8215: class;
8216: @end example
1.21 crook 8217:
1.26 crook 8218: This code defines a class @code{graphical} with an
8219: operation @code{draw}. We can perform the operation
8220: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 8221:
1.26 crook 8222: @example
8223: 100 100 t-rex draw
8224: @end example
1.21 crook 8225:
1.26 crook 8226: @noindent
8227: where @code{t-rex} is an object or object pointer, created with e.g.
8228: @code{graphical : t-rex}.
1.21 crook 8229:
1.26 crook 8230: @cindex abstract class
8231: How do we create a graphical object? With the present definitions,
8232: we cannot create a useful graphical object. The class
8233: @code{graphical} describes graphical objects in general, but not
8234: any concrete graphical object type (C++ users would call it an
8235: @emph{abstract class}); e.g., there is no method for the selector
8236: @code{draw} in the class @code{graphical}.
1.21 crook 8237:
1.26 crook 8238: For concrete graphical objects, we define child classes of the
8239: class @code{graphical}, e.g.:
1.21 crook 8240:
8241: @example
1.26 crook 8242: graphical class circle \ "graphical" is the parent class
8243: cell var circle-radius
8244: how:
8245: : draw ( x y -- )
8246: circle-radius @@ draw-circle ;
8247:
8248: : init ( n-radius -- (
8249: circle-radius ! ;
8250: class;
8251: @end example
8252:
8253: Here we define a class @code{circle} as a child of @code{graphical},
8254: with a field @code{circle-radius}; it defines new methods for the
8255: selectors @code{draw} and @code{init} (@code{init} is defined in
8256: @code{object}, the parent class of @code{graphical}).
1.21 crook 8257:
1.26 crook 8258: Now we can create a circle in the dictionary with:
1.21 crook 8259:
1.26 crook 8260: @example
8261: 50 circle : my-circle
1.21 crook 8262: @end example
8263:
1.26 crook 8264: @noindent
8265: @code{:} invokes @code{init}, thus initializing the field
8266: @code{circle-radius} with 50. We can draw this new circle at (100,100)
8267: with:
1.21 crook 8268:
8269: @example
1.26 crook 8270: 100 100 my-circle draw
1.21 crook 8271: @end example
8272:
1.26 crook 8273: @cindex selector invocation, restrictions
8274: @cindex class definition, restrictions
8275: Note: You can only invoke a selector if the receiving object belongs to
8276: the class where the selector was defined or one of its descendents;
8277: e.g., you can invoke @code{draw} only for objects belonging to
8278: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
8279: mechanism will check if you try to invoke a selector that is not
8280: defined in this class hierarchy, so you'll get an error at compilation
8281: time.
8282:
8283:
8284: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
8285: @subsubsection The @file{oof.fs} base class
8286: @cindex @file{oof.fs} base class
8287:
8288: When you define a class, you have to specify a parent class. So how do
8289: you start defining classes? There is one class available from the start:
8290: @code{object}. You have to use it as ancestor for all classes. It is the
8291: only class that has no parent. Classes are also objects, except that
8292: they don't have instance variables; class manipulation such as
8293: inheritance or changing definitions of a class is handled through
8294: selectors of the class @code{object}.
8295:
8296: @code{object} provides a number of selectors:
8297:
1.21 crook 8298: @itemize @bullet
8299: @item
1.26 crook 8300: @code{class} for subclassing, @code{definitions} to add definitions
8301: later on, and @code{class?} to get type informations (is the class a
8302: subclass of the class passed on the stack?).
8303: doc---object-class
8304: doc---object-definitions
8305: doc---object-class?
8306:
1.21 crook 8307: @item
1.26 crook 8308: @code{init} and @code{dispose} as constructor and destructor of the
8309: object. @code{init} is invocated after the object's memory is allocated,
8310: while @code{dispose} also handles deallocation. Thus if you redefine
8311: @code{dispose}, you have to call the parent's dispose with @code{super
8312: dispose}, too.
8313: doc---object-init
8314: doc---object-dispose
8315:
1.21 crook 8316: @item
1.26 crook 8317: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
8318: @code{[]} to create named and unnamed objects and object arrays or
8319: object pointers.
8320: doc---object-new
8321: doc---object-new[]
8322: doc---object-:
8323: doc---object-ptr
8324: doc---object-asptr
8325: doc---object-[]
1.21 crook 8326:
1.26 crook 8327: @item
8328: @code{::} and @code{super} for explicit scoping. You should use explicit
8329: scoping only for super classes or classes with the same set of instance
8330: variables. Explicitly-scoped selectors use early binding.
8331: doc---object-::
8332: doc---object-super
1.21 crook 8333:
1.26 crook 8334: @item
8335: @code{self} to get the address of the object
8336: doc---object-self
1.21 crook 8337:
8338: @item
1.26 crook 8339: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
8340: pointers and instance defers.
8341: doc---object-bind
8342: doc---object-bound
8343: doc---object-link
8344: doc---object-is
8345:
1.21 crook 8346: @item
1.26 crook 8347: @code{'} to obtain selector tokens, @code{send} to invocate selectors
8348: form the stack, and @code{postpone} to generate selector invocation code.
8349: doc---object-'
8350: doc---object-postpone
8351:
1.21 crook 8352: @item
1.26 crook 8353: @code{with} and @code{endwith} to select the active object from the
8354: stack, and enable its scope. Using @code{with} and @code{endwith}
8355: also allows you to create code using selector @code{postpone} without being
8356: trapped by the state-smart objects.
8357: doc---object-with
8358: doc---object-endwith
8359:
1.21 crook 8360: @end itemize
8361:
1.26 crook 8362: @node Class Declaration, Class Implementation, The OOF base class, OOF
8363: @subsubsection Class Declaration
8364: @cindex class declaration
8365:
8366: @itemize @bullet
8367: @item
8368: Instance variables
8369: doc---oof-var
1.21 crook 8370:
1.26 crook 8371: @item
8372: Object pointers
8373: doc---oof-ptr
8374: doc---oof-asptr
1.21 crook 8375:
1.26 crook 8376: @item
8377: Instance defers
8378: doc---oof-defer
1.21 crook 8379:
1.26 crook 8380: @item
8381: Method selectors
8382: doc---oof-early
8383: doc---oof-method
1.21 crook 8384:
1.26 crook 8385: @item
8386: Class-wide variables
8387: doc---oof-static
1.21 crook 8388:
1.26 crook 8389: @item
8390: End declaration
8391: doc---oof-how:
8392: doc---oof-class;
1.21 crook 8393:
1.26 crook 8394: @end itemize
1.21 crook 8395:
1.26 crook 8396: @c -------------------------------------------------------------
8397: @node Class Implementation, , Class Declaration, OOF
8398: @subsubsection Class Implementation
8399: @cindex class implementation
1.21 crook 8400:
1.26 crook 8401: @c -------------------------------------------------------------
8402: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
8403: @subsection The @file{mini-oof.fs} model
8404: @cindex mini-oof
1.1 anton 8405:
1.26 crook 8406: Gforth's third object oriented Forth package is a 12-liner. It uses a
8407: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
8408: and reduces to the bare minimum of features. This is based on a posting
8409: of Bernd Paysan in comp.arch.
1.1 anton 8410:
8411: @menu
1.26 crook 8412: * Basic Mini-OOF Usage::
8413: * Mini-OOF Example::
8414: * Mini-OOF Implementation::
1.1 anton 8415: @end menu
8416:
1.26 crook 8417: @c -------------------------------------------------------------
8418: @node Basic Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
8419: @subsubsection Basic @file{mini-oof.fs} Usage
8420: @cindex mini-oof usage
1.1 anton 8421:
1.28 crook 8422: There is a base class (@code{class}, which allocates one cell for the
8423: object pointer) plus seven other words: to define a method, a variable,
8424: a class; to end a class, to resolve binding, to allocate an object and
8425: to compile a class method.
1.26 crook 8426: @comment TODO better description of the last one
1.1 anton 8427:
1.26 crook 8428: doc-object
8429: doc-method
8430: doc-var
8431: doc-class
8432: doc-end-class
8433: doc-defines
8434: doc-new
8435: doc-::
1.1 anton 8436:
1.21 crook 8437:
1.26 crook 8438: @c -------------------------------------------------------------
8439: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
8440: @subsubsection Mini-OOF Example
8441: @cindex mini-oof example
1.21 crook 8442:
1.26 crook 8443: A short example shows how to use this package. This example, in slightly
8444: extended form, is supplied as @file{moof-exm.fs}
1.29 crook 8445: @comment TODO could flesh this out with some comments from the Forthwrite article
1.21 crook 8446:
1.26 crook 8447: @example
8448: object class
8449: method init
8450: method draw
8451: end-class graphical
8452: @end example
1.21 crook 8453:
1.26 crook 8454: This code defines a class @code{graphical} with an
8455: operation @code{draw}. We can perform the operation
8456: @code{draw} on any @code{graphical} object, e.g.:
1.1 anton 8457:
1.26 crook 8458: @example
8459: 100 100 t-rex draw
8460: @end example
1.1 anton 8461:
1.26 crook 8462: where @code{t-rex} is an object or object pointer, created with e.g.
8463: @code{graphical new Constant t-rex}.
1.1 anton 8464:
1.26 crook 8465: For concrete graphical objects, we define child classes of the
8466: class @code{graphical}, e.g.:
1.21 crook 8467:
8468: @example
1.26 crook 8469: graphical class
8470: cell var circle-radius
8471: end-class circle \ "graphical" is the parent class
1.21 crook 8472:
1.26 crook 8473: :noname ( x y -- )
8474: circle-radius @@ draw-circle ; circle defines draw
8475: :noname ( r -- )
8476: circle-radius ! ; circle defines init
1.21 crook 8477: @end example
8478:
1.26 crook 8479: There is no implicit init method, so we have to define one. The creation
8480: code of the object now has to call init explicitely.
1.21 crook 8481:
1.26 crook 8482: @example
8483: circle new Constant my-circle
8484: 50 my-circle init
8485: @end example
1.21 crook 8486:
1.26 crook 8487: It is also possible to add a function to create named objects with
8488: automatic call of @code{init}, given that all objects have @code{init}
8489: on the same place:
1.1 anton 8490:
8491: @example
1.26 crook 8492: : new: ( .. o "name" -- )
8493: new dup Constant init ;
8494: 80 circle new: large-circle
1.1 anton 8495: @end example
8496:
1.26 crook 8497: We can draw this new circle at (100,100) with:
1.1 anton 8498:
8499: @example
1.26 crook 8500: 100 100 my-circle draw
1.1 anton 8501: @end example
8502:
1.26 crook 8503: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
8504: @subsubsection @file{mini-oof.fs} Implementation
1.1 anton 8505:
1.26 crook 8506: Object-oriented systems with late binding typically use a
8507: ``vtable''-approach: the first variable in each object is a pointer to a
8508: table, which contains the methods as function pointers. The vtable
8509: may also contain other information.
1.1 anton 8510:
1.26 crook 8511: So first, let's declare methods:
1.1 anton 8512:
1.26 crook 8513: @example
8514: : method ( m v -- m' v ) Create over , swap cell+ swap
8515: DOES> ( ... o -- ... ) @ over @ + @ execute ;
8516: @end example
1.1 anton 8517:
1.26 crook 8518: During method declaration, the number of methods and instance
8519: variables is on the stack (in address units). @code{method} creates
8520: one method and increments the method number. To execute a method, it
8521: takes the object, fetches the vtable pointer, adds the offset, and
1.29 crook 8522: executes the @i{xt} stored there. Each method takes the object it is
1.26 crook 8523: invoked from as top of stack parameter. The method itself should
8524: consume that object.
1.1 anton 8525:
1.26 crook 8526: Now, we also have to declare instance variables
1.21 crook 8527:
1.26 crook 8528: @example
8529: : var ( m v size -- m v' ) Create over , +
8530: DOES> ( o -- addr ) @ + ;
8531: @end example
1.21 crook 8532:
1.26 crook 8533: As before, a word is created with the current offset. Instance
8534: variables can have different sizes (cells, floats, doubles, chars), so
8535: all we do is take the size and add it to the offset. If your machine
8536: has alignment restrictions, put the proper @code{aligned} or
8537: @code{faligned} before the variable, to adjust the variable
8538: offset. That's why it is on the top of stack.
1.2 jwilke 8539:
1.26 crook 8540: We need a starting point (the base object) and some syntactic sugar:
1.21 crook 8541:
1.26 crook 8542: @example
8543: Create object 1 cells , 2 cells ,
8544: : class ( class -- class methods vars ) dup 2@ ;
8545: @end example
1.21 crook 8546:
1.26 crook 8547: For inheritance, the vtable of the parent object has to be
8548: copied when a new, derived class is declared. This gives all the
8549: methods of the parent class, which can be overridden, though.
1.21 crook 8550:
1.2 jwilke 8551: @example
1.26 crook 8552: : end-class ( class methods vars -- )
8553: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
8554: cell+ dup cell+ r> rot @ 2 cells /string move ;
8555: @end example
8556:
8557: The first line creates the vtable, initialized with
8558: @code{noop}s. The second line is the inheritance mechanism, it
8559: copies the xts from the parent vtable.
1.2 jwilke 8560:
1.26 crook 8561: We still have no way to define new methods, let's do that now:
1.2 jwilke 8562:
1.26 crook 8563: @example
8564: : defines ( xt class -- ) ' >body @ + ! ;
1.2 jwilke 8565: @end example
8566:
1.26 crook 8567: To allocate a new object, we need a word, too:
1.2 jwilke 8568:
1.26 crook 8569: @example
8570: : new ( class -- o ) here over @ allot swap over ! ;
8571: @end example
1.2 jwilke 8572:
1.26 crook 8573: Sometimes derived classes want to access the method of the
8574: parent object. There are two ways to achieve this with Mini-OOF:
8575: first, you could use named words, and second, you could look up the
8576: vtable of the parent object.
1.2 jwilke 8577:
1.26 crook 8578: @example
8579: : :: ( class "name" -- ) ' >body @ + @ compile, ;
8580: @end example
1.2 jwilke 8581:
8582:
1.26 crook 8583: Nothing can be more confusing than a good example, so here is
8584: one. First let's declare a text object (called
8585: @code{button}), that stores text and position:
1.2 jwilke 8586:
1.26 crook 8587: @example
8588: object class
8589: cell var text
8590: cell var len
8591: cell var x
8592: cell var y
8593: method init
8594: method draw
8595: end-class button
8596: @end example
1.2 jwilke 8597:
1.26 crook 8598: @noindent
8599: Now, implement the two methods, @code{draw} and @code{init}:
1.2 jwilke 8600:
1.26 crook 8601: @example
8602: :noname ( o -- )
8603: >r r@ x @ r@ y @ at-xy r@ text @ r> len @ type ;
8604: button defines draw
8605: :noname ( addr u o -- )
8606: >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
8607: button defines init
8608: @end example
1.2 jwilke 8609:
1.26 crook 8610: @noindent
8611: To demonstrate inheritance, we define a class @code{bold-button}, with no
8612: new data and no new methods:
1.2 jwilke 8613:
1.26 crook 8614: @example
8615: button class
8616: end-class bold-button
1.1 anton 8617:
1.26 crook 8618: : bold 27 emit ." [1m" ;
8619: : normal 27 emit ." [0m" ;
8620: @end example
1.1 anton 8621:
1.26 crook 8622: @noindent
8623: The class @code{bold-button} has a different draw method to
8624: @code{button}, but the new method is defined in terms of the draw method
8625: for @code{button}:
1.1 anton 8626:
1.26 crook 8627: @example
8628: :noname bold [ button :: draw ] normal ; bold-button defines draw
8629: @end example
1.1 anton 8630:
1.26 crook 8631: @noindent
8632: Finally, create two objects and apply methods:
1.1 anton 8633:
1.26 crook 8634: @example
8635: button new Constant foo
8636: s" thin foo" foo init
8637: page
8638: foo draw
8639: bold-button new Constant bar
8640: s" fat bar" bar init
8641: 1 bar y !
8642: bar draw
8643: @end example
1.1 anton 8644:
8645:
1.26 crook 8646: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
8647: @subsubsection Comparison with other object models
8648: @cindex comparison of object models
8649: @cindex object models, comparison
1.1 anton 8650:
1.26 crook 8651: Many object-oriented Forth extensions have been proposed (@cite{A survey
8652: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
8653: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
8654: relation of the object models described here to two well-known and two
8655: closely-related (by the use of method maps) models.
1.1 anton 8656:
1.26 crook 8657: @cindex Neon model
8658: The most popular model currently seems to be the Neon model (see
8659: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
8660: 1997) by Andrew McKewan) but this model has a number of limitations
8661: @footnote{A longer version of this critique can be
8662: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
8663: Dimensions, May 1997) by Anton Ertl.}:
1.1 anton 8664:
1.26 crook 8665: @itemize @bullet
8666: @item
8667: It uses a @code{@emph{selector
8668: object}} syntax, which makes it unnatural to pass objects on the
8669: stack.
1.1 anton 8670:
1.26 crook 8671: @item
8672: It requires that the selector parses the input stream (at
8673: compile time); this leads to reduced extensibility and to bugs that are+
8674: hard to find.
1.1 anton 8675:
1.26 crook 8676: @item
8677: It allows using every selector to every object;
8678: this eliminates the need for classes, but makes it harder to create
8679: efficient implementations.
8680: @end itemize
1.1 anton 8681:
1.26 crook 8682: @cindex Pountain's object-oriented model
8683: Another well-known publication is @cite{Object-Oriented Forth} (Academic
8684: Press, London, 1987) by Dick Pountain. However, it is not really about
8685: object-oriented programming, because it hardly deals with late
8686: binding. Instead, it focuses on features like information hiding and
8687: overloading that are characteristic of modular languages like Ada (83).
1.1 anton 8688:
1.26 crook 8689: @cindex Zsoter's object-oriented model
8690: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1) 1996, pages 31-35)
8691: Andras Zsoter describes a model that makes heavy use of an active object
8692: (like @code{this} in @file{objects.fs}): The active object is not only
8693: used for accessing all fields, but also specifies the receiving object
8694: of every selector invocation; you have to change the active object
8695: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
8696: changes more or less implicitly at @code{m: ... ;m}. Such a change at
8697: the method entry point is unnecessary with the Zsoter's model, because
8698: the receiving object is the active object already. On the other hand, the explicit
8699: change is absolutely necessary in that model, because otherwise no one
8700: could ever change the active object. An ANS Forth implementation of this
8701: model is available at @url{http://www.forth.org/fig/oopf.html}.
1.1 anton 8702:
1.26 crook 8703: @cindex @file{oof.fs}, differences to other models
8704: The @file{oof.fs} model combines information hiding and overloading
8705: resolution (by keeping names in various word lists) with object-oriented
8706: programming. It sets the active object implicitly on method entry, but
8707: also allows explicit changing (with @code{>o...o>} or with
8708: @code{with...endwith}). It uses parsing and state-smart objects and
8709: classes for resolving overloading and for early binding: the object or
8710: class parses the selector and determines the method from this. If the
8711: selector is not parsed by an object or class, it performs a call to the
8712: selector for the active object (late binding), like Zsoter's model.
8713: Fields are always accessed through the active object. The big
8714: disadvantage of this model is the parsing and the state-smartness, which
8715: reduces extensibility and increases the opportunities for subtle bugs;
8716: essentially, you are only safe if you never tick or @code{postpone} an
8717: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1 anton 8718:
1.26 crook 8719: @cindex @file{mini-oof.fs}, differences to other models
8720: The @file{mini-oof.fs} model is quite similar to a very stripped-down version of
8721: the @file{objects.fs} model, but syntactically it is a mixture of the @file{objects.fs} and
8722: @file{oof.fs} models.
1.1 anton 8723:
1.26 crook 8724: @c -------------------------------------------------------------
8725: @node Passing Commands to the OS, Miscellaneous Words, Object-oriented Forth, Words
1.21 crook 8726: @section Passing Commands to the Operating System
8727: @cindex operating system - passing commands
8728: @cindex shell commands
8729:
8730: Gforth allows you to pass an arbitrary string to the host operating
8731: system shell (if such a thing exists) for execution.
8732:
8733: doc-sh
8734: doc-system
8735: doc-$?
1.23 crook 8736: doc-getenv
1.21 crook 8737:
1.26 crook 8738: @c -------------------------------------------------------------
1.21 crook 8739: @node Miscellaneous Words, , Passing Commands to the OS, Words
8740: @section Miscellaneous Words
8741: @cindex miscellaneous words
8742:
1.29 crook 8743: @comment TODO find homes for these
8744:
1.26 crook 8745: These section lists the ANS Forth words that are not documented
1.21 crook 8746: elsewhere in this manual. Ultimately, they all need proper homes.
8747:
8748: doc-ms
8749: doc-time&date
1.27 crook 8750:
1.21 crook 8751: doc-[compile]
8752:
1.26 crook 8753: The following ANS Forth words are not currently supported by Gforth
1.27 crook 8754: (@pxref{ANS conformance}):
1.21 crook 8755:
8756: @code{EDITOR}
8757: @code{EMIT?}
8758: @code{FORGET}
8759:
1.24 anton 8760: @c ******************************************************************
8761: @node Error messages, Tools, Words, Top
8762: @chapter Error messages
8763: @cindex error messages
8764: @cindex backtrace
8765:
8766: A typical Gforth error message looks like this:
8767:
8768: @example
8769: in file included from :-1
8770: in file included from ./yyy.fs:1
8771: ./xxx.fs:4: Invalid memory address
8772: bar
8773: ^^^
1.25 anton 8774: $400E664C @@
8775: $400E6664 foo
1.24 anton 8776: @end example
8777:
8778: The message identifying the error is @code{Invalid memory address}. The
8779: error happened when text-interpreting line 4 of the file
8780: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
8781: word on the line where the error happened, is pointed out (with
8782: @code{^^^}).
8783:
8784: The file containing the error was included in line 1 of @file{./yyy.fs},
8785: and @file{yyy.fs} was included from a non-file (in this case, by giving
8786: @file{yyy.fs} as command-line parameter to Gforth).
8787:
8788: At the end of the error message you find a return stack dump that can be
8789: interpreted as a backtrace (possibly empty). On top you find the top of
8790: the return stack when the @code{throw} happened, and at the bottom you
8791: find the return stack entry just above the return stack of the topmost
8792: text interpreter.
8793:
8794: To the right of most return stack entries you see a guess for the word
8795: that pushed that return stack entry as its return address. This gives a
8796: backtrace. In our case we see that @code{bar} called @code{foo}, and
8797: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
8798: address} exception).
8799:
8800: Note that the backtrace is not perfect: We don't know which return stack
8801: entries are return addresses (so we may get false positives); and in
8802: some cases (e.g., for @code{abort"}) we cannot determine from the return
8803: address the word that pushed the return address, so for some return
8804: addresses you see no names in the return stack dump.
1.25 anton 8805:
8806: @cindex @code{catch} and backtraces
8807: The return stack dump represents the return stack at the time when a
8808: specific @code{throw} was executed. In programs that make use of
8809: @code{catch}, it is not necessarily clear which @code{throw} should be
8810: used for the return stack dump (e.g., consider one @code{throw} that
8811: indicates an error, which is caught, and during recovery another error
8812: happens; which @code{throw} should be used for the stack dump). Gforth
8813: presents the return stack dump for the first @code{throw} after the last
8814: executed (not returned-to) @code{catch}; this works well in the usual
8815: case.
8816:
8817: @cindex @code{gforth-fast} and backtraces
8818: @cindex @code{gforth-fast}, difference from @code{gforth}
8819: @cindex backtraces with @code{gforth-fast}
8820: @cindex return stack dump with @code{gforth-fast}
8821: @code{gforth} is able to do a return stack dump for throws generated
8822: from primitives (e.g., invalid memory address, stack empty etc.);
8823: @code{gforth-fast} is only able to do a return stack dump from a
8824: directly called @code{throw} (including @code{abort} etc.). This is the
1.30 anton 8825: only difference (apart from a speed factor of between 1.15 (K6-2) and
8826: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}. Given an
8827: exception caused by a primitive in @code{gforth-fast}, you will
8828: typically see no return stack dump at all; however, if the exception is
8829: caught by @code{catch} (e.g., for restoring some state), and then
8830: @code{throw}n again, the return stack dump will be for the first such
8831: @code{throw}.
1.2 jwilke 8832:
1.5 anton 8833: @c ******************************************************************
1.24 anton 8834: @node Tools, ANS conformance, Error messages, Top
1.1 anton 8835: @chapter Tools
8836:
8837: @menu
8838: * ANS Report:: Report the words used, sorted by wordset.
8839: @end menu
8840:
8841: See also @ref{Emacs and Gforth}.
8842:
8843: @node ANS Report, , Tools, Tools
8844: @section @file{ans-report.fs}: Report the words used, sorted by wordset
8845: @cindex @file{ans-report.fs}
8846: @cindex report the words used in your program
8847: @cindex words used in your program
8848:
8849: If you want to label a Forth program as ANS Forth Program, you must
8850: document which wordsets the program uses; for extension wordsets, it is
8851: helpful to list the words the program requires from these wordsets
8852: (because Forth systems are allowed to provide only some words of them).
8853:
8854: The @file{ans-report.fs} tool makes it easy for you to determine which
8855: words from which wordset and which non-ANS words your application
8856: uses. You simply have to include @file{ans-report.fs} before loading the
8857: program you want to check. After loading your program, you can get the
8858: report with @code{print-ans-report}. A typical use is to run this as
8859: batch job like this:
8860: @example
8861: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
8862: @end example
8863:
8864: The output looks like this (for @file{compat/control.fs}):
8865: @example
8866: The program uses the following words
8867: from CORE :
8868: : POSTPONE THEN ; immediate ?dup IF 0=
8869: from BLOCK-EXT :
8870: \
8871: from FILE :
8872: (
8873: @end example
8874:
8875: @subsection Caveats
8876:
8877: Note that @file{ans-report.fs} just checks which words are used, not whether
8878: they are used in an ANS Forth conforming way!
8879:
8880: Some words are defined in several wordsets in the
8881: standard. @file{ans-report.fs} reports them for only one of the
8882: wordsets, and not necessarily the one you expect. It depends on usage
8883: which wordset is the right one to specify. E.g., if you only use the
8884: compilation semantics of @code{S"}, it is a Core word; if you also use
8885: its interpretation semantics, it is a File word.
8886:
8887: @c ******************************************************************
8888: @node ANS conformance, Model, Tools, Top
8889: @chapter ANS conformance
8890: @cindex ANS conformance of Gforth
8891:
8892: To the best of our knowledge, Gforth is an
8893:
8894: ANS Forth System
8895: @itemize @bullet
8896: @item providing the Core Extensions word set
8897: @item providing the Block word set
8898: @item providing the Block Extensions word set
8899: @item providing the Double-Number word set
8900: @item providing the Double-Number Extensions word set
8901: @item providing the Exception word set
8902: @item providing the Exception Extensions word set
8903: @item providing the Facility word set
1.40 anton 8904: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 8905: @item providing the File Access word set
8906: @item providing the File Access Extensions word set
8907: @item providing the Floating-Point word set
8908: @item providing the Floating-Point Extensions word set
8909: @item providing the Locals word set
8910: @item providing the Locals Extensions word set
8911: @item providing the Memory-Allocation word set
8912: @item providing the Memory-Allocation Extensions word set (that one's easy)
8913: @item providing the Programming-Tools word set
8914: @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
8915: @item providing the Search-Order word set
8916: @item providing the Search-Order Extensions word set
8917: @item providing the String word set
8918: @item providing the String Extensions word set (another easy one)
8919: @end itemize
8920:
8921: @cindex system documentation
8922: In addition, ANS Forth systems are required to document certain
8923: implementation choices. This chapter tries to meet these
8924: requirements. In many cases it gives a way to ask the system for the
8925: information instead of providing the information directly, in
8926: particular, if the information depends on the processor, the operating
8927: system or the installation options chosen, or if they are likely to
8928: change during the maintenance of Gforth.
8929:
8930: @comment The framework for the rest has been taken from pfe.
8931:
8932: @menu
8933: * The Core Words::
8934: * The optional Block word set::
8935: * The optional Double Number word set::
8936: * The optional Exception word set::
8937: * The optional Facility word set::
8938: * The optional File-Access word set::
8939: * The optional Floating-Point word set::
8940: * The optional Locals word set::
8941: * The optional Memory-Allocation word set::
8942: * The optional Programming-Tools word set::
8943: * The optional Search-Order word set::
8944: @end menu
8945:
8946:
8947: @c =====================================================================
8948: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
8949: @comment node-name, next, previous, up
8950: @section The Core Words
8951: @c =====================================================================
8952: @cindex core words, system documentation
8953: @cindex system documentation, core words
8954:
8955: @menu
8956: * core-idef:: Implementation Defined Options
8957: * core-ambcond:: Ambiguous Conditions
8958: * core-other:: Other System Documentation
8959: @end menu
8960:
8961: @c ---------------------------------------------------------------------
8962: @node core-idef, core-ambcond, The Core Words, The Core Words
8963: @subsection Implementation Defined Options
8964: @c ---------------------------------------------------------------------
8965: @cindex core words, implementation-defined options
8966: @cindex implementation-defined options, core words
8967:
8968:
8969: @table @i
8970: @item (Cell) aligned addresses:
8971: @cindex cell-aligned addresses
8972: @cindex aligned addresses
8973: processor-dependent. Gforth's alignment words perform natural alignment
8974: (e.g., an address aligned for a datum of size 8 is divisible by
8975: 8). Unaligned accesses usually result in a @code{-23 THROW}.
8976:
8977: @item @code{EMIT} and non-graphic characters:
8978: @cindex @code{EMIT} and non-graphic characters
8979: @cindex non-graphic characters and @code{EMIT}
8980: The character is output using the C library function (actually, macro)
8981: @code{putc}.
8982:
8983: @item character editing of @code{ACCEPT} and @code{EXPECT}:
8984: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
8985: @cindex editing in @code{ACCEPT} and @code{EXPECT}
8986: @cindex @code{ACCEPT}, editing
8987: @cindex @code{EXPECT}, editing
8988: This is modeled on the GNU readline library (@pxref{Readline
8989: Interaction, , Command Line Editing, readline, The GNU Readline
8990: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
8991: producing a full word completion every time you type it (instead of
1.28 crook 8992: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 8993:
8994: @item character set:
8995: @cindex character set
8996: The character set of your computer and display device. Gforth is
8997: 8-bit-clean (but some other component in your system may make trouble).
8998:
8999: @item Character-aligned address requirements:
9000: @cindex character-aligned address requirements
9001: installation-dependent. Currently a character is represented by a C
9002: @code{unsigned char}; in the future we might switch to @code{wchar_t}
9003: (Comments on that requested).
9004:
9005: @item character-set extensions and matching of names:
9006: @cindex character-set extensions and matching of names
1.26 crook 9007: @cindex case-sensitivity for name lookup
9008: @cindex name lookup, case-sensitivity
9009: @cindex locale and case-sensitivity
1.21 crook 9010: Any character except the ASCII NUL character can be used in a
1.1 anton 9011: name. Matching is case-insensitive (except in @code{TABLE}s). The
9012: matching is performed using the C function @code{strncasecmp}, whose
9013: function is probably influenced by the locale. E.g., the @code{C} locale
9014: does not know about accents and umlauts, so they are matched
9015: case-sensitively in that locale. For portability reasons it is best to
9016: write programs such that they work in the @code{C} locale. Then one can
9017: use libraries written by a Polish programmer (who might use words
9018: containing ISO Latin-2 encoded characters) and by a French programmer
9019: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
9020: funny results for some of the words (which ones, depends on the font you
9021: are using)). Also, the locale you prefer may not be available in other
9022: operating systems. Hopefully, Unicode will solve these problems one day.
9023:
9024: @item conditions under which control characters match a space delimiter:
9025: @cindex space delimiters
9026: @cindex control characters as delimiters
9027: If @code{WORD} is called with the space character as a delimiter, all
9028: white-space characters (as identified by the C macro @code{isspace()})
9029: are delimiters. @code{PARSE}, on the other hand, treats space like other
9030: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
9031: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
9032: interpreter (aka text interpreter) by default, treats all white-space
9033: characters as delimiters.
9034:
1.26 crook 9035: @item format of the control-flow stack:
9036: @cindex control-flow stack, format
9037: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 9038: stack item in cells is given by the constant @code{cs-item-size}. At the
9039: time of this writing, an item consists of a (pointer to a) locals list
9040: (third), an address in the code (second), and a tag for identifying the
9041: item (TOS). The following tags are used: @code{defstart},
9042: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
9043: @code{scopestart}.
9044:
9045: @item conversion of digits > 35
9046: @cindex digits > 35
9047: The characters @code{[\]^_'} are the digits with the decimal value
9048: 36@minus{}41. There is no way to input many of the larger digits.
9049:
9050: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
9051: @cindex @code{EXPECT}, display after end of input
9052: @cindex @code{ACCEPT}, display after end of input
9053: The cursor is moved to the end of the entered string. If the input is
9054: terminated using the @kbd{Return} key, a space is typed.
9055:
9056: @item exception abort sequence of @code{ABORT"}:
9057: @cindex exception abort sequence of @code{ABORT"}
9058: @cindex @code{ABORT"}, exception abort sequence
9059: The error string is stored into the variable @code{"error} and a
9060: @code{-2 throw} is performed.
9061:
9062: @item input line terminator:
9063: @cindex input line terminator
9064: @cindex line terminator on input
1.26 crook 9065: @cindex newline character on input
1.1 anton 9066: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
9067: lines. One of these characters is typically produced when you type the
9068: @kbd{Enter} or @kbd{Return} key.
9069:
9070: @item maximum size of a counted string:
9071: @cindex maximum size of a counted string
9072: @cindex counted string, maximum size
9073: @code{s" /counted-string" environment? drop .}. Currently 255 characters
9074: on all ports, but this may change.
9075:
9076: @item maximum size of a parsed string:
9077: @cindex maximum size of a parsed string
9078: @cindex parsed string, maximum size
9079: Given by the constant @code{/line}. Currently 255 characters.
9080:
9081: @item maximum size of a definition name, in characters:
9082: @cindex maximum size of a definition name, in characters
9083: @cindex name, maximum length
9084: 31
9085:
9086: @item maximum string length for @code{ENVIRONMENT?}, in characters:
9087: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
9088: @cindex @code{ENVIRONMENT?} string length, maximum
9089: 31
9090:
9091: @item method of selecting the user input device:
9092: @cindex user input device, method of selecting
9093: The user input device is the standard input. There is currently no way to
9094: change it from within Gforth. However, the input can typically be
9095: redirected in the command line that starts Gforth.
9096:
9097: @item method of selecting the user output device:
9098: @cindex user output device, method of selecting
9099: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 9100: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
9101: output when the user output device is a terminal, otherwise the output
9102: is buffered.
1.1 anton 9103:
9104: @item methods of dictionary compilation:
9105: What are we expected to document here?
9106:
9107: @item number of bits in one address unit:
9108: @cindex number of bits in one address unit
9109: @cindex address unit, size in bits
9110: @code{s" address-units-bits" environment? drop .}. 8 in all current
9111: ports.
9112:
9113: @item number representation and arithmetic:
9114: @cindex number representation and arithmetic
9115: Processor-dependent. Binary two's complement on all current ports.
9116:
9117: @item ranges for integer types:
9118: @cindex ranges for integer types
9119: @cindex integer types, ranges
9120: Installation-dependent. Make environmental queries for @code{MAX-N},
9121: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
9122: unsigned (and positive) types is 0. The lower bound for signed types on
9123: two's complement and one's complement machines machines can be computed
9124: by adding 1 to the upper bound.
9125:
9126: @item read-only data space regions:
9127: @cindex read-only data space regions
9128: @cindex data-space, read-only regions
9129: The whole Forth data space is writable.
9130:
9131: @item size of buffer at @code{WORD}:
9132: @cindex size of buffer at @code{WORD}
9133: @cindex @code{WORD} buffer size
9134: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
9135: shared with the pictured numeric output string. If overwriting
9136: @code{PAD} is acceptable, it is as large as the remaining dictionary
9137: space, although only as much can be sensibly used as fits in a counted
9138: string.
9139:
9140: @item size of one cell in address units:
9141: @cindex cell size
9142: @code{1 cells .}.
9143:
9144: @item size of one character in address units:
9145: @cindex char size
9146: @code{1 chars .}. 1 on all current ports.
9147:
9148: @item size of the keyboard terminal buffer:
9149: @cindex size of the keyboard terminal buffer
9150: @cindex terminal buffer, size
9151: Varies. You can determine the size at a specific time using @code{lp@@
9152: tib - .}. It is shared with the locals stack and TIBs of files that
9153: include the current file. You can change the amount of space for TIBs
9154: and locals stack at Gforth startup with the command line option
9155: @code{-l}.
9156:
9157: @item size of the pictured numeric output buffer:
9158: @cindex size of the pictured numeric output buffer
9159: @cindex pictured numeric output buffer, size
9160: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
9161: shared with @code{WORD}.
9162:
9163: @item size of the scratch area returned by @code{PAD}:
9164: @cindex size of the scratch area returned by @code{PAD}
9165: @cindex @code{PAD} size
9166: The remainder of dictionary space. @code{unused pad here - - .}.
9167:
9168: @item system case-sensitivity characteristics:
9169: @cindex case-sensitivity characteristics
1.26 crook 9170: Dictionary searches are case-insensitive (except in
1.1 anton 9171: @code{TABLE}s). However, as explained above under @i{character-set
9172: extensions}, the matching for non-ASCII characters is determined by the
9173: locale you are using. In the default @code{C} locale all non-ASCII
9174: characters are matched case-sensitively.
9175:
9176: @item system prompt:
9177: @cindex system prompt
9178: @cindex prompt
9179: @code{ ok} in interpret state, @code{ compiled} in compile state.
9180:
9181: @item division rounding:
9182: @cindex division rounding
9183: installation dependent. @code{s" floored" environment? drop .}. We leave
9184: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
9185: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
9186:
9187: @item values of @code{STATE} when true:
9188: @cindex @code{STATE} values
9189: -1.
9190:
9191: @item values returned after arithmetic overflow:
9192: On two's complement machines, arithmetic is performed modulo
9193: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
9194: arithmetic (with appropriate mapping for signed types). Division by zero
9195: typically results in a @code{-55 throw} (Floating-point unidentified
9196: fault), although a @code{-10 throw} (divide by zero) would be more
9197: appropriate.
9198:
9199: @item whether the current definition can be found after @t{DOES>}:
9200: @cindex @t{DOES>}, visibility of current definition
9201: No.
9202:
9203: @end table
9204:
9205: @c ---------------------------------------------------------------------
9206: @node core-ambcond, core-other, core-idef, The Core Words
9207: @subsection Ambiguous conditions
9208: @c ---------------------------------------------------------------------
9209: @cindex core words, ambiguous conditions
9210: @cindex ambiguous conditions, core words
9211:
9212: @table @i
9213:
9214: @item a name is neither a word nor a number:
9215: @cindex name not found
1.26 crook 9216: @cindex undefined word
1.1 anton 9217: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
9218: preserves the data and FP stack, so you don't lose more work than
9219: necessary.
9220:
9221: @item a definition name exceeds the maximum length allowed:
1.26 crook 9222: @cindex word name too long
1.1 anton 9223: @code{-19 throw} (Word name too long)
9224:
9225: @item addressing a region not inside the various data spaces of the forth system:
9226: @cindex Invalid memory address
1.32 anton 9227: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 9228: typically readable. Accessing other addresses gives results dependent on
9229: the operating system. On decent systems: @code{-9 throw} (Invalid memory
9230: address).
9231:
9232: @item argument type incompatible with parameter:
1.26 crook 9233: @cindex argument type mismatch
1.1 anton 9234: This is usually not caught. Some words perform checks, e.g., the control
9235: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
9236: mismatch).
9237:
9238: @item attempting to obtain the execution token of a word with undefined execution semantics:
9239: @cindex Interpreting a compile-only word, for @code{'} etc.
9240: @cindex execution token of words with undefined execution semantics
9241: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
9242: get an execution token for @code{compile-only-error} (which performs a
9243: @code{-14 throw} when executed).
9244:
9245: @item dividing by zero:
9246: @cindex dividing by zero
9247: @cindex floating point unidentified fault, integer division
1.24 anton 9248: On better platforms, this produces a @code{-10 throw} (Division by
9249: zero); on other systems, this typically results in a @code{-55 throw}
9250: (Floating-point unidentified fault).
1.1 anton 9251:
9252: @item insufficient data stack or return stack space:
9253: @cindex insufficient data stack or return stack space
9254: @cindex stack overflow
1.26 crook 9255: @cindex address alignment exception, stack overflow
1.1 anton 9256: @cindex Invalid memory address, stack overflow
9257: Depending on the operating system, the installation, and the invocation
9258: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 9259: it is not checked. If it is checked, you typically get a @code{-3 throw}
9260: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
9261: throw} (Invalid memory address) (depending on the platform and how you
9262: achieved the overflow) as soon as the overflow happens. If it is not
9263: checked, overflows typically result in mysterious illegal memory
9264: accesses, producing @code{-9 throw} (Invalid memory address) or
9265: @code{-23 throw} (Address alignment exception); they might also destroy
9266: the internal data structure of @code{ALLOCATE} and friends, resulting in
9267: various errors in these words.
1.1 anton 9268:
9269: @item insufficient space for loop control parameters:
9270: @cindex insufficient space for loop control parameters
9271: like other return stack overflows.
9272:
9273: @item insufficient space in the dictionary:
9274: @cindex insufficient space in the dictionary
9275: @cindex dictionary overflow
1.12 anton 9276: If you try to allot (either directly with @code{allot}, or indirectly
9277: with @code{,}, @code{create} etc.) more memory than available in the
9278: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
9279: to access memory beyond the end of the dictionary, the results are
9280: similar to stack overflows.
1.1 anton 9281:
9282: @item interpreting a word with undefined interpretation semantics:
9283: @cindex interpreting a word with undefined interpretation semantics
9284: @cindex Interpreting a compile-only word
9285: For some words, we have defined interpretation semantics. For the
9286: others: @code{-14 throw} (Interpreting a compile-only word).
9287:
9288: @item modifying the contents of the input buffer or a string literal:
9289: @cindex modifying the contents of the input buffer or a string literal
9290: These are located in writable memory and can be modified.
9291:
9292: @item overflow of the pictured numeric output string:
9293: @cindex overflow of the pictured numeric output string
9294: @cindex pictured numeric output string, overflow
1.24 anton 9295: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 9296:
9297: @item parsed string overflow:
9298: @cindex parsed string overflow
9299: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
9300:
9301: @item producing a result out of range:
9302: @cindex result out of range
9303: On two's complement machines, arithmetic is performed modulo
9304: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
9305: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 9306: typically results in a @code{-10 throw} (divide by zero) or @code{-55
9307: throw} (floating point unidentified fault). @code{convert} and
9308: @code{>number} currently overflow silently.
1.1 anton 9309:
9310: @item reading from an empty data or return stack:
9311: @cindex stack empty
9312: @cindex stack underflow
1.24 anton 9313: @cindex return stack underflow
1.1 anton 9314: The data stack is checked by the outer (aka text) interpreter after
9315: every word executed. If it has underflowed, a @code{-4 throw} (Stack
9316: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 9317: depending on operating system, installation, and invocation. If they are
9318: caught by a check, they typically result in @code{-4 throw} (Stack
9319: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
9320: (Invalid memory address), depending on the platform and which stack
9321: underflows and by how much. Note that even if the system uses checking
9322: (through the MMU), your program may have to underflow by a significant
9323: number of stack items to trigger the reaction (the reason for this is
9324: that the MMU, and therefore the checking, works with a page-size
9325: granularity). If there is no checking, the symptoms resulting from an
9326: underflow are similar to those from an overflow. Unbalanced return
9327: stack errors result in a variaty of symptoms, including @code{-9 throw}
9328: (Invalid memory address) and Illegal Instruction (typically @code{-260
9329: throw}).
1.1 anton 9330:
9331: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
9332: @cindex unexpected end of the input buffer
9333: @cindex zero-length string as a name
9334: @cindex Attempt to use zero-length string as a name
9335: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
9336: use zero-length string as a name). Words like @code{'} probably will not
9337: find what they search. Note that it is possible to create zero-length
9338: names with @code{nextname} (should it not?).
9339:
9340: @item @code{>IN} greater than input buffer:
9341: @cindex @code{>IN} greater than input buffer
9342: The next invocation of a parsing word returns a string with length 0.
9343:
9344: @item @code{RECURSE} appears after @code{DOES>}:
9345: @cindex @code{RECURSE} appears after @code{DOES>}
9346: Compiles a recursive call to the defining word, not to the defined word.
9347:
9348: @item argument input source different than current input source for @code{RESTORE-INPUT}:
9349: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 9350: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 9351: @cindex @code{RESTORE-INPUT}, Argument type mismatch
9352: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
9353: the end of the file was reached), its source-id may be
9354: reused. Therefore, restoring an input source specification referencing a
9355: closed file may lead to unpredictable results instead of a @code{-12
9356: THROW}.
9357:
9358: In the future, Gforth may be able to restore input source specifications
9359: from other than the current input source.
9360:
9361: @item data space containing definitions gets de-allocated:
9362: @cindex data space containing definitions gets de-allocated
9363: Deallocation with @code{allot} is not checked. This typically results in
9364: memory access faults or execution of illegal instructions.
9365:
9366: @item data space read/write with incorrect alignment:
9367: @cindex data space read/write with incorrect alignment
9368: @cindex alignment faults
1.26 crook 9369: @cindex address alignment exception
1.1 anton 9370: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 9371: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 9372: alignment turned on, incorrect alignment results in a @code{-9 throw}
9373: (Invalid memory address). There are reportedly some processors with
1.12 anton 9374: alignment restrictions that do not report violations.
1.1 anton 9375:
9376: @item data space pointer not properly aligned, @code{,}, @code{C,}:
9377: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
9378: Like other alignment errors.
9379:
9380: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
9381: Like other stack underflows.
9382:
9383: @item loop control parameters not available:
9384: @cindex loop control parameters not available
9385: Not checked. The counted loop words simply assume that the top of return
9386: stack items are loop control parameters and behave accordingly.
9387:
9388: @item most recent definition does not have a name (@code{IMMEDIATE}):
9389: @cindex most recent definition does not have a name (@code{IMMEDIATE})
9390: @cindex last word was headerless
9391: @code{abort" last word was headerless"}.
9392:
9393: @item name not defined by @code{VALUE} used by @code{TO}:
9394: @cindex name not defined by @code{VALUE} used by @code{TO}
9395: @cindex @code{TO} on non-@code{VALUE}s
9396: @cindex Invalid name argument, @code{TO}
9397: @code{-32 throw} (Invalid name argument) (unless name is a local or was
9398: defined by @code{CONSTANT}; in the latter case it just changes the constant).
9399:
9400: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
9401: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 9402: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 9403: @code{-13 throw} (Undefined word)
9404:
9405: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
9406: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
9407: Gforth behaves as if they were of the same type. I.e., you can predict
9408: the behaviour by interpreting all parameters as, e.g., signed.
9409:
9410: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
9411: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
9412: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
9413: compilation semantics of @code{TO}.
9414:
9415: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 9416: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 9417: @cindex @code{WORD}, string overflow
9418: Not checked. The string will be ok, but the count will, of course,
9419: contain only the least significant bits of the length.
9420:
9421: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
9422: @cindex @code{LSHIFT}, large shift counts
9423: @cindex @code{RSHIFT}, large shift counts
9424: Processor-dependent. Typical behaviours are returning 0 and using only
9425: the low bits of the shift count.
9426:
9427: @item word not defined via @code{CREATE}:
9428: @cindex @code{>BODY} of non-@code{CREATE}d words
9429: @code{>BODY} produces the PFA of the word no matter how it was defined.
9430:
9431: @cindex @code{DOES>} of non-@code{CREATE}d words
9432: @code{DOES>} changes the execution semantics of the last defined word no
9433: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
9434: @code{CREATE , DOES>}.
9435:
9436: @item words improperly used outside @code{<#} and @code{#>}:
9437: Not checked. As usual, you can expect memory faults.
9438:
9439: @end table
9440:
9441:
9442: @c ---------------------------------------------------------------------
9443: @node core-other, , core-ambcond, The Core Words
9444: @subsection Other system documentation
9445: @c ---------------------------------------------------------------------
9446: @cindex other system documentation, core words
9447: @cindex core words, other system documentation
9448:
9449: @table @i
9450: @item nonstandard words using @code{PAD}:
9451: @cindex @code{PAD} use by nonstandard words
9452: None.
9453:
9454: @item operator's terminal facilities available:
9455: @cindex operator's terminal facilities available
9456: After processing the command line, Gforth goes into interactive mode,
9457: and you can give commands to Gforth interactively. The actual facilities
9458: available depend on how you invoke Gforth.
9459:
9460: @item program data space available:
9461: @cindex program data space available
9462: @cindex data space available
9463: @code{UNUSED .} gives the remaining dictionary space. The total
9464: dictionary space can be specified with the @code{-m} switch
9465: (@pxref{Invoking Gforth}) when Gforth starts up.
9466:
9467: @item return stack space available:
9468: @cindex return stack space available
9469: You can compute the total return stack space in cells with
9470: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
9471: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
9472:
9473: @item stack space available:
9474: @cindex stack space available
9475: You can compute the total data stack space in cells with
9476: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
9477: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
9478:
9479: @item system dictionary space required, in address units:
9480: @cindex system dictionary space required, in address units
9481: Type @code{here forthstart - .} after startup. At the time of this
9482: writing, this gives 80080 (bytes) on a 32-bit system.
9483: @end table
9484:
9485:
9486: @c =====================================================================
9487: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
9488: @section The optional Block word set
9489: @c =====================================================================
9490: @cindex system documentation, block words
9491: @cindex block words, system documentation
9492:
9493: @menu
9494: * block-idef:: Implementation Defined Options
9495: * block-ambcond:: Ambiguous Conditions
9496: * block-other:: Other System Documentation
9497: @end menu
9498:
9499:
9500: @c ---------------------------------------------------------------------
9501: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
9502: @subsection Implementation Defined Options
9503: @c ---------------------------------------------------------------------
9504: @cindex implementation-defined options, block words
9505: @cindex block words, implementation-defined options
9506:
9507: @table @i
9508: @item the format for display by @code{LIST}:
9509: @cindex @code{LIST} display format
9510: First the screen number is displayed, then 16 lines of 64 characters,
9511: each line preceded by the line number.
9512:
9513: @item the length of a line affected by @code{\}:
9514: @cindex length of a line affected by @code{\}
9515: @cindex @code{\}, line length in blocks
9516: 64 characters.
9517: @end table
9518:
9519:
9520: @c ---------------------------------------------------------------------
9521: @node block-ambcond, block-other, block-idef, The optional Block word set
9522: @subsection Ambiguous conditions
9523: @c ---------------------------------------------------------------------
9524: @cindex block words, ambiguous conditions
9525: @cindex ambiguous conditions, block words
9526:
9527: @table @i
9528: @item correct block read was not possible:
9529: @cindex block read not possible
9530: Typically results in a @code{throw} of some OS-derived value (between
9531: -512 and -2048). If the blocks file was just not long enough, blanks are
9532: supplied for the missing portion.
9533:
9534: @item I/O exception in block transfer:
9535: @cindex I/O exception in block transfer
9536: @cindex block transfer, I/O exception
9537: Typically results in a @code{throw} of some OS-derived value (between
9538: -512 and -2048).
9539:
9540: @item invalid block number:
9541: @cindex invalid block number
9542: @cindex block number invalid
9543: @code{-35 throw} (Invalid block number)
9544:
9545: @item a program directly alters the contents of @code{BLK}:
9546: @cindex @code{BLK}, altering @code{BLK}
9547: The input stream is switched to that other block, at the same
9548: position. If the storing to @code{BLK} happens when interpreting
9549: non-block input, the system will get quite confused when the block ends.
9550:
9551: @item no current block buffer for @code{UPDATE}:
9552: @cindex @code{UPDATE}, no current block buffer
9553: @code{UPDATE} has no effect.
9554:
9555: @end table
9556:
9557: @c ---------------------------------------------------------------------
9558: @node block-other, , block-ambcond, The optional Block word set
9559: @subsection Other system documentation
9560: @c ---------------------------------------------------------------------
9561: @cindex other system documentation, block words
9562: @cindex block words, other system documentation
9563:
9564: @table @i
9565: @item any restrictions a multiprogramming system places on the use of buffer addresses:
9566: No restrictions (yet).
9567:
9568: @item the number of blocks available for source and data:
9569: depends on your disk space.
9570:
9571: @end table
9572:
9573:
9574: @c =====================================================================
9575: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
9576: @section The optional Double Number word set
9577: @c =====================================================================
9578: @cindex system documentation, double words
9579: @cindex double words, system documentation
9580:
9581: @menu
9582: * double-ambcond:: Ambiguous Conditions
9583: @end menu
9584:
9585:
9586: @c ---------------------------------------------------------------------
9587: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
9588: @subsection Ambiguous conditions
9589: @c ---------------------------------------------------------------------
9590: @cindex double words, ambiguous conditions
9591: @cindex ambiguous conditions, double words
9592:
9593: @table @i
1.29 crook 9594: @item @i{d} outside of range of @i{n} in @code{D>S}:
9595: @cindex @code{D>S}, @i{d} out of range of @i{n}
9596: The least significant cell of @i{d} is produced.
1.1 anton 9597:
9598: @end table
9599:
9600:
9601: @c =====================================================================
9602: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
9603: @section The optional Exception word set
9604: @c =====================================================================
9605: @cindex system documentation, exception words
9606: @cindex exception words, system documentation
9607:
9608: @menu
9609: * exception-idef:: Implementation Defined Options
9610: @end menu
9611:
9612:
9613: @c ---------------------------------------------------------------------
9614: @node exception-idef, , The optional Exception word set, The optional Exception word set
9615: @subsection Implementation Defined Options
9616: @c ---------------------------------------------------------------------
9617: @cindex implementation-defined options, exception words
9618: @cindex exception words, implementation-defined options
9619:
9620: @table @i
9621: @item @code{THROW}-codes used in the system:
9622: @cindex @code{THROW}-codes used in the system
9623: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 9624: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 9625: codes -512@minus{}-2047 are used for OS errors (for file and memory
9626: allocation operations). The mapping from OS error numbers to throw codes
9627: is -512@minus{}@code{errno}. One side effect of this mapping is that
9628: undefined OS errors produce a message with a strange number; e.g.,
9629: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
9630: @end table
9631:
9632: @c =====================================================================
9633: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
9634: @section The optional Facility word set
9635: @c =====================================================================
9636: @cindex system documentation, facility words
9637: @cindex facility words, system documentation
9638:
9639: @menu
9640: * facility-idef:: Implementation Defined Options
9641: * facility-ambcond:: Ambiguous Conditions
9642: @end menu
9643:
9644:
9645: @c ---------------------------------------------------------------------
9646: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
9647: @subsection Implementation Defined Options
9648: @c ---------------------------------------------------------------------
9649: @cindex implementation-defined options, facility words
9650: @cindex facility words, implementation-defined options
9651:
9652: @table @i
9653: @item encoding of keyboard events (@code{EKEY}):
9654: @cindex keyboard events, encoding in @code{EKEY}
9655: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 9656: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 ! anton 9657: Other keys are encoded with the constants @code{k-left}, @code{k-right},
! 9658: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
! 9659: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
! 9660: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 9661:
1.1 anton 9662:
9663: @item duration of a system clock tick:
9664: @cindex duration of a system clock tick
9665: @cindex clock tick duration
9666: System dependent. With respect to @code{MS}, the time is specified in
9667: microseconds. How well the OS and the hardware implement this, is
9668: another question.
9669:
9670: @item repeatability to be expected from the execution of @code{MS}:
9671: @cindex repeatability to be expected from the execution of @code{MS}
9672: @cindex @code{MS}, repeatability to be expected
9673: System dependent. On Unix, a lot depends on load. If the system is
9674: lightly loaded, and the delay is short enough that Gforth does not get
9675: swapped out, the performance should be acceptable. Under MS-DOS and
9676: other single-tasking systems, it should be good.
9677:
9678: @end table
9679:
9680:
9681: @c ---------------------------------------------------------------------
9682: @node facility-ambcond, , facility-idef, The optional Facility word set
9683: @subsection Ambiguous conditions
9684: @c ---------------------------------------------------------------------
9685: @cindex facility words, ambiguous conditions
9686: @cindex ambiguous conditions, facility words
9687:
9688: @table @i
9689: @item @code{AT-XY} can't be performed on user output device:
9690: @cindex @code{AT-XY} can't be performed on user output device
9691: Largely terminal dependent. No range checks are done on the arguments.
9692: No errors are reported. You may see some garbage appearing, you may see
9693: simply nothing happen.
9694:
9695: @end table
9696:
9697:
9698: @c =====================================================================
9699: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
9700: @section The optional File-Access word set
9701: @c =====================================================================
9702: @cindex system documentation, file words
9703: @cindex file words, system documentation
9704:
9705: @menu
9706: * file-idef:: Implementation Defined Options
9707: * file-ambcond:: Ambiguous Conditions
9708: @end menu
9709:
9710: @c ---------------------------------------------------------------------
9711: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
9712: @subsection Implementation Defined Options
9713: @c ---------------------------------------------------------------------
9714: @cindex implementation-defined options, file words
9715: @cindex file words, implementation-defined options
9716:
9717: @table @i
9718: @item file access methods used:
9719: @cindex file access methods used
9720: @code{R/O}, @code{R/W} and @code{BIN} work as you would
9721: expect. @code{W/O} translates into the C file opening mode @code{w} (or
9722: @code{wb}): The file is cleared, if it exists, and created, if it does
9723: not (with both @code{open-file} and @code{create-file}). Under Unix
9724: @code{create-file} creates a file with 666 permissions modified by your
9725: umask.
9726:
9727: @item file exceptions:
9728: @cindex file exceptions
9729: The file words do not raise exceptions (except, perhaps, memory access
9730: faults when you pass illegal addresses or file-ids).
9731:
9732: @item file line terminator:
9733: @cindex file line terminator
9734: System-dependent. Gforth uses C's newline character as line
9735: terminator. What the actual character code(s) of this are is
9736: system-dependent.
9737:
9738: @item file name format:
9739: @cindex file name format
9740: System dependent. Gforth just uses the file name format of your OS.
9741:
9742: @item information returned by @code{FILE-STATUS}:
9743: @cindex @code{FILE-STATUS}, returned information
9744: @code{FILE-STATUS} returns the most powerful file access mode allowed
9745: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
9746: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
9747: along with the returned mode.
9748:
9749: @item input file state after an exception when including source:
9750: @cindex exception when including source
9751: All files that are left via the exception are closed.
9752:
1.29 crook 9753: @item @i{ior} values and meaning:
9754: @cindex @i{ior} values and meaning
9755: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 9756: intended as throw codes. They typically are in the range
9757: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 9758: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 9759:
9760: @item maximum depth of file input nesting:
9761: @cindex maximum depth of file input nesting
9762: @cindex file input nesting, maximum depth
9763: limited by the amount of return stack, locals/TIB stack, and the number
9764: of open files available. This should not give you troubles.
9765:
9766: @item maximum size of input line:
9767: @cindex maximum size of input line
9768: @cindex input line size, maximum
9769: @code{/line}. Currently 255.
9770:
9771: @item methods of mapping block ranges to files:
9772: @cindex mapping block ranges to files
9773: @cindex files containing blocks
9774: @cindex blocks in files
9775: By default, blocks are accessed in the file @file{blocks.fb} in the
9776: current working directory. The file can be switched with @code{USE}.
9777:
9778: @item number of string buffers provided by @code{S"}:
9779: @cindex @code{S"}, number of string buffers
9780: 1
9781:
9782: @item size of string buffer used by @code{S"}:
9783: @cindex @code{S"}, size of string buffer
9784: @code{/line}. currently 255.
9785:
9786: @end table
9787:
9788: @c ---------------------------------------------------------------------
9789: @node file-ambcond, , file-idef, The optional File-Access word set
9790: @subsection Ambiguous conditions
9791: @c ---------------------------------------------------------------------
9792: @cindex file words, ambiguous conditions
9793: @cindex ambiguous conditions, file words
9794:
9795: @table @i
9796: @item attempting to position a file outside its boundaries:
9797: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
9798: @code{REPOSITION-FILE} is performed as usual: Afterwards,
9799: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
9800:
9801: @item attempting to read from file positions not yet written:
9802: @cindex reading from file positions not yet written
9803: End-of-file, i.e., zero characters are read and no error is reported.
9804:
1.29 crook 9805: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
9806: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 9807: An appropriate exception may be thrown, but a memory fault or other
9808: problem is more probable.
9809:
1.29 crook 9810: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
9811: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
9812: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
9813: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 9814: thrown.
9815:
9816: @item named file cannot be opened (@code{INCLUDED}):
9817: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 9818: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 9819:
9820: @item requesting an unmapped block number:
9821: @cindex unmapped block numbers
9822: There are no unmapped legal block numbers. On some operating systems,
9823: writing a block with a large number may overflow the file system and
9824: have an error message as consequence.
9825:
9826: @item using @code{source-id} when @code{blk} is non-zero:
9827: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
9828: @code{source-id} performs its function. Typically it will give the id of
9829: the source which loaded the block. (Better ideas?)
9830:
9831: @end table
9832:
9833:
9834: @c =====================================================================
9835: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
9836: @section The optional Floating-Point word set
9837: @c =====================================================================
9838: @cindex system documentation, floating-point words
9839: @cindex floating-point words, system documentation
9840:
9841: @menu
9842: * floating-idef:: Implementation Defined Options
9843: * floating-ambcond:: Ambiguous Conditions
9844: @end menu
9845:
9846:
9847: @c ---------------------------------------------------------------------
9848: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
9849: @subsection Implementation Defined Options
9850: @c ---------------------------------------------------------------------
9851: @cindex implementation-defined options, floating-point words
9852: @cindex floating-point words, implementation-defined options
9853:
9854: @table @i
9855: @item format and range of floating point numbers:
9856: @cindex format and range of floating point numbers
9857: @cindex floating point numbers, format and range
9858: System-dependent; the @code{double} type of C.
9859:
1.29 crook 9860: @item results of @code{REPRESENT} when @i{float} is out of range:
9861: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 9862: System dependent; @code{REPRESENT} is implemented using the C library
9863: function @code{ecvt()} and inherits its behaviour in this respect.
9864:
9865: @item rounding or truncation of floating-point numbers:
9866: @cindex rounding of floating-point numbers
9867: @cindex truncation of floating-point numbers
9868: @cindex floating-point numbers, rounding or truncation
9869: System dependent; the rounding behaviour is inherited from the hosting C
9870: compiler. IEEE-FP-based (i.e., most) systems by default round to
9871: nearest, and break ties by rounding to even (i.e., such that the last
9872: bit of the mantissa is 0).
9873:
9874: @item size of floating-point stack:
9875: @cindex floating-point stack size
9876: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
9877: the floating-point stack (in floats). You can specify this on startup
9878: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
9879:
9880: @item width of floating-point stack:
9881: @cindex floating-point stack width
9882: @code{1 floats}.
9883:
9884: @end table
9885:
9886:
9887: @c ---------------------------------------------------------------------
9888: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
9889: @subsection Ambiguous conditions
9890: @c ---------------------------------------------------------------------
9891: @cindex floating-point words, ambiguous conditions
9892: @cindex ambiguous conditions, floating-point words
9893:
9894: @table @i
9895: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
9896: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
9897: System-dependent. Typically results in a @code{-23 THROW} like other
9898: alignment violations.
9899:
9900: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
9901: @cindex @code{f@@} used with an address that is not float aligned
9902: @cindex @code{f!} used with an address that is not float aligned
9903: System-dependent. Typically results in a @code{-23 THROW} like other
9904: alignment violations.
9905:
9906: @item floating-point result out of range:
9907: @cindex floating-point result out of range
9908: System-dependent. Can result in a @code{-55 THROW} (Floating-point
9909: unidentified fault), or can produce a special value representing, e.g.,
9910: Infinity.
9911:
9912: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
9913: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
9914: System-dependent. Typically results in an alignment fault like other
9915: alignment violations.
9916:
1.35 anton 9917: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
9918: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 9919: The floating-point number is converted into decimal nonetheless.
9920:
9921: @item Both arguments are equal to zero (@code{FATAN2}):
9922: @cindex @code{FATAN2}, both arguments are equal to zero
9923: System-dependent. @code{FATAN2} is implemented using the C library
9924: function @code{atan2()}.
9925:
1.29 crook 9926: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
9927: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
9928: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 9929: because of small errors and the tan will be a very large (or very small)
9930: but finite number.
9931:
1.29 crook 9932: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
9933: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 9934: The result is rounded to the nearest float.
9935:
9936: @item dividing by zero:
9937: @cindex dividing by zero, floating-point
9938: @cindex floating-point dividing by zero
9939: @cindex floating-point unidentified fault, FP divide-by-zero
9940: @code{-55 throw} (Floating-point unidentified fault)
9941:
9942: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
9943: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
9944: System dependent. On IEEE-FP based systems the number is converted into
9945: an infinity.
9946:
1.29 crook 9947: @item @i{float}<1 (@code{FACOSH}):
9948: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 9949: @cindex floating-point unidentified fault, @code{FACOSH}
9950: @code{-55 throw} (Floating-point unidentified fault)
9951:
1.29 crook 9952: @item @i{float}=<-1 (@code{FLNP1}):
9953: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 9954: @cindex floating-point unidentified fault, @code{FLNP1}
9955: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29 crook 9956: negative infinity is typically produced for @i{float}=-1.
1.1 anton 9957:
1.29 crook 9958: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
9959: @cindex @code{FLN}, @i{float}=<0
9960: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 9961: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
9962: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29 crook 9963: negative infinity is typically produced for @i{float}=0.
1.1 anton 9964:
1.29 crook 9965: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
9966: @cindex @code{FASINH}, @i{float}<0
9967: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 9968: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
9969: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
9970: produces values for these inputs on my Linux box (Bug in the C library?)
9971:
1.29 crook 9972: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
9973: @cindex @code{FACOS}, |@i{float}|>1
9974: @cindex @code{FASIN}, |@i{float}|>1
9975: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 9976: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
9977: @code{-55 throw} (Floating-point unidentified fault).
9978:
1.29 crook 9979: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
9980: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 9981: @cindex floating-point unidentified fault, @code{F>D}
9982: @code{-55 throw} (Floating-point unidentified fault).
9983:
9984: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
9985: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
9986: This does not happen.
9987: @end table
9988:
9989: @c =====================================================================
9990: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
9991: @section The optional Locals word set
9992: @c =====================================================================
9993: @cindex system documentation, locals words
9994: @cindex locals words, system documentation
9995:
9996: @menu
9997: * locals-idef:: Implementation Defined Options
9998: * locals-ambcond:: Ambiguous Conditions
9999: @end menu
10000:
10001:
10002: @c ---------------------------------------------------------------------
10003: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
10004: @subsection Implementation Defined Options
10005: @c ---------------------------------------------------------------------
10006: @cindex implementation-defined options, locals words
10007: @cindex locals words, implementation-defined options
10008:
10009: @table @i
10010: @item maximum number of locals in a definition:
10011: @cindex maximum number of locals in a definition
10012: @cindex locals, maximum number in a definition
10013: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
10014: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
10015: characters. The number of locals in a definition is bounded by the size
10016: of locals-buffer, which contains the names of the locals.
10017:
10018: @end table
10019:
10020:
10021: @c ---------------------------------------------------------------------
10022: @node locals-ambcond, , locals-idef, The optional Locals word set
10023: @subsection Ambiguous conditions
10024: @c ---------------------------------------------------------------------
10025: @cindex locals words, ambiguous conditions
10026: @cindex ambiguous conditions, locals words
10027:
10028: @table @i
10029: @item executing a named local in interpretation state:
10030: @cindex local in interpretation state
10031: @cindex Interpreting a compile-only word, for a local
10032: Locals have no interpretation semantics. If you try to perform the
10033: interpretation semantics, you will get a @code{-14 throw} somewhere
10034: (Interpreting a compile-only word). If you perform the compilation
10035: semantics, the locals access will be compiled (irrespective of state).
10036:
1.29 crook 10037: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 10038: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
10039: @cindex @code{TO} on non-@code{VALUE}s and non-locals
10040: @cindex Invalid name argument, @code{TO}
10041: @code{-32 throw} (Invalid name argument)
10042:
10043: @end table
10044:
10045:
10046: @c =====================================================================
10047: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
10048: @section The optional Memory-Allocation word set
10049: @c =====================================================================
10050: @cindex system documentation, memory-allocation words
10051: @cindex memory-allocation words, system documentation
10052:
10053: @menu
10054: * memory-idef:: Implementation Defined Options
10055: @end menu
10056:
10057:
10058: @c ---------------------------------------------------------------------
10059: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
10060: @subsection Implementation Defined Options
10061: @c ---------------------------------------------------------------------
10062: @cindex implementation-defined options, memory-allocation words
10063: @cindex memory-allocation words, implementation-defined options
10064:
10065: @table @i
1.29 crook 10066: @item values and meaning of @i{ior}:
10067: @cindex @i{ior} values and meaning
10068: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 10069: intended as throw codes. They typically are in the range
10070: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 10071: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 10072:
10073: @end table
10074:
10075: @c =====================================================================
10076: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
10077: @section The optional Programming-Tools word set
10078: @c =====================================================================
10079: @cindex system documentation, programming-tools words
10080: @cindex programming-tools words, system documentation
10081:
10082: @menu
10083: * programming-idef:: Implementation Defined Options
10084: * programming-ambcond:: Ambiguous Conditions
10085: @end menu
10086:
10087:
10088: @c ---------------------------------------------------------------------
10089: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
10090: @subsection Implementation Defined Options
10091: @c ---------------------------------------------------------------------
10092: @cindex implementation-defined options, programming-tools words
10093: @cindex programming-tools words, implementation-defined options
10094:
10095: @table @i
10096: @item ending sequence for input following @code{;CODE} and @code{CODE}:
10097: @cindex @code{;CODE} ending sequence
10098: @cindex @code{CODE} ending sequence
10099: @code{END-CODE}
10100:
10101: @item manner of processing input following @code{;CODE} and @code{CODE}:
10102: @cindex @code{;CODE}, processing input
10103: @cindex @code{CODE}, processing input
10104: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
10105: the input is processed by the text interpreter, (starting) in interpret
10106: state.
10107:
10108: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
10109: @cindex @code{ASSEMBLER}, search order capability
10110: The ANS Forth search order word set.
10111:
10112: @item source and format of display by @code{SEE}:
10113: @cindex @code{SEE}, source and format of output
10114: The source for @code{see} is the intermediate code used by the inner
10115: interpreter. The current @code{see} tries to output Forth source code
10116: as well as possible.
10117:
10118: @end table
10119:
10120: @c ---------------------------------------------------------------------
10121: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
10122: @subsection Ambiguous conditions
10123: @c ---------------------------------------------------------------------
10124: @cindex programming-tools words, ambiguous conditions
10125: @cindex ambiguous conditions, programming-tools words
10126:
10127: @table @i
10128:
1.21 crook 10129: @item deleting the compilation word list (@code{FORGET}):
10130: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 10131: Not implemented (yet).
10132:
1.29 crook 10133: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
10134: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
10135: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 10136: @cindex control-flow stack underflow
10137: This typically results in an @code{abort"} with a descriptive error
10138: message (may change into a @code{-22 throw} (Control structure mismatch)
10139: in the future). You may also get a memory access error. If you are
10140: unlucky, this ambiguous condition is not caught.
10141:
1.29 crook 10142: @item @i{name} can't be found (@code{FORGET}):
10143: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 10144: Not implemented (yet).
10145:
1.29 crook 10146: @item @i{name} not defined via @code{CREATE}:
10147: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 10148: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
10149: the execution semantics of the last defined word no matter how it was
10150: defined.
10151:
10152: @item @code{POSTPONE} applied to @code{[IF]}:
10153: @cindex @code{POSTPONE} applied to @code{[IF]}
10154: @cindex @code{[IF]} and @code{POSTPONE}
10155: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
10156: equivalent to @code{[IF]}.
10157:
10158: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
10159: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
10160: Continue in the same state of conditional compilation in the next outer
10161: input source. Currently there is no warning to the user about this.
10162:
10163: @item removing a needed definition (@code{FORGET}):
10164: @cindex @code{FORGET}, removing a needed definition
10165: Not implemented (yet).
10166:
10167: @end table
10168:
10169:
10170: @c =====================================================================
10171: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
10172: @section The optional Search-Order word set
10173: @c =====================================================================
10174: @cindex system documentation, search-order words
10175: @cindex search-order words, system documentation
10176:
10177: @menu
10178: * search-idef:: Implementation Defined Options
10179: * search-ambcond:: Ambiguous Conditions
10180: @end menu
10181:
10182:
10183: @c ---------------------------------------------------------------------
10184: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
10185: @subsection Implementation Defined Options
10186: @c ---------------------------------------------------------------------
10187: @cindex implementation-defined options, search-order words
10188: @cindex search-order words, implementation-defined options
10189:
10190: @table @i
10191: @item maximum number of word lists in search order:
10192: @cindex maximum number of word lists in search order
10193: @cindex search order, maximum depth
10194: @code{s" wordlists" environment? drop .}. Currently 16.
10195:
10196: @item minimum search order:
10197: @cindex minimum search order
10198: @cindex search order, minimum
10199: @code{root root}.
10200:
10201: @end table
10202:
10203: @c ---------------------------------------------------------------------
10204: @node search-ambcond, , search-idef, The optional Search-Order word set
10205: @subsection Ambiguous conditions
10206: @c ---------------------------------------------------------------------
10207: @cindex search-order words, ambiguous conditions
10208: @cindex ambiguous conditions, search-order words
10209:
10210: @table @i
1.21 crook 10211: @item changing the compilation word list (during compilation):
10212: @cindex changing the compilation word list (during compilation)
10213: @cindex compilation word list, change before definition ends
10214: The word is entered into the word list that was the compilation word list
1.1 anton 10215: at the start of the definition. Any changes to the name field (e.g.,
10216: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
10217: are applied to the latest defined word (as reported by @code{last} or
1.21 crook 10218: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1 anton 10219:
10220: @item search order empty (@code{previous}):
10221: @cindex @code{previous}, search order empty
1.26 crook 10222: @cindex vocstack empty, @code{previous}
1.1 anton 10223: @code{abort" Vocstack empty"}.
10224:
10225: @item too many word lists in search order (@code{also}):
10226: @cindex @code{also}, too many word lists in search order
1.26 crook 10227: @cindex vocstack full, @code{also}
1.1 anton 10228: @code{abort" Vocstack full"}.
10229:
10230: @end table
10231:
10232: @c ***************************************************************
10233: @node Model, Integrating Gforth, ANS conformance, Top
10234: @chapter Model
10235:
10236: This chapter has yet to be written. It will contain information, on
10237: which internal structures you can rely.
10238:
10239: @c ***************************************************************
10240: @node Integrating Gforth, Emacs and Gforth, Model, Top
10241: @chapter Integrating Gforth into C programs
10242:
10243: This is not yet implemented.
10244:
10245: Several people like to use Forth as scripting language for applications
10246: that are otherwise written in C, C++, or some other language.
10247:
10248: The Forth system ATLAST provides facilities for embedding it into
10249: applications; unfortunately it has several disadvantages: most
10250: importantly, it is not based on ANS Forth, and it is apparently dead
10251: (i.e., not developed further and not supported). The facilities
1.21 crook 10252: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 10253: making the switch should not be hard.
10254:
10255: We also tried to design the interface such that it can easily be
10256: implemented by other Forth systems, so that we may one day arrive at a
10257: standardized interface. Such a standard interface would allow you to
10258: replace the Forth system without having to rewrite C code.
10259:
10260: You embed the Gforth interpreter by linking with the library
10261: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
10262: global symbols in this library that belong to the interface, have the
10263: prefix @code{forth_}. (Global symbols that are used internally have the
10264: prefix @code{gforth_}).
10265:
10266: You can include the declarations of Forth types and the functions and
10267: variables of the interface with @code{#include <forth.h>}.
10268:
10269: Types.
10270:
10271: Variables.
10272:
10273: Data and FP Stack pointer. Area sizes.
10274:
10275: functions.
10276:
10277: forth_init(imagefile)
10278: forth_evaluate(string) exceptions?
10279: forth_goto(address) (or forth_execute(xt)?)
10280: forth_continue() (a corountining mechanism)
10281:
10282: Adding primitives.
10283:
10284: No checking.
10285:
10286: Signals?
10287:
10288: Accessing the Stacks
10289:
1.26 crook 10290: @c ******************************************************************
1.1 anton 10291: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
10292: @chapter Emacs and Gforth
10293: @cindex Emacs and Gforth
10294:
10295: @cindex @file{gforth.el}
10296: @cindex @file{forth.el}
10297: @cindex Rydqvist, Goran
10298: @cindex comment editing commands
10299: @cindex @code{\}, editing with Emacs
10300: @cindex debug tracer editing commands
10301: @cindex @code{~~}, removal with Emacs
10302: @cindex Forth mode in Emacs
10303: Gforth comes with @file{gforth.el}, an improved version of
10304: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 10305: improvements are:
10306:
10307: @itemize @bullet
10308: @item
10309: A better (but still not perfect) handling of indentation.
10310: @item
10311: Comment paragraph filling (@kbd{M-q})
10312: @item
10313: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
10314: @item
10315: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 ! anton 10316: @item
! 10317: Support of the @code{info-lookup} feature for looking up the
! 10318: documentation of a word.
1.26 crook 10319: @end itemize
10320:
10321: I left the stuff I do not use alone, even though some of it only makes
10322: sense for TILE. To get a description of these features, enter Forth mode
10323: and type @kbd{C-h m}.
1.1 anton 10324:
10325: @cindex source location of error or debugging output in Emacs
10326: @cindex error output, finding the source location in Emacs
10327: @cindex debugging output, finding the source location in Emacs
10328: In addition, Gforth supports Emacs quite well: The source code locations
10329: given in error messages, debugging output (from @code{~~}) and failed
10330: assertion messages are in the right format for Emacs' compilation mode
10331: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
10332: Manual}) so the source location corresponding to an error or other
10333: message is only a few keystrokes away (@kbd{C-x `} for the next error,
10334: @kbd{C-c C-c} for the error under the cursor).
10335:
10336: @cindex @file{TAGS} file
10337: @cindex @file{etags.fs}
10338: @cindex viewing the source of a word in Emacs
1.26 crook 10339: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file will
10340: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 10341: contains the definitions of all words defined afterwards. You can then
10342: find the source for a word using @kbd{M-.}. Note that emacs can use
10343: several tags files at the same time (e.g., one for the Gforth sources
10344: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
10345: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
10346: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
10347: @file{/usr/local/share/gforth/0.2.0/TAGS}).
10348:
1.41 ! anton 10349: @cindex viewing the documentation of a word in Emacs
! 10350: @cindex context-sensitive help
! 10351: Moreover, for words documented in this manual, you can look up the
! 10352: glossary entry quickly by using @kbd{C-h TAB}
! 10353: (@code{info-lookup-symbol}, see @pxref{Documentation, ,Documentation
! 10354: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
! 10355: later.
! 10356:
! 10357:
1.1 anton 10358: @cindex @file{.emacs}
10359: To get all these benefits, add the following lines to your @file{.emacs}
10360: file:
10361:
10362: @example
10363: (autoload 'forth-mode "gforth.el")
10364: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
10365: @end example
10366:
1.26 crook 10367: @c ******************************************************************
1.1 anton 10368: @node Image Files, Engine, Emacs and Gforth, Top
10369: @chapter Image Files
1.26 crook 10370: @cindex image file
10371: @cindex @file{.fi} files
1.1 anton 10372: @cindex precompiled Forth code
10373: @cindex dictionary in persistent form
10374: @cindex persistent form of dictionary
10375:
10376: An image file is a file containing an image of the Forth dictionary,
10377: i.e., compiled Forth code and data residing in the dictionary. By
10378: convention, we use the extension @code{.fi} for image files.
10379:
10380: @menu
1.18 anton 10381: * Image Licensing Issues:: Distribution terms for images.
10382: * Image File Background:: Why have image files?
1.29 crook 10383: * Non-Relocatable Image Files:: don't always work.
1.18 anton 10384: * Data-Relocatable Image Files:: are better.
1.29 crook 10385: * Fully Relocatable Image Files:: better yet.
1.18 anton 10386: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 10387: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 10388: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 10389: @end menu
10390:
1.18 anton 10391: @node Image Licensing Issues, Image File Background, Image Files, Image Files
10392: @section Image Licensing Issues
10393: @cindex license for images
10394: @cindex image license
10395:
10396: An image created with @code{gforthmi} (@pxref{gforthmi}) or
10397: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
10398: original image; i.e., according to copyright law it is a derived work of
10399: the original image.
10400:
10401: Since Gforth is distributed under the GNU GPL, the newly created image
10402: falls under the GNU GPL, too. In particular, this means that if you
10403: distribute the image, you have to make all of the sources for the image
10404: available, including those you wrote. For details see @ref{License, ,
10405: GNU General Public License (Section 3)}.
10406:
10407: If you create an image with @code{cross} (@pxref{cross.fs}), the image
10408: contains only code compiled from the sources you gave it; if none of
10409: these sources is under the GPL, the terms discussed above do not apply
10410: to the image. However, if your image needs an engine (a gforth binary)
10411: that is under the GPL, you should make sure that you distribute both in
10412: a way that is at most a @emph{mere aggregation}, if you don't want the
10413: terms of the GPL to apply to the image.
10414:
10415: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 10416: @section Image File Background
10417: @cindex image file background
10418:
10419: Our Forth system consists not only of primitives, but also of
10420: definitions written in Forth. Since the Forth compiler itself belongs to
10421: those definitions, it is not possible to start the system with the
10422: primitives and the Forth source alone. Therefore we provide the Forth
1.26 crook 10423: code as an image file in nearly executable form. When Gforth starts up,
10424: a C routine loads the image file into memory, optionally relocates the
10425: addresses, then sets up the memory (stacks etc.) according to
10426: information in the image file, and (finally) starts executing Forth
10427: code.
1.1 anton 10428:
10429: The image file variants represent different compromises between the
10430: goals of making it easy to generate image files and making them
10431: portable.
10432:
10433: @cindex relocation at run-time
1.26 crook 10434: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 10435: run-time. This avoids many of the complications discussed below (image
10436: files are data relocatable without further ado), but costs performance
10437: (one addition per memory access).
10438:
10439: @cindex relocation at load-time
1.26 crook 10440: By contrast, the Gforth loader performs relocation at image load time. The
10441: loader also has to replace tokens that represent primitive calls with the
1.1 anton 10442: appropriate code-field addresses (or code addresses in the case of
10443: direct threading).
10444:
10445: There are three kinds of image files, with different degrees of
10446: relocatability: non-relocatable, data-relocatable, and fully relocatable
10447: image files.
10448:
10449: @cindex image file loader
10450: @cindex relocating loader
10451: @cindex loader for image files
10452: These image file variants have several restrictions in common; they are
10453: caused by the design of the image file loader:
10454:
10455: @itemize @bullet
10456: @item
10457: There is only one segment; in particular, this means, that an image file
10458: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 10459: them). The contents of the stacks are not represented, either.
1.1 anton 10460:
10461: @item
10462: The only kinds of relocation supported are: adding the same offset to
10463: all cells that represent data addresses; and replacing special tokens
10464: with code addresses or with pieces of machine code.
10465:
10466: If any complex computations involving addresses are performed, the
10467: results cannot be represented in the image file. Several applications that
10468: use such computations come to mind:
10469: @itemize @minus
10470: @item
10471: Hashing addresses (or data structures which contain addresses) for table
10472: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
10473: purpose, you will have no problem, because the hash tables are
10474: recomputed automatically when the system is started. If you use your own
10475: hash tables, you will have to do something similar.
10476:
10477: @item
10478: There's a cute implementation of doubly-linked lists that uses
10479: @code{XOR}ed addresses. You could represent such lists as singly-linked
10480: in the image file, and restore the doubly-linked representation on
10481: startup.@footnote{In my opinion, though, you should think thrice before
10482: using a doubly-linked list (whatever implementation).}
10483:
10484: @item
10485: The code addresses of run-time routines like @code{docol:} cannot be
10486: represented in the image file (because their tokens would be replaced by
10487: machine code in direct threaded implementations). As a workaround,
10488: compute these addresses at run-time with @code{>code-address} from the
10489: executions tokens of appropriate words (see the definitions of
10490: @code{docol:} and friends in @file{kernel.fs}).
10491:
10492: @item
10493: On many architectures addresses are represented in machine code in some
10494: shifted or mangled form. You cannot put @code{CODE} words that contain
10495: absolute addresses in this form in a relocatable image file. Workarounds
10496: are representing the address in some relative form (e.g., relative to
10497: the CFA, which is present in some register), or loading the address from
10498: a place where it is stored in a non-mangled form.
10499: @end itemize
10500: @end itemize
10501:
10502: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
10503: @section Non-Relocatable Image Files
10504: @cindex non-relocatable image files
1.26 crook 10505: @cindex image file, non-relocatable
1.1 anton 10506:
10507: These files are simple memory dumps of the dictionary. They are specific
10508: to the executable (i.e., @file{gforth} file) they were created
10509: with. What's worse, they are specific to the place on which the
10510: dictionary resided when the image was created. Now, there is no
10511: guarantee that the dictionary will reside at the same place the next
10512: time you start Gforth, so there's no guarantee that a non-relocatable
10513: image will work the next time (Gforth will complain instead of crashing,
10514: though).
10515:
10516: You can create a non-relocatable image file with
10517:
10518: doc-savesystem
10519:
10520: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
10521: @section Data-Relocatable Image Files
10522: @cindex data-relocatable image files
1.26 crook 10523: @cindex image file, data-relocatable
1.1 anton 10524:
10525: These files contain relocatable data addresses, but fixed code addresses
10526: (instead of tokens). They are specific to the executable (i.e.,
10527: @file{gforth} file) they were created with. For direct threading on some
10528: architectures (e.g., the i386), data-relocatable images do not work. You
10529: get a data-relocatable image, if you use @file{gforthmi} with a
10530: Gforth binary that is not doubly indirect threaded (@pxref{Fully
10531: Relocatable Image Files}).
10532:
10533: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
10534: @section Fully Relocatable Image Files
10535: @cindex fully relocatable image files
1.26 crook 10536: @cindex image file, fully relocatable
1.1 anton 10537:
10538: @cindex @file{kern*.fi}, relocatability
10539: @cindex @file{gforth.fi}, relocatability
10540: These image files have relocatable data addresses, and tokens for code
10541: addresses. They can be used with different binaries (e.g., with and
10542: without debugging) on the same machine, and even across machines with
10543: the same data formats (byte order, cell size, floating point
10544: format). However, they are usually specific to the version of Gforth
10545: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
10546: are fully relocatable.
10547:
10548: There are two ways to create a fully relocatable image file:
10549:
10550: @menu
1.29 crook 10551: * gforthmi:: The normal way
1.1 anton 10552: * cross.fs:: The hard way
10553: @end menu
10554:
10555: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
10556: @subsection @file{gforthmi}
10557: @cindex @file{comp-i.fs}
10558: @cindex @file{gforthmi}
10559:
10560: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 10561: image @i{file} that contains everything you would load by invoking
10562: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 10563: @example
1.29 crook 10564: gforthmi @i{file} @i{options}
1.1 anton 10565: @end example
10566:
10567: E.g., if you want to create an image @file{asm.fi} that has the file
10568: @file{asm.fs} loaded in addition to the usual stuff, you could do it
10569: like this:
10570:
10571: @example
10572: gforthmi asm.fi asm.fs
10573: @end example
10574:
1.27 crook 10575: @file{gforthmi} is implemented as a sh script and works like this: It
10576: produces two non-relocatable images for different addresses and then
10577: compares them. Its output reflects this: first you see the output (if
10578: any) of the two Gforth invocations that produce the nonrelocatable image
10579: files, then you see the output of the comparing program: It displays the
10580: offset used for data addresses and the offset used for code addresses;
1.1 anton 10581: moreover, for each cell that cannot be represented correctly in the
10582: image files, it displays a line like the following one:
10583:
10584: @example
10585: 78DC BFFFFA50 BFFFFA40
10586: @end example
10587:
10588: This means that at offset $78dc from @code{forthstart}, one input image
10589: contains $bffffa50, and the other contains $bffffa40. Since these cells
10590: cannot be represented correctly in the output image, you should examine
10591: these places in the dictionary and verify that these cells are dead
10592: (i.e., not read before they are written).
1.39 anton 10593:
10594: @cindex --application, @code{gforthmi} option
10595: If you insert the option @code{--application} in front of the image file
10596: name, you will get an image that uses the @code{--appl-image} option
10597: instead of the @code{--image-file} option (@pxref{Invoking
10598: Gforth}). When you execute such an image on Unix (by typing the image
10599: name as command), the Gforth engine will pass all options to the image
10600: instead of trying to interpret them as engine options.
1.1 anton 10601:
1.27 crook 10602: If you type @file{gforthmi} with no arguments, it prints some usage
10603: instructions.
10604:
1.1 anton 10605: @cindex @code{savesystem} during @file{gforthmi}
10606: @cindex @code{bye} during @file{gforthmi}
10607: @cindex doubly indirect threaded code
10608: @cindex environment variable @code{GFORTHD}
10609: @cindex @code{GFORTHD} environment variable
10610: @cindex @code{gforth-ditc}
1.29 crook 10611: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 10612: words @code{savesystem} and @code{bye} must be visible. A special doubly
10613: indirect threaded version of the @file{gforth} executable is used for
10614: creating the nonrelocatable images; you can pass the exact filename of
10615: this executable through the environment variable @code{GFORTHD}
10616: (default: @file{gforth-ditc}); if you pass a version that is not doubly
10617: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 10618: data-relocatable image (because there is no code address offset). The
10619: normal @file{gforth} executable is used for creating the relocatable
10620: image; you can pass the exact filename of this executable through the
10621: environment variable @code{GFORTH}.
1.1 anton 10622:
10623: @node cross.fs, , gforthmi, Fully Relocatable Image Files
10624: @subsection @file{cross.fs}
10625: @cindex @file{cross.fs}
10626: @cindex cross-compiler
10627: @cindex metacompiler
10628:
10629: You can also use @code{cross}, a batch compiler that accepts a Forth-like
10630: programming language. This @code{cross} language has to be documented
10631: yet.
10632:
10633: @cindex target compiler
10634: @code{cross} also allows you to create image files for machines with
10635: different data sizes and data formats than the one used for generating
10636: the image file. You can also use it to create an application image that
10637: does not contain a Forth compiler. These features are bought with
10638: restrictions and inconveniences in programming. E.g., addresses have to
10639: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
10640: order to make the code relocatable.
10641:
10642:
10643: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
10644: @section Stack and Dictionary Sizes
10645: @cindex image file, stack and dictionary sizes
10646: @cindex dictionary size default
10647: @cindex stack size default
10648:
10649: If you invoke Gforth with a command line flag for the size
10650: (@pxref{Invoking Gforth}), the size you specify is stored in the
10651: dictionary. If you save the dictionary with @code{savesystem} or create
10652: an image with @file{gforthmi}, this size will become the default
10653: for the resulting image file. E.g., the following will create a
1.21 crook 10654: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 10655:
10656: @example
10657: gforthmi gforth.fi -m 1M
10658: @end example
10659:
10660: In other words, if you want to set the default size for the dictionary
10661: and the stacks of an image, just invoke @file{gforthmi} with the
10662: appropriate options when creating the image.
10663:
10664: @cindex stack size, cache-friendly
10665: Note: For cache-friendly behaviour (i.e., good performance), you should
10666: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
10667: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
10668: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
10669:
10670: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
10671: @section Running Image Files
10672: @cindex running image files
10673: @cindex invoking image files
10674: @cindex image file invocation
10675:
10676: @cindex -i, invoke image file
10677: @cindex --image file, invoke image file
1.29 crook 10678: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 10679: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
10680: @example
1.29 crook 10681: gforth -i @i{image}
1.1 anton 10682: @end example
10683:
10684: @cindex executable image file
1.26 crook 10685: @cindex image file, executable
1.1 anton 10686: If your operating system supports starting scripts with a line of the
10687: form @code{#! ...}, you just have to type the image file name to start
10688: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 10689: just a convention). I.e., to run Gforth with the image file @i{image},
10690: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 10691: This works because every @code{.fi} file starts with a line of this
10692: format:
10693:
10694: @example
10695: #! /usr/local/bin/gforth-0.4.0 -i
10696: @end example
10697:
10698: The file and pathname for the Gforth engine specified on this line is
10699: the specific Gforth executable that it was built against; i.e. the value
10700: of the environment variable @code{GFORTH} at the time that
10701: @file{gforthmi} was executed.
1.1 anton 10702:
1.27 crook 10703: You can make use of the same shell capability to make a Forth source
10704: file into an executable. For example, if you place this text in a file:
1.26 crook 10705:
10706: @example
10707: #! /usr/local/bin/gforth
10708:
10709: ." Hello, world" CR
10710: bye
10711: @end example
10712:
10713: @noindent
1.27 crook 10714: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 10715: directly from the command line. The sequence @code{#!} is used in two
10716: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 10717: system@footnote{The Unix kernel actually recognises two types of files:
10718: executable files and files of data, where the data is processed by an
10719: interpreter that is specified on the ``interpreter line'' -- the first
10720: line of the file, starting with the sequence #!. There may be a small
10721: limit (e.g., 32) on the number of characters that may be specified on
10722: the interpreter line.} secondly it is treated as a comment character by
10723: Gforth. Because of the second usage, a space is required between
10724: @code{#!} and the path to the executable.
1.27 crook 10725:
10726: The disadvantage of this latter technique, compared with using
10727: @file{gforthmi}, is that it is slower; the Forth source code is compiled
10728: on-the-fly, each time the program is invoked.
10729:
1.26 crook 10730: @comment TODO describe the #! magic with reference to the Power Tools book.
10731:
1.1 anton 10732: doc-#!
10733:
10734: @node Modifying the Startup Sequence, , Running Image Files, Image Files
10735: @section Modifying the Startup Sequence
10736: @cindex startup sequence for image file
10737: @cindex image file initialization sequence
10738: @cindex initialization sequence of image file
10739:
10740: You can add your own initialization to the startup sequence through the
1.26 crook 10741: deferred word @code{'cold}. @code{'cold} is invoked just before the
10742: image-specific command line processing (by default, loading files and
10743: evaluating (@code{-e}) strings) starts.
1.1 anton 10744:
10745: A sequence for adding your initialization usually looks like this:
10746:
10747: @example
10748: :noname
10749: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
10750: ... \ your stuff
10751: ; IS 'cold
10752: @end example
10753:
10754: @cindex turnkey image files
1.26 crook 10755: @cindex image file, turnkey applications
1.1 anton 10756: You can make a turnkey image by letting @code{'cold} execute a word
10757: (your turnkey application) that never returns; instead, it exits Gforth
10758: via @code{bye} or @code{throw}.
10759:
10760: @cindex command-line arguments, access
10761: @cindex arguments on the command line, access
10762: You can access the (image-specific) command-line arguments through the
1.26 crook 10763: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1 anton 10764: access to @code{argv}.
10765:
1.26 crook 10766: If @code{'cold} exits normally, Gforth processes the command-line
10767: arguments as files to be loaded and strings to be evaluated. Therefore,
10768: @code{'cold} should remove the arguments it has used in this case.
10769:
10770: doc-'cold
1.1 anton 10771: doc-argc
10772: doc-argv
10773: doc-arg
10774:
10775:
10776: @c ******************************************************************
1.13 pazsan 10777: @node Engine, Binding to System Library, Image Files, Top
1.1 anton 10778: @chapter Engine
10779: @cindex engine
10780: @cindex virtual machine
10781:
1.26 crook 10782: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 10783: may be helpful for finding your way in the Gforth sources.
10784:
10785: The ideas in this section have also been published in the papers
10786: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
10787: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
10788: Ertl, presented at EuroForth '93; the latter is available at
10789: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
10790:
10791: @menu
10792: * Portability::
10793: * Threading::
10794: * Primitives::
10795: * Performance::
10796: @end menu
10797:
10798: @node Portability, Threading, Engine, Engine
10799: @section Portability
10800: @cindex engine portability
10801:
1.26 crook 10802: An important goal of the Gforth Project is availability across a wide
10803: range of personal machines. fig-Forth, and, to a lesser extent, F83,
10804: achieved this goal by manually coding the engine in assembly language
10805: for several then-popular processors. This approach is very
10806: labor-intensive and the results are short-lived due to progress in
10807: computer architecture.
1.1 anton 10808:
10809: @cindex C, using C for the engine
10810: Others have avoided this problem by coding in C, e.g., Mitch Bradley
10811: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
10812: particularly popular for UNIX-based Forths due to the large variety of
10813: architectures of UNIX machines. Unfortunately an implementation in C
10814: does not mix well with the goals of efficiency and with using
10815: traditional techniques: Indirect or direct threading cannot be expressed
10816: in C, and switch threading, the fastest technique available in C, is
10817: significantly slower. Another problem with C is that it is very
10818: cumbersome to express double integer arithmetic.
10819:
10820: @cindex GNU C for the engine
10821: @cindex long long
10822: Fortunately, there is a portable language that does not have these
10823: limitations: GNU C, the version of C processed by the GNU C compiler
10824: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
10825: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
10826: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
10827: threading possible, its @code{long long} type (@pxref{Long Long, ,
10828: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
10829: double numbers@footnote{Unfortunately, long longs are not implemented
10830: properly on all machines (e.g., on alpha-osf1, long longs are only 64
10831: bits, the same size as longs (and pointers), but they should be twice as
1.4 anton 10832: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1 anton 10833: C Manual}). So, we had to implement doubles in C after all. Still, on
10834: most machines we can use long longs and achieve better performance than
10835: with the emulation package.}. GNU C is available for free on all
10836: important (and many unimportant) UNIX machines, VMS, 80386s running
10837: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
10838: on all these machines.
10839:
10840: Writing in a portable language has the reputation of producing code that
10841: is slower than assembly. For our Forth engine we repeatedly looked at
10842: the code produced by the compiler and eliminated most compiler-induced
10843: inefficiencies by appropriate changes in the source code.
10844:
10845: @cindex explicit register declarations
10846: @cindex --enable-force-reg, configuration flag
10847: @cindex -DFORCE_REG
10848: However, register allocation cannot be portably influenced by the
10849: programmer, leading to some inefficiencies on register-starved
10850: machines. We use explicit register declarations (@pxref{Explicit Reg
10851: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
10852: improve the speed on some machines. They are turned on by using the
10853: configuration flag @code{--enable-force-reg} (@code{gcc} switch
10854: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
10855: machine, but also on the compiler version: On some machines some
10856: compiler versions produce incorrect code when certain explicit register
10857: declarations are used. So by default @code{-DFORCE_REG} is not used.
10858:
10859: @node Threading, Primitives, Portability, Engine
10860: @section Threading
10861: @cindex inner interpreter implementation
10862: @cindex threaded code implementation
10863:
10864: @cindex labels as values
10865: GNU C's labels as values extension (available since @code{gcc-2.0},
10866: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 10867: makes it possible to take the address of @i{label} by writing
10868: @code{&&@i{label}}. This address can then be used in a statement like
10869: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 10870: @code{goto x}.
10871:
1.26 crook 10872: @cindex @code{NEXT}, indirect threaded
1.1 anton 10873: @cindex indirect threaded inner interpreter
10874: @cindex inner interpreter, indirect threaded
1.26 crook 10875: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 10876: @example
10877: cfa = *ip++;
10878: ca = *cfa;
10879: goto *ca;
10880: @end example
10881: @cindex instruction pointer
10882: For those unfamiliar with the names: @code{ip} is the Forth instruction
10883: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
10884: execution token and points to the code field of the next word to be
10885: executed; The @code{ca} (code address) fetched from there points to some
10886: executable code, e.g., a primitive or the colon definition handler
10887: @code{docol}.
10888:
1.26 crook 10889: @cindex @code{NEXT}, direct threaded
1.1 anton 10890: @cindex direct threaded inner interpreter
10891: @cindex inner interpreter, direct threaded
10892: Direct threading is even simpler:
10893: @example
10894: ca = *ip++;
10895: goto *ca;
10896: @end example
10897:
10898: Of course we have packaged the whole thing neatly in macros called
1.26 crook 10899: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 10900:
10901: @menu
10902: * Scheduling::
10903: * Direct or Indirect Threaded?::
10904: * DOES>::
10905: @end menu
10906:
10907: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
10908: @subsection Scheduling
10909: @cindex inner interpreter optimization
10910:
10911: There is a little complication: Pipelined and superscalar processors,
10912: i.e., RISC and some modern CISC machines can process independent
10913: instructions while waiting for the results of an instruction. The
10914: compiler usually reorders (schedules) the instructions in a way that
10915: achieves good usage of these delay slots. However, on our first tries
10916: the compiler did not do well on scheduling primitives. E.g., for
10917: @code{+} implemented as
10918: @example
10919: n=sp[0]+sp[1];
10920: sp++;
10921: sp[0]=n;
10922: NEXT;
10923: @end example
1.26 crook 10924: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1 anton 10925: scheduling. After a little thought the problem becomes clear: The
1.21 crook 10926: compiler cannot know that @code{sp} and @code{ip} point to different
10927: addresses (and the version of @code{gcc} we used would not know it even
10928: if it was possible), so it could not move the load of the cfa above the
10929: store to the TOS. Indeed the pointers could be the same, if code on or
10930: very near the top of stack were executed. In the interest of speed we
10931: chose to forbid this probably unused ``feature'' and helped the compiler
1.26 crook 10932: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21 crook 10933: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1 anton 10934: @example
10935: n=sp[0]+sp[1];
10936: sp++;
10937: NEXT_P1;
10938: sp[0]=n;
10939: NEXT_P2;
10940: @end example
10941: This can be scheduled optimally by the compiler.
10942:
10943: This division can be turned off with the switch @code{-DCISC_NEXT}. This
10944: switch is on by default on machines that do not profit from scheduling
10945: (e.g., the 80386), in order to preserve registers.
10946:
10947: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
10948: @subsection Direct or Indirect Threaded?
10949: @cindex threading, direct or indirect?
10950:
10951: @cindex -DDIRECT_THREADED
10952: Both! After packaging the nasty details in macro definitions we
10953: realized that we could switch between direct and indirect threading by
10954: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
10955: defining a few machine-specific macros for the direct-threading case.
10956: On the Forth level we also offer access words that hide the
10957: differences between the threading methods (@pxref{Threading Words}).
10958:
10959: Indirect threading is implemented completely machine-independently.
10960: Direct threading needs routines for creating jumps to the executable
1.21 crook 10961: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
10962: machine-dependent, but they do not amount to many source lines. Therefore,
10963: even porting direct threading to a new machine requires little effort.
1.1 anton 10964:
10965: @cindex --enable-indirect-threaded, configuration flag
10966: @cindex --enable-direct-threaded, configuration flag
10967: The default threading method is machine-dependent. You can enforce a
10968: specific threading method when building Gforth with the configuration
10969: flag @code{--enable-direct-threaded} or
10970: @code{--enable-indirect-threaded}. Note that direct threading is not
10971: supported on all machines.
10972:
10973: @node DOES>, , Direct or Indirect Threaded?, Threading
10974: @subsection DOES>
10975: @cindex @code{DOES>} implementation
10976:
1.26 crook 10977: @cindex @code{dodoes} routine
10978: @cindex @code{DOES>}-code
1.1 anton 10979: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
10980: the chunk of code executed by every word defined by a
10981: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
10982: the Forth code to be executed, i.e. the code after the
1.26 crook 10983: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1 anton 10984:
1.21 crook 10985: In fig-Forth the code field points directly to the @code{dodoes} and the
1.26 crook 10986: @code{DOES>}code address is stored in the cell after the code address (i.e. at
1.29 crook 10987: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1 anton 10988: the Forth-79 and all later standards, because in fig-Forth this address
10989: lies in the body (which is illegal in these standards). However, by
10990: making the code field larger for all words this solution becomes legal
10991: again. We use this approach for the indirect threaded version and for
10992: direct threading on some machines. Leaving a cell unused in most words
10993: is a bit wasteful, but on the machines we are targeting this is hardly a
10994: problem. The other reason for having a code field size of two cells is
10995: to avoid having different image files for direct and indirect threaded
10996: systems (direct threaded systems require two-cell code fields on many
10997: machines).
10998:
1.26 crook 10999: @cindex @code{DOES>}-handler
1.1 anton 11000: The other approach is that the code field points or jumps to the cell
1.26 crook 11001: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
11002: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
11003: @code{DOES>}-code address by computing the code address, i.e., the address of
1.1 anton 11004: the jump to dodoes, and add the length of that jump field. A variant of
11005: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
11006: return address (which can be found in the return register on RISCs) is
1.26 crook 11007: the @code{DOES>}-code address. Since the two cells available in the code field
1.1 anton 11008: are used up by the jump to the code address in direct threading on many
11009: architectures, we use this approach for direct threading on these
11010: architectures. We did not want to add another cell to the code field.
11011:
11012: @node Primitives, Performance, Threading, Engine
11013: @section Primitives
11014: @cindex primitives, implementation
11015: @cindex virtual machine instructions, implementation
11016:
11017: @menu
11018: * Automatic Generation::
11019: * TOS Optimization::
11020: * Produced code::
11021: @end menu
11022:
11023: @node Automatic Generation, TOS Optimization, Primitives, Primitives
11024: @subsection Automatic Generation
11025: @cindex primitives, automatic generation
11026:
11027: @cindex @file{prims2x.fs}
11028: Since the primitives are implemented in a portable language, there is no
11029: longer any need to minimize the number of primitives. On the contrary,
11030: having many primitives has an advantage: speed. In order to reduce the
11031: number of errors in primitives and to make programming them easier, we
11032: provide a tool, the primitive generator (@file{prims2x.fs}), that
11033: automatically generates most (and sometimes all) of the C code for a
11034: primitive from the stack effect notation. The source for a primitive
11035: has the following form:
11036:
11037: @cindex primitive source format
11038: @format
1.29 crook 11039: @i{Forth-name} @i{stack-effect} @i{category} [@i{pronounc.}]
11040: [@code{""}@i{glossary entry}@code{""}]
11041: @i{C code}
1.1 anton 11042: [@code{:}
1.29 crook 11043: @i{Forth code}]
1.1 anton 11044: @end format
11045:
11046: The items in brackets are optional. The category and glossary fields
11047: are there for generating the documentation, the Forth code is there
11048: for manual implementations on machines without GNU C. E.g., the source
11049: for the primitive @code{+} is:
11050: @example
11051: + n1 n2 -- n core plus
11052: n = n1+n2;
11053: @end example
11054:
11055: This looks like a specification, but in fact @code{n = n1+n2} is C
11056: code. Our primitive generation tool extracts a lot of information from
11057: the stack effect notations@footnote{We use a one-stack notation, even
11058: though we have separate data and floating-point stacks; The separate
11059: notation can be generated easily from the unified notation.}: The number
11060: of items popped from and pushed on the stack, their type, and by what
11061: name they are referred to in the C code. It then generates a C code
11062: prelude and postlude for each primitive. The final C code for @code{+}
11063: looks like this:
11064:
11065: @example
11066: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
11067: /* */ /* documentation */
11068: @{
11069: DEF_CA /* definition of variable ca (indirect threading) */
11070: Cell n1; /* definitions of variables */
11071: Cell n2;
11072: Cell n;
11073: n1 = (Cell) sp[1]; /* input */
11074: n2 = (Cell) TOS;
11075: sp += 1; /* stack adjustment */
11076: NAME("+") /* debugging output (with -DDEBUG) */
11077: @{
11078: n = n1+n2; /* C code taken from the source */
11079: @}
11080: NEXT_P1; /* NEXT part 1 */
11081: TOS = (Cell)n; /* output */
11082: NEXT_P2; /* NEXT part 2 */
11083: @}
11084: @end example
11085:
11086: This looks long and inefficient, but the GNU C compiler optimizes quite
11087: well and produces optimal code for @code{+} on, e.g., the R3000 and the
11088: HP RISC machines: Defining the @code{n}s does not produce any code, and
11089: using them as intermediate storage also adds no cost.
11090:
1.26 crook 11091: There are also other optimizations that are not illustrated by this
11092: example: assignments between simple variables are usually for free (copy
1.1 anton 11093: propagation). If one of the stack items is not used by the primitive
11094: (e.g. in @code{drop}), the compiler eliminates the load from the stack
11095: (dead code elimination). On the other hand, there are some things that
11096: the compiler does not do, therefore they are performed by
11097: @file{prims2x.fs}: The compiler does not optimize code away that stores
11098: a stack item to the place where it just came from (e.g., @code{over}).
11099:
11100: While programming a primitive is usually easy, there are a few cases
11101: where the programmer has to take the actions of the generator into
11102: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 11103: fall through to @code{NEXT}.
1.1 anton 11104:
11105: @node TOS Optimization, Produced code, Automatic Generation, Primitives
11106: @subsection TOS Optimization
11107: @cindex TOS optimization for primitives
11108: @cindex primitives, keeping the TOS in a register
11109:
11110: An important optimization for stack machine emulators, e.g., Forth
11111: engines, is keeping one or more of the top stack items in
1.29 crook 11112: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
11113: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 11114: @itemize @bullet
11115: @item
1.29 crook 11116: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 11117: due to fewer loads from and stores to the stack.
1.29 crook 11118: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
11119: @i{y<n}, due to additional moves between registers.
1.1 anton 11120: @end itemize
11121:
11122: @cindex -DUSE_TOS
11123: @cindex -DUSE_NO_TOS
11124: In particular, keeping one item in a register is never a disadvantage,
11125: if there are enough registers. Keeping two items in registers is a
11126: disadvantage for frequent words like @code{?branch}, constants,
11127: variables, literals and @code{i}. Therefore our generator only produces
11128: code that keeps zero or one items in registers. The generated C code
11129: covers both cases; the selection between these alternatives is made at
11130: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
11131: code for @code{+} is just a simple variable name in the one-item case,
11132: otherwise it is a macro that expands into @code{sp[0]}. Note that the
11133: GNU C compiler tries to keep simple variables like @code{TOS} in
11134: registers, and it usually succeeds, if there are enough registers.
11135:
11136: @cindex -DUSE_FTOS
11137: @cindex -DUSE_NO_FTOS
11138: The primitive generator performs the TOS optimization for the
11139: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
11140: operations the benefit of this optimization is even larger:
11141: floating-point operations take quite long on most processors, but can be
11142: performed in parallel with other operations as long as their results are
11143: not used. If the FP-TOS is kept in a register, this works. If
11144: it is kept on the stack, i.e., in memory, the store into memory has to
11145: wait for the result of the floating-point operation, lengthening the
11146: execution time of the primitive considerably.
11147:
11148: The TOS optimization makes the automatic generation of primitives a
11149: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
11150: @code{TOS} is not sufficient. There are some special cases to
11151: consider:
11152: @itemize @bullet
11153: @item In the case of @code{dup ( w -- w w )} the generator must not
11154: eliminate the store to the original location of the item on the stack,
11155: if the TOS optimization is turned on.
11156: @item Primitives with stack effects of the form @code{--}
1.29 crook 11157: @i{out1}...@i{outy} must store the TOS to the stack at the start.
11158: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 11159: must load the TOS from the stack at the end. But for the null stack
11160: effect @code{--} no stores or loads should be generated.
11161: @end itemize
11162:
11163: @node Produced code, , TOS Optimization, Primitives
11164: @subsection Produced code
11165: @cindex primitives, assembly code listing
11166:
11167: @cindex @file{engine.s}
11168: To see what assembly code is produced for the primitives on your machine
11169: with your compiler and your flag settings, type @code{make engine.s} and
11170: look at the resulting file @file{engine.s}.
11171:
11172: @node Performance, , Primitives, Engine
11173: @section Performance
11174: @cindex performance of some Forth interpreters
11175: @cindex engine performance
11176: @cindex benchmarking Forth systems
11177: @cindex Gforth performance
11178:
11179: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
11180: impossible to write a significantly faster engine.
11181:
11182: On register-starved machines like the 386 architecture processors
11183: improvements are possible, because @code{gcc} does not utilize the
11184: registers as well as a human, even with explicit register declarations;
11185: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
11186: and hand-tuned it for the 486; this system is 1.19 times faster on the
11187: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 11188: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
11189: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
11190: registers fit in real registers (and we can even afford to use the TOS
11191: optimization), resulting in a speedup of 1.14 on the sieve over the
11192: earlier results.
1.1 anton 11193:
11194: @cindex Win32Forth performance
11195: @cindex NT Forth performance
11196: @cindex eforth performance
11197: @cindex ThisForth performance
11198: @cindex PFE performance
11199: @cindex TILE performance
1.40 anton 11200: The potential advantage of assembly language implementations
1.1 anton 11201: is not necessarily realized in complete Forth systems: We compared
1.40 anton 11202: Gforth-0.4.9 (direct threaded, compiled with @code{gcc-2.95.1} and
1.1 anton 11203: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
11204: 1994) and Eforth (with and without peephole (aka pinhole) optimization
11205: of the threaded code); all these systems were written in assembly
11206: language. We also compared Gforth with three systems written in C:
11207: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
11208: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21 crook 11209: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
11210: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1 anton 11211: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
11212: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
11213: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
11214: 486DX2/66 with similar memory performance under Windows NT. Marcel
11215: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
11216: added the peephole optimizer, ran the benchmarks and reported the
11217: results.
1.40 anton 11218:
1.1 anton 11219: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
11220: matrix multiplication come from the Stanford integer benchmarks and have
11221: been translated into Forth by Martin Fraeman; we used the versions
11222: included in the TILE Forth package, but with bigger data set sizes; and
11223: a recursive Fibonacci number computation for benchmarking calling
11224: performance. The following table shows the time taken for the benchmarks
11225: scaled by the time taken by Gforth (in other words, it shows the speedup
11226: factor that Gforth achieved over the other systems).
11227:
11228: @example
1.40 anton 11229: relative Win32- NT eforth This-
1.1 anton 11230: time Gforth Forth Forth eforth +opt PFE Forth TILE
1.40 anton 11231: sieve 1.00 1.58 1.30 1.58 0.97 1.80 3.63 9.79
11232: bubble 1.00 1.55 1.67 1.75 1.04 1.78 4.59
11233: matmul 1.00 1.67 1.53 1.66 0.84 1.79 4.63
11234: fib 1.00 1.75 1.53 1.40 0.99 1.99 3.43 4.93
1.1 anton 11235: @end example
11236:
1.26 crook 11237: You may be quite surprised by the good performance of Gforth when
11238: compared with systems written in assembly language. One important reason
11239: for the disappointing performance of these other systems is probably
11240: that they are not written optimally for the 486 (e.g., they use the
11241: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
11242: but costly method for relocating the Forth image: like @code{cforth}, it
11243: computes the actual addresses at run time, resulting in two address
11244: computations per @code{NEXT} (@pxref{Image File Background}).
11245:
1.40 anton 11246: Only Eforth with the peephole optimizer performs comparable to
11247: Gforth. The speedups achieved with peephole optimization of threaded
11248: code are quite remarkable. Adding a peephole optimizer to Gforth should
11249: cause similar speedups.
1.1 anton 11250:
11251: The speedup of Gforth over PFE, ThisForth and TILE can be easily
11252: explained with the self-imposed restriction of the latter systems to
11253: standard C, which makes efficient threading impossible (however, the
1.4 anton 11254: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 11255: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
11256: Moreover, current C compilers have a hard time optimizing other aspects
11257: of the ThisForth and the TILE source.
11258:
1.26 crook 11259: The performance of Gforth on 386 architecture processors varies widely
11260: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
11261: allocate any of the virtual machine registers into real machine
11262: registers by itself and would not work correctly with explicit register
1.40 anton 11263: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
1.26 crook 11264: the Sieve) than the one measured above.
1.1 anton 11265:
1.26 crook 11266: Note that there have been several releases of Win32Forth since the
11267: release presented here, so the results presented above may have little
1.40 anton 11268: predictive value for the performance of Win32Forth today (results for
11269: the current release on an i486DX2/66 are welcome).
1.1 anton 11270:
11271: @cindex @file{Benchres}
11272: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
11273: Maierhofer (presented at EuroForth '95), an indirect threaded version of
11274: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
1.40 anton 11275: version of Gforth is slower on a 486 than the direct threaded version
11276: used here. The paper available at
1.1 anton 11277: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
11278: it also contains numbers for some native code systems. You can find a
11279: newer version of these measurements at
11280: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
11281: find numbers for Gforth on various machines in @file{Benchres}.
11282:
1.26 crook 11283: @c ******************************************************************
1.13 pazsan 11284: @node Binding to System Library, Cross Compiler, Engine, Top
1.14 pazsan 11285: @chapter Binding to System Library
1.13 pazsan 11286:
11287: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14 pazsan 11288: @chapter Cross Compiler
1.13 pazsan 11289:
11290: Cross Compiler
11291:
11292: @menu
11293: * Using the Cross Compiler::
11294: * How the Cross Compiler Works::
11295: @end menu
11296:
1.21 crook 11297: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 11298: @section Using the Cross Compiler
1.13 pazsan 11299:
1.21 crook 11300: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 11301: @section How the Cross Compiler Works
1.13 pazsan 11302:
11303: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 11304: @appendix Bugs
1.1 anton 11305: @cindex bug reporting
11306:
1.21 crook 11307: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 11308:
11309: If you find a bug, please send a bug report to
1.33 anton 11310: @email{bug-gforth@@gnu.org}. A bug report should include this
1.21 crook 11311: information:
11312:
11313: @itemize @bullet
11314: @item
11315: The Gforth version used (it is announced at the start of an
11316: interactive Gforth session).
11317: @item
11318: The machine and operating system (on Unix
11319: systems @code{uname -a} will report this information).
11320: @item
11321: The installation options (send the file @file{config.status}).
11322: @item
11323: A complete list of changes (if any) you (or your installer) have made to the
11324: Gforth sources.
11325: @item
11326: A program (or a sequence of keyboard commands) that reproduces the bug.
11327: @item
11328: A description of what you think constitutes the buggy behaviour.
11329: @end itemize
1.1 anton 11330:
11331: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
11332: to Report Bugs, gcc.info, GNU C Manual}.
11333:
11334:
1.21 crook 11335: @node Origin, Forth-related information, Bugs, Top
11336: @appendix Authors and Ancestors of Gforth
1.1 anton 11337:
11338: @section Authors and Contributors
11339: @cindex authors of Gforth
11340: @cindex contributors to Gforth
11341:
11342: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
11343: Ertl. The third major author was Jens Wilke. Lennart Benschop (who was
11344: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
11345: with their continuous feedback. Lennart Benshop contributed
11346: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
11347: support for calling C libraries. Helpful comments also came from Paul
11348: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.12 anton 11349: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
11350: release of Gforth-0.2.1 there were also helpful comments from many
11351: others; thank you all, sorry for not listing you here (but digging
1.23 crook 11352: through my mailbox to extract your names is on my to-do list). Since the
11353: release of Gforth-0.4.0 Neal Crook worked on the manual.
1.1 anton 11354:
11355: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
11356: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 11357: was developed across the Internet, and its authors did not meet
1.20 pazsan 11358: physically for the first 4 years of development.
1.1 anton 11359:
11360: @section Pedigree
1.26 crook 11361: @cindex pedigree of Gforth
1.1 anton 11362:
1.20 pazsan 11363: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1 anton 11364: Dirk Zoller) will cross-fertilize each other. Of course, a significant
11365: part of the design of Gforth was prescribed by ANS Forth.
11366:
1.20 pazsan 11367: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 11368: 32 bit native code version of VolksForth for the Atari ST, written
11369: mostly by Dietrich Weineck.
11370:
11371: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
11372: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
11373: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
11374:
11375: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
11376: Forth-83 standard. !! Pedigree? When?
11377:
11378: A team led by Bill Ragsdale implemented fig-Forth on many processors in
11379: 1979. Robert Selzer and Bill Ragsdale developed the original
11380: implementation of fig-Forth for the 6502 based on microForth.
11381:
11382: The principal architect of microForth was Dean Sanderson. microForth was
11383: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
11384: the 1802, and subsequently implemented on the 8080, the 6800 and the
11385: Z80.
11386:
11387: All earlier Forth systems were custom-made, usually by Charles Moore,
11388: who discovered (as he puts it) Forth during the late 60s. The first full
11389: Forth existed in 1971.
11390:
11391: A part of the information in this section comes from @cite{The Evolution
11392: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
11393: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
11394: Notices 28(3), 1993. You can find more historical and genealogical
11395: information about Forth there.
11396:
1.21 crook 11397: @node Forth-related information, Word Index, Origin, Top
11398: @appendix Other Forth-related information
11399: @cindex Forth-related information
11400:
11401: @menu
11402: * Internet resources::
11403: * Books::
11404: * The Forth Interest Group::
11405: * Conferences::
11406: @end menu
11407:
11408:
11409: @node Internet resources, Books, Forth-related information, Forth-related information
11410: @section Internet resources
1.26 crook 11411: @cindex internet resources
1.21 crook 11412:
11413: @cindex comp.lang.forth
11414: @cindex frequently asked questions
11415: There is an active newsgroup (comp.lang.forth) discussing Forth and
11416: Forth-related issues. A frequently-asked-questions (FAQ) list
11417: is posted to the newsgroup regulary, and archived at these sites:
11418:
11419: @itemize @bullet
11420: @item
11421: @url{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
11422: @item
11423: @url{ftp://ftp.forth.org/pub/Forth/FAQ/}
11424: @end itemize
11425:
11426: The FAQ list should be considered mandatory reading before posting to
11427: the newsgroup.
11428:
11429: Here are some other web sites holding Forth-related material:
11430:
11431: @itemize @bullet
11432: @item
11433: @url{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
11434: @item
11435: @url{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
11436: @item
11437: @url{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
11438: @item
11439: @url{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
11440: Research page, including links to the Journal of Forth Application and
11441: Research (JFAR) and a searchable Forth bibliography.
11442: @end itemize
11443:
11444:
11445: @node Books, The Forth Interest Group, Internet resources, Forth-related information
11446: @section Books
1.26 crook 11447: @cindex books on Forth
1.21 crook 11448:
11449: As the Standard is relatively new, there are not many books out yet. It
11450: is not recommended to learn Forth by using Gforth and a book that is not
11451: written for ANS Forth, as you will not know your mistakes from the
11452: deviations of the book. However, books based on the Forth-83 standard
11453: should be ok, because ANS Forth is primarily an extension of Forth-83.
11454:
11455: @cindex standard document for ANS Forth
11456: @cindex ANS Forth document
11457: The definite reference if you want to write ANS Forth programs is, of
1.26 crook 11458: course, the ANS Forth document. It is available in printed form from the
1.21 crook 11459: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
11460: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
11461: $200. You can also get it from Global Engineering Documents (Tel.: USA
11462: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
11463:
11464: @cite{dpANS6}, the last draft of the standard, which was then submitted
11465: to ANSI for publication is available electronically and for free in some
11466: MS Word format, and it has been converted to HTML
11467: (@url{http://www.taygeta.com/forth/dpans.html}; this is my favourite
11468: format); this HTML version also includes the answers to Requests for
11469: Interpretation (RFIs). Some pointers to these versions can be found
11470: through @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
11471:
1.26 crook 11472: @cindex introductory book on Forth
11473: @cindex book on Forth, introductory
1.21 crook 11474: @cindex Woehr, Jack: @cite{Forth: The New Model}
11475: @cindex @cite{Forth: The new model} (book)
11476: @cite{Forth: The New Model} by Jack Woehr (Prentice-Hall, 1993) is an
11477: introductory book based on a draft version of the standard. It does not
11478: cover the whole standard. It also contains interesting background
11479: information (Jack Woehr was in the ANS Forth Technical Committee). It is
11480: not appropriate for complete newbies, but programmers experienced in
11481: other languages should find it ok.
11482:
11483: @cindex Conklin, Edward K., and Elizabeth Rather: @cite{Forth Programmer's Handbook}
11484: @cindex Rather, Elizabeth and Edward K. Conklin: @cite{Forth Programmer's Handbook}
11485: @cindex @cite{Forth Programmer's Handbook} (book)
11486: @cite{Forth Programmer's Handbook} by Edward K. Conklin, Elizabeth
11487: D. Rather and the technical staff of Forth, Inc. (Forth, Inc., 1997;
11488: ISBN 0-9662156-0-5) contains little introductory material. The majority
11489: of the book is similar to @ref{Words}, but the book covers most of the
11490: standard words and some non-standard words (whereas this manual is
11491: quite incomplete). In addition, the book contains a chapter on
11492: programming style. The major drawback of this book is that it usually
11493: does not identify what is standard and what is specific to the Forth
11494: system described in the book (probably one of Forth, Inc.'s systems).
11495: Fortunately, many of the non-standard programming practices described in
11496: the book work in Gforth, too. Still, this drawback makes the book
11497: hardly more useful than a pre-ANS book.
11498:
11499: @node The Forth Interest Group, Conferences, Books, Forth-related information
11500: @section The Forth Interest Group
11501: @cindex Forth interest group (FIG)
11502:
11503: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26 crook 11504: member-supported organisation. It publishes a regular magazine,
11505: @var{FORTH Dimensions}, and offers other benefits of membership. You can
11506: contact the FIG through their office email address:
11507: @email{office@@forth.org} or by visiting their web site at
11508: @url{http://www.forth.org/}. This web site also includes links to FIG
11509: chapters in other countries and American cities
1.21 crook 11510: (@url{http://www.forth.org/chapters.html}).
11511:
11512: @node Conferences, , The Forth Interest Group, Forth-related information
11513: @section Conferences
11514: @cindex Conferences
11515:
11516: There are several regular conferences related to Forth. They are all
1.26 crook 11517: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
11518: news group:
1.21 crook 11519:
11520: @itemize @bullet
11521: @item
11522: FORML -- the Forth modification laboratory convenes every year near
11523: Monterey, California.
11524: @item
11525: The Rochester Forth Conference -- an annual conference traditionally
11526: held in Rochester, New York.
11527: @item
11528: EuroForth -- this European conference takes place annually.
11529: @end itemize
11530:
11531:
1.41 ! anton 11532: @node Word Index, Name Index, Forth-related information, Top
1.1 anton 11533: @unnumbered Word Index
11534:
1.26 crook 11535: This index is a list of Forth words that have ``glossary'' entries
11536: within this manual. Each word is listed with its stack effect and
11537: wordset.
1.1 anton 11538:
11539: @printindex fn
11540:
1.41 ! anton 11541: @node Name Index, Concept Index, Word Index, Top
! 11542: @unnumbered Name Index
! 11543:
! 11544: This index is a list of Forth words that have ``glossary'' entries
! 11545: within this manual.
! 11546:
! 11547: @printindex ky
! 11548:
! 11549: @node Concept Index, , Name Index, Top
1.1 anton 11550: @unnumbered Concept and Word Index
11551:
1.26 crook 11552: Not all entries listed in this index are present verbatim in the
11553: text. This index also duplicates, in abbreviated form, all of the words
11554: listed in the Word Index (only the names are listed for the words here).
1.1 anton 11555:
11556: @printindex cp
11557:
11558: @contents
11559: @bye
11560:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>