Annotation of gforth/doc/gforth.ds, revision 1.32
1.1 anton 1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28 crook 3:
1.21 crook 4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28 crook 5: @comment 1. x-ref all ambiguous or implementation-defined features?
6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
7: @comment 3. words in miscellaneous section need a home.
8: @comment 4. search for TODO for other minor and major works required.
9: @comment 5. [rats] change all @var to @i in Forth source so that info
10: @comment file looks decent.
1.29 crook 11: @comment .. would be useful to have a word that identified all deferred words
12: @comment should semantics stuff in intro be moved to another section
13:
1.28 crook 14:
1.1 anton 15: @comment %**start of header (This is for running Texinfo on a region.)
16: @setfilename gforth.info
17: @settitle Gforth Manual
18: @dircategory GNU programming tools
19: @direntry
20: * Gforth: (gforth). A fast interpreter for the Forth language.
21: @end direntry
22: @comment @setchapternewpage odd
1.29 crook 23: @comment TODO this gets left in by HTML converter
1.12 anton 24: @macro progstyle {}
25: Programming style note:
1.3 anton 26: @end macro
1.1 anton 27: @comment %**end of header (This is for running Texinfo on a region.)
28:
1.29 crook 29:
30: @comment ----------------------------------------------------------
31: @comment macros for beautifying glossary entries
32: @comment if these are used, need to strip them out for HTML converter
33: @comment else they get repeated verbatim in HTML output.
34: @comment .. not working yet.
35:
36: @macro GLOSS-START {}
37: @iftex
38: @ninerm
39: @end iftex
40: @end macro
41:
42: @macro GLOSS-END {}
43: @iftex
44: @rm
45: @end iftex
46: @end macro
47:
48: @comment ----------------------------------------------------------
49:
50:
1.10 anton 51: @include version.texi
52:
1.1 anton 53: @ifinfo
1.11 anton 54: This file documents Gforth @value{VERSION}
1.1 anton 55:
1.26 crook 56: Copyright @copyright{} 1995-1999 Free Software Foundation, Inc.
1.1 anton 57:
58: Permission is granted to make and distribute verbatim copies of
59: this manual provided the copyright notice and this permission notice
60: are preserved on all copies.
61:
62: @ignore
63: Permission is granted to process this file through TeX and print the
64: results, provided the printed document carries a copying permission
65: notice identical to this one except for the removal of this paragraph
66: (this paragraph not being relevant to the printed manual).
67:
68: @end ignore
69: Permission is granted to copy and distribute modified versions of this
70: manual under the conditions for verbatim copying, provided also that the
71: sections entitled "Distribution" and "General Public License" are
72: included exactly as in the original, and provided that the entire
73: resulting derived work is distributed under the terms of a permission
74: notice identical to this one.
75:
76: Permission is granted to copy and distribute translations of this manual
77: into another language, under the above conditions for modified versions,
78: except that the sections entitled "Distribution" and "General Public
79: License" may be included in a translation approved by the author instead
80: of in the original English.
81: @end ifinfo
82:
83: @finalout
84: @titlepage
85: @sp 10
86: @center @titlefont{Gforth Manual}
87: @sp 2
1.11 anton 88: @center for version @value{VERSION}
1.1 anton 89: @sp 2
90: @center Anton Ertl
1.6 pazsan 91: @center Bernd Paysan
1.5 anton 92: @center Jens Wilke
1.23 crook 93: @center Neal Crook
1.1 anton 94: @sp 3
1.29 crook 95: @center This manual is permanently under construction and was last updated on 04-May-1999
1.1 anton 96:
97: @comment The following two commands start the copyright page.
98: @page
99: @vskip 0pt plus 1filll
1.29 crook 100: Copyright @copyright{} 1995--1999 Free Software Foundation, Inc.
1.1 anton 101:
102: @comment !! Published by ... or You can get a copy of this manual ...
103:
104: Permission is granted to make and distribute verbatim copies of
105: this manual provided the copyright notice and this permission notice
106: are preserved on all copies.
107:
108: Permission is granted to copy and distribute modified versions of this
109: manual under the conditions for verbatim copying, provided also that the
110: sections entitled "Distribution" and "General Public License" are
111: included exactly as in the original, and provided that the entire
112: resulting derived work is distributed under the terms of a permission
113: notice identical to this one.
114:
115: Permission is granted to copy and distribute translations of this manual
116: into another language, under the above conditions for modified versions,
117: except that the sections entitled "Distribution" and "General Public
118: License" may be included in a translation approved by the author instead
119: of in the original English.
120: @end titlepage
121:
122:
123: @node Top, License, (dir), (dir)
124: @ifinfo
125: Gforth is a free implementation of ANS Forth available on many
1.11 anton 126: personal machines. This manual corresponds to version @value{VERSION}.
1.1 anton 127: @end ifinfo
128:
129: @menu
1.21 crook 130: * License:: The GPL
1.26 crook 131: * Goals:: About the Gforth Project
1.29 crook 132: * Gforth Environment:: Starting (and exiting) Gforth
1.21 crook 133: * Introduction:: An introduction to ANS Forth
1.1 anton 134: * Words:: Forth words available in Gforth
1.24 anton 135: * Error messages:: How to interpret them
1.1 anton 136: * Tools:: Programming tools
137: * ANS conformance:: Implementation-defined options etc.
138: * Model:: The abstract machine of Gforth
139: * Integrating Gforth:: Forth as scripting language for applications
140: * Emacs and Gforth:: The Gforth Mode
141: * Image Files:: @code{.fi} files contain compiled code
142: * Engine:: The inner interpreter and the primitives
1.24 anton 143: * Binding to System Library::
1.13 pazsan 144: * Cross Compiler:: The Cross Compiler
1.1 anton 145: * Bugs:: How to report them
146: * Origin:: Authors and ancestors of Gforth
1.21 crook 147: * Forth-related information:: Books and places to look on the WWW
1.1 anton 148: * Word Index:: An item for each Forth word
149: * Concept Index:: A menu covering many topics
1.12 anton 150:
1.24 anton 151: @detailmenu --- The Detailed Node Listing ---
1.12 anton 152:
1.26 crook 153: Goals of Gforth
154:
155: * Gforth Extensions Sinful?::
156:
1.29 crook 157: Gforth Environment
158:
1.32 ! anton 159: * Invoking Gforth:: Getting in
! 160: * Leaving Gforth:: Getting out
! 161: * Command-line editing::
1.29 crook 162: * Upper and lower case::
1.32 ! anton 163: * Environment variables:: ..that affect how Gforth starts up
! 164: * Gforth Files:: What gets installed and where
1.29 crook 165:
1.24 anton 166: An Introduction to ANS Forth
167:
168: * Introducing the Text Interpreter::
169: * Stacks and Postfix notation::
170: * Your first definition::
171: * How does that work?::
172: * Forth is written in Forth::
173: * Review - elements of a Forth system::
1.29 crook 174: * Where to go next::
1.24 anton 175: * Exercises::
176:
1.12 anton 177: Forth Words
178:
179: * Notation::
1.21 crook 180: * Comments::
181: * Boolean Flags::
1.12 anton 182: * Arithmetic::
183: * Stack Manipulation::
184: * Memory::
185: * Control Structures::
186: * Defining Words::
1.21 crook 187: * The Text Interpreter::
1.12 anton 188: * Tokens for Words::
1.21 crook 189: * Word Lists::
190: * Environmental Queries::
1.12 anton 191: * Files::
192: * Blocks::
193: * Other I/O::
194: * Programming Tools::
195: * Assembler and Code Words::
196: * Threading Words::
1.26 crook 197: * Locals::
198: * Structures::
199: * Object-oriented Forth::
1.21 crook 200: * Passing Commands to the OS::
201: * Miscellaneous Words::
1.12 anton 202:
203: Arithmetic
204:
205: * Single precision::
206: * Bitwise operations::
1.21 crook 207: * Double precision:: Double-cell integer arithmetic
208: * Numeric comparison::
1.32 ! anton 209: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 210: * Floating Point::
211:
212: Stack Manipulation
213:
214: * Data stack::
215: * Floating point stack::
216: * Return stack::
217: * Locals stack::
218: * Stack pointer manipulation::
219:
220: Memory
221:
1.32 ! anton 222: * Memory model::
! 223: * Dictionary allocation::
! 224: * Heap Allocation::
! 225: * Memory Access::
! 226: * Address arithmetic::
! 227: * Memory Blocks::
1.12 anton 228:
229: Control Structures
230:
1.32 ! anton 231: * Selection:: IF.. ELSE.. ENDIF
! 232: * Simple Loops:: BEGIN..
! 233: * Counted Loops:: DO
! 234: * Arbitrary control structures::
! 235: * Calls and returns::
1.12 anton 236: * Exception Handling::
237:
238: Defining Words
239:
1.32 ! anton 240: * Simple Defining Words:: Variables, values and constants
! 241: * Colon Definitions::
! 242: * User-defined Defining Words::
! 243: * Supplying names::
! 244: * Interpretation and Compilation Semantics::
1.12 anton 245:
1.21 crook 246: The Text Interpreter
247:
1.29 crook 248: * Input Sources::
1.21 crook 249: * Number Conversion::
250: * Interpret/Compile states::
251: * Literals::
252: * Interpreter Directives::
253:
1.26 crook 254: Word Lists
255:
256: * Why use word lists?::
257: * Word list examples::
258:
259: Files
260:
261: * Forth source files::
262: * General files::
263: * Search Paths::
264: * Forth Search Paths::
265: * General Search Paths::
266:
267: Other I/O
268:
1.32 ! anton 269: * Simple numeric output:: Predefined formats
! 270: * Formatted numeric output:: Formatted (pictured) output
! 271: * String Formats:: How Forth stores strings in memory
! 272: * Displaying characters and strings:: Other stuff
! 273: * Input:: Input
1.26 crook 274:
275: Programming Tools
276:
277: * Debugging:: Simple and quick.
278: * Assertions:: Making your programs self-checking.
279: * Singlestep Debugger:: Executing your program word by word.
280:
281: Locals
282:
283: * Gforth locals::
284: * ANS Forth locals::
285:
286: Gforth locals
287:
288: * Where are locals visible by name?::
289: * How long do locals live?::
290: * Programming Style::
291: * Implementation::
292:
1.12 anton 293: Structures
294:
295: * Why explicit structure support?::
296: * Structure Usage::
297: * Structure Naming Convention::
298: * Structure Implementation::
299: * Structure Glossary::
300:
301: Object-oriented Forth
302:
1.24 anton 303: * Why object-oriented programming?::
304: * Object-Oriented Terminology::
305: * Objects::
306: * OOF::
307: * Mini-OOF::
1.23 crook 308: * Comparison with other object models::
1.12 anton 309:
1.24 anton 310: The @file{objects.fs} model
1.12 anton 311:
312: * Properties of the Objects model::
313: * Basic Objects Usage::
1.23 crook 314: * The Objects base class::
1.12 anton 315: * Creating objects::
316: * Object-Oriented Programming Style::
317: * Class Binding::
318: * Method conveniences::
319: * Classes and Scoping::
320: * Object Interfaces::
321: * Objects Implementation::
322: * Objects Glossary::
323:
1.24 anton 324: The @file{oof.fs} model
1.12 anton 325:
326: * Properties of the OOF model::
327: * Basic OOF Usage::
1.23 crook 328: * The OOF base class::
1.12 anton 329: * Class Declaration::
330: * Class Implementation::
331:
1.24 anton 332: The @file{mini-oof.fs} model
1.23 crook 333:
334: * Basic Mini-OOF Usage::
335: * Mini-OOF Example::
336: * Mini-OOF Implementation::
337:
1.12 anton 338: Tools
339:
340: * ANS Report:: Report the words used, sorted by wordset.
341:
342: ANS conformance
343:
344: * The Core Words::
345: * The optional Block word set::
346: * The optional Double Number word set::
347: * The optional Exception word set::
348: * The optional Facility word set::
349: * The optional File-Access word set::
350: * The optional Floating-Point word set::
351: * The optional Locals word set::
352: * The optional Memory-Allocation word set::
353: * The optional Programming-Tools word set::
354: * The optional Search-Order word set::
355:
356: The Core Words
357:
358: * core-idef:: Implementation Defined Options
359: * core-ambcond:: Ambiguous Conditions
360: * core-other:: Other System Documentation
361:
362: The optional Block word set
363:
364: * block-idef:: Implementation Defined Options
365: * block-ambcond:: Ambiguous Conditions
366: * block-other:: Other System Documentation
367:
368: The optional Double Number word set
369:
370: * double-ambcond:: Ambiguous Conditions
371:
372: The optional Exception word set
373:
374: * exception-idef:: Implementation Defined Options
375:
376: The optional Facility word set
377:
378: * facility-idef:: Implementation Defined Options
379: * facility-ambcond:: Ambiguous Conditions
380:
381: The optional File-Access word set
382:
383: * file-idef:: Implementation Defined Options
384: * file-ambcond:: Ambiguous Conditions
385:
386: The optional Floating-Point word set
387:
388: * floating-idef:: Implementation Defined Options
389: * floating-ambcond:: Ambiguous Conditions
390:
391: The optional Locals word set
392:
393: * locals-idef:: Implementation Defined Options
394: * locals-ambcond:: Ambiguous Conditions
395:
396: The optional Memory-Allocation word set
397:
398: * memory-idef:: Implementation Defined Options
399:
400: The optional Programming-Tools word set
401:
402: * programming-idef:: Implementation Defined Options
403: * programming-ambcond:: Ambiguous Conditions
404:
405: The optional Search-Order word set
406:
407: * search-idef:: Implementation Defined Options
408: * search-ambcond:: Ambiguous Conditions
409:
410: Image Files
411:
1.24 anton 412: * Image Licensing Issues:: Distribution terms for images.
413: * Image File Background:: Why have image files?
1.32 ! anton 414: * Non-Relocatable Image Files:: don't always work.
1.24 anton 415: * Data-Relocatable Image Files:: are better.
1.32 ! anton 416: * Fully Relocatable Image Files:: better yet.
1.24 anton 417: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 ! anton 418: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 419: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 420:
421: Fully Relocatable Image Files
422:
1.27 crook 423: * gforthmi:: The normal way
1.12 anton 424: * cross.fs:: The hard way
425:
426: Engine
427:
428: * Portability::
429: * Threading::
430: * Primitives::
431: * Performance::
432:
433: Threading
434:
435: * Scheduling::
436: * Direct or Indirect Threaded?::
437: * DOES>::
438:
439: Primitives
440:
441: * Automatic Generation::
442: * TOS Optimization::
443: * Produced code::
1.13 pazsan 444:
445: Cross Compiler
446:
447: * Using the Cross Compiler::
448: * How the Cross Compiler Works::
449:
1.24 anton 450: Other Forth-related information
1.21 crook 451:
452: * Internet resources::
453: * Books::
454: * The Forth Interest Group::
455: * Conferences::
456:
1.24 anton 457: @end detailmenu
1.1 anton 458: @end menu
459:
1.26 crook 460: @node License, Goals, Top, Top
1.1 anton 461: @unnumbered GNU GENERAL PUBLIC LICENSE
462: @center Version 2, June 1991
463:
464: @display
465: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
466: 675 Mass Ave, Cambridge, MA 02139, USA
467:
468: Everyone is permitted to copy and distribute verbatim copies
469: of this license document, but changing it is not allowed.
470: @end display
471:
472: @unnumberedsec Preamble
473:
474: The licenses for most software are designed to take away your
475: freedom to share and change it. By contrast, the GNU General Public
476: License is intended to guarantee your freedom to share and change free
477: software---to make sure the software is free for all its users. This
478: General Public License applies to most of the Free Software
479: Foundation's software and to any other program whose authors commit to
480: using it. (Some other Free Software Foundation software is covered by
481: the GNU Library General Public License instead.) You can apply it to
482: your programs, too.
483:
484: When we speak of free software, we are referring to freedom, not
485: price. Our General Public Licenses are designed to make sure that you
486: have the freedom to distribute copies of free software (and charge for
487: this service if you wish), that you receive source code or can get it
488: if you want it, that you can change the software or use pieces of it
489: in new free programs; and that you know you can do these things.
490:
491: To protect your rights, we need to make restrictions that forbid
492: anyone to deny you these rights or to ask you to surrender the rights.
493: These restrictions translate to certain responsibilities for you if you
494: distribute copies of the software, or if you modify it.
495:
496: For example, if you distribute copies of such a program, whether
497: gratis or for a fee, you must give the recipients all the rights that
498: you have. You must make sure that they, too, receive or can get the
499: source code. And you must show them these terms so they know their
500: rights.
501:
502: We protect your rights with two steps: (1) copyright the software, and
503: (2) offer you this license which gives you legal permission to copy,
504: distribute and/or modify the software.
505:
506: Also, for each author's protection and ours, we want to make certain
507: that everyone understands that there is no warranty for this free
508: software. If the software is modified by someone else and passed on, we
509: want its recipients to know that what they have is not the original, so
510: that any problems introduced by others will not reflect on the original
511: authors' reputations.
512:
513: Finally, any free program is threatened constantly by software
514: patents. We wish to avoid the danger that redistributors of a free
515: program will individually obtain patent licenses, in effect making the
516: program proprietary. To prevent this, we have made it clear that any
517: patent must be licensed for everyone's free use or not licensed at all.
518:
519: The precise terms and conditions for copying, distribution and
520: modification follow.
521:
522: @iftex
523: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
524: @end iftex
525: @ifinfo
526: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
527: @end ifinfo
528:
529: @enumerate 0
530: @item
531: This License applies to any program or other work which contains
532: a notice placed by the copyright holder saying it may be distributed
533: under the terms of this General Public License. The ``Program'', below,
534: refers to any such program or work, and a ``work based on the Program''
535: means either the Program or any derivative work under copyright law:
536: that is to say, a work containing the Program or a portion of it,
537: either verbatim or with modifications and/or translated into another
538: language. (Hereinafter, translation is included without limitation in
539: the term ``modification''.) Each licensee is addressed as ``you''.
540:
541: Activities other than copying, distribution and modification are not
542: covered by this License; they are outside its scope. The act of
543: running the Program is not restricted, and the output from the Program
544: is covered only if its contents constitute a work based on the
545: Program (independent of having been made by running the Program).
546: Whether that is true depends on what the Program does.
547:
548: @item
549: You may copy and distribute verbatim copies of the Program's
550: source code as you receive it, in any medium, provided that you
551: conspicuously and appropriately publish on each copy an appropriate
552: copyright notice and disclaimer of warranty; keep intact all the
553: notices that refer to this License and to the absence of any warranty;
554: and give any other recipients of the Program a copy of this License
555: along with the Program.
556:
557: You may charge a fee for the physical act of transferring a copy, and
558: you may at your option offer warranty protection in exchange for a fee.
559:
560: @item
561: You may modify your copy or copies of the Program or any portion
562: of it, thus forming a work based on the Program, and copy and
563: distribute such modifications or work under the terms of Section 1
564: above, provided that you also meet all of these conditions:
565:
566: @enumerate a
567: @item
568: You must cause the modified files to carry prominent notices
569: stating that you changed the files and the date of any change.
570:
571: @item
572: You must cause any work that you distribute or publish, that in
573: whole or in part contains or is derived from the Program or any
574: part thereof, to be licensed as a whole at no charge to all third
575: parties under the terms of this License.
576:
577: @item
578: If the modified program normally reads commands interactively
579: when run, you must cause it, when started running for such
580: interactive use in the most ordinary way, to print or display an
581: announcement including an appropriate copyright notice and a
582: notice that there is no warranty (or else, saying that you provide
583: a warranty) and that users may redistribute the program under
584: these conditions, and telling the user how to view a copy of this
585: License. (Exception: if the Program itself is interactive but
586: does not normally print such an announcement, your work based on
587: the Program is not required to print an announcement.)
588: @end enumerate
589:
590: These requirements apply to the modified work as a whole. If
591: identifiable sections of that work are not derived from the Program,
592: and can be reasonably considered independent and separate works in
593: themselves, then this License, and its terms, do not apply to those
594: sections when you distribute them as separate works. But when you
595: distribute the same sections as part of a whole which is a work based
596: on the Program, the distribution of the whole must be on the terms of
597: this License, whose permissions for other licensees extend to the
598: entire whole, and thus to each and every part regardless of who wrote it.
599:
600: Thus, it is not the intent of this section to claim rights or contest
601: your rights to work written entirely by you; rather, the intent is to
602: exercise the right to control the distribution of derivative or
603: collective works based on the Program.
604:
605: In addition, mere aggregation of another work not based on the Program
606: with the Program (or with a work based on the Program) on a volume of
607: a storage or distribution medium does not bring the other work under
608: the scope of this License.
609:
610: @item
611: You may copy and distribute the Program (or a work based on it,
612: under Section 2) in object code or executable form under the terms of
613: Sections 1 and 2 above provided that you also do one of the following:
614:
615: @enumerate a
616: @item
617: Accompany it with the complete corresponding machine-readable
618: source code, which must be distributed under the terms of Sections
619: 1 and 2 above on a medium customarily used for software interchange; or,
620:
621: @item
622: Accompany it with a written offer, valid for at least three
623: years, to give any third party, for a charge no more than your
624: cost of physically performing source distribution, a complete
625: machine-readable copy of the corresponding source code, to be
626: distributed under the terms of Sections 1 and 2 above on a medium
627: customarily used for software interchange; or,
628:
629: @item
630: Accompany it with the information you received as to the offer
631: to distribute corresponding source code. (This alternative is
632: allowed only for noncommercial distribution and only if you
633: received the program in object code or executable form with such
634: an offer, in accord with Subsection b above.)
635: @end enumerate
636:
637: The source code for a work means the preferred form of the work for
638: making modifications to it. For an executable work, complete source
639: code means all the source code for all modules it contains, plus any
640: associated interface definition files, plus the scripts used to
641: control compilation and installation of the executable. However, as a
642: special exception, the source code distributed need not include
643: anything that is normally distributed (in either source or binary
644: form) with the major components (compiler, kernel, and so on) of the
645: operating system on which the executable runs, unless that component
646: itself accompanies the executable.
647:
648: If distribution of executable or object code is made by offering
649: access to copy from a designated place, then offering equivalent
650: access to copy the source code from the same place counts as
651: distribution of the source code, even though third parties are not
652: compelled to copy the source along with the object code.
653:
654: @item
655: You may not copy, modify, sublicense, or distribute the Program
656: except as expressly provided under this License. Any attempt
657: otherwise to copy, modify, sublicense or distribute the Program is
658: void, and will automatically terminate your rights under this License.
659: However, parties who have received copies, or rights, from you under
660: this License will not have their licenses terminated so long as such
661: parties remain in full compliance.
662:
663: @item
664: You are not required to accept this License, since you have not
665: signed it. However, nothing else grants you permission to modify or
666: distribute the Program or its derivative works. These actions are
667: prohibited by law if you do not accept this License. Therefore, by
668: modifying or distributing the Program (or any work based on the
669: Program), you indicate your acceptance of this License to do so, and
670: all its terms and conditions for copying, distributing or modifying
671: the Program or works based on it.
672:
673: @item
674: Each time you redistribute the Program (or any work based on the
675: Program), the recipient automatically receives a license from the
676: original licensor to copy, distribute or modify the Program subject to
677: these terms and conditions. You may not impose any further
678: restrictions on the recipients' exercise of the rights granted herein.
679: You are not responsible for enforcing compliance by third parties to
680: this License.
681:
682: @item
683: If, as a consequence of a court judgment or allegation of patent
684: infringement or for any other reason (not limited to patent issues),
685: conditions are imposed on you (whether by court order, agreement or
686: otherwise) that contradict the conditions of this License, they do not
687: excuse you from the conditions of this License. If you cannot
688: distribute so as to satisfy simultaneously your obligations under this
689: License and any other pertinent obligations, then as a consequence you
690: may not distribute the Program at all. For example, if a patent
691: license would not permit royalty-free redistribution of the Program by
692: all those who receive copies directly or indirectly through you, then
693: the only way you could satisfy both it and this License would be to
694: refrain entirely from distribution of the Program.
695:
696: If any portion of this section is held invalid or unenforceable under
697: any particular circumstance, the balance of the section is intended to
698: apply and the section as a whole is intended to apply in other
699: circumstances.
700:
701: It is not the purpose of this section to induce you to infringe any
702: patents or other property right claims or to contest validity of any
703: such claims; this section has the sole purpose of protecting the
704: integrity of the free software distribution system, which is
705: implemented by public license practices. Many people have made
706: generous contributions to the wide range of software distributed
707: through that system in reliance on consistent application of that
708: system; it is up to the author/donor to decide if he or she is willing
709: to distribute software through any other system and a licensee cannot
710: impose that choice.
711:
712: This section is intended to make thoroughly clear what is believed to
713: be a consequence of the rest of this License.
714:
715: @item
716: If the distribution and/or use of the Program is restricted in
717: certain countries either by patents or by copyrighted interfaces, the
718: original copyright holder who places the Program under this License
719: may add an explicit geographical distribution limitation excluding
720: those countries, so that distribution is permitted only in or among
721: countries not thus excluded. In such case, this License incorporates
722: the limitation as if written in the body of this License.
723:
724: @item
725: The Free Software Foundation may publish revised and/or new versions
726: of the General Public License from time to time. Such new versions will
727: be similar in spirit to the present version, but may differ in detail to
728: address new problems or concerns.
729:
730: Each version is given a distinguishing version number. If the Program
731: specifies a version number of this License which applies to it and ``any
732: later version'', you have the option of following the terms and conditions
733: either of that version or of any later version published by the Free
734: Software Foundation. If the Program does not specify a version number of
735: this License, you may choose any version ever published by the Free Software
736: Foundation.
737:
738: @item
739: If you wish to incorporate parts of the Program into other free
740: programs whose distribution conditions are different, write to the author
741: to ask for permission. For software which is copyrighted by the Free
742: Software Foundation, write to the Free Software Foundation; we sometimes
743: make exceptions for this. Our decision will be guided by the two goals
744: of preserving the free status of all derivatives of our free software and
745: of promoting the sharing and reuse of software generally.
746:
747: @iftex
748: @heading NO WARRANTY
749: @end iftex
750: @ifinfo
751: @center NO WARRANTY
752: @end ifinfo
753:
754: @item
755: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
756: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
757: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
758: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
759: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
760: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
761: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
762: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
763: REPAIR OR CORRECTION.
764:
765: @item
766: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
767: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
768: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
769: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
770: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
771: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
772: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
773: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
774: POSSIBILITY OF SUCH DAMAGES.
775: @end enumerate
776:
777: @iftex
778: @heading END OF TERMS AND CONDITIONS
779: @end iftex
780: @ifinfo
781: @center END OF TERMS AND CONDITIONS
782: @end ifinfo
783:
784: @page
785: @unnumberedsec How to Apply These Terms to Your New Programs
786:
787: If you develop a new program, and you want it to be of the greatest
788: possible use to the public, the best way to achieve this is to make it
789: free software which everyone can redistribute and change under these terms.
790:
791: To do so, attach the following notices to the program. It is safest
792: to attach them to the start of each source file to most effectively
793: convey the exclusion of warranty; and each file should have at least
794: the ``copyright'' line and a pointer to where the full notice is found.
795:
796: @smallexample
797: @var{one line to give the program's name and a brief idea of what it does.}
798: Copyright (C) 19@var{yy} @var{name of author}
799:
800: This program is free software; you can redistribute it and/or modify
801: it under the terms of the GNU General Public License as published by
802: the Free Software Foundation; either version 2 of the License, or
803: (at your option) any later version.
804:
805: This program is distributed in the hope that it will be useful,
806: but WITHOUT ANY WARRANTY; without even the implied warranty of
807: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
808: GNU General Public License for more details.
809:
810: You should have received a copy of the GNU General Public License
811: along with this program; if not, write to the Free Software
812: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
813: @end smallexample
814:
815: Also add information on how to contact you by electronic and paper mail.
816:
817: If the program is interactive, make it output a short notice like this
818: when it starts in an interactive mode:
819:
820: @smallexample
821: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
822: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
823: type `show w'.
824: This is free software, and you are welcome to redistribute it
825: under certain conditions; type `show c' for details.
826: @end smallexample
827:
828: The hypothetical commands @samp{show w} and @samp{show c} should show
829: the appropriate parts of the General Public License. Of course, the
830: commands you use may be called something other than @samp{show w} and
831: @samp{show c}; they could even be mouse-clicks or menu items---whatever
832: suits your program.
833:
834: You should also get your employer (if you work as a programmer) or your
835: school, if any, to sign a ``copyright disclaimer'' for the program, if
836: necessary. Here is a sample; alter the names:
837:
838: @smallexample
839: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
840: `Gnomovision' (which makes passes at compilers) written by James Hacker.
841:
842: @var{signature of Ty Coon}, 1 April 1989
843: Ty Coon, President of Vice
844: @end smallexample
845:
846: This General Public License does not permit incorporating your program into
847: proprietary programs. If your program is a subroutine library, you may
848: consider it more useful to permit linking proprietary applications with the
849: library. If this is what you want to do, use the GNU Library General
850: Public License instead of this License.
851:
852: @iftex
853: @unnumbered Preface
854: @cindex Preface
1.21 crook 855: This manual documents Gforth. Some introductory material is provided for
856: readers who are unfamiliar with Forth or who are migrating to Gforth
857: from other Forth compilers. However, this manual is primarily a
858: reference manual.
1.1 anton 859: @end iftex
860:
1.28 crook 861: @comment TODO much more blurb here.
1.26 crook 862:
863: @c ******************************************************************
1.29 crook 864: @node Goals, Gforth Environment, License, Top
1.26 crook 865: @comment node-name, next, previous, up
866: @chapter Goals of Gforth
867: @cindex goals of the Gforth project
868: The goal of the Gforth Project is to develop a standard model for
869: ANS Forth. This can be split into several subgoals:
870:
871: @itemize @bullet
872: @item
873: Gforth should conform to the ANS Forth Standard.
874: @item
875: It should be a model, i.e. it should define all the
876: implementation-dependent things.
877: @item
878: It should become standard, i.e. widely accepted and used. This goal
879: is the most difficult one.
880: @end itemize
881:
882: To achieve these goals Gforth should be
883: @itemize @bullet
884: @item
885: Similar to previous models (fig-Forth, F83)
886: @item
887: Powerful. It should provide for all the things that are considered
888: necessary today and even some that are not yet considered necessary.
889: @item
890: Efficient. It should not get the reputation of being exceptionally
891: slow.
892: @item
893: Free.
894: @item
895: Available on many machines/easy to port.
896: @end itemize
897:
898: Have we achieved these goals? Gforth conforms to the ANS Forth
899: standard. It may be considered a model, but we have not yet documented
900: which parts of the model are stable and which parts we are likely to
901: change. It certainly has not yet become a de facto standard, but it
902: appears to be quite popular. It has some similarities to and some
903: differences from previous models. It has some powerful features, but not
904: yet everything that we envisioned. We certainly have achieved our
905: execution speed goals (@pxref{Performance}). It is free and available
906: on many machines.
907:
908: @menu
909: * Gforth Extensions Sinful?::
910: @end menu
911:
912: @node Gforth Extensions Sinful?, , Goals, Goals
913: @comment node-name, next, previous, up
914: @section Is it a Sin to use Gforth Extensions?
915: @cindex Gforth extensions
916:
917: If you've been paying attention, you will have realised that there is an
918: ANS (American National Standard) for Forth. As you read through the rest
1.29 crook 919: of this manual, you will see documentation for @i{Standard} words, and
920: documentation for some appealing Gforth @i{extensions}. You might ask
921: yourself the question: @i{``Given that there is a standard, would I be
1.26 crook 922: committing a sin to use (non-Standard) Gforth extensions?''}
923:
924: The answer to that question is somewhat pragmatic and somewhat
925: philosophical. Consider these points:
926:
927: @itemize @bullet
928: @item
929: A number of the Gforth extensions can be implemented in ANS Forth using
930: files provided in the @file{compat/} directory. These are mentioned in
931: the text in passing.
932: @item
933: Forth has a rich historical precedent for programmers taking advantage
934: of implementation-dependent features of their tools (for example,
935: relying on a knowledge of the dictionary structure). Sometimes these
936: techniques are necessary to extract every last bit of performance from
937: the hardware, sometimes they are just a programming shorthand.
938: @item
939: The best way to break the rules is to know what the rules are. To learn
940: the rules, there is no substitute for studying the text of the Standard
941: itself. In particular, Appendix A of the Standard (@var{Rationale})
942: provides a valuable insight into the thought processes of the technical
943: committee.
944: @item
945: The best reason to break a rule is because you have to; because it's
946: more productive to do that, because it makes your code run fast enough
947: or because you can see no Standard way to achieve what you want to
948: achieve.
949: @end itemize
950:
951: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
952: analyse your program and determine what non-Standard definitions it
953: relies upon.
954:
1.29 crook 955:
1.26 crook 956: @c ******************************************************************
1.29 crook 957: @node Gforth Environment, Introduction, Goals, Top
958: @chapter Gforth Environment
959: @cindex Gforth environment
1.21 crook 960:
1.29 crook 961: Note: ultimately, the gforth man page will be auto-generated from the
962: material in this chapter.
1.21 crook 963:
964: @menu
1.29 crook 965: * Invoking Gforth:: Getting in
966: * Leaving Gforth:: Getting out
967: * Command-line editing::
968: * Upper and lower case::
969: * Environment variables:: ..that affect how Gforth starts up
970: * Gforth Files:: What gets installed and where
1.21 crook 971: @end menu
972:
1.30 anton 973: @xref{Image Files} for related information about the creation of images.
1.29 crook 974:
1.21 crook 975: @comment ----------------------------------------------
1.29 crook 976: @node Invoking Gforth, Leaving Gforth, ,Gforth Environment
977: @section Invoking Gforth
978: @cindex invoking Gforth
979: @cindex running Gforth
980: @cindex command-line options
981: @cindex options on the command line
982: @cindex flags on the command line
1.21 crook 983:
1.30 anton 984: Gforth is made up of two parts; an executable ``engine'' (named
985: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
986: will usually just say @code{gforth} -- this automatically loads the
987: default image file @file{gforth.fi}. In many other cases the default
988: Gforth image will be invoked like this:
1.21 crook 989: @example
1.30 anton 990: gforth [file | -e forth-code] ...
1.21 crook 991: @end example
1.29 crook 992: @noindent
993: This interprets the contents of the files and the Forth code in the order they
994: are given.
1.21 crook 995:
1.30 anton 996: In addition to the @file{gforth} engine, there is also an engine called
997: @file{gforth-fast}, which is faster, but gives less informative error
998: messages (@pxref{Error messages}).
999:
1.29 crook 1000: In general, the command line looks like this:
1.21 crook 1001:
1002: @example
1.30 anton 1003: gforth[-fast] [engine options] [image options]
1.21 crook 1004: @end example
1005:
1.30 anton 1006: The engine options must come before the rest of the command
1.29 crook 1007: line. They are:
1.26 crook 1008:
1.29 crook 1009: @table @code
1010: @cindex -i, command-line option
1011: @cindex --image-file, command-line option
1012: @item --image-file @i{file}
1013: @itemx -i @i{file}
1014: Loads the Forth image @i{file} instead of the default
1015: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 1016:
1.29 crook 1017: @cindex --path, command-line option
1018: @cindex -p, command-line option
1019: @item --path @i{path}
1020: @itemx -p @i{path}
1021: Uses @i{path} for searching the image file and Forth source code files
1022: instead of the default in the environment variable @code{GFORTHPATH} or
1023: the path specified at installation time (e.g.,
1024: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
1025: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 1026:
1.29 crook 1027: @cindex --dictionary-size, command-line option
1028: @cindex -m, command-line option
1029: @cindex @i{size} parameters for command-line options
1030: @cindex size of the dictionary and the stacks
1031: @item --dictionary-size @i{size}
1032: @itemx -m @i{size}
1033: Allocate @i{size} space for the Forth dictionary space instead of
1034: using the default specified in the image (typically 256K). The
1035: @i{size} specification for this and subsequent options consists of
1036: an integer and a unit (e.g.,
1037: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
1038: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
1039: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
1040: @code{e} is used.
1.21 crook 1041:
1.29 crook 1042: @cindex --data-stack-size, command-line option
1043: @cindex -d, command-line option
1044: @item --data-stack-size @i{size}
1045: @itemx -d @i{size}
1046: Allocate @i{size} space for the data stack instead of using the
1047: default specified in the image (typically 16K).
1.21 crook 1048:
1.29 crook 1049: @cindex --return-stack-size, command-line option
1050: @cindex -r, command-line option
1051: @item --return-stack-size @i{size}
1052: @itemx -r @i{size}
1053: Allocate @i{size} space for the return stack instead of using the
1054: default specified in the image (typically 15K).
1.21 crook 1055:
1.29 crook 1056: @cindex --fp-stack-size, command-line option
1057: @cindex -f, command-line option
1058: @item --fp-stack-size @i{size}
1059: @itemx -f @i{size}
1060: Allocate @i{size} space for the floating point stack instead of
1061: using the default specified in the image (typically 15.5K). In this case
1062: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 1063:
1.29 crook 1064: @cindex --locals-stack-size, command-line option
1065: @cindex -l, command-line option
1066: @item --locals-stack-size @i{size}
1067: @itemx -l @i{size}
1068: Allocate @i{size} space for the locals stack instead of using the
1069: default specified in the image (typically 14.5K).
1.21 crook 1070:
1.29 crook 1071: @cindex -h, command-line option
1072: @cindex --help, command-line option
1073: @item --help
1074: @itemx -h
1075: Print a message about the command-line options
1.21 crook 1076:
1.29 crook 1077: @cindex -v, command-line option
1078: @cindex --version, command-line option
1079: @item --version
1080: @itemx -v
1081: Print version and exit
1.21 crook 1082:
1.29 crook 1083: @cindex --debug, command-line option
1084: @item --debug
1085: Print some information useful for debugging on startup.
1.21 crook 1086:
1.29 crook 1087: @cindex --offset-image, command-line option
1088: @item --offset-image
1089: Start the dictionary at a slightly different position than would be used
1090: otherwise (useful for creating data-relocatable images,
1091: @pxref{Data-Relocatable Image Files}).
1.21 crook 1092:
1.29 crook 1093: @cindex --no-offset-im, command-line option
1094: @item --no-offset-im
1095: Start the dictionary at the normal position.
1.21 crook 1096:
1.29 crook 1097: @cindex --clear-dictionary, command-line option
1098: @item --clear-dictionary
1099: Initialize all bytes in the dictionary to 0 before loading the image
1100: (@pxref{Data-Relocatable Image Files}).
1101:
1102: @cindex --die-on-signal, command-line-option
1103: @item --die-on-signal
1104: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
1105: or the segmentation violation SIGSEGV) by translating it into a Forth
1106: @code{THROW}. With this option, Gforth exits if it receives such a
1107: signal. This option is useful when the engine and/or the image might be
1108: severely broken (such that it causes another signal before recovering
1109: from the first); this option avoids endless loops in such cases.
1110: @end table
1111:
1112: @cindex loading files at startup
1113: @cindex executing code on startup
1114: @cindex batch processing with Gforth
1115: As explained above, the image-specific command-line arguments for the
1116: default image @file{gforth.fi} consist of a sequence of filenames and
1117: @code{-e @var{forth-code}} options that are interpreted in the sequence
1118: in which they are given. The @code{-e @var{forth-code}} or
1119: @code{--evaluate @var{forth-code}} option evaluates the Forth
1120: code. This option takes only one argument; if you want to evaluate more
1121: Forth words, you have to quote them or use @code{-e} several times. To exit
1122: after processing the command line (instead of entering interactive mode)
1123: append @code{-e bye} to the command line.
1124:
1125: @cindex versions, invoking other versions of Gforth
1126: If you have several versions of Gforth installed, @code{gforth} will
1127: invoke the version that was installed last. @code{gforth-@i{version}}
1128: invokes a specific version. You may want to use the option
1129: @code{--path}, if your environment contains the variable
1130: @code{GFORTHPATH}.
1131:
1132: Not yet implemented:
1133: On startup the system first executes the system initialization file
1134: (unless the option @code{--no-init-file} is given; note that the system
1135: resulting from using this option may not be ANS Forth conformant). Then
1136: the user initialization file @file{.gforth.fs} is executed, unless the
1137: option @code{--no-rc} is given; this file is first searched in @file{.},
1138: then in @file{~}, then in the normal path (see above).
1.21 crook 1139:
1140:
1141:
1.29 crook 1142: @comment ----------------------------------------------
1143: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
1144: @section Leaving Gforth
1145: @cindex Gforth - leaving
1146: @cindex leaving Gforth
1.21 crook 1147:
1.30 anton 1148: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
1149: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
1150: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1151: data are discarded. @xref{Image Files} for ways of saving the state of
1152: the system before leaving Gforth.
1.21 crook 1153:
1.29 crook 1154: doc-bye
1.21 crook 1155:
1.29 crook 1156: @comment ----------------------------------------------
1157: @node Command-line editing, Upper and lower case,Leaving Gforth,Gforth Environment
1158: @section Command-line editing
1159: @cindex command-line editing
1.21 crook 1160:
1.29 crook 1161: Gforth maintains a history file that records every line that you type to
1162: the text interpreter. This file is preserved between sessions, and is
1163: used to provide a command-line recall facility; if you type ctrl-P
1164: repeatedly you can recall successively older commands from this (or
1165: previous) session(s). The full list of command-line editing facilities is:
1.21 crook 1166:
1.30 anton 1167: @comment use @table? - anton
1.21 crook 1168: @itemize @bullet
1169: @item
1.30 anton 1170: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
1.29 crook 1171: commands from the history buffer.
1172: @item
1.30 anton 1173: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
1.29 crook 1174: from the history buffer.
1175: @item
1.30 anton 1176: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
1.29 crook 1177: @item
1.30 anton 1178: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
1.29 crook 1179: @item
1.30 anton 1180: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
1.29 crook 1181: closing up the line.
1182: @item
1.30 anton 1183: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
1.29 crook 1184: @item
1.30 anton 1185: @kbd{Ctrl-a} to move the cursor to the start of the line.
1.21 crook 1186: @item
1.30 anton 1187: @kbd{Ctrl-e} to move the cursor to the end of the line.
1.21 crook 1188: @item
1.30 anton 1189: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
1.29 crook 1190: line.
1.21 crook 1191: @item
1.30 anton 1192: @key{TAB} to step through all possible full-word completions of the word
1.29 crook 1193: currently being typed.
1.21 crook 1194: @item
1.30 anton 1195: @kbd{Ctrl-d} at the start of the line to terminate Gforth (gracefully,
1196: using @code{bye}).
1.21 crook 1197: @end itemize
1198:
1.29 crook 1199: When editing, displayable characters are inserted to the left of the
1200: cursor position; the line is always in ``insert'' (as opposed to
1201: ``overstrike'') mode.
1202:
1203: @cindex history file
1204: @cindex @file{.gforth-history}
1205: On Unix systems, the history file is @file{~/.gforth-history} by
1206: default@footnote{i.e. it is stored in the user's home directory.}. You
1207: can find out the name and location of your history file using:
1208:
1209: @example
1210: history-file type \ Unix-class systems
1.21 crook 1211:
1.29 crook 1212: history-file type \ Other systems
1213: history-dir type
1.21 crook 1214: @end example
1215:
1.29 crook 1216: If you enter long definitions by hand, you can use a text editor to
1217: paste them out of the history file into a Forth source file for reuse at
1218: a later time.
1219:
1220: Gforth never trims the size of the history file, so you should do this
1221: periodically, if necessary.
1222:
1223: @comment this is all defined in history.fs
1224:
1225:
1226:
1227: @comment ----------------------------------------------
1228: @node Upper and lower case, Environment variables,Command-line editing,Gforth Environment
1229: @section Upper and lower case
1230: @cindex case-sensitivity
1231: @cindex upper and lower case
1232:
1233: Gforth is case-insensitive, so you can enter definitions and invoke
1234: Standard words using upper, lower or mixed case (however,
1235: @pxref{core-idef, Implementation-defined options, Implementation-defined
1236: options}).
1237:
1.30 anton 1238: ANS Forth only @i{requires} implementations to recognise Standard words
1239: when they are typed entirely in upper case. Therefore, a Standard
1240: program must use upper case for all Standard words. You can use whatever
1241: case you like for words that you define, but in a standard program you
1242: have to use the words in the same case that you defined them.
1243:
1244: Gforth supports case sensitivity through @code{table}s (case-sensitive
1245: wordlists, @pxref{Word Lists}).
1246:
1247: Two people have asked how to convert Gforth to case sensitivity; while
1248: we think this is a bad idea, you can change all wordlists into tables
1249: like this:
1.29 crook 1250:
1.30 anton 1251: @example
1252: ' table-find forth-wordlist wordlist-map @ !
1253: @end example
1254:
1255: Note that you now have to type the predefined words in the same case
1256: that we defined them, which are varying. You may want to convert them
1257: to your favourite case before doing this operation (I won't explain how,
1258: because if you are even contemplating to do this, you'd better have
1259: enough knowledge of Forth systems to know this already).
1.29 crook 1260:
1261: @comment ----------------------------------------------
1262: @node Environment variables, Gforth Files, Upper and lower case,Gforth Environment
1263: @section Environment variables
1264: @cindex environment variables
1.21 crook 1265:
1.29 crook 1266: Gforth uses these environment variables:
1.21 crook 1267:
1.29 crook 1268: @itemize @bullet
1269: @item
1270: @cindex GFORTHHIST - environment variable
1271: GFORTHHIST - (Unix systems only) specifies the directory in which to
1272: open/create the history file, @file{.gforth-history}. Default:
1273: @code{$HOME}.
1.21 crook 1274:
1.29 crook 1275: @item
1276: @cindex GFORTHPATH - environment variable
1277: GFORTHPATH - specifies the path used when searching for the gforth image file and
1278: for Forth source-code files.
1.21 crook 1279:
1.29 crook 1280: @item
1281: @cindex GFORTH - environment variable
1282: GFORTH - used by @file{gforthmi} @xref{gforthmi}.
1.26 crook 1283:
1.29 crook 1284: @item
1285: @cindex GFORTHD - environment variable
1286: GFORTHD - used by @file{gforthmi} @xref{gforthmi}.
1.21 crook 1287:
1.29 crook 1288: @item
1289: @cindex TMP, TEMP - environment variable
1290: TMP, TEMP - (non-Unix systems only) used as a potential location for the
1291: history file.
1292: @end itemize
1.21 crook 1293:
1.29 crook 1294: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1295: @comment mentioning these.
1.21 crook 1296:
1.29 crook 1297: All the Gforth environment variables default to sensible values if they
1298: are not set.
1.21 crook 1299:
1300:
1.29 crook 1301: @comment ----------------------------------------------
1302: @node Gforth Files, ,Environment variables,Gforth Environment
1303: @section Gforth files
1304: @cindex Gforth files
1.21 crook 1305:
1.30 anton 1306: When you Gforth on a Unix system in the default places, it installs
1307: files in these locations:
1.21 crook 1308:
1.26 crook 1309: @itemize @bullet
1310: @item
1.29 crook 1311: @file{/usr/local/bin/gforth}
1312: @item
1313: @file{/usr/local/bin/gforthmi}
1314: @item
1315: @file{/usr/local/man/man1/gforth.1} - man page.
1316: @item
1317: @file{/usr/local/info} - the Info version of this manual.
1318: @item
1.30 anton 1319: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1.29 crook 1320: @item
1321: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1.26 crook 1322: @item
1.30 anton 1323: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1.26 crook 1324: @item
1.30 anton 1325: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1.26 crook 1326: @end itemize
1.21 crook 1327:
1.30 anton 1328: You can select different places for installation by using
1329: @code{configure} options (listed with @code{configure --help}).
1.21 crook 1330:
1.29 crook 1331: @c ******************************************************************
1332: @node Introduction, Words, Gforth Environment, Top
1333: @comment node-name, next, previous, up
1334: @chapter An Introduction to ANS Forth
1335: @cindex Forth - an introduction
1.21 crook 1336:
1.29 crook 1337: The primary purpose of this manual is to document Gforth. However, since
1338: Forth is not a widely-known language and there is a lack of up-to-date
1339: teaching material, it seems worthwhile to provide some introductory
1340: material. @xref{Forth-related information} for other sources of Forth-related
1341: information.
1.21 crook 1342:
1.29 crook 1343: The examples in this section should work on any ANS Forth; the
1344: output shown was produced using Gforth. Each example attempts to
1345: reproduce the exact output that Gforth produces. If you try out the
1346: examples (and you should), what you should type is shown @kbd{like this}
1347: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 1348: that, where the example shows @key{RET} it means that you should
1.29 crook 1349: press the ``carriage return'' key. Unfortunately, some output formats for
1350: this manual cannot show the difference between @kbd{this} and
1351: @code{this} which will make trying out the examples harder (but not
1352: impossible).
1.21 crook 1353:
1.29 crook 1354: Forth is an unusual language. It provides an interactive development
1355: environment which includes both an interpreter and compiler. Forth
1356: programming style encourages you to break a problem down into many
1357: @cindex factoring
1358: small fragments (@dfn{factoring}), and then to develop and test each
1359: fragment interactively. Forth advocates assert that breaking the
1360: edit-compile-test cycle used by conventional programming languages can
1361: lead to great productivity improvements.
1.21 crook 1362:
1.29 crook 1363: @menu
1364: * Introducing the Text Interpreter::
1365: * Stacks and Postfix notation::
1366: * Your first definition::
1367: * How does that work?::
1368: * Forth is written in Forth::
1369: * Review - elements of a Forth system::
1370: * Where to go next::
1371: * Exercises::
1372: @end menu
1.21 crook 1373:
1.29 crook 1374: @comment ----------------------------------------------
1375: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
1376: @section Introducing the Text Interpreter
1377: @cindex text interpreter
1378: @cindex outer interpreter
1.21 crook 1379:
1.30 anton 1380: @c IMO this is too detailed and the pace is too slow for
1381: @c an introduction. If you know German, take a look at
1382: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
1383: @c to see how I do it - anton
1384:
1.29 crook 1385: When you invoke the Forth image, you will see a startup banner printed
1386: and nothing else (if you have Gforth installed on your system, try
1.30 anton 1387: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 1388: its command line interpreter, which is called the @dfn{Text Interpreter}
1389: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.30 anton 1390: about the text interpreter as you read through this chapter, but
1391: @pxref{The Text Interpreter} for more detail).
1.21 crook 1392:
1.29 crook 1393: Although it's not obvious, Forth is actually waiting for your
1.30 anton 1394: input. Type a number and press the @key{RET} key:
1.21 crook 1395:
1.26 crook 1396: @example
1.30 anton 1397: @kbd{45@key{RET}} ok
1.26 crook 1398: @end example
1.21 crook 1399:
1.29 crook 1400: Rather than give you a prompt to invite you to input something, the text
1401: interpreter prints a status message @i{after} it has processed a line
1402: of input. The status message in this case (``@code{ ok}'' followed by
1403: carriage-return) indicates that the text interpreter was able to process
1404: all of your input successfully. Now type something illegal:
1405:
1406: @example
1.30 anton 1407: @kbd{qwer341@key{RET}}
1.29 crook 1408: :1: Undefined word
1409: qwer341
1410: ^^^^^^^
1411: $400D2BA8 Bounce
1412: $400DBDA8 no.extensions
1413: @end example
1.23 crook 1414:
1.29 crook 1415: The exact text, other than the ``Undefined word'' may differ slightly on
1416: your system, but the effect is the same; when the text interpreter
1417: detects an error, it discards any remaining text on a line, resets
1.30 anton 1418: certain internal state and prints an error message. @xref{Error
1419: messages} for a detailed description of error messages.
1.23 crook 1420:
1.29 crook 1421: The text interpreter waits for you to press carriage-return, and then
1422: processes your input line. Starting at the beginning of the line, it
1423: breaks the line into groups of characters separated by spaces. For each
1424: group of characters in turn, it makes two attempts to do something:
1.23 crook 1425:
1.29 crook 1426: @itemize @bullet
1427: @item
1428: It tries to treat it as a command. It does this by searching a @dfn{name
1429: dictionary}. If the group of characters matches an entry in the name
1430: dictionary, the name dictionary provides the text interpreter with
1431: information that allows the text interpreter perform some actions. In
1432: Forth jargon, we say that the group
1433: @cindex word
1434: @cindex definition
1435: @cindex execution token
1436: @cindex xt
1437: of characters names a @dfn{word}, that the dictionary search returns an
1438: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
1439: word, and that the text interpreter executes the xt. Often, the terms
1440: @dfn{word} and @dfn{definition} are used interchangeably.
1441: @item
1442: If the text interpreter fails to find a match in the name dictionary, it
1443: tries to treat the group of characters as a number in the current number
1444: base (when you start up Forth, the current number base is base 10). If
1445: the group of characters legitimately represents a number, the text
1446: interpreter pushes the number onto a stack (we'll learn more about that
1447: in the next section).
1448: @end itemize
1.23 crook 1449:
1.29 crook 1450: If the text interpreter is unable to do either of these things with any
1451: group of characters, it discards the group of characters and the rest of
1452: the line, then prints an error message. If the text interpreter reaches
1453: the end of the line without error, it prints the status message ``@code{ ok}''
1454: followed by carriage-return.
1.21 crook 1455:
1.29 crook 1456: This is the simplest command we can give to the text interpreter:
1.23 crook 1457:
1458: @example
1.30 anton 1459: @key{RET} ok
1.23 crook 1460: @end example
1.21 crook 1461:
1.29 crook 1462: The text interpreter did everything we asked it to do (nothing) without
1463: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
1464: command:
1.21 crook 1465:
1.23 crook 1466: @example
1.30 anton 1467: @kbd{12 dup fred dup@key{RET}}
1.29 crook 1468: :1: Undefined word
1469: 12 dup fred dup
1470: ^^^^
1471: $400D2BA8 Bounce
1472: $400DBDA8 no.extensions
1.23 crook 1473: @end example
1.21 crook 1474:
1.29 crook 1475: When you press the carriage-return key, the text interpreter starts to
1476: work its way along the line:
1.21 crook 1477:
1.29 crook 1478: @itemize @bullet
1479: @item
1480: When it gets to the space after the @code{2}, it takes the group of
1481: characters @code{12} and looks them up in the name
1482: dictionary@footnote{We can't tell if it found them or not, but assume
1483: for now that it did not}. There is no match for this group of characters
1484: in the name dictionary, so it tries to treat them as a number. It is
1485: able to do this successfully, so it puts the number, 12, ``on the stack''
1486: (whatever that means).
1487: @item
1488: The text interpreter resumes scanning the line and gets the next group
1489: of characters, @code{dup}. It looks it up in the name dictionary and
1490: (you'll have to take my word for this) finds it, and executes the word
1491: @code{dup} (whatever that means).
1492: @item
1493: Once again, the text interpreter resumes scanning the line and gets the
1494: group of characters @code{fred}. It looks them up in the name
1495: dictionary, but can't find them. It tries to treat them as a number, but
1496: they don't represent any legal number.
1497: @end itemize
1.21 crook 1498:
1.29 crook 1499: At this point, the text interpreter gives up and prints an error
1500: message. The error message shows exactly how far the text interpreter
1501: got in processing the line. In particular, it shows that the text
1502: interpreter made no attempt to do anything with the final character
1503: group, @code{dup}, even though we have good reason to believe that the
1504: text interpreter would have no problem looking that word up and
1505: executing it a second time.
1.21 crook 1506:
1507:
1.29 crook 1508: @comment ----------------------------------------------
1509: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
1510: @section Stacks, postfix notation and parameter passing
1511: @cindex text interpreter
1512: @cindex outer interpreter
1.21 crook 1513:
1.29 crook 1514: In procedural programming languages (like C and Pascal), the
1515: building-block of programs is the @dfn{function} or @dfn{procedure}. These
1516: functions or procedures are called with @dfn{explicit parameters}. For
1517: example, in C we might write:
1.21 crook 1518:
1.23 crook 1519: @example
1.29 crook 1520: total = total + new_volume(length,height,depth);
1.23 crook 1521: @end example
1.21 crook 1522:
1.23 crook 1523: @noindent
1.29 crook 1524: where new_volume is a function-call to another piece of code, and total,
1525: length, height and depth are all variables. length, height and depth are
1526: parameters to the function-call.
1.21 crook 1527:
1.29 crook 1528: In Forth, the equivalent of the function or procedure is the
1529: @dfn{definition} and parameters are implicitly passed between
1530: definitions using a shared stack that is visible to the
1531: programmer. Although Forth does support variables, the existence of the
1532: stack means that they are used far less often than in most other
1533: programming languages. When the text interpreter encounters a number, it
1534: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 1535: actual number is implementation-dependent ...) and the particular stack
1.29 crook 1536: used for any operation is implied unambiguously by the operation being
1537: performed. The stack used for all integer operations is called the @dfn{data
1538: stack} and, since this is the stack used most commonly, references to
1539: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 1540:
1.29 crook 1541: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 1542:
1.23 crook 1543: @example
1.30 anton 1544: @kbd{1 2 3@key{RET}} ok
1.23 crook 1545: @end example
1.21 crook 1546:
1.29 crook 1547: Then this instructs the text interpreter to placed three numbers on the
1548: (data) stack. An analogy for the behaviour of the stack is to take a
1549: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
1550: the table. The 3 was the last card onto the pile (``last-in'') and if
1551: you take a card off the pile then, unless you're prepared to fiddle a
1552: bit, the card that you take off will be the 3 (``first-out''). The
1553: number that will be first-out of the stack is called the @dfn{top of
1554: stack}, which
1555: @cindex TOS definition
1556: is often abbreviated to @dfn{TOS}.
1.21 crook 1557:
1.29 crook 1558: To understand how parameters are passed in Forth, consider the
1559: behaviour of the definition @code{+} (pronounced ``plus''). You will not
1560: be surprised to learn that this definition performs addition. More
1561: precisely, it adds two number together and produces a result. Where does
1562: it get the two numbers from? It takes the top two numbers off the
1563: stack. Where does it place the result? On the stack. You can act-out the
1564: behaviour of @code{+} with your playing cards like this:
1.21 crook 1565:
1566: @itemize @bullet
1567: @item
1.29 crook 1568: Pick up two cards from the stack on the table
1.21 crook 1569: @item
1.29 crook 1570: Stare at them intently and ask yourself ``what @i{is} the sum of these two
1571: numbers''
1.21 crook 1572: @item
1.29 crook 1573: Decide that the answer is 5
1.21 crook 1574: @item
1.29 crook 1575: Shuffle the two cards back into the pack and find a 5
1.21 crook 1576: @item
1.29 crook 1577: Put a 5 on the remaining ace that's on the table.
1.21 crook 1578: @end itemize
1579:
1.29 crook 1580: If you don't have a pack of cards handy but you do have Forth running,
1581: you can use the definition @code{.s} to show the current state of the stack,
1582: without affecting the stack. Type:
1.21 crook 1583:
1584: @example
1.30 anton 1585: @kbd{clearstack 1 2 3@key{RET}} ok
1586: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 1587: @end example
1588:
1.29 crook 1589: The text interpreter looks up the word @code{clearstack} and executes
1590: it; it tidies up the stack and removes any entries that may have been
1591: left on it by earlier examples. The text interpreter pushes each of the
1592: three numbers in turn onto the stack. Finally, the text interpreter
1593: looks up the word @code{.s} and executes it. The effect of executing
1594: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
1595: followed by a list of all the items on the stack; the item on the far
1596: right-hand side is the TOS.
1.21 crook 1597:
1.29 crook 1598: You can now type:
1.21 crook 1599:
1.29 crook 1600: @example
1.30 anton 1601: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 1602: @end example
1.21 crook 1603:
1.29 crook 1604: @noindent
1605: which is correct; there are now 2 items on the stack and the result of
1606: the addition is 5.
1.23 crook 1607:
1.29 crook 1608: If you're playing with cards, try doing a second addition: pick up the
1609: two cards, work out that their sum is 6, shuffle them into the pack,
1610: look for a 6 and place that on the table. You now have just one item on
1611: the stack. What happens if you try to do a third addition? Pick up the
1612: first card, pick up the second card -- ah! There is no second card. This
1613: is called a @dfn{stack underflow} and consitutes an error. If you try to
1614: do the same thing with Forth it will report an error (probably a Stack
1615: Underflow or an Invalid Memory Address error).
1.23 crook 1616:
1.29 crook 1617: The opposite situation to a stack underflow is a @dfn{stack overflow},
1618: which simply accepts that there is a finite amount of storage space
1619: reserved for the stack. To stretch the playing card analogy, if you had
1620: enough packs of cards and you piled the cards up on the table, you would
1621: eventually be unable to add another card; you'd hit the ceiling. Gforth
1622: allows you to set the maximum size of the stacks. In general, the only
1623: time that you will get a stack overflow is because a definition has a
1624: bug in it and is generating data on the stack uncontrollably.
1.23 crook 1625:
1.29 crook 1626: There's one final use for the playing card analogy. If you model your
1627: stack using a pack of playing cards, the maximum number of items on
1628: your stack will be 52 (I assume you didn't use the Joker). The maximum
1629: @i{value} of any item on the stack is 13 (the King). In fact, the only
1630: possible numbers are positive integer numbers 1 through 13; you can't
1631: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
1632: think about some of the cards, you can accommodate different
1633: numbers. For example, you could think of the Jack as representing 0,
1634: the Queen as representing -1 and the King as representing -2. Your
1635: *range* remains unchanged (you can still only represent a total of 13
1636: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 1637:
1.29 crook 1638: In that analogy, the limit was the amount of information that a single
1639: stack entry could hold, and Forth has a similar limit. In Forth, the
1640: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
1641: implementation dependent and affects the maximum value that a stack
1642: entry can hold. A Standard Forth provides a cell size of at least
1643: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 1644:
1.29 crook 1645: Forth does not do any type checking for you, so you are free to
1646: manipulate and combine stack items in any way you wish. A convenient way
1647: of treating stack items is as 2's complement signed integers, and that
1648: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 1649:
1.29 crook 1650: @example
1.30 anton 1651: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 1652: @end example
1.21 crook 1653:
1.29 crook 1654: If you use numbers and definitions like @code{+} in order to turn Forth
1655: into a great big pocket calculator, you will realise that it's rather
1656: different from a normal calculator. Rather than typing 2 + 3 = you had
1657: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
1658: result). The terminology used to describe this difference is to say that
1659: your calculator uses @dfn{Infix Notation} (parameters and operators are
1660: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
1661: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 1662:
1.29 crook 1663: Whilst postfix notation might look confusing to begin with, it has
1664: several important advantages:
1.21 crook 1665:
1.23 crook 1666: @itemize @bullet
1667: @item
1.29 crook 1668: it is unambiguous
1.23 crook 1669: @item
1.29 crook 1670: it is more concise
1.23 crook 1671: @item
1.29 crook 1672: it fits naturally with a stack-based system
1.23 crook 1673: @end itemize
1.21 crook 1674:
1.29 crook 1675: To examine these claims in more detail, consider these sums:
1.21 crook 1676:
1.29 crook 1677: @example
1678: 6 + 5 * 4 =
1679: 4 * 5 + 6 =
1680: @end example
1.21 crook 1681:
1.29 crook 1682: If you're just learning maths or your maths is very rusty, you will
1683: probably come up with the answer 44 for the first and 26 for the
1684: second. If you are a bit of a whizz at maths you will remember the
1685: @i{convention} that multiplication takes precendence over addition, and
1686: you'd come up with the answer 26 both times. To explain the answer 26
1687: to someone who got the answer 44, you'd probably rewrite the first sum
1688: like this:
1.21 crook 1689:
1.29 crook 1690: @example
1691: 6 + (5 * 4) =
1692: @end example
1.21 crook 1693:
1.29 crook 1694: If what you really wanted was to perform the addition before the
1695: multiplication, you would have to use parentheses to force it.
1.21 crook 1696:
1.29 crook 1697: If you did the first two sums on a pocket calculator you would probably
1698: get the right answers, unless you were very cautious and entered them using
1699: these keystroke sequences:
1.21 crook 1700:
1.29 crook 1701: 6 + 5 = * 4 =
1702: 4 * 5 = + 6 =
1.21 crook 1703:
1.29 crook 1704: Postfix notation is unambiguous because the order that the operators
1705: are applied is always explicit; that also means that parentheses are
1706: never required. The operators are @i{active} (the act of quoting the
1707: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 1708:
1.29 crook 1709: The sum 6 + 5 * 4 can be written (in postfix notation) in two
1710: equivalent ways:
1.26 crook 1711:
1712: @example
1.29 crook 1713: 6 5 4 * + or:
1714: 5 4 * 6 +
1.26 crook 1715: @end example
1.23 crook 1716:
1.29 crook 1717: An important thing that you should notice about this notation is that
1718: the @i{order} of the numbers does not change; if you want to subtract
1719: 2 from 10 you type @code{10 2 -}.
1.1 anton 1720:
1.29 crook 1721: The reason that Forth uses postfix notation is very simple to explain: it
1722: makes the implementation extremely simple, and it follows naturally from
1723: using the stack as a mechanism for passing parameters. Another way of
1724: thinking about this is to realise that all Forth definitions are
1725: @i{active}; they execute as they are encountered by the text
1726: interpreter. The result of this is that the syntax of Forth is trivially
1727: simple.
1.1 anton 1728:
1729:
1730:
1.29 crook 1731: @comment ----------------------------------------------
1732: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
1733: @section Your first Forth definition
1734: @cindex first definition
1.1 anton 1735:
1.29 crook 1736: Until now, the examples we've seen have been trivial; we've just been
1737: using Forth as a bigger-than-pocket calculator. Also, each calculation
1738: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
1739: again@footnote{That's not quite true. If you press the up-arrow key on
1740: your keyboard you should be able to scroll back to any earlier command,
1741: edit it and re-enter it.} In this section we'll see how to add new
1742: words to Forth's vocabulary.
1.1 anton 1743:
1.29 crook 1744: The easiest way to create a new word is to use a @dfn{colon
1745: definition}. We'll define a few and try them out before worrying too
1746: much about how they work. Try typing in these examples; be careful to
1747: copy the spaces accurately:
1.1 anton 1748:
1.29 crook 1749: @example
1750: : add-two 2 + . ;
1751: : greet ." Hello and welcome" ;
1752: : demo 5 add-two ;
1753: @end example
1.1 anton 1754:
1.29 crook 1755: @noindent
1756: Now try them out:
1.1 anton 1757:
1.29 crook 1758: @example
1.30 anton 1759: @kbd{greet@key{RET}} Hello and welcome ok
1760: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
1761: @kbd{4 add-two@key{RET}} 6 ok
1762: @kbd{demo@key{RET}} 7 ok
1763: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 1764: @end example
1.1 anton 1765:
1.29 crook 1766: The first new thing that we've introduced here is the pair of words
1767: @code{:} and @code{;}. These are used to start and terminate a new
1768: definition, respectively. The first word after the @code{:} is the name
1769: for the new definition.
1.1 anton 1770:
1.29 crook 1771: As you can see from the examples, a definition is built up of words that
1772: have already been defined; Forth makes no distinction between
1773: definitions that existed when you started the system up, and those that
1774: you define yourself.
1.1 anton 1775:
1.29 crook 1776: The examples also introduce the words @code{.} (dot), @code{."}
1777: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
1778: the stack and displays it. It's like @code{.s} except that it only
1779: displays the top item of the stack and it is destructive; after it has
1780: executed, the number is no longer on the stack. There is always one
1781: space printed after the number, and no spaces before it. Dot-quote
1782: defines a string (a sequence of characters) that will be printed when
1783: the word is executed. The string can contain any printable characters
1784: except @code{"}. A @code{"} has a special function; it is not a Forth
1785: word but it acts as a delimiter (the way that delimiters work is
1786: described in the next section). Finally, @code{dup} duplicates the value
1787: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 1788:
1.29 crook 1789: We already know that the text interpreter searches through the
1790: dictionary to locate names. If you've followed the examples earlier, you
1791: will already have a definition called @code{add-two}. Lets try modifying
1792: it by typing in a new definition:
1.1 anton 1793:
1.29 crook 1794: @example
1.30 anton 1795: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 1796: @end example
1.5 anton 1797:
1.29 crook 1798: Forth recognised that we were defining a word that already exists, and
1799: printed a message to warn us of that fact. Let's try out the new
1800: definition:
1.5 anton 1801:
1.29 crook 1802: @example
1.30 anton 1803: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 1804: @end example
1.1 anton 1805:
1.29 crook 1806: @noindent
1807: All that we've actually done here, though, is to create a new
1808: definition, with a particular name. The fact that there was already a
1809: definition with the same name did not make any difference to the way
1810: that the new definition was created (except that Forth printed a warning
1811: message). The old definition of add-two still exists (try @code{demo}
1812: again to see that this is true). Any new definition will use the new
1813: definition of @code{add-two}, but old definitions continue to use the
1814: version that already existed at the time that they were @code{compiled}.
1.1 anton 1815:
1.29 crook 1816: Before you go on to the next section, try defining and redefining some
1817: words of your own.
1.1 anton 1818:
1.29 crook 1819: @comment ----------------------------------------------
1820: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
1821: @section How does that work?
1822: @cindex parsing words
1.1 anton 1823:
1.30 anton 1824: @c That's pretty deep (IMO way too deep) for an introduction. - anton
1825:
1826: @c Is it a good idea to talk about the interpretation semantics of a
1827: @c number? We don't have an xt to go along with it. - anton
1828:
1829: @c Now that I have eliminated execution semantics, I wonder if it would not
1830: @c be better to keep them (or add run-time semantics), to make it easier to
1831: @c explain what compilation semantics usually does. - anton
1832:
1.29 crook 1833: Now we're going to take another look at the definition of @code{add-two}
1834: from the previous section. From our knowledge of the way that the text
1835: interpreter works, we would have expected this result when we tried to
1836: define @code{add-two}:
1.21 crook 1837:
1.29 crook 1838: @example
1.30 anton 1839: @kbd{: add-two 2 + . " ;@key{RET}}
1.29 crook 1840: ^^^^^^^
1841: Error: Undefined word
1842: @end example
1.28 crook 1843:
1.29 crook 1844: The reason that this didn't happen is bound up in the way that @code{:}
1845: works. The word @code{:} does two special things. The first special
1846: thing that it does prevents the text interpreter from ever seeing the
1847: characters @code{add-two}. The text interpreter uses a variable called
1848: @cindex modifying >IN
1849: @code{>IN} (pronounced ''to-in'') to keep track of where it is in the
1850: input line. When it encounters the word @code{:} it behaves in exactly
1851: the same way as it does for any other word; it looks it up in the name
1852: dictionary, finds its xt and executes it. When @code{:} executes, it
1853: looks at the input buffer, finds the word @code{add-two} and advances the
1854: value of @code{>IN} to point past it. It then does some other stuff
1855: associated with creating the new definition (including creating an entry
1856: for @code{add-two} in the name dictionary). When the execution of @code{:}
1857: completes, control returns to the text interpreter, which is oblivious
1858: to the fact that it has been tricked into ignoring part of the input
1859: line.
1.21 crook 1860:
1.29 crook 1861: @cindex parsing words
1862: Words like @code{:} -- words that advance the value of @code{>IN} and so
1863: prevent the text interpreter from acting on the whole of the input line
1864: -- are called @dfn{parsing words}.
1.21 crook 1865:
1.29 crook 1866: @cindex @code{state} - effect on the text interpreter
1867: @cindex text interpreter - effect of state
1868: The second special thing that @code{:} does is change the value of a
1869: variable called @code{state}, which affects the way that the text
1870: interpreter behaves. When Gforth starts up, @code{state} has the value
1871: 0, and the text interpreter is said to be @dfn{interpreting}. During a
1872: colon definition (started with @code{:}), @code{state} is set to -1 and
1873: the text interpreter is said to be @dfn{compiling}. The word @code{;}
1874: ends the definition -- one of the things that it does is to change the
1875: value of @code{state} back to 0.
1.21 crook 1876:
1.29 crook 1877: We have already seen how the text interpreter behaves when it is
1878: interpreting; it looks for each character sequence in the dictionary,
1879: finds its xt and executes it, or it converts it to a number and pushes
1880: it onto the stack, or it fails to do either and generates an error.
1.21 crook 1881:
1.29 crook 1882: When the text interpreter is compiling, its behaviour is slightly
1883: different; it still looks for each character sequence in the dictionary
1.30 anton 1884: and finds it, or converts it to a number, or fails to do either and
1885: generates an error. But instead of the execution token of a word it
1886: finds and executes the compilation token. For most words executing the
1887: compilation token results in laying down (@dfn{compiling}) the execution
1888: token, i.e., some magic to make that xt or number get executed or pushed
1889: at a later time; at the time that @code{add-two} is
1890: @dfn{executed}. Therefore, when you execute @code{add-two} its
1891: @dfn{run-time effect} is exactly the same as if you had typed @code{2 +
1892: .} outside of a definition, and pressed carriage-return.
1.28 crook 1893:
1.30 anton 1894: In Forth, every word or number can be described in terms of two
1.29 crook 1895: properties:
1.28 crook 1896:
1897: @itemize @bullet
1898: @item
1.30 anton 1899: Its @dfn{interpretation semantics}, represented by the execution token.
1.28 crook 1900: @item
1.30 anton 1901: Its @dfn{compilation semantics}, represented by the compilation token.
1.29 crook 1902: @end itemize
1903:
1.30 anton 1904: The value of @code{state} determines whether the text interpreter will
1905: use the compilation or interpretation semantics of a word or number that
1906: it encounters.
1.29 crook 1907:
1908: @itemize @bullet
1.28 crook 1909: @item
1.29 crook 1910: @cindex interpretation semantics
1911: When the text interpreter encounters a word or number in @dfn{interpret}
1912: state, it performs the @dfn{interpretation semantics} of the word or
1913: number.
1.28 crook 1914: @item
1.29 crook 1915: @cindex compilation semantics
1916: When the text interpreter encounters a word or number in @dfn{compile}
1917: state, it performs the @dfn{compilation semantics} of the word or
1918: number.
1919: @end itemize
1920:
1921: @noindent
1922: Numbers are always treated in a fixed way:
1923:
1924: @itemize @bullet
1.28 crook 1925: @item
1.30 anton 1926: When the number is @dfn{interpreted}, its behaviour is to push the number onto the stack.
1.28 crook 1927: @item
1.30 anton 1928: When the number is @dfn{compiled}, a piece of code is appended to the
1929: current definition that pushes the number when it runs. (In other words,
1930: the compilation semantics of a number are to postpone its interpretation
1931: semantics until the run-time of the definition that it is being compiled
1932: into.)
1.29 crook 1933: @end itemize
1934:
1935: The behaviour of a word is not so regular, but most have @i{default
1.30 anton 1936: compilation semantics} which means that they behave like this:
1.29 crook 1937:
1938: @itemize @bullet
1.28 crook 1939: @item
1.30 anton 1940: The @dfn{interpretation semantics} of the word are to do something useful.
1941: @item
1.29 crook 1942: The @dfn{compilation semantics} of the word are to append its
1.30 anton 1943: @dfn{interpretation semantics} to the current definition (so that its
1944: run-time behaviour is to do something useful).
1.28 crook 1945: @end itemize
1946:
1.30 anton 1947: @cindex immediate words
1.29 crook 1948: The actual behaviour of any particular word depends upon the way in
1949: which it was defined. When the text interpreter finds the word in the
1950: name dictionary, it not only retrieves the xt for the word, it also
1951: retrieves some flags: the @dfn{compile-only} flag and the @dfn{immediate
1952: flag}. The compile-only flag indicates that the word has no
1.30 anton 1953: interpretation semantics (the run-time behaviour for the default
1954: compilation semantics is not affected by this flag, however); any
1955: attempt to interpret a word that has the compile-only flag set will
1956: generate an error (for example, @code{IF} has no interpretation
1957: semantics). The immediate flag changes the compilation semantics of the
1958: word; if it is set, the compilation semantics are equal to the
1959: interpretation semantics (again ignoring the compile-only flag). it. In
1960: other words, these so-called @dfn{immediate} words behave like this:
1.29 crook 1961:
1962: @itemize @bullet
1963: @item
1.30 anton 1964: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 1965: @item
1.30 anton 1966: The @dfn{compilation semantics} of the word are to do something useful
1967: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 1968: @end itemize
1.28 crook 1969:
1.29 crook 1970: This example shows the difference between an immediate and a
1971: non-immediate word:
1.28 crook 1972:
1.29 crook 1973: @example
1974: : show-state state @@ . ;
1975: : show-state-now show-state ; immediate
1976: : word1 show-state ;
1977: : word2 show-state-now ;
1.28 crook 1978: @end example
1.23 crook 1979:
1.29 crook 1980: The word @code{immediate} after the definition of @code{show-state-now}
1981: makes that word an immediate word. These definitions introduce a new
1982: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
1983: variable, and leaves it on the stack. Therefore, the behaviour of
1984: @code{show-state} is to print a number that represents the current value
1985: of @code{state}.
1.28 crook 1986:
1.29 crook 1987: When you execute @code{word1}, it prints the number 0, indicating that
1988: the system is interpreting. When the text interpreter compiled the
1989: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 1990: compilation semantics are to append its interpretation semantics to the
1.29 crook 1991: current definition. When you execute @code{word1}, it performs the
1.30 anton 1992: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 1993: (and therefore @code{show-state}) are executed, the system is
1994: interpreting.
1.28 crook 1995:
1.30 anton 1996: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 1997: you should have seen the number -1 printed, followed by ``@code{
1998: ok}''. When the text interpreter compiled the definition of
1999: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 2000: whose compilation semantics are therefore to perform its interpretation
1.29 crook 2001: semantics. It is executed straight away (even before the text
2002: interpreter has moved on to process another group of characters; the
2003: @code{;} in this example). The effect of executing it are to display the
2004: value of @code{state} @i{at the time that the definition of}
2005: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
2006: system is compiling at this time. If you execute @code{word2} it does
2007: nothing at all.
1.28 crook 2008:
1.29 crook 2009: @cindex @code{."}, how it works
2010: Before leaving the subject of immediate words, consider the behaviour of
2011: @code{."} in the definition of @code{greet}, in the previous
2012: section. This word is both a parsing word and an immediate word. Notice
2013: that there is a space between @code{."} and the start of the text
2014: @code{Hello and welcome}, but that there is no space between the last
2015: letter of @code{welcome} and the @code{"} character. The reason for this
2016: is that @code{."} is a Forth word; it must have a space after it so that
2017: the text interpreter can identify it. The @code{"} is not a Forth word;
2018: it is a @dfn{delimiter}. The examples earlier show that, when the string
2019: is displayed, there is neither a space before the @code{H} nor after the
2020: @code{e}. Since @code{."} is an immediate word, it executes at the time
2021: that @code{greet} is defined. When it executes, its behaviour is to
2022: search forward in the input line looking for the delimiter. When it
2023: finds the delimiter, it updates @code{>IN} to point past the
2024: delimiter. It also compiles some magic code into the definition of
2025: @code{greet}; the xt of a run-time routine that prints a text string. It
2026: compiles the string @code{Hello and welcome} into memory so that it is
2027: available to be printed later. When the text interpreter gains control,
2028: the next word it finds in the input stream is @code{;} and so it
2029: terminates the definition of @code{greet}.
1.28 crook 2030:
2031:
2032: @comment ----------------------------------------------
1.29 crook 2033: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
2034: @section Forth is written in Forth
2035: @cindex structure of Forth programs
2036:
2037: When you start up a Forth compiler, a large number of definitions
2038: already exist. In Forth, you develop a new application using bottom-up
2039: programming techniques to create new definitions that are defined in
2040: terms of existing definitions. As you create each definition you can
2041: test and debug it interactively.
2042:
2043: If you have tried out the examples in this section, you will probably
2044: have typed them in by hand; when you leave Gforth, your definitions will
2045: be lost. You can avoid this by using a text editor to enter Forth source
2046: code into a file, and then loading code from the file using
2047: @code{include} (@xref{Forth source files}). A Forth source file is
2048: processed by the text interpreter, just as though you had typed it in by
2049: hand@footnote{Actually, there are some subtle differences -- see
2050: @ref{The Text Interpreter}.}.
2051:
2052: Gforth also supports the traditional Forth alternative to using text
2053: files for program entry (@xref{Blocks}).
1.28 crook 2054:
1.29 crook 2055: In common with many, if not most, Forth compilers, most of Gforth is
2056: actually written in Forth. All of the @file{.fs} files in the
2057: installation directory@footnote{For example,
1.30 anton 2058: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 2059: study to see examples of Forth programming.
1.28 crook 2060:
1.29 crook 2061: Gforth maintains a history file that records every line that you type to
2062: the text interpreter. This file is preserved between sessions, and is
2063: used to provide a command-line recall facility. If you enter long
2064: definitions by hand, you can use a text editor to paste them out of the
2065: history file into a Forth source file for reuse at a later time
2066: (@pxref{Command-line editing} for more information).
1.28 crook 2067:
2068:
2069: @comment ----------------------------------------------
1.29 crook 2070: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
2071: @section Review - elements of a Forth system
2072: @cindex elements of a Forth system
1.28 crook 2073:
1.29 crook 2074: To summarise this chapter:
1.28 crook 2075:
2076: @itemize @bullet
2077: @item
1.29 crook 2078: Forth programs use @dfn{factoring} to break a problem down into small
2079: fragments called @dfn{words} or @dfn{definitions}.
2080: @item
2081: Forth program development is an interactive process.
2082: @item
2083: The main command loop that accepts input, and controls both
2084: interpretation and compilation, is called the @dfn{text interpreter}
2085: (also known as the @dfn{outer interpreter}).
2086: @item
2087: Forth has a very simple syntax, consisting of words and numbers
2088: separated by spaces or carriage-return characters. Any additional syntax
2089: is imposed by @dfn{parsing words}.
2090: @item
2091: Forth uses a stack to pass parameters between words. As a result, it
2092: uses postfix notation.
2093: @item
2094: To use a word that has previously been defined, the text interpreter
2095: searches for the word in the @dfn{name dictionary}.
2096: @item
1.30 anton 2097: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 2098: @item
1.29 crook 2099: The text interpreter uses the value of @code{state} to select between
2100: the use of the @dfn{interpretation semantics} and the @dfn{compilation
2101: semantics} of a word that it encounters.
1.28 crook 2102: @item
1.30 anton 2103: The relationship between the @dfn{interpretation semantics} and
2104: @dfn{compilation semantics} for a word
1.29 crook 2105: depend upon the way in which the word was defined (for example, whether
2106: it is an @dfn{immediate} word).
1.28 crook 2107: @item
1.29 crook 2108: Forth definitions can be implemented in Forth (called @dfn{high-level
2109: definitions}) or in some other way (usually a lower-level language and
2110: as a result often called @dfn{low-level definitions}, @dfn{code
2111: definitions} or @dfn{primitives}).
1.28 crook 2112: @item
1.29 crook 2113: Many Forth systems are implemented mainly in Forth.
1.28 crook 2114: @end itemize
2115:
2116:
1.29 crook 2117: @comment ----------------------------------------------
2118: @node Where to go next,Exercises,Review - elements of a Forth system, Introduction
2119: @section Where To Go Next
2120: @cindex where to go next
1.28 crook 2121:
1.29 crook 2122: Amazing as it may seem, if you have read (and understood) this far, you
2123: know almost all the fundamentals about the inner workings of a Forth
2124: system. You certainly know enough to be able to read and understand the
2125: rest of this manual and the ANS Forth document, to learn more about the
2126: facilities that Forth in general and Gforth in particular provide. Even
2127: scarier, you know almost enough to implement your own Forth system.
1.30 anton 2128: However, that's not a good idea just yet... better to try writing some
1.29 crook 2129: programs in Gforth.
1.28 crook 2130:
1.29 crook 2131: Forth has such a rich vocabulary that it can be hard to know where to
2132: start in learning it. This section suggests a few sets of words that are
2133: enough to write small but useful programs. Use the word index in this
2134: document to learn more about each word, then try it out and try to write
2135: small definitions using it. Start by experimenting with these words:
1.28 crook 2136:
2137: @itemize @bullet
2138: @item
1.29 crook 2139: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
2140: @item
2141: Comparison: @code{MIN MAX =}
2142: @item
2143: Logic: @code{AND OR XOR NOT}
2144: @item
2145: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 2146: @item
1.29 crook 2147: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 2148: @item
1.29 crook 2149: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 2150: @item
1.29 crook 2151: Defining words: @code{: ; CREATE}
1.28 crook 2152: @item
1.29 crook 2153: Memory allocation words: @code{ALLOT ,}
1.28 crook 2154: @item
1.29 crook 2155: Tools: @code{SEE WORDS .S MARKER}
2156: @end itemize
2157:
2158: When you have mastered those, go on to:
2159:
2160: @itemize @bullet
1.28 crook 2161: @item
1.29 crook 2162: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 2163: @item
1.29 crook 2164: Memory access: @code{@@ !}
1.28 crook 2165: @end itemize
1.23 crook 2166:
1.29 crook 2167: When you have mastered these, there's nothing for it but to read through
2168: the whole of this manual and find out what you've missed.
2169:
2170: @comment ----------------------------------------------
2171: @node Exercises, ,Where to go next, Introduction
2172: @section Exercises
2173: @cindex exercises
2174:
2175: TODO: provide a set of programming excercises linked into the stuff done
2176: already and into other sections of the manual. Provide solutions to all
2177: the exercises in a .fs file in the distribution.
2178:
2179: @c Get some inspiration from Starting Forth and Kelly&Spies.
2180:
2181: @c excercises:
2182: @c 1. take inches and convert to feet and inches.
2183: @c 2. take temperature and convert from fahrenheight to celcius;
2184: @c may need to care about symmetric vs floored??
2185: @c 3. take input line and do character substitution
2186: @c to encipher or decipher
2187: @c 4. as above but work on a file for in and out
2188: @c 5. take input line and convert to pig-latin
2189: @c
2190: @c thing of sets of things to exercise then come up with
2191: @c problems that need those things.
2192:
2193:
1.26 crook 2194: @c ******************************************************************
1.29 crook 2195: @node Words, Error messages, Introduction, Top
1.1 anton 2196: @chapter Forth Words
1.26 crook 2197: @cindex words
1.1 anton 2198:
2199: @menu
2200: * Notation::
1.21 crook 2201: * Comments::
2202: * Boolean Flags::
1.1 anton 2203: * Arithmetic::
2204: * Stack Manipulation::
1.5 anton 2205: * Memory::
1.1 anton 2206: * Control Structures::
2207: * Defining Words::
1.21 crook 2208: * The Text Interpreter::
1.12 anton 2209: * Tokens for Words::
1.21 crook 2210: * Word Lists::
2211: * Environmental Queries::
1.12 anton 2212: * Files::
2213: * Blocks::
2214: * Other I/O::
2215: * Programming Tools::
2216: * Assembler and Code Words::
2217: * Threading Words::
1.26 crook 2218: * Locals::
2219: * Structures::
2220: * Object-oriented Forth::
1.21 crook 2221: * Passing Commands to the OS::
2222: * Miscellaneous Words::
1.1 anton 2223: @end menu
2224:
1.21 crook 2225: @node Notation, Comments, Words, Words
1.1 anton 2226: @section Notation
2227: @cindex notation of glossary entries
2228: @cindex format of glossary entries
2229: @cindex glossary notation format
2230: @cindex word glossary entry format
2231:
2232: The Forth words are described in this section in the glossary notation
2233: that has become a de-facto standard for Forth texts, i.e.,
2234:
2235: @format
1.29 crook 2236: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 2237: @end format
1.29 crook 2238: @i{Description}
1.1 anton 2239:
2240: @table @var
2241: @item word
1.28 crook 2242: The name of the word.
1.1 anton 2243:
2244: @item Stack effect
2245: @cindex stack effect
1.29 crook 2246: The stack effect is written in the notation @code{@i{before} --
2247: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 2248: stack entries before and after the execution of the word. The rest of
2249: the stack is not touched by the word. The top of stack is rightmost,
2250: i.e., a stack sequence is written as it is typed in. Note that Gforth
2251: uses a separate floating point stack, but a unified stack
1.29 crook 2252: notation. Also, return stack effects are not shown in @i{stack
2253: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 2254: the type and/or the function of the item. See below for a discussion of
2255: the types.
2256:
2257: All words have two stack effects: A compile-time stack effect and a
2258: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 2259: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 2260: this standard behaviour, or the word does other unusual things at
2261: compile time, both stack effects are shown; otherwise only the run-time
2262: stack effect is shown.
2263:
2264: @cindex pronounciation of words
2265: @item pronunciation
2266: How the word is pronounced.
2267:
2268: @cindex wordset
2269: @item wordset
1.21 crook 2270: The ANS Forth standard is divided into several word sets. A standard
2271: system need not support all of them. Therefore, in theory, the fewer
2272: word sets your program uses the more portable it will be. However, we
2273: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 2274: all word sets. Words that are not defined in ANS Forth have
1.21 crook 2275: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 2276: describes words that will work in future releases of Gforth;
2277: @code{gforth-internal} words are more volatile. Environmental query
2278: strings are also displayed like words; you can recognize them by the
1.21 crook 2279: @code{environment} in the word set field.
1.1 anton 2280:
2281: @item Description
2282: A description of the behaviour of the word.
2283: @end table
2284:
2285: @cindex types of stack items
2286: @cindex stack item types
2287: The type of a stack item is specified by the character(s) the name
2288: starts with:
2289:
2290: @table @code
2291: @item f
2292: @cindex @code{f}, stack item type
2293: Boolean flags, i.e. @code{false} or @code{true}.
2294: @item c
2295: @cindex @code{c}, stack item type
2296: Char
2297: @item w
2298: @cindex @code{w}, stack item type
2299: Cell, can contain an integer or an address
2300: @item n
2301: @cindex @code{n}, stack item type
2302: signed integer
2303: @item u
2304: @cindex @code{u}, stack item type
2305: unsigned integer
2306: @item d
2307: @cindex @code{d}, stack item type
2308: double sized signed integer
2309: @item ud
2310: @cindex @code{ud}, stack item type
2311: double sized unsigned integer
2312: @item r
2313: @cindex @code{r}, stack item type
2314: Float (on the FP stack)
1.21 crook 2315: @item a-
1.1 anton 2316: @cindex @code{a_}, stack item type
2317: Cell-aligned address
1.21 crook 2318: @item c-
1.1 anton 2319: @cindex @code{c_}, stack item type
2320: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 2321: @item f-
1.1 anton 2322: @cindex @code{f_}, stack item type
2323: Float-aligned address
1.21 crook 2324: @item df-
1.1 anton 2325: @cindex @code{df_}, stack item type
2326: Address aligned for IEEE double precision float
1.21 crook 2327: @item sf-
1.1 anton 2328: @cindex @code{sf_}, stack item type
2329: Address aligned for IEEE single precision float
2330: @item xt
2331: @cindex @code{xt}, stack item type
2332: Execution token, same size as Cell
2333: @item wid
2334: @cindex @code{wid}, stack item type
1.21 crook 2335: Word list ID, same size as Cell
1.1 anton 2336: @item f83name
2337: @cindex @code{f83name}, stack item type
2338: Pointer to a name structure
2339: @item "
2340: @cindex @code{"}, stack item type
1.12 anton 2341: string in the input stream (not on the stack). The terminating character
2342: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 2343: quotes.
2344: @end table
2345:
1.21 crook 2346: @node Comments, Boolean Flags, Notation, Words
2347: @section Comments
1.26 crook 2348: @cindex comments
1.21 crook 2349:
1.29 crook 2350: Forth supports two styles of comment; the traditional @i{in-line} comment,
2351: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 2352:
1.23 crook 2353: doc-(
1.21 crook 2354: doc-\
1.23 crook 2355: doc-\G
1.21 crook 2356:
2357: @node Boolean Flags, Arithmetic, Comments, Words
2358: @section Boolean Flags
1.26 crook 2359: @cindex Boolean flags
1.21 crook 2360:
2361: A Boolean flag is cell-sized. A cell with all bits clear represents the
2362: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 2363: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 2364: a cell that has @i{any} bit set as @code{true}.
1.21 crook 2365:
2366: doc-true
2367: doc-false
1.29 crook 2368: doc-on
2369: doc-off
1.21 crook 2370:
2371: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 2372: @section Arithmetic
2373: @cindex arithmetic words
2374:
2375: @cindex division with potentially negative operands
2376: Forth arithmetic is not checked, i.e., you will not hear about integer
2377: overflow on addition or multiplication, you may hear about division by
2378: zero if you are lucky. The operator is written after the operands, but
2379: the operands are still in the original order. I.e., the infix @code{2-1}
2380: corresponds to @code{2 1 -}. Forth offers a variety of division
2381: operators. If you perform division with potentially negative operands,
2382: you do not want to use @code{/} or @code{/mod} with its undefined
2383: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
2384: former, @pxref{Mixed precision}).
1.26 crook 2385: @comment TODO discuss the different division forms and the std approach
1.1 anton 2386:
2387: @menu
2388: * Single precision::
2389: * Bitwise operations::
1.21 crook 2390: * Double precision:: Double-cell integer arithmetic
2391: * Numeric comparison::
1.29 crook 2392: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 2393: * Floating Point::
2394: @end menu
2395:
2396: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
2397: @subsection Single precision
2398: @cindex single precision arithmetic words
2399:
1.21 crook 2400: By default, numbers in Forth are single-precision integers that are 1
1.26 crook 2401: cell in size. They can be signed or unsigned, depending upon how you
1.21 crook 2402: treat them. @xref{Number Conversion} for the rules used by the text
2403: interpreter for recognising single-precision integers.
2404:
1.1 anton 2405: doc-+
1.21 crook 2406: doc-1+
1.1 anton 2407: doc--
1.21 crook 2408: doc-1-
1.1 anton 2409: doc-*
2410: doc-/
2411: doc-mod
2412: doc-/mod
2413: doc-negate
2414: doc-abs
2415: doc-min
2416: doc-max
1.21 crook 2417: doc-d>s
1.27 crook 2418: doc-floored
1.1 anton 2419:
1.21 crook 2420: @node Bitwise operations, Double precision, Single precision, Arithmetic
1.1 anton 2421: @subsection Bitwise operations
2422: @cindex bitwise operation words
2423:
2424: doc-and
2425: doc-or
2426: doc-xor
2427: doc-invert
1.21 crook 2428: doc-lshift
2429: doc-rshift
1.1 anton 2430: doc-2*
1.21 crook 2431: doc-d2*
1.1 anton 2432: doc-2/
1.21 crook 2433: doc-d2/
2434:
2435: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
2436: @subsection Double precision
2437: @cindex double precision arithmetic words
2438:
2439: @xref{Number Conversion} for the rules used by the text interpreter for
2440: recognising double-precision integers.
2441:
2442: A double precision number is represented by a cell pair, with the most
1.31 anton 2443: significant cell at the TOS. It is trivial to convert an unsigned
1.26 crook 2444: single to an (unsigned) double; simply push a @code{0} onto the
2445: TOS. Since numbers are represented by Gforth using 2's complement
2446: arithmetic, converting a signed single to a (signed) double requires
1.31 anton 2447: sign-extension across the most significant cell. This can be achieved
1.26 crook 2448: using @code{s>d}. The moral of the story is that you cannot convert a
2449: number without knowing whether it represents an unsigned or a
2450: signed number.
1.21 crook 2451:
2452: doc-s>d
2453: doc-d+
2454: doc-d-
2455: doc-dnegate
2456: doc-dabs
2457: doc-dmin
2458: doc-dmax
2459:
2460: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
2461: @subsection Numeric comparison
2462: @cindex numeric comparison words
2463:
1.28 crook 2464: doc-<
2465: doc-<=
2466: doc-<>
2467: doc-=
2468: doc->
2469: doc->=
2470:
1.21 crook 2471: doc-0<
1.23 crook 2472: doc-0<=
1.21 crook 2473: doc-0<>
2474: doc-0=
1.23 crook 2475: doc-0>
2476: doc-0>=
1.28 crook 2477:
2478: doc-u<
2479: doc-u<=
1.31 anton 2480: @c TODO why u<> and u= ... they are the same as <> and =
2481: @c commented them out because they are unnecessary
2482: @c doc-u<>
2483: @c doc-u=
1.28 crook 2484: doc-u>
2485: doc-u>=
2486:
2487: doc-within
2488:
2489: doc-d<
2490: doc-d<=
2491: doc-d<>
2492: doc-d=
2493: doc-d>
2494: doc-d>=
1.23 crook 2495:
1.21 crook 2496: doc-d0<
1.23 crook 2497: doc-d0<=
2498: doc-d0<>
1.21 crook 2499: doc-d0=
1.23 crook 2500: doc-d0>
2501: doc-d0>=
2502:
1.21 crook 2503: doc-du<
1.28 crook 2504: doc-du<=
1.31 anton 2505: @c doc-du<>
2506: @c doc-du=
1.28 crook 2507: doc-du>
2508: doc-du>=
1.1 anton 2509:
1.21 crook 2510: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 2511: @subsection Mixed precision
2512: @cindex mixed precision arithmetic words
2513:
2514: doc-m+
2515: doc-*/
2516: doc-*/mod
2517: doc-m*
2518: doc-um*
2519: doc-m*/
2520: doc-um/mod
2521: doc-fm/mod
2522: doc-sm/rem
2523:
1.21 crook 2524: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 2525: @subsection Floating Point
2526: @cindex floating point arithmetic words
2527:
1.21 crook 2528: @xref{Number Conversion} for the rules used by the text interpreter for
2529: recognising floating-point numbers.
1.1 anton 2530:
1.32 ! anton 2531: Gforth has a separate floating point
1.26 crook 2532: stack, but the documentation uses the unified notation.
1.1 anton 2533:
2534: @cindex floating-point arithmetic, pitfalls
2535: Floating point numbers have a number of unpleasant surprises for the
2536: unwary (e.g., floating point addition is not associative) and even a few
2537: for the wary. You should not use them unless you know what you are doing
2538: or you don't care that the results you get are totally bogus. If you
2539: want to learn about the problems of floating point numbers (and how to
2540: avoid them), you might start with @cite{David Goldberg, What Every
2541: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
1.17 anton 2542: Computing Surveys 23(1):5@minus{}48, March 1991}
2543: (@url{http://www.validgh.com/goldberg/paper.ps}).
1.1 anton 2544:
1.21 crook 2545: doc-d>f
2546: doc-f>d
1.1 anton 2547: doc-f+
2548: doc-f-
2549: doc-f*
2550: doc-f/
2551: doc-fnegate
2552: doc-fabs
2553: doc-fmax
2554: doc-fmin
2555: doc-floor
2556: doc-fround
2557: doc-f**
2558: doc-fsqrt
2559: doc-fexp
2560: doc-fexpm1
2561: doc-fln
2562: doc-flnp1
2563: doc-flog
2564: doc-falog
1.32 ! anton 2565: doc-f2*
! 2566: doc-f2/
! 2567: doc-1/f
! 2568: doc-precision
! 2569: doc-set-precision
! 2570:
! 2571: @cindex angles in trigonometric operations
! 2572: @cindex trigonometric operations
! 2573: Angles in floating point operations are given in radians (a full circle
! 2574: has 2 pi radians).
! 2575:
1.1 anton 2576: doc-fsin
2577: doc-fcos
2578: doc-fsincos
2579: doc-ftan
2580: doc-fasin
2581: doc-facos
2582: doc-fatan
2583: doc-fatan2
2584: doc-fsinh
2585: doc-fcosh
2586: doc-ftanh
2587: doc-fasinh
2588: doc-facosh
2589: doc-fatanh
1.21 crook 2590: doc-pi
1.28 crook 2591:
1.32 ! anton 2592: @cindex equality of floats
! 2593: @cindex floating-point comparisons
1.31 anton 2594: One particular problem with floating-point arithmetic is that comparison
2595: for equality often fails when you would expect it to succeed. For this
2596: reason approximate equality is often preferred (but you still have to
2597: know what you are doing). The comparison words are:
2598:
2599: doc-f~rel
2600: doc-f~abs
2601: doc-f=
2602: doc-f~
2603: doc-f<>
2604:
2605: doc-f<
2606: doc-f<=
2607: doc-f>
2608: doc-f>=
2609:
1.21 crook 2610: doc-f0<
1.28 crook 2611: doc-f0<=
2612: doc-f0<>
1.21 crook 2613: doc-f0=
1.28 crook 2614: doc-f0>
2615: doc-f0>=
2616:
1.1 anton 2617:
2618: @node Stack Manipulation, Memory, Arithmetic, Words
2619: @section Stack Manipulation
2620: @cindex stack manipulation words
2621:
2622: @cindex floating-point stack in the standard
1.21 crook 2623: Gforth maintains a number of separate stacks:
2624:
1.29 crook 2625: @cindex data stack
2626: @cindex parameter stack
1.21 crook 2627: @itemize @bullet
2628: @item
1.29 crook 2629: A data stack (also known as the @dfn{parameter stack}) -- for
2630: characters, cells, addresses, and double cells.
1.21 crook 2631:
1.29 crook 2632: @cindex floating-point stack
1.21 crook 2633: @item
2634: A floating point stack -- for floating point numbers.
2635:
1.29 crook 2636: @cindex return stack
1.21 crook 2637: @item
2638: A return stack -- for storing the return addresses of colon
1.32 ! anton 2639: definitions and other (non-FP) data.
1.21 crook 2640:
1.29 crook 2641: @cindex locals stack
1.21 crook 2642: @item
2643: A locals stack for storing local variables.
2644: @end itemize
2645:
1.1 anton 2646: @menu
2647: * Data stack::
2648: * Floating point stack::
2649: * Return stack::
2650: * Locals stack::
2651: * Stack pointer manipulation::
2652: @end menu
2653:
2654: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
2655: @subsection Data stack
2656: @cindex data stack manipulation words
2657: @cindex stack manipulations words, data stack
2658:
2659: doc-drop
2660: doc-nip
2661: doc-dup
2662: doc-over
2663: doc-tuck
2664: doc-swap
1.21 crook 2665: doc-pick
1.1 anton 2666: doc-rot
2667: doc--rot
2668: doc-?dup
2669: doc-roll
2670: doc-2drop
2671: doc-2nip
2672: doc-2dup
2673: doc-2over
2674: doc-2tuck
2675: doc-2swap
2676: doc-2rot
2677:
2678: @node Floating point stack, Return stack, Data stack, Stack Manipulation
2679: @subsection Floating point stack
2680: @cindex floating-point stack manipulation words
2681: @cindex stack manipulation words, floating-point stack
2682:
1.32 ! anton 2683: Whilst every sane Forth has a separate floating-point stack, it is not
! 2684: strictly required; an ANS Forth system could theoretically keep
! 2685: floating-point numbers on the data stack. As an additional difficulty,
! 2686: you don't know how many cells a floating-point number takes. It is
! 2687: reportedly possible to write words in a way that they work also for a
! 2688: unified stack model, but we do not recommend trying it. Instead, just
! 2689: say that your program has an environmental dependency on a separate
! 2690: floating-point stack.
! 2691:
! 2692: doc-floating-stack
! 2693:
1.1 anton 2694: doc-fdrop
2695: doc-fnip
2696: doc-fdup
2697: doc-fover
2698: doc-ftuck
2699: doc-fswap
1.21 crook 2700: doc-fpick
1.1 anton 2701: doc-frot
2702:
2703: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
2704: @subsection Return stack
2705: @cindex return stack manipulation words
2706: @cindex stack manipulation words, return stack
2707:
1.32 ! anton 2708: @cindex return stack and locals
! 2709: @cindex locals and return stack
! 2710: A Forth system is allowed to keep local variables on the
! 2711: return stack. This is reasonable, as local variables usually eliminate
! 2712: the need to use the return stack explicitly. So, if you want to produce
! 2713: a standard compliant program and you are using local variables in a
! 2714: word, forget about return stack manipulations in that word (refer to the
! 2715: standard document for the exact rules).
! 2716:
1.1 anton 2717: doc->r
2718: doc-r>
2719: doc-r@
2720: doc-rdrop
2721: doc-2>r
2722: doc-2r>
2723: doc-2r@
2724: doc-2rdrop
2725:
2726: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
2727: @subsection Locals stack
2728:
1.26 crook 2729: @comment TODO
1.21 crook 2730:
1.1 anton 2731: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
2732: @subsection Stack pointer manipulation
2733: @cindex stack pointer manipulation words
2734:
1.21 crook 2735: doc-sp0
1.1 anton 2736: doc-sp@
2737: doc-sp!
1.21 crook 2738: doc-fp0
1.1 anton 2739: doc-fp@
2740: doc-fp!
1.21 crook 2741: doc-rp0
1.1 anton 2742: doc-rp@
2743: doc-rp!
1.21 crook 2744: doc-lp0
1.1 anton 2745: doc-lp@
2746: doc-lp!
2747:
2748: @node Memory, Control Structures, Stack Manipulation, Words
2749: @section Memory
1.26 crook 2750: @cindex memory words
1.1 anton 2751:
1.32 ! anton 2752: @menu
! 2753: * Memory model::
! 2754: * Dictionary allocation::
! 2755: * Heap Allocation::
! 2756: * Memory Access::
! 2757: * Address arithmetic::
! 2758: * Memory Blocks::
! 2759: @end menu
! 2760:
! 2761: @node Memory model, Dictionary allocation, Memory, Memory
! 2762: @subsection ANS Forth and Gforth memory models
! 2763:
! 2764: @c The ANS Forth description is a mess (e.g., is the heap part of
! 2765: @c the dictionary?), so let's not stick to closely with it.
! 2766:
! 2767: ANS Forth considers a Forth system as consisting of several memories, of
! 2768: which only @dfn{data space} is managed and accessible with the memory
! 2769: words. Memory not necessarily in data space includes the stacks, the
! 2770: code (called code space) and the headers (called name space). In Gforth
! 2771: everything is in data space, but the code for the primitives is usually
! 2772: read-only.
! 2773:
! 2774: Data space is divided into a number of areas: The (data space portion of
! 2775: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
! 2776: refer to the search data structure embodied in word lists and headers,
! 2777: because it is used for looking up names, just as you would in a
! 2778: conventional dictionary.}, the heap, and a number of system-allocated
! 2779: buffers.
! 2780:
! 2781: In ANS Forth data space is also divided into contiguous regions. You
! 2782: can only use address arithmetic within a contiguous region, not between
! 2783: them. Usually each allocation gives you one contiguous region, but the
! 2784: Dictionary allocation words have additional rules (@pxref{Dictionary
! 2785: allocation}).
! 2786:
! 2787: Gforth provides one big address space, and address arithmetic can be
! 2788: performed between any addresses. However, in the dictionary headers or
! 2789: code are interleaved with data, so almost the only contiguous data space
! 2790: regions there are those described by ANS Forth as contiguous; but you
! 2791: can be sure that the dictionary is allocated towards increasing
! 2792: addresses even between contiguous regions. The memory order of
! 2793: allocations in the heap is platform-dependent (and possibly different
! 2794: from one run to the next).
! 2795:
! 2796: @subsubsection ANS Forth dictionary details
! 2797:
! 2798: @c !! I have deleted some of the stuff this section refers to - anton
1.27 crook 2799:
1.32 ! anton 2800: This section is just informative, you can skip it if you are in a hurry.
1.27 crook 2801:
1.29 crook 2802: When you create a colon definition, the text interpreter compiles the
1.32 ! anton 2803: code for the definition into the code space and compiles the name
! 2804: of the definition into the header space, together with other
1.27 crook 2805: information about the definition (such as its execution token).
2806:
2807: When you create a variable, the execution of @code{variable} will
1.32 ! anton 2808: compile some code, assign one cell in data space, and compile the name
! 2809: of the variable into the header space.
1.27 crook 2810:
2811: @cindex memory regions - relationship between them
2812: ANS Forth does not specify the relationship between the three memory
2813: regions, and specifies that a Standard program must not access code or
2814: data space directly -- it may only access data space directly. In
2815: addition, the Standard defines what relationships you may and may not
2816: rely on when allocating regions in data space. These constraints are
2817: simply a reflection of the many diverse techniques that are used to
2818: implement Forth systems; understanding and following the requirements of
2819: the Standard allows you to write portable programs -- programs that run
2820: in the same way on any of these diverse systems. Another way of looking
2821: at this is to say that ANS Forth was designed to permit compliant Forth
2822: systems to be implemented in many diverse ways.
2823:
2824: @cindex memory regions - how they are assigned
1.29 crook 2825: Here are some examples of ways in which name, code and data spaces
2826: might be assigned in different Forth implementations:
1.27 crook 2827:
2828: @itemize @bullet
2829: @item
2830: For a Forth system that runs from RAM under a general-purpose operating
2831: system, it can be convenient to interleave name, code and data spaces in
2832: a single contiguous memory region. This organisation can be
2833: memory-efficient (for example, because the relationship between the name
1.32 ! anton 2834: dictionary entry and the associated code space entry can be
1.27 crook 2835: implicit, rather than requiring an explicit memory pointer to reference
1.32 ! anton 2836: from the header space and the code space). This is the
1.27 crook 2837: organisation used by Gforth, as this example@footnote{The addresses
2838: in the example have been truncated to fit it onto the page, and the
2839: addresses and data shown will not match the output from your system} shows:
2840: @example
2841: hex
2842: variable fred 123456 fred !
2843: variable jim abcd jim !
2844: : foo + / - ;
2845: ' fred 10 - 50 dump
2846: ..80: 5C 46 0E 40 84 66 72 65 - 64 20 20 20 20 20 20 20 \F.@.fred
2847: ..90: D0 9B 04 08 00 00 00 00 - 56 34 12 00 80 46 0E 40 ........V4...F.@
2848: ..A0: 83 6A 69 6D 20 20 20 20 - D0 9B 04 08 00 00 00 00 .jim ........
2849: ..B0: CD AB 00 00 9C 46 0E 40 - 83 66 6F 6F 20 20 20 20 .....F.@.foo
2850: ..C0: 80 9B 04 08 00 00 00 00 - E4 2E 05 08 0C 2F 05 08 ............./..
2851: @end example
2852:
2853: @item
2854: For a high-performance system running on a modern RISC processor with a
2855: modified Harvard architecture (one that has a unified main memory but
2856: separate instruction and data caches), it is desirable to separate
2857: processor instructions from processor data. This encourages a high cache
1.32 ! anton 2858: density and therefore a high cache hit rate. The Forth code space
1.27 crook 2859: is not necessarily made up entirely of processor instructions; its
2860: nature is dependent upon the Forth implementation.
2861:
2862: @item
2863: A Forth compiler that runs on a segmented 8086 processor could be
2864: designed to interleave the name, code and data spaces within a single
2865: 64Kbyte segment. A more common implementation choice is to use a
2866: separate 64Kbyte segment for each region, which provides more memory
2867: overall but provides an address map in which only the data space is
2868: accessible.
2869:
2870: @item
2871: Microprocessors exist that run Forth (or many of the primitives required
2872: to implement the Forth virtual machine efficiently) directly. On these
2873: processors, the relationship between name, code and data spaces may be
1.32 ! anton 2874: imposed as a side-effect of the architecture of the processor.
1.27 crook 2875:
2876: @item
2877: A Forth compiler that executes from ROM on an embedded system needs its
2878: data space separated from the name and code spaces so that the data
2879: space can be mapped to a RAM area.
2880:
2881: @item
2882: A Forth compiler that runs on an embedded system may have a requirement
2883: for a small memory footprint. On such a system it can be useful to
1.32 ! anton 2884: separate the header space from the data and code spaces; once the
! 2885: application has been compiled, the header space is no longer
1.27 crook 2886: required@footnote{more strictly speaking, most applications can be
1.32 ! anton 2887: designed so that this is the case}. The header space can be deleted
1.29 crook 2888: entirely, or could be stored in memory on a remote @i{host} system for
1.27 crook 2889: debug and development purposes. In the latter case, the compiler running
1.29 crook 2890: on the @i{target} system could implement a protocol across a
1.32 ! anton 2891: communication link that would allow it to interrogate the header space.
1.27 crook 2892: @end itemize
2893:
1.1 anton 2894:
1.32 ! anton 2895: @node Dictionary allocation, Heap Allocation, Memory model, Memory
! 2896: @subsection Dictionary allocation
1.27 crook 2897: @cindex reserving data space
2898: @cindex data space - reserving some
2899:
1.32 ! anton 2900: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
! 2901: you want to deallocate X, you also deallocate everything
! 2902: allocated after X.
! 2903:
! 2904: The allocations using the words below are contiguous and grow the region
! 2905: towards increasing addresses. Other words that allocate dictionary
! 2906: memory of any kind (i.e., defining words including @code{:noname}) end
! 2907: the contiguous region and start a new one.
! 2908:
! 2909: In ANS Forth only @code{create}d words are guaranteed to produce an
! 2910: address that is the start of the following contiguous region. In
! 2911: particular, the cell allocated by @code{variable} is not guaranteed to
! 2912: be contiguous with following @code{allot}ed memory.
! 2913:
! 2914: You can deallocate memory by using @code{allot} with a negative argument
! 2915: (with some restrictions, see @code{allot}). For larger deallocations use
! 2916: @code{marker}.
1.27 crook 2917:
1.29 crook 2918:
1.27 crook 2919: doc-here
2920: doc-unused
2921: doc-allot
2922: doc-c,
1.29 crook 2923: doc-f,
1.27 crook 2924: doc-,
2925: doc-2,
1.29 crook 2926: @cindex user space
2927: doc-udp
2928: doc-uallot
1.27 crook 2929:
1.32 ! anton 2930: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
! 2931: course you should allocate memory in an aligned way, too. I.e., before
! 2932: allocating allocating a cell, @code{here} must be cell-aligned, etc.
! 2933: The words below align @code{here} if it is not already. Basically it is
! 2934: only already aligned for a type, if the last allocation was a multiple
! 2935: of the size of this type and if @code{here} was aligned for this type
! 2936: before.
! 2937:
! 2938: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
! 2939: ANS Forth (@code{maxalign}ed in Gforth).
! 2940:
! 2941: doc-align
! 2942: doc-falign
! 2943: doc-sfalign
! 2944: doc-dfalign
! 2945: doc-maxalign
! 2946: doc-cfalign
! 2947:
! 2948:
! 2949: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
! 2950: @subsection Heap allocation
! 2951: @cindex heap allocation
! 2952: @cindex dynamic allocation of memory
! 2953: @cindex memory-allocation word set
! 2954:
! 2955: Heap allocation supports deallocation of allocated memory in any
! 2956: order. Dictionary allocation is not affected by it (i.e., it does not
! 2957: end a contiguous region). In Gforth, these words are implemented using
! 2958: the standard C library calls malloc(), free() and resize().
! 2959:
! 2960: doc-allocate
! 2961: doc-free
! 2962: doc-resize
! 2963:
1.27 crook 2964:
1.32 ! anton 2965: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 2966: @subsection Memory Access
2967: @cindex memory access words
2968:
2969: doc-@
2970: doc-!
2971: doc-+!
2972: doc-c@
2973: doc-c!
2974: doc-2@
2975: doc-2!
2976: doc-f@
2977: doc-f!
2978: doc-sf@
2979: doc-sf!
2980: doc-df@
2981: doc-df!
2982:
1.32 ! anton 2983: @node Address arithmetic, Memory Blocks, Memory Access, Memory
! 2984: @subsection Address arithmetic
1.1 anton 2985: @cindex address arithmetic words
2986:
1.32 ! anton 2987: Address arithmetic is the foundation on which data structures like
! 2988: arrays, records (@pxref{Structures}) and objects (@pxref{Object-oriented
! 2989: Forth}) are built.
! 2990:
1.1 anton 2991: ANS Forth does not specify the sizes of the data types. Instead, it
2992: offers a number of words for computing sizes and doing address
1.29 crook 2993: arithmetic. Address arithmetic is performed in terms of address units
2994: (aus); on most systems the address unit is one byte. Note that a
2995: character may have more than one au, so @code{chars} is no noop (on
2996: systems where it is a noop, it compiles to nothing).
1.1 anton 2997:
2998: @cindex alignment of addresses for types
2999: ANS Forth also defines words for aligning addresses for specific
3000: types. Many computers require that accesses to specific data types
3001: must only occur at specific addresses; e.g., that cells may only be
3002: accessed at addresses divisible by 4. Even if a machine allows unaligned
3003: accesses, it can usually perform aligned accesses faster.
3004:
3005: For the performance-conscious: alignment operations are usually only
3006: necessary during the definition of a data structure, not during the
3007: (more frequent) accesses to it.
3008:
3009: ANS Forth defines no words for character-aligning addresses. This is not
3010: an oversight, but reflects the fact that addresses that are not
3011: char-aligned have no use in the standard and therefore will not be
3012: created.
3013:
3014: @cindex @code{CREATE} and alignment
1.29 crook 3015: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 3016: are cell-aligned; in addition, Gforth guarantees that these addresses
3017: are aligned for all purposes.
3018:
1.26 crook 3019: Note that the ANS Forth word @code{char} has nothing to do with address
3020: arithmetic.
1.1 anton 3021:
3022: doc-chars
3023: doc-char+
3024: doc-cells
3025: doc-cell+
3026: doc-cell
3027: doc-aligned
3028: doc-floats
3029: doc-float+
3030: doc-float
3031: doc-faligned
3032: doc-sfloats
3033: doc-sfloat+
3034: doc-sfaligned
3035: doc-dfloats
3036: doc-dfloat+
3037: doc-dfaligned
3038: doc-maxaligned
3039: doc-cfaligned
3040: doc-address-unit-bits
3041:
1.32 ! anton 3042: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 3043: @subsection Memory Blocks
3044: @cindex memory block words
1.27 crook 3045: @cindex character strings - moving and copying
3046:
3047: Memory blocks often represent character strings; @xref{String Formats}
3048: for ways of storing character strings in memory. @xref{Displaying
3049: characters and strings} for other string-processing words.
1.1 anton 3050:
1.32 ! anton 3051: Some of these words work on address units. Others work on character
! 3052: units (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
! 3053: address. Choose the correct operation depending upon your data type.
1.21 crook 3054:
3055: When copying characters between overlapping memory regions, choose
3056: carefully between @code{cmove} and @code{cmove>}.
3057:
1.29 crook 3058: You can only use any of these words @i{portably} to access data space.
1.21 crook 3059:
1.27 crook 3060: @comment TODO - think the naming of the arguments is wrong for move
1.29 crook 3061: @comment well, really it seems to be the Standard that's wrong; it
3062: @comment describes MOVE as a word that requires a CELL-aligned source
3063: @comment and destination address but a xtranfer count that need not
3064: @comment be a multiple of CELL.
1.1 anton 3065: doc-move
3066: doc-erase
3067: doc-cmove
3068: doc-cmove>
3069: doc-fill
3070: doc-blank
1.21 crook 3071: doc-compare
3072: doc-search
1.27 crook 3073: doc--trailing
3074: doc-/string
3075:
3076: @comment TODO examples
3077:
1.1 anton 3078:
1.26 crook 3079: @node Control Structures, Defining Words, Memory, Words
1.1 anton 3080: @section Control Structures
3081: @cindex control structures
3082:
3083: Control structures in Forth cannot be used in interpret state, only in
1.29 crook 3084: compile state@footnote{To be precise, they have no interpretation
3085: semantics (@pxref{Interpretation and Compilation Semantics}).}, i.e., in
1.1 anton 3086: a colon definition. We do not like this limitation, but have not seen a
3087: satisfying way around it yet, although many schemes have been proposed.
3088:
3089: @menu
1.29 crook 3090: * Selection:: IF.. ELSE.. ENDIF
3091: * Simple Loops:: BEGIN..
3092: * Counted Loops:: DO
3093: * Arbitrary control structures::
3094: * Calls and returns::
1.1 anton 3095: * Exception Handling::
3096: @end menu
3097:
3098: @node Selection, Simple Loops, Control Structures, Control Structures
3099: @subsection Selection
3100: @cindex selection control structures
3101: @cindex control structures for selection
3102:
3103: @cindex @code{IF} control structure
3104: @example
1.29 crook 3105: @i{flag}
1.1 anton 3106: IF
1.29 crook 3107: @i{code}
1.1 anton 3108: ENDIF
3109: @end example
1.21 crook 3110: @noindent
1.1 anton 3111: or
3112: @example
1.29 crook 3113: @i{flag}
1.1 anton 3114: IF
1.29 crook 3115: @i{code1}
1.1 anton 3116: ELSE
1.29 crook 3117: @i{code2}
1.1 anton 3118: ENDIF
3119: @end example
3120:
3121: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
3122: standard, and @code{ENDIF} is not, although it is quite popular. We
3123: recommend using @code{ENDIF}, because it is less confusing for people
3124: who also know other languages (and is not prone to reinforcing negative
3125: prejudices against Forth in these people). Adding @code{ENDIF} to a
3126: system that only supplies @code{THEN} is simple:
3127: @example
1.21 crook 3128: : ENDIF POSTPONE THEN ; immediate
1.1 anton 3129: @end example
3130:
3131: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
3132: (adv.)} has the following meanings:
3133: @quotation
3134: ... 2b: following next after in order ... 3d: as a necessary consequence
3135: (if you were there, then you saw them).
3136: @end quotation
3137: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
3138: and many other programming languages has the meaning 3d.]
3139:
1.21 crook 3140: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 3141: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 3142: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 3143: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
3144: @file{compat/control.fs}.
3145:
3146: @cindex @code{CASE} control structure
3147: @example
1.29 crook 3148: @i{n}
1.1 anton 3149: CASE
1.29 crook 3150: @i{n1} OF @i{code1} ENDOF
3151: @i{n2} OF @i{code2} ENDOF
1.1 anton 3152: @dots{}
3153: ENDCASE
3154: @end example
3155:
1.29 crook 3156: Executes the first @i{codei}, where the @i{ni} is equal to
3157: @i{n}. A default case can be added by simply writing the code after
3158: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
1.1 anton 3159: but must not consume it.
3160:
3161: @node Simple Loops, Counted Loops, Selection, Control Structures
3162: @subsection Simple Loops
3163: @cindex simple loops
3164: @cindex loops without count
3165:
3166: @cindex @code{WHILE} loop
3167: @example
3168: BEGIN
1.29 crook 3169: @i{code1}
3170: @i{flag}
1.1 anton 3171: WHILE
1.29 crook 3172: @i{code2}
1.1 anton 3173: REPEAT
3174: @end example
3175:
1.29 crook 3176: @i{code1} is executed and @i{flag} is computed. If it is true,
3177: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 3178: false, execution continues after the @code{REPEAT}.
3179:
3180: @cindex @code{UNTIL} loop
3181: @example
3182: BEGIN
1.29 crook 3183: @i{code}
3184: @i{flag}
1.1 anton 3185: UNTIL
3186: @end example
3187:
1.29 crook 3188: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 3189:
3190: @cindex endless loop
3191: @cindex loops, endless
3192: @example
3193: BEGIN
1.29 crook 3194: @i{code}
1.1 anton 3195: AGAIN
3196: @end example
3197:
3198: This is an endless loop.
3199:
3200: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
3201: @subsection Counted Loops
3202: @cindex counted loops
3203: @cindex loops, counted
3204: @cindex @code{DO} loops
3205:
3206: The basic counted loop is:
3207: @example
1.29 crook 3208: @i{limit} @i{start}
1.1 anton 3209: ?DO
1.29 crook 3210: @i{body}
1.1 anton 3211: LOOP
3212: @end example
3213:
1.29 crook 3214: This performs one iteration for every integer, starting from @i{start}
3215: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 3216: accessed with @code{i}. For example, the loop:
1.1 anton 3217: @example
3218: 10 0 ?DO
3219: i .
3220: LOOP
3221: @end example
1.21 crook 3222: @noindent
3223: prints @code{0 1 2 3 4 5 6 7 8 9}
3224:
1.1 anton 3225: The index of the innermost loop can be accessed with @code{i}, the index
3226: of the next loop with @code{j}, and the index of the third loop with
3227: @code{k}.
3228:
3229: doc-i
3230: doc-j
3231: doc-k
3232:
3233: The loop control data are kept on the return stack, so there are some
1.21 crook 3234: restrictions on mixing return stack accesses and counted loop words. In
3235: particuler, if you put values on the return stack outside the loop, you
3236: cannot read them inside the loop@footnote{well, not in a way that is
3237: portable.}. If you put values on the return stack within a loop, you
3238: have to remove them before the end of the loop and before accessing the
3239: index of the loop.
1.1 anton 3240:
3241: There are several variations on the counted loop:
3242:
1.21 crook 3243: @itemize @bullet
3244: @item
3245: @code{LEAVE} leaves the innermost counted loop immediately; execution
3246: continues after the associated @code{LOOP} or @code{NEXT}. For example:
3247:
3248: @example
3249: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
3250: @end example
3251: prints @code{0 1 2 3}
3252:
1.1 anton 3253:
1.21 crook 3254: @item
3255: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
3256: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
3257: return stack so @code{EXIT} can get to its return address. For example:
3258:
3259: @example
3260: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
3261: @end example
3262: prints @code{0 1 2 3}
3263:
3264:
3265: @item
1.29 crook 3266: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 3267: (and @code{LOOP} iterates until they become equal by wrap-around
3268: arithmetic). This behaviour is usually not what you want. Therefore,
3269: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 3270: @code{?DO}), which do not enter the loop if @i{start} is greater than
3271: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 3272: unsigned loop parameters.
3273:
1.21 crook 3274: @item
3275: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
3276: the loop, independent of the loop parameters. Do not use @code{DO}, even
3277: if you know that the loop is entered in any case. Such knowledge tends
3278: to become invalid during maintenance of a program, and then the
3279: @code{DO} will make trouble.
3280:
3281: @item
1.29 crook 3282: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
3283: index by @i{n} instead of by 1. The loop is terminated when the border
3284: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 3285:
1.21 crook 3286: @example
3287: 4 0 +DO i . 2 +LOOP
3288: @end example
3289: @noindent
3290: prints @code{0 2}
3291:
3292: @example
3293: 4 1 +DO i . 2 +LOOP
3294: @end example
3295: @noindent
3296: prints @code{1 3}
1.1 anton 3297:
3298:
3299: @cindex negative increment for counted loops
3300: @cindex counted loops with negative increment
1.29 crook 3301: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 3302:
1.21 crook 3303: @example
3304: -1 0 ?DO i . -1 +LOOP
3305: @end example
3306: @noindent
3307: prints @code{0 -1}
1.1 anton 3308:
1.21 crook 3309: @example
3310: 0 0 ?DO i . -1 +LOOP
3311: @end example
3312: prints nothing.
1.1 anton 3313:
1.29 crook 3314: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
3315: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
3316: index by @i{u} each iteration. The loop is terminated when the border
3317: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 3318: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
3319:
1.21 crook 3320: @example
3321: -2 0 -DO i . 1 -LOOP
3322: @end example
3323: @noindent
3324: prints @code{0 -1}
1.1 anton 3325:
1.21 crook 3326: @example
3327: -1 0 -DO i . 1 -LOOP
3328: @end example
3329: @noindent
3330: prints @code{0}
3331:
3332: @example
3333: 0 0 -DO i . 1 -LOOP
3334: @end example
3335: @noindent
3336: prints nothing.
1.1 anton 3337:
1.21 crook 3338: @end itemize
1.1 anton 3339:
3340: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 3341: @code{-LOOP} are not defined in ANS Forth. However, an implementation
3342: for these words that uses only standard words is provided in
3343: @file{compat/loops.fs}.
1.1 anton 3344:
3345:
3346: @cindex @code{FOR} loops
1.26 crook 3347: Another counted loop is:
1.1 anton 3348: @example
1.29 crook 3349: @i{n}
1.1 anton 3350: FOR
1.29 crook 3351: @i{body}
1.1 anton 3352: NEXT
3353: @end example
3354: This is the preferred loop of native code compiler writers who are too
1.26 crook 3355: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 3356: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
3357: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 3358: Forth systems may behave differently, even if they support @code{FOR}
3359: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 3360:
3361: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
3362: @subsection Arbitrary control structures
3363: @cindex control structures, user-defined
3364:
3365: @cindex control-flow stack
3366: ANS Forth permits and supports using control structures in a non-nested
3367: way. Information about incomplete control structures is stored on the
3368: control-flow stack. This stack may be implemented on the Forth data
3369: stack, and this is what we have done in Gforth.
3370:
3371: @cindex @code{orig}, control-flow stack item
3372: @cindex @code{dest}, control-flow stack item
3373: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
3374: entry represents a backward branch target. A few words are the basis for
3375: building any control structure possible (except control structures that
3376: need storage, like calls, coroutines, and backtracking).
3377:
3378: doc-if
3379: doc-ahead
3380: doc-then
3381: doc-begin
3382: doc-until
3383: doc-again
3384: doc-cs-pick
3385: doc-cs-roll
3386:
1.21 crook 3387: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
3388: manipulate the control-flow stack in a portable way. Without them, you
3389: would need to know how many stack items are occupied by a control-flow
3390: entry (many systems use one cell. In Gforth they currently take three,
3391: but this may change in the future).
3392:
1.1 anton 3393: Some standard control structure words are built from these words:
3394:
3395: doc-else
3396: doc-while
3397: doc-repeat
3398:
3399: Gforth adds some more control-structure words:
3400:
3401: doc-endif
3402: doc-?dup-if
3403: doc-?dup-0=-if
3404:
3405: Counted loop words constitute a separate group of words:
3406:
3407: doc-?do
3408: doc-+do
3409: doc-u+do
3410: doc--do
3411: doc-u-do
3412: doc-do
3413: doc-for
3414: doc-loop
3415: doc-+loop
3416: doc--loop
3417: doc-next
3418: doc-leave
3419: doc-?leave
3420: doc-unloop
3421: doc-done
3422:
1.21 crook 3423: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
3424: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 3425: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
3426: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
3427: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
3428: resolved (by using one of the loop-ending words or @code{DONE}).
3429:
1.26 crook 3430: Another group of control structure words are:
1.1 anton 3431:
3432: doc-case
3433: doc-endcase
3434: doc-of
3435: doc-endof
3436:
1.21 crook 3437: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
3438: @code{CS-ROLL}.
1.1 anton 3439:
3440: @subsubsection Programming Style
3441:
3442: In order to ensure readability we recommend that you do not create
3443: arbitrary control structures directly, but define new control structure
3444: words for the control structure you want and use these words in your
1.26 crook 3445: program. For example, instead of writing:
1.1 anton 3446:
3447: @example
1.26 crook 3448: BEGIN
1.1 anton 3449: ...
1.26 crook 3450: IF [ 1 CS-ROLL ]
1.1 anton 3451: ...
1.26 crook 3452: AGAIN THEN
1.1 anton 3453: @end example
3454:
1.21 crook 3455: @noindent
1.1 anton 3456: we recommend defining control structure words, e.g.,
3457:
3458: @example
1.26 crook 3459: : WHILE ( DEST -- ORIG DEST )
3460: POSTPONE IF
3461: 1 CS-ROLL ; immediate
3462:
3463: : REPEAT ( orig dest -- )
3464: POSTPONE AGAIN
3465: POSTPONE THEN ; immediate
1.1 anton 3466: @end example
3467:
1.21 crook 3468: @noindent
1.1 anton 3469: and then using these to create the control structure:
3470:
3471: @example
1.26 crook 3472: BEGIN
1.1 anton 3473: ...
1.26 crook 3474: WHILE
1.1 anton 3475: ...
1.26 crook 3476: REPEAT
1.1 anton 3477: @end example
3478:
3479: That's much easier to read, isn't it? Of course, @code{REPEAT} and
3480: @code{WHILE} are predefined, so in this example it would not be
3481: necessary to define them.
3482:
3483: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
3484: @subsection Calls and returns
3485: @cindex calling a definition
3486: @cindex returning from a definition
3487:
1.3 anton 3488: @cindex recursive definitions
3489: A definition can be called simply be writing the name of the definition
1.26 crook 3490: to be called. Normally a definition is invisible during its own
1.3 anton 3491: definition. If you want to write a directly recursive definition, you
1.26 crook 3492: can use @code{recursive} to make the current definition visible, or
3493: @code{recurse} to call the current definition directly.
1.3 anton 3494:
3495: doc-recursive
3496: doc-recurse
3497:
1.21 crook 3498: @comment TODO add example of the two recursion methods
1.12 anton 3499: @quotation
3500: @progstyle
3501: I prefer using @code{recursive} to @code{recurse}, because calling the
3502: definition by name is more descriptive (if the name is well-chosen) than
3503: the somewhat cryptic @code{recurse}. E.g., in a quicksort
3504: implementation, it is much better to read (and think) ``now sort the
3505: partitions'' than to read ``now do a recursive call''.
3506: @end quotation
1.3 anton 3507:
1.29 crook 3508: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 3509:
3510: @example
1.28 crook 3511: Defer foo
1.3 anton 3512:
3513: : bar ( ... -- ... )
3514: ... foo ... ;
3515:
3516: :noname ( ... -- ... )
3517: ... bar ... ;
3518: IS foo
3519: @end example
3520:
1.26 crook 3521: The current definition returns control to the calling definition when
1.29 crook 3522: the end of the definition is reached or @code{EXIT} is
3523: encountered. Deferred words are discussed in more detail in @ref{Simple
3524: Defining Words}.
1.1 anton 3525:
3526: doc-exit
3527: doc-;s
3528:
3529: @node Exception Handling, , Calls and returns, Control Structures
3530: @subsection Exception Handling
1.26 crook 3531: @cindex exceptions
1.1 anton 3532:
1.26 crook 3533: If your program detects a fatal error condition, the simplest action
3534: that it can take is to @code{quit}. This resets the return stack and
3535: restarts the text interpreter, but does not print any error message.
1.21 crook 3536:
1.26 crook 3537: The next stage in severity is to execute @code{abort}, which has the
3538: same effect as @code{quit}, with the addition that it resets the data
3539: stack.
1.1 anton 3540:
1.26 crook 3541: A slightly more sophisticated approach is use use @code{abort"}, which
3542: compiles a string to be used as an error message and does a conditional
3543: @code{abort} at run-time. For example:
1.1 anton 3544:
1.26 crook 3545: @example
1.30 anton 3546: @kbd{: checker abort" That flag was true" ." A false flag" ;@key{RET}} ok
3547: @kbd{0 checker@key{RET}} A false flag ok
3548: @kbd{1 checker@key{RET}}
1.26 crook 3549: :1: That flag was true
3550: 1 checker
3551: ^^^^^^^
3552: $400D1648 throw
3553: $400E4660
3554: @end example
1.1 anton 3555:
1.26 crook 3556: These simple techniques allow a program to react to a fatal error
3557: condition, but they are not exactly user-friendly. The ANS Forth
3558: Exception word set provides the pair of words @code{throw} and
3559: @code{catch}, which can be used to provide sophisticated error-handling.
1.1 anton 3560:
1.26 crook 3561: @code{catch} has a similar behaviour to @code{execute}, in that it takes
1.29 crook 3562: an @i{xt} as a parameter and starts execution of the xt. However,
1.26 crook 3563: before passing control to the xt, @code{catch} pushes an
1.29 crook 3564: @dfn{exception frame} onto the @dfn{exception stack}. This exception
1.26 crook 3565: frame is used to restore the system to a known state if a detected error
3566: occurs during the execution of the xt. A typical way to use @code{catch}
3567: would be:
1.1 anton 3568:
1.26 crook 3569: @example
3570: ... ['] foo catch IF ...
3571: @end example
1.1 anton 3572:
1.26 crook 3573: Whilst @code{foo} executes, it can call other words to any level of
3574: nesting, as usual. If @code{foo} (and all the words that it calls)
3575: execute successfully, control will ultimately passes to the word following
3576: the @code{catch}, and there will be a @code{true} flag (0) at
3577: TOS. However, if any word detects an error, it can terminate the
3578: execution of @code{foo} by pushing an error code onto the stack and then
3579: performing a @code{throw}. The execution of @code{throw} will pass
3580: control to the word following the @code{catch}, but this time the TOS
3581: will hold the error code. Therefore, the @code{IF} in the example
3582: can be used to determine whether @code{foo} executed successfully.
1.1 anton 3583:
1.26 crook 3584: This simple example shows how you can use @code{throw} and @code{catch}
3585: to ``take over'' exception handling from the system:
1.1 anton 3586: @example
1.26 crook 3587: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
1.1 anton 3588: @end example
3589:
1.26 crook 3590: The next example is more sophisticated and shows a multi-level
3591: @code{throw} and @code{catch}. To understand this example, start at the
3592: definition of @code{top-level} and work backwards:
3593:
1.1 anton 3594: @example
1.26 crook 3595: : lowest-level ( -- c )
3596: key dup 27 = if
3597: 1 throw \ ESCAPE key pressed
3598: else
3599: ." lowest-level successfull" CR
3600: then
3601: ;
3602:
3603: : lower-level ( -- c )
3604: lowest-level
3605: \ at this level consider a CTRL-U to be a fatal error
3606: dup 21 = if \ CTRL-U
3607: 2 throw
3608: else
3609: ." lower-level successfull" CR
3610: then
3611: ;
3612:
3613: : low-level ( -- c )
3614: ['] lower-level catch
3615: ?dup if
3616: \ error occurred - do we recognise it?
3617: dup 1 = if
3618: \ ESCAPE key pressed.. pretend it was an E
3619: [char] E
3620: else throw \ propogate the error upwards
3621: then
3622: then
3623: ." low-level successfull" CR
3624: ;
3625:
3626: : top-level ( -- )
3627: CR ['] low-level catch \ CATCH is used like EXECUTE
3628: ?dup if \ error occurred..
3629: ." Error " . ." occurred - contact your supplier"
3630: else
3631: ." The '" emit ." ' key was pressed" CR
3632: then
3633: ;
1.1 anton 3634: @end example
3635:
1.26 crook 3636: The ANS Forth document assigns @code{throw} codes thus:
1.1 anton 3637:
1.26 crook 3638: @itemize @bullet
3639: @item
3640: codes in the range -1 -- -255 are reserved to be assigned by the
3641: Standard. Assignments for codes in the range -1 -- -58 are currently
3642: documented in the Standard. In particular, @code{-1 throw} is equivalent
3643: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
3644: @item
3645: codes in the range -256 -- -4095 are reserved to be assigned by the system.
3646: @item
3647: all other codes may be assigned by programs.
3648: @end itemize
1.1 anton 3649:
1.26 crook 3650: Gforth provides the word @code{exception} as a mechanism for assigning
3651: system throw codes to applications. This allows multiple applications to
3652: co-exist in memory without any clash of @code{throw} codes. A definition
3653: of @code{exception} in ANS Forth is provided in
3654: @file{compat/exception.fs}.
1.1 anton 3655:
1.26 crook 3656: doc-quit
3657: doc-abort
3658: doc-abort"
1.1 anton 3659:
1.26 crook 3660: doc-catch
1.29 crook 3661: doc-throw
3662: doc---exception-exception
3663:
3664:
3665: @c -------------------------------------------------------------
3666: @node Defining Words, The Text Interpreter, Control Structures, Words
3667: @section Defining Words
3668: @cindex defining words
3669:
3670: @menu
3671: * Simple Defining Words:: Variables, values and constants
3672: * Colon Definitions::
3673: * User-defined Defining Words::
3674: * Supplying names::
3675: * Interpretation and Compilation Semantics::
3676: @end menu
3677:
3678: @node Simple Defining Words, Colon Definitions, Defining Words, Defining Words
3679: @subsection Simple Defining Words
3680: @cindex simple defining words
3681: @cindex defining words, simple
3682:
3683: Defining words are used to create new entries in the dictionary. The
3684: simplest defining word is @code{CREATE}. @code{CREATE} is used like
3685: this:
3686:
3687: @example
3688: CREATE new-word1
3689: @end example
3690:
3691: @code{CREATE} is a parsing word that generates a dictionary entry for
3692: @code{new-word1}. When @code{new-word1} is executed, all that it does is
3693: leave an address on the stack. The address represents the value of
3694: the data space pointer (@code{HERE}) at the time that @code{new-word1}
3695: was defined. Therefore, @code{CREATE} is a way of associating a name
3696: with the address of a region of memory.
3697:
3698: By extending this example to reserve some memory in data space, we end
3699: up with a @i{variable}. Here are two different ways to do it:
3700:
3701: @example
3702: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
3703: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
3704: @end example
3705:
3706: The variable can be examined and modified using @code{@@} (``fetch'') and
3707: @code{!} (``store'') like this:
3708:
3709: @example
3710: new-word2 @@ . \ get address, fetch from it and display
3711: 1234 new-word2 ! \ new value, get address, store to it
3712: @end example
3713:
3714: As a final refinement, the whole code sequence can be wrapped up in a
3715: defining word (pre-empting the subject of the next section), making it
3716: easier to create new variables:
3717:
3718: @example
3719: : myvariable ( "name" -- a-addr ) CREATE 1 cells allot ;
3720:
3721: myvariable foo
3722: myvariable joe
3723:
3724: 45 3 * foo ! \ set foo to 135
3725: 1234 joe ! \ set joe to 1234
3726: 3 joe +! \ increment joe by 3.. to 1237
3727: @end example
3728:
3729: Not surprisingly, there is no need to define @code{myvariable}, since
3730: Forth already has a definition @code{Variable}. It behaves in exactly
3731: the same way as @code{myvariable} but it is implemented in an optimised
3732: way. Forth also provides @code{2Variable} and @code{fvariable} for
3733: double and floating-point variables, respectively.
3734:
3735: @cindex arrays
3736: A similar mechanism can be used to create arrays. For example, an
3737: 80-character text input buffer:
3738:
3739: @example
3740: CREATE text-buf 80 chars allot
3741:
3742: text-buf 0 chars c@@ \ the 1st character (offset 0)
3743: text-buf 3 chars c@@ \ the 4th character (offset 3)
3744: @end example
3745:
3746: You can build arbitrarily complex data structures by allocating
3747: appropriate areas of memory. @xref{Structures} for further discussions
3748: of this, and to learn about some Gforth tools that make it easier.
3749:
3750: @cindex user variables
3751: @cindex user space
3752: The defining word @code{User} behaves in the same way as @code{Variable}.
3753: The difference is that it reserves space in @i{user (data) space} rather
3754: than normal data space. In a Forth system that has a multi-tasker, each
3755: task has its own set of user variables.
3756:
3757: @comment TODO is that stuff about user variables strictly correct? Is it
3758: @comment just terminal tasks that have user variables?
3759: @comment should document tasker.fs (with some examples) elsewhere
3760: @comment in this manual, then expand on user space and user variables.
3761:
3762: After @code{CREATE} and @code{Variable}s, the next defining word to
3763: consider is @code{Constant}. @code{Constant} allows you to declare a
3764: fixed value and refer to it by name. For example:
3765:
3766: @example
3767: 12 Constant INCHES-PER-FOOT
3768: 3E+08 fconstant SPEED-O-LIGHT
3769: @end example
3770:
3771: A @code{Variable} can be both read and written, so its run-time
3772: behaviour is to supply an address through which its current value can be
3773: manipulated. In contrast, the value of a @code{Constant} cannot be
3774: changed once it has been declared@footnote{Well, often it can be -- but
3775: not in a Standard, portable way. It's safer to use a @code{Value} (read
3776: on).} so it's not necessary to supply the address -- it is more
3777: efficient to return the value of the constant directly. That's exactly
3778: what happens; the run-time effect of a constant is to put its value on
3779: the top of the stack (@ref{User-defined Defining Words} describes one
3780: way of implementing @code{Constant}).
3781:
3782: Gforth also provides @code{2Constant} and @code{fconstant} for defining
3783: double and floating-point constants, respectively.
3784:
3785: Constants in Forth behave differently from their equivalents in other
3786: programming languages. In other languages, a constant (such as an EQU in
3787: assembler or a #define in C) only exists at compile-time; in the
3788: executable program the constant has been translated into an absolute
3789: number and, unless you are using a symbolic debugger, it's impossible to
3790: know what abstract thing that number represents. In Forth a constant has
1.32 ! anton 3791: an entry in the header space and remains there after the code that
1.29 crook 3792: uses it has been defined. In fact, it must remain in the dictionary
3793: since it has run-time duties to perform. For example:
3794:
3795: @example
3796: 12 Constant INCHES-PER-FOOT
3797: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
3798: @end example
3799:
3800: @cindex in-lining of constants
3801: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
3802: associated with the constant @code{INCHES-PER-FOOT}. If you use
3803: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
3804: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
3805: attempt to optimise constants by in-lining them where they are used. You
3806: can force Gforth to in-line a constant like this:
3807:
3808: @example
3809: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
3810: @end example
3811:
3812: If you use @code{see} to decompile @i{this} version of
3813: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
3814: longer present. @xref{Interpret/Compile states} and @xref{Literals}
3815: explain to this works.
3816:
3817: In-lining constants in this way might improve execution time
3818: fractionally, and can ensure that a constant is now only referenced at
3819: compile-time. However, the definition of the constant still remains in
3820: the dictionary. Some Forth compilers provide a mechanism for controlling
3821: a second dictionary for holding transient words such that this second
3822: dictionary can be deleted later in order to recover memory
3823: space. However, there is no standard way of doing this.
3824:
3825: One aspect of constants and variables that can sometimes be confusing is
3826: that they have different stack effects; one returns its value whilst the
3827: other returns the address of its value. The defining word @code{Value}
3828: provides an alternative to @code{Variable}, and has the same stack
3829: effect as a constant. A @code{Value} needs an additional word, @code{TO}
3830: to allow its value to be changed. Here are some examples:
3831:
3832: @example
3833: 12 Value APPLES \ a Value is initialised when it is declared.. like a
3834: \ constant but unlike a variable
3835: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
3836: APPLES \ puts 34 on the top of the stack.
3837: @end example
3838:
3839: The defining word @code{Defer} allows you to define a word by name
3840: without defining its behaviour; the definition of its behaviour is
3841: deferred. Here are two situation where this can be useful:
3842:
3843: @itemize @bullet
3844: @item
3845: Where you want to allow the behaviour of a word to be altered later, and
3846: for all precompiled references to the word to change when its behaviour
3847: is changed.
3848: @item
3849: For mutual recursion; @xref{Calls and returns}.
3850: @end itemize
3851:
3852: In the following example, @code{foo} always invokes the version of
3853: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
3854: always invokes the version that prints ``@code{Hello}''. There is no way
3855: of getting @code{foo} to use the later version without re-ordering the
3856: source code and recompilng it.
3857:
3858: @example
3859: : greet ." Good morning" ;
3860: : foo ... greet ... ;
3861: : greet ." Hello" ;
3862: : bar ... greet ... ;
3863: @end example
3864:
3865: This problem can be solved by defining @code{greet} as a @code{Defer}red
3866: word. The behaviour of a @code{Defer}red word can be defined and
3867: redefined at any time by using @code{IS} to associate the xt of a
3868: previously-defined word with it. The previous example becomes:
3869:
3870: @example
3871: Defer greet
3872: : foo ... greet ... ;
3873: : bar ... greet ... ;
3874: : greet1 ." Good morning" ;
3875: : greet2 ." Hello" ;
3876: ' greet2 IS greet \ make greet behave like greet2
3877: @end example
3878:
3879: A deferred word can only inherit default semantics from the xt (because
3880: that is all that an xt can represent -- @pxref{Tokens for Words} for
3881: more discussion of this). However, the semantics of the deferred word
3882: itself can be modified at the time that it is defined. For example:
3883:
3884: @example
3885: : bar .... ; compile-only
3886: Defer fred immediate
3887: Defer jim
3888:
3889: ' bar IS jim \ jim has default semantics
3890: ' bar IS fred \ fred is immediate
3891: @end example
1.1 anton 3892:
1.29 crook 3893: The defining word @code{Alias} allows you to define a word by name that
3894: has the same behaviour as some other word. Here are two situation where
3895: this can be useful:
1.1 anton 3896:
1.29 crook 3897: @itemize @bullet
3898: @item
3899: When you want access to a word's definition from a different word list
3900: (for an example of this, see the definition of the @code{Root} word list
3901: in the Gforth source).
3902: @item
3903: When you want to create a synonym; a definition that can be known by
3904: either of two names (for example, @code{THEN} and @code{ENDIF} are
3905: aliases).
3906: @end itemize
1.1 anton 3907:
1.29 crook 3908: The word whose behaviour the alias is to inherit is represented by an
3909: xt. Therefore, the alias can only inherits default semantics from its
3910: ancestor. The semantics of the alias itself can be modified at the time
3911: that it is defined. For example:
1.1 anton 3912:
1.29 crook 3913: @example
3914: : foo ... ; immediate
1.1 anton 3915:
1.29 crook 3916: ' foo Alias bar \ bar is not an immediate word
3917: ' foo Alias fooby immediate \ fooby is an immediate word
3918: @end example
1.26 crook 3919:
1.29 crook 3920: Words that are aliases have the same xt. Their semantics can differ
3921: because the rules about a word's semantics are stored in the name
3922: dictionary, and the aliases each have their own dictionary entry. It
3923: follows that words that are aliases have different name tokens and may
3924: have the same or different compilation tokens. Once again, see
3925: @ref{Tokens for Words} for more discussions of this.
1.27 crook 3926:
1.29 crook 3927: doc-create
1.26 crook 3928: doc-variable
3929: doc-2variable
3930: doc-fvariable
3931: doc-user
1.29 crook 3932: doc-constant
3933: doc-2constant
3934: doc-fconstant
1.26 crook 3935: doc-value
3936: doc-to
3937: doc-defer
3938: doc-is
1.29 crook 3939: doc-alias
3940: @comment TODO document these: what's defers <is> [is]
3941: doc-what's
1.28 crook 3942: doc-defers
1.26 crook 3943:
3944: Definitions in ANS Forth for @code{defer}, @code{<is>} and
3945: @code{[is]} are provided in @file{compat/defer.fs}.
1.29 crook 3946:
1.1 anton 3947:
1.26 crook 3948: @node Colon Definitions, User-defined Defining Words, Simple Defining Words, Defining Words
3949: @subsection Colon Definitions
3950: @cindex colon definitions
1.1 anton 3951:
1.26 crook 3952: @example
3953: : name ( ... -- ... )
3954: word1 word2 word3 ;
3955: @end example
1.1 anton 3956:
1.29 crook 3957: @noindent
3958: Creates a word called @code{name} that, upon execution, executes
1.26 crook 3959: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.1 anton 3960:
1.29 crook 3961: The explanation above is somewhat superficial. @xref{Your first
3962: definition} for simple examples of colon definitions, then
3963: @xref{Interpretation and Compilation Semantics} for an in-depth
3964: discussion of some of the issues involved.
1.26 crook 3965:
3966: doc-:
3967: doc-;
1.1 anton 3968:
1.26 crook 3969: @node User-defined Defining Words, Supplying names, Colon Definitions, Defining Words
3970: @subsection User-defined Defining Words
3971: @cindex user-defined defining words
3972: @cindex defining words, user-defined
1.1 anton 3973:
1.29 crook 3974: You can create a new defining word by wrapping defining-time code around
3975: an existing defining word and putting the sequence in a colon
3976: definition. For example, suppose that you have a word @code{stats} that
3977: gathers statistics about colon definitions given the @i{xt} of the
3978: definition, and you want every colon definition in your application to
3979: make a call to @code{stats}. You can define and use a new version of
3980: @code{:} like this:
3981:
3982: @example
3983: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
3984: ... ; \ other code
3985:
3986: : my: : lastxt postpone literal ['] stats compile, ;
3987:
3988: my: foo + - ;
3989: @end example
3990:
3991: When @code{foo} is defined using @code{my:} these steps occur:
3992:
3993: @itemize @bullet
3994: @item
3995: @code{my:} is executed.
3996: @item
3997: The @code{:} within the definition (the one between @code{my:} and
3998: @code{lastxt}) is executed, and does just what it always does; it parses
3999: the input stream for a name, builds a dictionary header for the name
4000: @code{foo} and switches @code{state} from interpret to compile.
4001: @item
4002: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
4003: being defined -- @code{foo} -- onto the stack.
4004: @item
4005: The code that was produced by @code{postpone literal} is executed; this
4006: causes the value on the stack to be compiled as a literal in the code
4007: area of @code{foo}.
4008: @item
4009: The code @code{['] stats} compiles a literal into the definition of
4010: @code{my:}. When @code{compile,} is executed, that literal -- the
4011: execution token for @code{stats} -- is layed down in the code area of
4012: @code{foo} , following the literal@footnote{Strictly speaking, the
4013: mechanism that @code{compile,} uses to convert an @i{xt} into something
4014: in the code area is implementation-dependent. A threaded implementation
4015: might spit out the execution token directly whilst another
4016: implementation might spit out a native code sequence.}.
4017: @item
4018: At this point, the execution of @code{my:} is complete, and control
4019: returns to the text interpreter. The text interpreter is in compile
4020: state, so subsequent text @code{+ -} is compiled into the definition of
4021: @code{foo} and the @code{;} terminates the definition as always.
4022: @end itemize
4023:
4024: You can use @code{see} to decompile a word that was defined using
4025: @code{my:} and see how it is different from a normal @code{:}
4026: definition. For example:
4027:
4028: @example
4029: : bar + - ; \ like foo but using : rather than my:
4030: see bar
4031: : bar
4032: + - ;
4033: see foo
4034: : foo
4035: 107645672 stats + - ;
4036:
4037: \ use ' stats . to show that 107645672 is the xt for stats
4038: @end example
4039:
4040:
4041: Rather than edit your application's source code to change every @code{:}
4042: to a @code{my:}, use a deferred word:
4043:
4044: @example
4045: : real: : ; \ retain access to the original
4046: defer : \ redefine as a deferred word
4047: ' my: IS : \ use special version of :
4048: \
4049: \ load application here
4050: \
4051: ' real: IS : \ go back to the original
4052: @end example
4053:
4054: You can use techniques like this to make new defining words in terms of
4055: @i{any} existing defining word.
1.1 anton 4056:
4057:
1.29 crook 4058: @cindex defining defining words
1.26 crook 4059: @cindex @code{CREATE} ... @code{DOES>}
4060: If you want the words defined with your defining words to behave
4061: differently from words defined with standard defining words, you can
4062: write your defining word like this:
1.1 anton 4063:
4064: @example
1.26 crook 4065: : def-word ( "name" -- )
1.29 crook 4066: CREATE @i{code1}
1.26 crook 4067: DOES> ( ... -- ... )
1.29 crook 4068: @i{code2} ;
1.26 crook 4069:
4070: def-word name
1.1 anton 4071: @end example
4072:
1.29 crook 4073: @cindex child words
4074: This fragment defines a @dfn{defining word} @code{def-word} and then
4075: executes it. When @code{def-word} executes, it @code{CREATE}s a new
4076: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
4077: is not executed at this time. The word @code{name} is sometimes called a
4078: @dfn{child} of @code{def-word}.
4079:
4080: When you execute @code{name}, the address of the body of @code{name} is
4081: put on the data stack and @i{code2} is executed (the address of the body
4082: of @code{name} is the address @code{HERE} returns immediately after the
4083: @code{CREATE}).
4084:
4085: @cindex atavism in child words
4086: You can use @code{def-word} to define a set of child word that behave
4087: differently, though atavistically; they all have a common run-time
4088: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
4089: builds a data area in the body of the child word. The structure of the
4090: data is common to all children of @code{def-word}, but the data values
4091: are specific -- and private -- to each child word. When a child word is
4092: executed, the address of its private data area is passed as a parameter
4093: on TOS to be used and manipulated@footnote{It is legitimate both to read
4094: and write to this data area.} by @i{code2}.
4095:
4096: The two fragments of code that make up the defining words act (are
4097: executed) at two completely separate times:
1.1 anton 4098:
1.29 crook 4099: @itemize @bullet
4100: @item
4101: At @i{define time}, the defining word executes @i{code1} to generate a
4102: child word
4103: @item
4104: At @i{child execution time}, when a child word is invoked, @i{code2}
4105: is executed, using parameters (data) that are private and specific to
4106: the child word.
4107: @end itemize
4108:
4109: @c NAC I think this is a really bad example, because it diminishes
4110: @c rather than emphasising the fact that some important stuff happens
4111: @c at define time, and other important stuff happens at child-invocation
4112: @c time, and that those two times are potentially very different.
4113: @c
4114: @c In other words, if you make the following definitions:
4115: @c @example
4116: @c : def-word1 ( "name" -- )
4117: @c CREATE @i{code1} ;
4118: @c
4119: @c : action1 ( ... -- ... )
4120: @c @i{code2} ;
4121: @c
4122: @c def-word1 name1
4123: @c @end example
4124: @c
4125: @c Using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 4126:
1.29 crook 4127: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 4128:
1.1 anton 4129: @example
1.29 crook 4130: : CONSTANT ( w "name" -- )
4131: CREATE ,
1.26 crook 4132: DOES> ( -- w )
4133: @@ ;
1.1 anton 4134: @end example
4135:
1.29 crook 4136: @comment There is a beautiful description of how this works and what
4137: @comment it does in the Forthwrite 100th edition.. as well as an elegant
4138: @comment commentary on the Counting Fruits problem.
4139:
4140: When you create a constant with @code{5 CONSTANT five}, a set of
4141: define-time actions take place; first a new word @code{five} is created,
4142: then the value 5 is laid down in the body of @code{five} with
4143: @code{,}. When @code{five} is invoked, the address of the body is put on
4144: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
4145: no code of its own; it simply contains a data field and a pointer to the
4146: code that follows @code{DOES>} in its defining word. That makes words
4147: created in this way very compact.
4148:
4149: The final example in this section is intended to remind you that space
4150: reserved in @code{CREATE}d words is @i{data} space and therefore can be
4151: both read and written by a Standard program@footnote{Exercise: use this
4152: example as a starting point for your own implementation of @code{Value}
4153: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
4154: @code{[']}.}:
4155:
4156: @example
4157: : foo ( "name" -- )
4158: CREATE -1 ,
4159: DOES> ( -- )
4160: @@ .;
4161:
4162: foo first-word
4163: foo second-word
4164:
4165: 123 ' first-word >BODY !
4166: @end example
4167:
4168: If @code{first-word} had been a @code{CREATE}d word, we could simply
4169: have executed it to get the address of its data field. However, since it
4170: was defined to have @code{DOES>} actions, its execution semantics are to
4171: perform those @code{DOES>} actions. To get the address of its data field
4172: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
4173: translate the xt into the address of the data field. When you execute
4174: @code{first-word}, it will display @code{123}. When you execute
4175: @code{second-word} it will display @code{-1}.
1.26 crook 4176:
4177: @cindex stack effect of @code{DOES>}-parts
4178: @cindex @code{DOES>}-parts, stack effect
1.29 crook 4179: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 4180: the stack effect of the defined words, not the stack effect of the
4181: following code (the following code expects the address of the body on
4182: the top of stack, which is not reflected in the stack comment). This is
4183: the convention that I use and recommend (it clashes a bit with using
4184: locals declarations for stack effect specification, though).
1.1 anton 4185:
1.26 crook 4186: @subsubsection Applications of @code{CREATE..DOES>}
4187: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 4188:
1.26 crook 4189: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 4190:
1.26 crook 4191: @cindex factoring similar colon definitions
4192: When you see a sequence of code occurring several times, and you can
4193: identify a meaning, you will factor it out as a colon definition. When
4194: you see similar colon definitions, you can factor them using
4195: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
4196: that look very similar:
1.1 anton 4197: @example
1.26 crook 4198: : ori, ( reg-target reg-source n -- )
4199: 0 asm-reg-reg-imm ;
4200: : andi, ( reg-target reg-source n -- )
4201: 1 asm-reg-reg-imm ;
1.1 anton 4202: @end example
4203:
1.26 crook 4204: @noindent
4205: This could be factored with:
4206: @example
4207: : reg-reg-imm ( op-code -- )
4208: CREATE ,
4209: DOES> ( reg-target reg-source n -- )
4210: @@ asm-reg-reg-imm ;
4211:
4212: 0 reg-reg-imm ori,
4213: 1 reg-reg-imm andi,
4214: @end example
1.1 anton 4215:
1.26 crook 4216: @cindex currying
4217: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
4218: supply a part of the parameters for a word (known as @dfn{currying} in
4219: the functional language community). E.g., @code{+} needs two
4220: parameters. Creating versions of @code{+} with one parameter fixed can
4221: be done like this:
1.1 anton 4222: @example
1.26 crook 4223: : curry+ ( n1 -- )
4224: CREATE ,
4225: DOES> ( n2 -- n1+n2 )
4226: @@ + ;
4227:
4228: 3 curry+ 3+
4229: -2 curry+ 2-
1.1 anton 4230: @end example
4231:
1.26 crook 4232: @subsubsection The gory details of @code{CREATE..DOES>}
4233: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 4234:
1.26 crook 4235: doc-does>
1.1 anton 4236:
1.26 crook 4237: @cindex @code{DOES>} in a separate definition
4238: This means that you need not use @code{CREATE} and @code{DOES>} in the
4239: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 4240: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 4241: @example
4242: : does1
4243: DOES> ( ... -- ... )
4244: ... ;
1.1 anton 4245:
1.26 crook 4246: : does2
4247: DOES> ( ... -- ... )
4248: ... ;
1.1 anton 4249:
1.26 crook 4250: : def-word ( ... -- ... )
4251: create ...
4252: IF
4253: does1
4254: ELSE
4255: does2
4256: ENDIF ;
4257: @end example
1.1 anton 4258:
1.26 crook 4259: In this example, the selection of whether to use @code{does1} or
4260: @code{does2} is made at compile-time; at the time that the child word is
1.29 crook 4261: @code{CREATE}d.
1.1 anton 4262:
1.26 crook 4263: @cindex @code{DOES>} in interpretation state
4264: In a standard program you can apply a @code{DOES>}-part only if the last
4265: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
4266: will override the behaviour of the last word defined in any case. In a
4267: standard program, you can use @code{DOES>} only in a colon
4268: definition. In Gforth, you can also use it in interpretation state, in a
4269: kind of one-shot mode; for example:
1.1 anton 4270: @example
1.26 crook 4271: CREATE name ( ... -- ... )
1.29 crook 4272: @i{initialization}
1.26 crook 4273: DOES>
1.29 crook 4274: @i{code} ;
1.1 anton 4275: @end example
4276:
1.26 crook 4277: @noindent
4278: is equivalent to the standard:
1.1 anton 4279: @example
1.26 crook 4280: :noname
4281: DOES>
1.29 crook 4282: @i{code} ;
1.26 crook 4283: CREATE name EXECUTE ( ... -- ... )
1.29 crook 4284: @i{initialization}
1.1 anton 4285: @end example
4286:
1.26 crook 4287: You can get the address of the body of a word with:
4288:
4289: doc->body
1.1 anton 4290:
1.26 crook 4291: @node Supplying names, Interpretation and Compilation Semantics, User-defined Defining Words, Defining Words
1.29 crook 4292: @subsection Supplying the name of a defined word
1.26 crook 4293: @cindex names for defined words
4294: @cindex defining words, name parameter
1.1 anton 4295:
1.26 crook 4296: @cindex defining words, name given in a string
1.29 crook 4297: By default, a defining word takes the name for the defined word from the
1.26 crook 4298: input stream. Sometimes you want to supply the name from a string. You
4299: can do this with:
1.1 anton 4300:
1.26 crook 4301: doc-nextname
1.1 anton 4302:
1.26 crook 4303: For example:
1.1 anton 4304:
1.26 crook 4305: @example
4306: s" foo" nextname create
4307: @end example
4308: @noindent
4309: is equivalent to:
4310: @example
4311: create foo
4312: @end example
1.1 anton 4313:
1.26 crook 4314: @cindex defining words without name
1.29 crook 4315: Sometimes you want to define an @dfn{anonymous word}; a word without a
1.26 crook 4316: name. You can do this with:
1.1 anton 4317:
1.26 crook 4318: doc-:noname
1.1 anton 4319:
1.26 crook 4320: This leaves the execution token for the word on the stack after the
4321: closing @code{;}. Here's an example in which a deferred word is
4322: initialised with an @code{xt} from an anonymous colon definition:
4323: @example
4324: Defer deferred
4325: :noname ( ... -- ... )
4326: ... ;
4327: IS deferred
4328: @end example
1.1 anton 4329:
1.29 crook 4330: @noindent
1.26 crook 4331: Gforth provides an alternative way of doing this, using two separate
4332: words:
1.1 anton 4333:
1.26 crook 4334: doc-noname
4335: @cindex execution token of last defined word
4336: doc-lastxt
1.1 anton 4337:
1.29 crook 4338: @noindent
1.26 crook 4339: The previous example can be rewritten using @code{noname} and
4340: @code{lastxt}:
1.1 anton 4341:
1.26 crook 4342: @example
4343: Defer deferred
4344: noname : ( ... -- ... )
4345: ... ;
4346: lastxt IS deferred
4347: @end example
1.1 anton 4348:
1.29 crook 4349: @noindent
1.26 crook 4350: @code{lastxt} also works when the last word was not defined as
1.29 crook 4351: @code{noname}. It also has the useful property that is is valid as soon
4352: as the header for a definition has been build. Thus:
4353:
4354: @example
4355: lastxt . : foo [ lastxt . ] ; ' foo .
4356: @end example
4357:
4358: @noindent
4359: prints 3 numbers; the last two are the same.
1.1 anton 4360:
4361:
1.26 crook 4362: @node Interpretation and Compilation Semantics, , Supplying names, Defining Words
4363: @subsection Interpretation and Compilation Semantics
4364: @cindex semantics, interpretation and compilation
1.1 anton 4365:
1.26 crook 4366: @cindex interpretation semantics
4367: The @dfn{interpretation semantics} of a word are what the text
4368: interpreter does when it encounters the word in interpret state. It also
4369: appears in some other contexts, e.g., the execution token returned by
1.29 crook 4370: @code{' @i{word}} identifies the interpretation semantics of
4371: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
4372: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 4373:
1.26 crook 4374: @cindex compilation semantics
4375: The @dfn{compilation semantics} of a word are what the text interpreter
4376: does when it encounters the word in compile state. It also appears in
1.29 crook 4377: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
1.26 crook 4378: standard terminology, ``appends to the current definition''.} the
1.29 crook 4379: compilation semantics of @i{word}.
1.1 anton 4380:
1.26 crook 4381: @cindex execution semantics
4382: The standard also talks about @dfn{execution semantics}. They are used
4383: only for defining the interpretation and compilation semantics of many
4384: words. By default, the interpretation semantics of a word are to
4385: @code{execute} its execution semantics, and the compilation semantics of
4386: a word are to @code{compile,} its execution semantics.@footnote{In
4387: standard terminology: The default interpretation semantics are its
4388: execution semantics; the default compilation semantics are to append its
4389: execution semantics to the execution semantics of the current
4390: definition.}
4391:
4392: @comment TODO expand, make it co-operate with new sections on text interpreter.
4393:
4394: @cindex immediate words
4395: @cindex compile-only words
4396: You can change the semantics of the most-recently defined word:
4397:
4398: doc-immediate
4399: doc-compile-only
4400: doc-restrict
4401:
4402: Note that ticking (@code{'}) a compile-only word gives an error
4403: (``Interpreting a compile-only word'').
1.1 anton 4404:
1.26 crook 4405: Gforth also allows you to define words with arbitrary combinations of
4406: interpretation and compilation semantics.
1.1 anton 4407:
1.26 crook 4408: doc-interpret/compile:
1.1 anton 4409:
1.26 crook 4410: This feature was introduced for implementing @code{TO} and @code{S"}. I
4411: recommend that you do not define such words, as cute as they may be:
4412: they make it hard to get at both parts of the word in some contexts.
4413: E.g., assume you want to get an execution token for the compilation
4414: part. Instead, define two words, one that embodies the interpretation
4415: part, and one that embodies the compilation part. Once you have done
4416: that, you can define a combined word with @code{interpret/compile:} for
4417: the convenience of your users.
1.1 anton 4418:
1.26 crook 4419: You might try to use this feature to provide an optimizing
4420: implementation of the default compilation semantics of a word. For
4421: example, by defining:
1.1 anton 4422: @example
1.26 crook 4423: :noname
4424: foo bar ;
4425: :noname
4426: POSTPONE foo POSTPONE bar ;
1.29 crook 4427: interpret/compile: opti-foobar
1.1 anton 4428: @end example
1.26 crook 4429:
1.23 crook 4430: @noindent
1.26 crook 4431: as an optimizing version of:
4432:
1.1 anton 4433: @example
1.26 crook 4434: : foobar
4435: foo bar ;
1.1 anton 4436: @end example
4437:
1.26 crook 4438: Unfortunately, this does not work correctly with @code{[compile]},
4439: because @code{[compile]} assumes that the compilation semantics of all
4440: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 4441: opti-foobar} would compile compilation semantics, whereas
4442: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 4443:
1.26 crook 4444: @cindex state-smart words (are a bad idea)
1.29 crook 4445: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 4446: by @code{interpret/compile:} (words are state-smart if they check
4447: @code{STATE} during execution). E.g., they would try to code
4448: @code{foobar} like this:
1.1 anton 4449:
1.26 crook 4450: @example
4451: : foobar
4452: STATE @@
4453: IF ( compilation state )
4454: POSTPONE foo POSTPONE bar
4455: ELSE
4456: foo bar
4457: ENDIF ; immediate
4458: @end example
1.1 anton 4459:
1.26 crook 4460: Although this works if @code{foobar} is only processed by the text
4461: interpreter, it does not work in other contexts (like @code{'} or
4462: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
4463: for a state-smart word, not for the interpretation semantics of the
4464: original @code{foobar}; when you execute this execution token (directly
4465: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
4466: state, the result will not be what you expected (i.e., it will not
4467: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
4468: write them@footnote{For a more detailed discussion of this topic, see
4469: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
4470: Ertl; presented at EuroForth '98 and available from
4471: @url{http://www.complang.tuwien.ac.at/papers/}}!
1.1 anton 4472:
1.26 crook 4473: @cindex defining words with arbitrary semantics combinations
4474: It is also possible to write defining words that define words with
4475: arbitrary combinations of interpretation and compilation semantics. In
4476: general, they look like this:
1.1 anton 4477:
1.26 crook 4478: @example
4479: : def-word
4480: create-interpret/compile
1.29 crook 4481: @i{code1}
1.26 crook 4482: interpretation>
1.29 crook 4483: @i{code2}
1.26 crook 4484: <interpretation
4485: compilation>
1.29 crook 4486: @i{code3}
1.26 crook 4487: <compilation ;
4488: @end example
1.1 anton 4489:
1.29 crook 4490: For a @i{word} defined with @code{def-word}, the interpretation
4491: semantics are to push the address of the body of @i{word} and perform
4492: @i{code2}, and the compilation semantics are to push the address of
4493: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 4494: can also be defined like this (except that the defined constants don't
4495: behave correctly when @code{[compile]}d):
1.1 anton 4496:
1.26 crook 4497: @example
4498: : constant ( n "name" -- )
4499: create-interpret/compile
4500: ,
4501: interpretation> ( -- n )
4502: @@
4503: <interpretation
4504: compilation> ( compilation. -- ; run-time. -- n )
4505: @@ postpone literal
4506: <compilation ;
4507: @end example
1.1 anton 4508:
1.26 crook 4509: doc-create-interpret/compile
4510: doc-interpretation>
4511: doc-<interpretation
4512: doc-compilation>
4513: doc-<compilation
1.1 anton 4514:
1.29 crook 4515: Words defined with @code{interpret/compile:} and
1.26 crook 4516: @code{create-interpret/compile} have an extended header structure that
4517: differs from other words; however, unless you try to access them with
4518: plain address arithmetic, you should not notice this. Words for
4519: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 4520: @code{'} @i{word} @code{>body} also gives you the body of a word created
4521: with @code{create-interpret/compile}.
1.1 anton 4522:
1.27 crook 4523: doc-postpone
1.29 crook 4524: @comment TODO -- expand glossary text for POSTPONE
1.27 crook 4525:
1.26 crook 4526: @c ----------------------------------------------------------
4527: @node The Text Interpreter, Tokens for Words, Defining Words, Words
4528: @section The Text Interpreter
4529: @cindex interpreter - outer
4530: @cindex text interpreter
4531: @cindex outer interpreter
1.1 anton 4532:
1.29 crook 4533: The text interpreter@footnote{This is an expanded version of the
4534: material in @ref{Introducing the Text Interpreter}.} is an endless loop
4535: that processes input from the current input device. A popular
4536: implementation technique for Forth is to implement a @dfn{forth virtual
4537: machine} using a loop called the @dfn{inner interpreter}. Because of
4538: this naming, the text interpreter is also known as the @dfn{outer
1.27 crook 4539: interpreter}.
4540:
1.29 crook 4541: @cindex interpret state
4542: @cindex compile state
4543: The text interpreter operates in one of two states: @dfn{interpret
4544: state} and @dfn{compile state}. The current state is defined by the
4545: aptly-named variable, @code{state}.
4546:
4547: This section starts by describing how the text interpreter behaves when
4548: it is in interpret state, processing input from the user input device --
4549: the keyboard. This is the mode that a Forth system is in after it starts
4550: up.
4551:
4552: @cindex input buffer
4553: @cindex terminal input buffer
4554: The text interpreter works from an area of memory called the @dfn{input
4555: buffer}@footnote{When the text interpreter is processing input from the
4556: keyboard, this area of memory is called the @dfn{terminal input buffer}
4557: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
4558: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 4559: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 4560: leading spaces (called @dfn{delimiters}) then parses a string (a
4561: sequence of non-space characters) until it reaches either a space
4562: character or the end of the buffer. Having parsed a string, it makes two
4563: attempts to process it:
1.27 crook 4564:
1.29 crook 4565: @cindex dictionary
1.27 crook 4566: @itemize @bullet
4567: @item
1.29 crook 4568: It looks for the string in a @dfn{dictionary} of definitions. If the
4569: string is found, the string names a @dfn{definition} (also known as a
4570: @dfn{word}) and the dictionary search returns information that allows
4571: the text interpreter to perform the word's @dfn{interpretation
4572: semantics}. In most cases, this simply means that the word will be
4573: executed.
1.27 crook 4574: @item
4575: If the string is not found in the dictionary, the text interpreter
1.29 crook 4576: attempts to treat it as a number, using the rules described in
4577: @ref{Number Conversion}. If the string represents a legal number in the
4578: current radix, the number is pushed onto a parameter stack (the data
4579: stack for integers, the floating-point stack for floating-point
4580: numbers).
4581: @end itemize
4582:
4583: If both attempts fail, or if the word is found in the dictionary but has
4584: no interpretation semantics@footnote{This happens if the word was
4585: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
4586: remainder of the input buffer, issues an error message and waits for
4587: more input. If one of the attempts succeeds, the text interpreter
4588: repeats the parsing process until the whole of the input buffer has been
4589: processed, at which point it prints the status message ``@code{ ok}''
4590: and waits for more input.
4591:
4592: @cindex parse area
4593: The text interpreter keeps track of its position in the input buffer by
4594: updating a variable called @code{>IN} (pronounced ``to-in''). The value
4595: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
4596: of the input buffer. The region from offset @code{>IN @@} to the end of
4597: the input buffer is called the @dfn{parse area}@footnote{In other words,
4598: the text interpreter processes the contents of the input buffer by
4599: parsing strings from the parse area until the parse area is empty.}.
4600: This example shows how @code{>IN} changes as the text interpreter parses
4601: the input buffer:
4602:
4603: @example
4604: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
4605: CR ." ->" TYPE ." <-" ; IMMEDIATE
4606:
4607: 1 2 3 remaining + remaining .
4608:
4609: : foo 1 2 3 remaining SWAP remaining ;
4610: @end example
4611:
4612: @noindent
4613: The result is:
4614:
4615: @example
4616: ->+ remaining .<-
4617: ->.<-5 ok
4618:
4619: ->SWAP remaining ;-<
4620: ->;<- ok
4621: @end example
4622:
4623: @cindex parsing words
4624: The value of @code{>IN} can also be modified by a word in the input
4625: buffer that is executed by the text interpreter. This means that a word
4626: can ``trick'' the text interpreter into either skipping a section of the
4627: input buffer@footnote{This is how parsing words work.} or into parsing a
4628: section twice. For example:
1.27 crook 4629:
1.29 crook 4630: @example
4631: : lat ." <<lat>>" ;
4632: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
4633: @end example
4634:
4635: @noindent
4636: When @code{flat} is executed, this output is produced@footnote{Exercise
4637: for the reader: what would happen if the @code{3} were replaced with
4638: @code{4}?}:
4639:
4640: @example
4641: <<flat>><<lat>>
4642: @end example
4643:
4644: @noindent
4645: Two important notes about the behaviour of the text interpreter:
1.27 crook 4646:
4647: @itemize @bullet
4648: @item
4649: It processes each input string to completion before parsing additional
1.29 crook 4650: characters from the input buffer.
4651: @item
4652: It treats the input buffer as a read-only region (and so must your code).
4653: @end itemize
4654:
4655: @noindent
4656: When the text interpreter is in compile state, its behaviour changes in
4657: these ways:
4658:
4659: @itemize @bullet
4660: @item
4661: If a parsed string is found in the dictionary, the text interpreter will
4662: perform the word's @dfn{compilation semantics}. In most cases, this
4663: simply means that the execution semantics of the word will be appended
4664: to the current definition.
1.27 crook 4665: @item
1.29 crook 4666: When a number is encountered, it is compiled into the current definition
4667: (as a literal) rather than being pushed onto a parameter stack.
4668: @item
4669: If an error occurs, @code{state} is modified to put the text interpreter
4670: back into interpret state.
4671: @item
4672: Each time a line is entered from the keyboard, Gforth prints
4673: ``@code{ compiled}'' rather than `` @code{ok}''.
4674: @end itemize
4675:
4676: @cindex text interpreter - input sources
4677: When the text interpreter is using an input device other than the
4678: keyboard, its behaviour changes in these ways:
4679:
4680: @itemize @bullet
4681: @item
4682: When the parse area is empty, the text interpreter attempts to refill
4683: the input buffer from the input source. When the input source is
4684: exhausted, the input source is set back to the user input device.
4685: @item
4686: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
4687: time the parse area is emptied.
4688: @item
4689: If an error occurs, the input source is set back to the user input
4690: device.
1.27 crook 4691: @end itemize
1.21 crook 4692:
1.29 crook 4693: @ref{Input Sources} describes this in more detail.
4694:
1.26 crook 4695: doc->in
1.27 crook 4696: doc-source
4697:
1.26 crook 4698: doc-tib
4699: doc-#tib
1.1 anton 4700:
1.26 crook 4701: @menu
1.29 crook 4702: * Input Sources::
1.26 crook 4703: * Number Conversion::
4704: * Interpret/Compile states::
4705: * Literals::
4706: * Interpreter Directives::
4707: @end menu
1.1 anton 4708:
1.29 crook 4709: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
4710: @subsection Input Sources
4711: @cindex input sources
4712: @cindex text interpreter - input sources
4713:
4714: By default, the text interpreter accepts input from the user input
4715: device (the keyboard) when Forth starts up. The text interpreter can
4716: process input from any of these sources:
4717:
4718: @itemize @bullet
4719: @item
4720: The user input device -- the keyboard.
4721: @item
4722: A file, using the words described in @ref{Forth source files}.
4723: @item
4724: A block, using the words described in @ref{Blocks}.
4725: @item
4726: A text string, using @code{evaluate}.
4727: @end itemize
4728:
4729: A program can identify the current input device from the values of
4730: @code{source-id} and @code{blk}.
4731:
4732: doc-source-id
4733: doc-blk
4734:
4735: doc-save-input
4736: doc-restore-input
4737:
4738: doc-evaluate
1.1 anton 4739:
1.29 crook 4740:
4741: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 4742: @subsection Number Conversion
4743: @cindex number conversion
4744: @cindex double-cell numbers, input format
4745: @cindex input format for double-cell numbers
4746: @cindex single-cell numbers, input format
4747: @cindex input format for single-cell numbers
4748: @cindex floating-point numbers, input format
4749: @cindex input format for floating-point numbers
1.1 anton 4750:
1.29 crook 4751: This section describes the rules that the text interpreter uses when it
4752: tries to convert a string into a number.
1.1 anton 4753:
1.26 crook 4754: Let <digit> represent any character that is a legal digit in the current
1.29 crook 4755: number base@footnote{For example, 0-9 when the number base is decimal or
4756: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 4757:
1.26 crook 4758: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 4759:
1.29 crook 4760: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
4761: in the braces (@i{a} or @i{b} or neither).
1.1 anton 4762:
1.26 crook 4763: Let * represent any number of instances of the previous character
4764: (including none).
1.1 anton 4765:
1.26 crook 4766: Let any other character represent itself.
1.1 anton 4767:
1.29 crook 4768: @noindent
1.26 crook 4769: Now, the conversion rules are:
1.21 crook 4770:
1.26 crook 4771: @itemize @bullet
4772: @item
4773: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 4774: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 4775: @item
4776: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 4777: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 4778: arithmetic. Examples are -45 -5681 -0
4779: @item
4780: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 4781: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
4782: (all three of these represent the same number).
1.26 crook 4783: @item
4784: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 4785: double-precision (double-cell-sized) negative integer, and is
1.26 crook 4786: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 4787: -34.65 (all three of these represent the same number).
1.26 crook 4788: @item
1.29 crook 4789: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
4790: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.26 crook 4791: number. Examples are 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 4792: number) +12.E-4
1.26 crook 4793: @end itemize
1.1 anton 4794:
1.26 crook 4795: By default, the number base used for integer number conversion is given
1.29 crook 4796: by the contents of the variable @code{BASE}. Base 10 (decimal) is
1.26 crook 4797: always used for floating-point number conversion.
1.1 anton 4798:
1.29 crook 4799: doc-dpl
1.26 crook 4800: doc-base
4801: doc-hex
4802: doc-decimal
1.1 anton 4803:
1.26 crook 4804: @cindex '-prefix for character strings
4805: @cindex &-prefix for decimal numbers
4806: @cindex %-prefix for binary numbers
4807: @cindex $-prefix for hexadecimal numbers
1.29 crook 4808: Gforth allows you to override the value of @code{BASE} by using a
4809: prefix@footnote{Some Forth implementations provide a similar scheme by
4810: implementing @code{$} etc. as parsing words that process the subsequent
4811: number in the input stream and push it onto the stack. For example, see
4812: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
4813: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
4814: is required between the prefix and the number.} before the first digit
4815: of an (integer) number. Four prefixes are supported:
1.1 anton 4816:
1.26 crook 4817: @itemize @bullet
4818: @item
4819: @code{&} -- decimal number
4820: @item
4821: @code{%} -- binary number
4822: @item
4823: @code{$} -- hexadecimal number
4824: @item
4825: @code{'} -- base 256 number
4826: @end itemize
1.1 anton 4827:
1.26 crook 4828: Here are some examples, with the equivalent decimal number shown after
4829: in braces:
1.1 anton 4830:
1.26 crook 4831: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
4832: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
4833: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
4834: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 4835:
1.26 crook 4836: @cindex number conversion - traps for the unwary
1.29 crook 4837: @noindent
1.26 crook 4838: Number conversion has a number of traps for the unwary:
1.1 anton 4839:
1.26 crook 4840: @itemize @bullet
4841: @item
4842: You cannot determine the current number base using the code sequence
4843: @code{BASE @@ .} -- the number base is always 10 in the current number
4844: base. Instead, use something like @code{BASE @@ DECIMAL DUP . BASE !}
4845: @item
4846: If the number base is set to a value greater than 14 (for example,
4847: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
4848: it to be intepreted as either a single-precision integer or a
4849: floating-point number (Gforth treats it as an integer). The ambiguity
4850: can be resolved by explicitly stating the sign of the mantissa and/or
4851: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
4852: ambiguity arises; either representation will be treated as a
4853: floating-point number.
4854: @item
1.29 crook 4855: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 4856: It is used to specify file types.
4857: @item
4858: ANS Forth requires the @code{.} of a double-precision number to
4859: be the final character in the string. Allowing the @code{.} to be
4860: anywhere after the first digit is a Gforth extension.
4861: @item
4862: The number conversion process does not check for overflow.
4863: @item
4864: In Gforth, number conversion to floating-point numbers always use base
4865: 10, irrespective of the value of @code{BASE}. In ANS Forth,
4866: conversion to floating-point numbers whilst the value of
4867: @code{BASE} is not 10 is an ambiguous condition.
4868: @end itemize
1.1 anton 4869:
1.29 crook 4870: @ref{Input} describes words that you can use to read numbers into your
4871: programs.
1.1 anton 4872:
1.26 crook 4873: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
4874: @subsection Interpret/Compile states
4875: @cindex Interpret/Compile states
1.1 anton 4876:
1.29 crook 4877: A standard program is not permitted to change @code{state}
4878: explicitly. However, it can change @code{state} implicitly, using the
4879: words @code{[} and @code{]}. When @code{[} is executed it switches
4880: @code{state} to interpret state, and therefore the text interpreter
4881: starts interpreting. When @code{]} is executed it switches @code{state}
4882: to compile state and therefore the text interpreter starts
4883: compiling. The most common usage for these words is to compile literals,
4884: as shown in @ref{Literals}. However, they give you the freedom to switch
4885: modes at will. Here is an example of building a jump-table of execution
4886: tokens:
4887:
4888: @example
4889: : AA ." this is A" ;
4890: : BB ." this is B" ;
4891: : CC ." this is C" ;
4892:
4893: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
4894: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
4895: cells table + @ execute ;
4896: @end example
4897:
4898: @noindent
4899: Now @code{0 go} will display ``@code{this is A}''. The table can be
4900: built far more neatly@footnote{The source code is neater.. what is
4901: compiled in memory in each case is identical.} like this:
4902:
4903: @example
4904: create table ] aa bb cc [
4905: @end example
4906:
4907: The problem with this code is that it is not portable; it will only work
4908: on systems where code space and data space co-incide. The reason is that
4909: both tables @i{compile} execution tokens -- into code space. The
4910: Standard only allows data space to be assigned for a @code{CREATE}d
4911: word. In addition, the Standard only allows @code{@@} to access data
4912: space, whilst this example is using it to access code space. The only
4913: portable, Standard way to build this table is to build it in data space,
4914: like this:
4915:
4916: @example
4917: create table ' aa , ' bb , ' cc ,
4918: @end example
4919:
4920: @noindent
4921: A similar technique can be used to build a table of constants:
4922:
4923: @example
4924: create primes 1 , 3 , 5 , 7 , 11 ,
4925: @end example
1.1 anton 4926:
1.26 crook 4927: doc-state
4928: doc-[
4929: doc-]
1.1 anton 4930:
1.26 crook 4931: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
4932: @subsection Literals
4933: @cindex Literals
1.21 crook 4934:
1.29 crook 4935: Often, you want to use a number within a colon definition. When you do
4936: this, the text interpreter automatically compiles the number as a
4937: @i{literal}. A literal is a number whose run-time effect is to be pushed
4938: onto the stack. If you had to do some maths to generate the number, you
4939: might write it like this:
4940:
4941: @example
4942: : HOUR-TO-SEC ( n1 -- n2 )
4943: 60 * \ to minutes
4944: 60 * ; \ to seconds
4945: @end example
4946:
4947: It is very clear what this definition is doing, but it's inefficient
4948: since it is performing 2 multiples at run-time. An alternative would be
4949: to write:
4950:
4951: @example
4952: : HOUR-TO-SEC ( n1 -- n2 )
4953: 3600 * ; \ to seconds
4954: @end example
4955:
4956: Which does the same thing, and has the advantage of using a single
4957: multiply. Ideally, we'd like the efficiency of the second with the
4958: readability of the first.
4959:
4960: @code{Literal} allows us to achieve that. It takes a number from the
4961: stack and lays it down in the current definition just as though the
4962: number had been typed directly into the definition. Our first attempt
4963: might look like this:
4964:
4965: @example
4966: 60 \ mins per hour
4967: 60 * \ seconds per minute
4968: : HOUR-TO-SEC ( n1 -- n2 )
4969: Literal * ; \ to seconds
4970: @end example
4971:
4972: But this produces the error message @code{unstructured}. What happened?
4973: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
4974: @i{colon-sys} is implementation-defined. In other words, once we start a
4975: colon definition we can't portably access anything that was on the stack
4976: before the definition began@footnote{@cite{Two Problems in ANS Forth},
4977: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
4978: some situations where you might want to access stack items above
4979: colon-sys, and provides a solution to the problem.}. The correct way of
4980: solving this problem in this instance is to use @code{[ ]} like this:
4981:
4982: @example
4983: : HOUR-TO-SEC ( n1 -- n2 )
4984: [ 60 \ minutes per hour
4985: 60 * ] \ seconds per minute
4986: LITERAL * ; \ to seconds
4987: @end example
1.23 crook 4988:
1.26 crook 4989: doc-literal
4990: doc-]L
4991: doc-2literal
4992: doc-fliteral
1.1 anton 4993:
1.29 crook 4994: @node Interpreter Directives, , Literals, The Text Interpreter
1.26 crook 4995: @subsection Interpreter Directives
4996: @cindex interpreter directives
1.1 anton 4997:
1.29 crook 4998: These words are usually used in interpret state; typically to control
4999: which parts of a source file are processed by the text
1.26 crook 5000: interpreter. There are only a few ANS Forth Standard words, but Gforth
5001: supplements these with a rich set of immediate control structure words
5002: to compensate for the fact that the non-immediate versions can only be
1.29 crook 5003: used in compile state (@pxref{Control Structures}). Typical usages:
5004:
5005: @example
5006: FALSE Constant ASSEMBLER
5007: .
5008: .
5009: ASSEMBLER [IF]
5010: : ASSEMBLER-FEATURE
5011: ...
5012: ;
5013: [ENDIF]
5014: .
5015: .
5016: : SEE
5017: ... \ general-purpose SEE code
5018: [ ASSEMBLER [IF] ]
5019: ... \ assembler-specific SEE code
5020: [ [ENDIF] ]
5021: ;
5022: @end example
1.1 anton 5023:
1.26 crook 5024: doc-[IF]
5025: doc-[ELSE]
5026: doc-[THEN]
5027: doc-[ENDIF]
1.1 anton 5028:
1.26 crook 5029: doc-[IFDEF]
5030: doc-[IFUNDEF]
1.1 anton 5031:
1.26 crook 5032: doc-[?DO]
5033: doc-[DO]
5034: doc-[FOR]
5035: doc-[LOOP]
5036: doc-[+LOOP]
5037: doc-[NEXT]
1.1 anton 5038:
1.26 crook 5039: doc-[BEGIN]
5040: doc-[UNTIL]
5041: doc-[AGAIN]
5042: doc-[WHILE]
5043: doc-[REPEAT]
1.1 anton 5044:
1.27 crook 5045:
5046:
1.26 crook 5047: @c -------------------------------------------------------------
5048: @node Tokens for Words, Word Lists, The Text Interpreter, Words
5049: @section Tokens for Words
5050: @cindex tokens for words
1.1 anton 5051:
1.28 crook 5052: This section describes the creation and use of tokens that represent
1.29 crook 5053: words.
5054:
1.32 ! anton 5055: Named words have information stored in their header space entries to
1.29 crook 5056: indicate any non-default semantics (@pxref{Interpretation and
5057: Compilation Semantics}). The semantics can be modified, using
5058: @code{immediate} and/or @code{compile-only}, at the time that the words
1.32 ! anton 5059: are defined. Unnamed words have (by definition) no header space
1.29 crook 5060: entry, and therefore must have default semantics.
1.21 crook 5061:
1.26 crook 5062: Named words have interpretation and compilation semantics. Unnamed words
5063: just have execution semantics.
1.21 crook 5064:
1.29 crook 5065: @cindex xt
5066: @cindex execution token
5067: The execution semantics of an unnamed word are represented by an
5068: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
5069: the execution token of the last word defined can be produced with
5070: @code{lastxt}.
5071:
5072: The interpretation semantics of a named word are also represented by an
5073: execution token. You can produce the execution token using @code{'} or
5074: @code{[']}. A simple example shows the difference between the two:
1.21 crook 5075:
1.29 crook 5076: @example
5077: : greet ( -- ) ." Hello" ;
5078: : foo ( -- xt ) ['] greet ; \ ['] parses greet at compile-time
5079: : bar ( -- ) ' EXECUTE ; \ ' parses at run-time
1.1 anton 5080:
1.29 crook 5081: \ the next four lines all do the same thing
5082: foo EXECUTE
5083: greet
5084: ' greet EXECUTE
5085: boo greet
5086: @end example
1.1 anton 5087:
1.29 crook 5088: An execution token occupies one cell.
1.26 crook 5089: @cindex code field address
5090: @cindex CFA
1.29 crook 5091: In Gforth, the abstract data type @i{execution token} is implemented
1.26 crook 5092: as a code field address (CFA).
5093: @comment TODO note that the standard does not say what it represents..
5094: @comment and you cannot necessarily compile it in all Forths (eg native
5095: @comment compilers?).
1.1 anton 5096:
1.29 crook 5097: For literals, use @code{'} in interpreted code and @code{[']} in
5098: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
5099: unusually by complaining about compile-only words. To get the execution
5100: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
5101: or @code{[COMP'] @i{name} DROP}.
1.1 anton 5102:
1.26 crook 5103: @cindex compilation token
1.29 crook 5104: The compilation semantics of a named word are represented by a
5105: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
5106: @i{xt} is an execution token. The compilation semantics represented by
5107: the compilation token can be performed with @code{execute}, which
5108: consumes the whole compilation token, with an additional stack effect
5109: determined by the represented compilation semantics.
5110:
5111: At present, the @i{w} part of a compilation token is an execution token,
5112: and the @i{xt} part represents either @code{execute} or
5113: @code{compile,}@footnote{Depending upon the compilation semantics of the
5114: word. If the word has default compilation semantics, the @i{xt} will
5115: represent @code{compile,}. If the word is @code{immediate}, the @i{xt}
5116: will represent @code{execute}.}. However, don't rely on that knowledge,
5117: unless necessary; future versions of Gforth may introduce unusual
5118: compilation tokens (e.g., a compilation token that represents the
5119: compilation semantics of a literal).
1.1 anton 5120:
1.26 crook 5121: You can compile the compilation semantics with @code{postpone,}. I.e.,
1.29 crook 5122: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
5123: @i{word}}.
1.21 crook 5124:
1.26 crook 5125: @cindex name token
5126: @cindex name field address
5127: @cindex NFA
1.29 crook 5128: Named words are also represented by the @dfn{name token}, (@i{nt}). In
5129: Gforth, the abstract data type @emph{name token} is implemented as a
5130: name field address (NFA).
5131:
5132: doc-execute
5133: doc-compile,
5134: doc-[']
5135: doc-'
5136: doc-[comp']
5137: doc-comp'
5138: doc-postpone,
1.1 anton 5139:
1.26 crook 5140: doc-find-name
5141: doc-name>int
5142: doc-name?int
5143: doc-name>comp
5144: doc-name>string
1.1 anton 5145:
1.26 crook 5146: @c -------------------------------------------------------------
5147: @node Word Lists, Environmental Queries, Tokens for Words, Words
5148: @section Word Lists
5149: @cindex word lists
1.32 ! anton 5150: @cindex header space
1.1 anton 5151:
1.26 crook 5152: @cindex wid
5153: All definitions other than those created by @code{:noname} have an entry
1.32 ! anton 5154: in the header space. The header space is fragmented into a number
1.29 crook 5155: of parts, called @dfn{word lists}. A word list is identified by a
5156: cell-sized word list identifier (@i{wid}) in much the same way as a
1.26 crook 5157: file is identified by a file handle. The numerical value of the wid has
5158: no (portable) meaning, and might change from session to session.
1.1 anton 5159:
1.26 crook 5160: @cindex compilation word list
5161: At any one time, a single word list is defined as the word list to which
1.29 crook 5162: all new definitions will be added -- this is called the @dfn{compilation
1.26 crook 5163: word list}. When Gforth is started, the compilation word list is the
5164: word list called @code{FORTH-WORDLIST}.
1.1 anton 5165:
1.26 crook 5166: @cindex search order stack
1.29 crook 5167: Forth maintains a stack of word lists, representing the @dfn{search
1.32 ! anton 5168: order}. When the header space is searched (for example, when
1.26 crook 5169: attempting to find a word's execution token during compilation), only
5170: those word lists that are currently in the search order are
5171: searched. The most recently-defined word in the word list at the top of
5172: the word list stack is searched first, and the search proceeds until
5173: either the word is located or the oldest definition in the word list at
5174: the bottom of the stack is reached. Definitions of the word may exist in
5175: more than one word lists; the search order determines which version will
5176: be found.
1.1 anton 5177:
1.29 crook 5178: The ANS Forth ``Search order'' word set is intended to provide a set of
5179: low-level tools that allow various different schemes to be
1.26 crook 5180: implemented. Gforth provides @code{vocabulary}, a traditional Forth
5181: word. @file{compat/vocabulary.fs} provides an implementation in ANS
5182: Standard Forth.
1.1 anton 5183:
1.27 crook 5184: @comment TODO: locals section refers to here, saying that every word list (aka
5185: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.1 anton 5186:
1.27 crook 5187: @comment the thisone- prefix is used to pick out the true definition of a
5188: @comment word from the source files, rather than some alias.
1.26 crook 5189: doc-forth-wordlist
5190: doc-definitions
5191: doc-get-current
5192: doc-set-current
5193: doc-get-order
1.27 crook 5194: doc---thisone-set-order
1.26 crook 5195: doc-wordlist
1.30 anton 5196: doc-table
1.26 crook 5197: doc-also
1.27 crook 5198: doc---thisone-forth
1.26 crook 5199: doc-only
1.27 crook 5200: doc---thisone-order
1.26 crook 5201: doc-previous
1.15 anton 5202:
1.26 crook 5203: doc-find
5204: doc-search-wordlist
1.15 anton 5205:
1.26 crook 5206: doc-words
5207: doc-vlist
1.1 anton 5208:
1.26 crook 5209: doc-mappedwordlist
5210: doc-root
5211: doc-vocabulary
5212: doc-seal
5213: doc-vocs
5214: doc-current
5215: doc-context
1.1 anton 5216:
1.26 crook 5217: @menu
5218: * Why use word lists?::
5219: * Word list examples::
5220: @end menu
5221:
5222: @node Why use word lists?, Word list examples, Word Lists, Word Lists
5223: @subsection Why use word lists?
5224: @cindex word lists - why use them?
5225:
1.29 crook 5226: Here are some reasons for using multiple word lists:
1.26 crook 5227:
5228: @itemize @bullet
5229: @item
1.32 ! anton 5230: To improve compilation speed by reducing the number of header space
1.26 crook 5231: entries that must be searched. This is achieved by creating a new
5232: word list that contains all of the definitions that are used in the
5233: definition of a Forth system but which would not usually be used by
5234: programs running on that system. That word list would be on the search
5235: list when the Forth system was compiled but would be removed from the
5236: search list for normal operation. This can be a useful technique for
5237: low-performance systems (for example, 8-bit processors in embedded
5238: systems) but is unlikely to be necessary in high-performance desktop
5239: systems.
5240: @item
5241: To prevent a set of words from being used outside the context in which
5242: they are valid. Two classic examples of this are an integrated editor
5243: (all of the edit commands are defined in a separate word list; the
5244: search order is set to the editor word list when the editor is invoked;
5245: the old search order is restored when the editor is terminated) and an
5246: integrated assembler (the op-codes for the machine are defined in a
5247: separate word list which is used when a @code{CODE} word is defined).
5248: @item
5249: To prevent a name-space clash between multiple definitions with the same
5250: name. For example, when building a cross-compiler you might have a word
5251: @code{IF} that generates conditional code for your target system. By
5252: placing this definition in a different word list you can control whether
5253: the host system's @code{IF} or the target system's @code{IF} get used in
5254: any particular context by controlling the order of the word lists on the
5255: search order stack.
5256: @end itemize
1.1 anton 5257:
1.26 crook 5258: @node Word list examples, ,Why use word lists?, Word Lists
5259: @subsection Word list examples
5260: @cindex word lists - examples
1.1 anton 5261:
1.26 crook 5262: Here is an example of creating and using a new wordlist using ANS
5263: Forth Standard words:
1.1 anton 5264:
5265: @example
1.26 crook 5266: wordlist constant my-new-words-wordlist
5267: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
1.21 crook 5268:
1.26 crook 5269: \ add it to the search order
5270: also my-new-words
1.21 crook 5271:
1.26 crook 5272: \ alternatively, add it to the search order and make it
5273: \ the compilation word list
5274: also my-new-words definitions
5275: \ type "order" to see the problem
1.21 crook 5276: @end example
5277:
1.26 crook 5278: The problem with this example is that @code{order} has no way to
5279: associate the name @code{my-new-words} with the wid of the word list (in
5280: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
5281: that has no associated name). There is no Standard way of associating a
5282: name with a wid.
5283:
5284: In Gforth, this example can be re-coded using @code{vocabulary}, which
5285: associates a name with a wid:
1.21 crook 5286:
1.26 crook 5287: @example
5288: vocabulary my-new-words
1.21 crook 5289:
1.26 crook 5290: \ add it to the search order
5291: my-new-words
1.21 crook 5292:
1.26 crook 5293: \ alternatively, add it to the search order and make it
5294: \ the compilation word list
5295: my-new-words definitions
5296: \ type "order" to see that the problem is solved
5297: @end example
1.23 crook 5298:
1.26 crook 5299: @c -------------------------------------------------------------
5300: @node Environmental Queries, Files, Word Lists, Words
5301: @section Environmental Queries
5302: @cindex environmental queries
1.21 crook 5303:
1.26 crook 5304: ANS Forth introduced the idea of ``environmental queries'' as a way
5305: for a program running on a system to determine certain characteristics of the system.
5306: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 5307:
1.32 ! anton 5308: The Standard requires that the header space used for environmental queries
! 5309: be distinct from the header space used for definitions.
1.21 crook 5310:
1.26 crook 5311: Typically, environmental queries are supported by creating a set of
1.29 crook 5312: definitions in a word list that is @i{only} used during environmental
1.26 crook 5313: queries; that is what Gforth does. There is no Standard way of adding
5314: definitions to the set of recognised environmental queries, but any
5315: implementation that supports the loading of optional word sets must have
5316: some mechanism for doing this (after loading the word set, the
5317: associated environmental query string must return @code{true}). In
5318: Gforth, the word list used to honour environmental queries can be
5319: manipulated just like any other word list.
1.21 crook 5320:
1.26 crook 5321: doc-environment?
5322: doc-environment-wordlist
1.21 crook 5323:
1.26 crook 5324: doc-gforth
5325: doc-os-class
1.21 crook 5326:
1.26 crook 5327: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
5328: returning two items on the stack, querying it using @code{environment?}
5329: will return an additional item; the @code{true} flag that shows that the
5330: string was recognised.
1.21 crook 5331:
1.26 crook 5332: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 5333:
1.26 crook 5334: Here are some examples of using environmental queries:
1.21 crook 5335:
1.26 crook 5336: @example
5337: s" address-unit-bits" environment? 0=
5338: [IF]
5339: cr .( environmental attribute address-units-bits unknown... ) cr
5340: [THEN]
1.21 crook 5341:
1.26 crook 5342: s" block" environment? [IF] DROP include block.fs [THEN]
1.21 crook 5343:
1.26 crook 5344: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
1.21 crook 5345:
1.26 crook 5346: s" gforth" environment? [IF] .( Gforth version ) TYPE
5347: [ELSE] .( Not Gforth..) [THEN]
5348: @end example
1.21 crook 5349:
5350:
1.26 crook 5351: Here is an example of adding a definition to the environment word list:
1.21 crook 5352:
1.26 crook 5353: @example
5354: get-current environment-wordlist set-current
5355: true constant block
5356: true constant block-ext
5357: set-current
5358: @end example
1.21 crook 5359:
1.26 crook 5360: You can see what definitions are in the environment word list like this:
1.21 crook 5361:
1.26 crook 5362: @example
5363: get-order 1+ environment-wordlist swap set-order words previous
5364: @end example
1.21 crook 5365:
5366:
1.26 crook 5367: @c -------------------------------------------------------------
5368: @node Files, Blocks, Environmental Queries, Words
5369: @section Files
1.28 crook 5370: @cindex files
5371: @cindex I/O - file-handling
1.21 crook 5372:
1.26 crook 5373: Gforth provides facilities for accessing files that are stored in the
5374: host operating system's file-system. Files that are processed by Gforth
5375: can be divided into two categories:
1.21 crook 5376:
1.23 crook 5377: @itemize @bullet
5378: @item
1.29 crook 5379: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 5380: @item
1.29 crook 5381: Files that are processed by some other program (@dfn{general files}).
1.26 crook 5382: @end itemize
5383:
5384: @menu
5385: * Forth source files::
5386: * General files::
5387: * Search Paths::
5388: * Forth Search Paths::
5389: * General Search Paths::
5390: @end menu
5391:
1.21 crook 5392:
1.26 crook 5393: @c -------------------------------------------------------------
5394: @node Forth source files, General files, Files, Files
5395: @subsection Forth source files
5396: @cindex including files
5397: @cindex Forth source files
1.21 crook 5398:
1.26 crook 5399: The simplest way to interpret the contents of a file is to use one of
5400: these two formats:
1.21 crook 5401:
1.26 crook 5402: @example
5403: include mysource.fs
5404: s" mysource.fs" included
5405: @end example
1.21 crook 5406:
1.26 crook 5407: Sometimes you want to include a file only if it is not included already
5408: (by, say, another source file). In that case, you can use one of these
5409: fomats:
1.21 crook 5410:
1.26 crook 5411: @example
5412: require mysource.fs
5413: needs mysource.fs
5414: s" mysource.fs" required
5415: @end example
1.21 crook 5416:
1.26 crook 5417: @cindex stack effect of included files
5418: @cindex including files, stack effect
5419: I recommend that you write your source files such that interpreting them
5420: does not change the stack. This allows using these files with
5421: @code{required} and friends without complications. For example:
1.21 crook 5422:
1.26 crook 5423: @example
5424: 1 require foo.fs drop
5425: @end example
1.21 crook 5426:
1.26 crook 5427: doc-include-file
5428: doc-included
1.28 crook 5429: doc-included?
1.26 crook 5430: doc-include
5431: doc-required
5432: doc-require
5433: doc-needs
1.28 crook 5434: doc-init-included-files
1.21 crook 5435:
1.26 crook 5436: A definition in ANS Forth for @code{required} is provided in
5437: @file{compat/required.fs}.
1.21 crook 5438:
1.26 crook 5439: @c -------------------------------------------------------------
5440: @node General files, Search Paths, Forth source files, Files
5441: @subsection General files
5442: @cindex general files
5443: @cindex file-handling
1.21 crook 5444:
1.26 crook 5445: Files are opened/created by name and type. The following types are
5446: recognised:
1.1 anton 5447:
1.26 crook 5448: doc-r/o
5449: doc-r/w
5450: doc-w/o
5451: doc-bin
1.1 anton 5452:
1.26 crook 5453: When a file is opened/created, it returns a file identifier,
1.29 crook 5454: @i{wfileid} that is used for all other file commands. All file
5455: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 5456: successful operation and an implementation-defined non-zero value in the
5457: case of an error.
1.21 crook 5458:
1.26 crook 5459: doc-open-file
5460: doc-create-file
1.21 crook 5461:
1.26 crook 5462: doc-close-file
5463: doc-delete-file
5464: doc-rename-file
5465: doc-read-file
5466: doc-read-line
5467: doc-write-file
5468: doc-write-line
5469: doc-emit-file
5470: doc-flush-file
1.21 crook 5471:
1.26 crook 5472: doc-file-status
5473: doc-file-position
5474: doc-reposition-file
5475: doc-file-size
5476: doc-resize-file
1.21 crook 5477:
1.26 crook 5478: @c ---------------------------------------------------------
5479: @node Search Paths, Forth Search Paths, General files, Files
5480: @subsection Search Paths
5481: @cindex path for @code{included}
5482: @cindex file search path
5483: @cindex @code{include} search path
5484: @cindex search path for files
1.21 crook 5485:
1.26 crook 5486: If you specify an absolute filename (i.e., a filename starting with
5487: @file{/} or @file{~}, or with @file{:} in the second position (as in
5488: @samp{C:...})) for @code{included} and friends, that file is included
5489: just as you would expect.
1.21 crook 5490:
1.26 crook 5491: For relative filenames, Gforth uses a search path similar to Forth's
5492: search order (@pxref{Word Lists}). It tries to find the given filename
5493: in the directories present in the path, and includes the first one it
5494: finds. There are separate search paths for Forth source files and
5495: general files.
1.21 crook 5496:
1.26 crook 5497: If the search path contains the directory @file{.} (as it should), this
5498: refers to the directory that the present file was @code{included}
5499: from. This allows files to include other files relative to their own
5500: position (irrespective of the current working directory or the absolute
5501: position). This feature is essential for libraries consisting of
5502: several files, where a file may include other files from the library.
5503: It corresponds to @code{#include "..."} in C. If the current input
5504: source is not a file, @file{.} refers to the directory of the innermost
5505: file being included, or, if there is no file being included, to the
5506: current working directory.
1.21 crook 5507:
1.26 crook 5508: Use @file{~+} to refer to the current working directory (as in the
5509: @code{bash}).
1.1 anton 5510:
1.26 crook 5511: If the filename starts with @file{./}, the search path is not searched
5512: (just as with absolute filenames), and the @file{.} has the same meaning
5513: as described above.
1.1 anton 5514:
1.26 crook 5515: @c ---------------------------------------------------------
5516: @node Forth Search Paths, General Search Paths, Search Paths, Files
5517: @subsubsection Forth Search Paths
1.28 crook 5518: @cindex search path control - Forth
1.5 anton 5519:
1.26 crook 5520: The search path is initialized when you start Gforth (@pxref{Invoking
5521: Gforth}). You can display it and change it using these words:
1.5 anton 5522:
1.26 crook 5523: doc-.fpath
5524: doc-fpath+
5525: doc-fpath=
5526: doc-open-fpath-file
1.5 anton 5527:
1.26 crook 5528: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 5529:
1.26 crook 5530: @example
5531: fpath= /usr/lib/forth/|./
5532: require timer.fs
5533: @end example
1.5 anton 5534:
1.26 crook 5535: @c ---------------------------------------------------------
5536: @node General Search Paths, , Forth Search Paths, Files
5537: @subsubsection General Search Paths
5538: @cindex search path control - for user applications
1.5 anton 5539:
1.26 crook 5540: Your application may need to search files in several directories, like
5541: @code{included} does. To facilitate this, Gforth allows you to define
5542: and use your own search paths, by providing generic equivalents of the
5543: Forth search path words:
1.5 anton 5544:
1.26 crook 5545: doc-.path
5546: doc-path+
5547: doc-path=
5548: doc-open-path-file
1.5 anton 5549:
1.26 crook 5550: Here's an example of creating a search path:
1.5 anton 5551:
1.26 crook 5552: @example
5553: \ Make a buffer for the path:
5554: create mypath 100 chars , \ maximum length (is checked)
5555: 0 , \ real len
5556: 100 chars allot \ space for path
5557: @end example
1.5 anton 5558:
1.26 crook 5559: @c -------------------------------------------------------------
5560: @node Blocks, Other I/O, Files, Words
5561: @section Blocks
1.28 crook 5562: @cindex I/O - blocks
5563: @cindex blocks
5564:
5565: When you run Gforth on a modern desk-top computer, it runs under the
5566: control of an operating system which provides certain services. One of
5567: these services is @var{file services}, which allows Forth source code
5568: and data to be stored in files and read into Gforth (@pxref{Files}).
5569:
5570: Traditionally, Forth has been an important programming language on
5571: systems where it has interfaced directly to the underlying hardware with
5572: no intervening operating system. Forth provides a mechanism, called
1.29 crook 5573: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 5574:
5575: A block is a 1024-byte data area, which can be used to hold data or
5576: Forth source code. No structure is imposed on the contents of the
5577: block. A block is identified by its number; blocks are numbered
5578: contiguously from 1 to an implementation-defined maximum.
5579:
5580: A typical system that used blocks but no operating system might use a
5581: single floppy-disk drive for mass storage, with the disks formatted to
5582: provide 256-byte sectors. Blocks would be implemented by assigning the
5583: first four sectors of the disk to block 1, the second four sectors to
5584: block 2 and so on, up to the limit of the capacity of the disk. The disk
5585: would not contain any file system information, just the set of blocks.
5586:
1.29 crook 5587: @cindex blocks file
1.28 crook 5588: On systems that do provide file services, blocks are typically
1.29 crook 5589: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 5590: file}. The size of the blocks file will be an exact multiple of 1024
5591: bytes, corresponding to the number of blocks it contains. This is the
5592: mechanism that Gforth uses.
5593:
1.29 crook 5594: @cindex @file{blocks.fb}
1.28 crook 5595: Only 1 blocks file can be open at a time. If you use block words without
5596: having specified a blocks file, Gforth defaults to the blocks file
5597: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
5598: locate a blocks file (@pxref{Forth Search Paths}).
5599:
1.29 crook 5600: @cindex block buffers
1.28 crook 5601: When you read and write blocks under program control, Gforth uses a
1.29 crook 5602: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 5603: not used when you use @code{load} to interpret the contents of a block.
5604:
5605: The behaviour of the block buffers is directly analagous to that of a
5606: cache. Each block buffer has three states:
5607:
5608: @itemize @bullet
5609: @item
5610: Unassigned
5611: @item
5612: Assigned-clean
5613: @item
5614: Assigned-dirty
5615: @end itemize
5616:
1.29 crook 5617: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 5618: block, the block (specified by its block number) must be assigned to a
5619: block buffer.
5620:
5621: The assignment of a block to a block buffer is performed by @code{block}
5622: or @code{buffer}. Use @code{block} when you wish to modify the existing
5623: contents of a block. Use @code{buffer} when you don't care about the
5624: existing contents of the block@footnote{The ANS Forth definition of
5625: @code{block} is intended not to cause disk I/O; if the data associated
5626: with the particular block is already stored in a block buffer due to an
5627: earlier @code{block} command, @code{buffer} will return that block
5628: buffer and the existing contents of the block will be
5629: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 5630: block buffer for the block.}.
1.28 crook 5631:
5632: Once a block has been assigned to a block buffer, the block buffer state
1.29 crook 5633: becomes @i{assigned-clean}. Data can now be manipulated within the
1.28 crook 5634: block buffer.
5635:
5636: When the contents of a block buffer is changed it is necessary,
5637: @i{before calling} @code{block} @i{or} @code{buffer} @i{again}, to
5638: either abandon the changes (by doing nothing) or commit the changes,
5639: using @code{update}. Using @code{update} does not change the blocks
1.29 crook 5640: file; it simply changes a block buffer's state to @i{assigned-dirty}.
1.28 crook 5641:
1.29 crook 5642: The word @code{flush} causes all @i{assigned-dirty} blocks to be
1.28 crook 5643: written back to the blocks file on disk. Leaving Gforth using @code{bye}
5644: also causes a @code{flush} to be performed.
5645:
1.29 crook 5646: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 5647: algorithm to assign a block buffer to a block. That means that any
5648: particular block can only be assigned to one specific block buffer,
1.29 crook 5649: called (for the particular operation) the @i{victim buffer}. If the
5650: victim buffer is @i{unassigned} or @i{assigned-clean} it can be
5651: allocated to the new block immediately. If it is @i{assigned-dirty}
1.28 crook 5652: its current contents must be written out to disk before it can be
5653: allocated to the new block.
5654:
5655: Although no structure is imposed on the contents of a block, it is
5656: traditional to display the contents as 16 lines each of 64 characters. A
5657: block provides a single, continuous stream of input (for example, it
5658: acts as a single parse area) -- there are no end-of-line characters
5659: within a block, and no end-of-file character at the end of a
5660: block. There are two consequences of this:
1.26 crook 5661:
1.28 crook 5662: @itemize @bullet
5663: @item
5664: The last character of one line wraps straight into the first character
5665: of the following line
5666: @item
5667: The word @code{\} -- comment to end of line -- requires special
5668: treatment; in the context of a block it causes all characters until the
5669: end of the current 64-character ``line'' to be ignored.
5670: @end itemize
5671:
5672: In Gforth, when you use @code{block} with a non-existent block number,
5673: the current block file will be extended to the appropriate size and the
5674: block buffer will be initialised with spaces.
5675:
1.29 crook 5676: Gforth doesn't encourage the use of blocks; the mechanism is only
5677: provided for backward compatibility -- ANS Forth requires blocks to be
5678: available when files are.
1.28 crook 5679:
5680: Common techniques that are used when working with blocks include:
5681:
5682: @itemize @bullet
5683: @item
5684: A screen editor that allows you to edit blocks without leaving the Forth
5685: environment.
5686: @item
5687: Shadow screens; where every code block has an associated block
5688: containing comments (for example: code in odd block numbers, comments in
5689: even block numbers). Typically, the block editor provides a convenient
5690: mechanism to toggle between code and comments.
5691: @item
5692: Load blocks; a single block (typically block 1) contains a number of
5693: @code{thru} commands which @code{load} the whole of the application.
5694: @item
5695: Chaining blocks; a block terminates with a @code{-->} so that a whole
5696: application can be @code{load}ed by @code{load}ing a single block.
5697: @end itemize
1.26 crook 5698:
1.29 crook 5699: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
5700: integrated into a Forth programming environment.
1.26 crook 5701:
5702: @comment TODO what about errors on open-blocks?
5703: doc-open-blocks
5704: doc-use
5705: doc-get-block-fid
5706: doc-block-position
1.28 crook 5707:
5708: doc-scr
5709: doc-list
5710:
5711: doc---block-block
5712: doc-buffer
5713:
1.26 crook 5714: doc-update
1.28 crook 5715: doc-updated?
1.26 crook 5716: doc-save-buffers
5717: doc-empty-buffers
5718: doc-empty-buffer
5719: doc-flush
1.28 crook 5720:
1.26 crook 5721: doc-load
5722: doc-thru
5723: doc-+load
5724: doc-+thru
5725: doc---block--->
5726: doc-block-included
5727:
5728: @c -------------------------------------------------------------
5729: @node Other I/O, Programming Tools, Blocks, Words
5730: @section Other I/O
1.28 crook 5731: @cindex I/O - keyboard and display
1.26 crook 5732:
5733: @menu
5734: * Simple numeric output:: Predefined formats
5735: * Formatted numeric output:: Formatted (pictured) output
5736: * String Formats:: How Forth stores strings in memory
5737: * Displaying characters and strings:: Other stuff
5738: * Input:: Input
5739: @end menu
5740:
5741: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
5742: @subsection Simple numeric output
1.28 crook 5743: @cindex numeric output - simple/free-format
1.5 anton 5744:
1.26 crook 5745: The simplest output functions are those that display numbers from the
5746: data or floating-point stacks. Floating-point output is always displayed
5747: using base 10. Numbers displayed from the data stack use the value stored
5748: in @code{base}.
1.5 anton 5749:
1.26 crook 5750: doc-.
5751: doc-dec.
5752: doc-hex.
5753: doc-u.
5754: doc-.r
5755: doc-u.r
5756: doc-d.
5757: doc-ud.
5758: doc-d.r
5759: doc-ud.r
5760: doc-f.
5761: doc-fe.
5762: doc-fs.
1.5 anton 5763:
1.26 crook 5764: Examples of printing the number 1234.5678E23 in the different floating-point output
5765: formats are shown below:
1.5 anton 5766:
5767: @example
1.26 crook 5768: f. 123456779999999000000000000.
5769: fe. 123.456779999999E24
5770: fs. 1.23456779999999E26
1.5 anton 5771: @end example
5772:
5773:
1.26 crook 5774: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
5775: @subsection Formatted numeric output
1.28 crook 5776: @cindex formatted numeric output
1.26 crook 5777: @cindex pictured numeric output
1.28 crook 5778: @cindex numeric output - formatted
1.26 crook 5779:
1.29 crook 5780: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 5781: output} for formatted printing of integers. In this technique, digits
5782: are extracted from the number (using the current output radix defined by
5783: @code{base}), converted to ASCII codes and appended to a string that is
5784: built in a scratch-pad area of memory (@pxref{core-idef,
5785: Implementation-defined options, Implementation-defined
5786: options}). Arbitrary characters can be appended to the string during the
5787: extraction process. The completed string is specified by an address
5788: and length and can be manipulated (@code{TYPE}ed, copied, modified)
5789: under program control.
1.5 anton 5790:
1.26 crook 5791: All of the words described in the previous section for simple numeric
5792: output are implemented in Gforth using pictured numeric output.
1.5 anton 5793:
1.26 crook 5794: Three important things to remember about Pictured Numeric Output:
1.5 anton 5795:
1.26 crook 5796: @itemize @bullet
5797: @item
1.28 crook 5798: It always operates on double-precision numbers; to display a
5799: single-precision number, convert it first (@pxref{Double precision} for
5800: ways of doing this).
1.26 crook 5801: @item
1.28 crook 5802: It always treats the double-precision number as though it were
5803: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 5804: @item
5805: The string is built up from right to left; least significant digit first.
5806: @end itemize
1.5 anton 5807:
1.26 crook 5808: doc-<#
5809: doc-#
5810: doc-#s
5811: doc-hold
5812: doc-sign
5813: doc-#>
1.5 anton 5814:
1.26 crook 5815: doc-represent
1.5 anton 5816:
1.26 crook 5817: Here are some examples of using pictured numeric output:
1.5 anton 5818:
5819: @example
1.26 crook 5820: : my-u. ( u -- )
5821: \ Simplest use of pns.. behaves like Standard u.
5822: 0 \ convert to unsigned double
5823: <# \ start conversion
5824: #s \ convert all digits
5825: #> \ complete conversion
5826: TYPE SPACE ; \ display, with trailing space
1.5 anton 5827:
1.26 crook 5828: : cents-only ( u -- )
5829: 0 \ convert to unsigned double
5830: <# \ start conversion
5831: # # \ convert two least-significant digits
5832: #> \ complete conversion, discard other digits
5833: TYPE SPACE ; \ display, with trailing space
1.5 anton 5834:
1.26 crook 5835: : dollars-and-cents ( u -- )
5836: 0 \ convert to unsigned double
5837: <# \ start conversion
5838: # # \ convert two least-significant digits
5839: [char] . hold \ insert decimal point
5840: #s \ convert remaining digits
5841: [char] $ hold \ append currency symbol
5842: #> \ complete conversion
5843: TYPE SPACE ; \ display, with trailing space
1.5 anton 5844:
1.26 crook 5845: : my-. ( n -- )
5846: \ handling negatives.. behaves like Standard .
5847: s>d \ convert to signed double
5848: swap over dabs \ leave sign byte followed by unsigned double
5849: <# \ start conversion
5850: #s \ convert all digits
5851: rot sign \ get at sign byte, append "-" if needed
5852: #> \ complete conversion
5853: TYPE SPACE ; \ display, with trailing space
1.5 anton 5854:
1.26 crook 5855: : account. ( n -- )
5856: \ accountants don't like minus signs, they use braces
5857: \ for negative numbers
5858: s>d \ convert to signed double
5859: swap over dabs \ leave sign byte followed by unsigned double
5860: <# \ start conversion
5861: 2 pick \ get copy of sign byte
5862: 0< IF [char] ) hold THEN \ right-most character of output
5863: #s \ convert all digits
5864: rot \ get at sign byte
5865: 0< IF [char] ( hold THEN
5866: #> \ complete conversion
5867: TYPE SPACE ; \ display, with trailing space
1.5 anton 5868: @end example
5869:
1.26 crook 5870: Here are some examples of using these words:
1.5 anton 5871:
5872: @example
1.26 crook 5873: 1 my-u. 1
5874: hex -1 my-u. decimal FFFFFFFF
5875: 1 cents-only 01
5876: 1234 cents-only 34
5877: 2 dollars-and-cents $0.02
5878: 1234 dollars-and-cents $12.34
5879: 123 my-. 123
5880: -123 my. -123
5881: 123 account. 123
5882: -456 account. (456)
1.5 anton 5883: @end example
5884:
5885:
1.26 crook 5886: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
5887: @subsection String Formats
1.27 crook 5888: @cindex strings - see character strings
5889: @cindex character strings - formats
1.28 crook 5890: @cindex I/O - see character strings
1.26 crook 5891:
1.27 crook 5892: Forth commonly uses two different methods for representing character
5893: strings:
1.26 crook 5894:
5895: @itemize @bullet
5896: @item
5897: @cindex address of counted string
1.29 crook 5898: As a @dfn{counted string}, represented by a @i{c-addr}. The char
5899: addressed by @i{c-addr} contains a character-count, @i{n}, of the
5900: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 5901: memory.
5902: @item
1.29 crook 5903: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
5904: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 5905: first byte of the string.
5906: @end itemize
5907:
5908: ANS Forth encourages the use of the second format when representing
5909: strings on the stack, whilst conceeding that the counted string format
5910: remains useful as a way of storing strings in memory.
5911:
5912: doc-count
5913:
5914: @xref{Memory Blocks} for words that move, copy and search
5915: for strings. @xref{Displaying characters and strings,} for words that
5916: display characters and strings.
5917:
5918:
5919: @node Displaying characters and strings, Input, String Formats, Other I/O
5920: @subsection Displaying characters and strings
1.27 crook 5921: @cindex characters - compiling and displaying
5922: @cindex character strings - compiling and displaying
1.26 crook 5923:
5924: This section starts with a glossary of Forth words and ends with a set
5925: of examples.
5926:
5927: doc-bl
5928: doc-space
5929: doc-spaces
5930: doc-emit
5931: doc-toupper
5932: doc-."
5933: doc-.(
5934: doc-type
5935: doc-cr
1.27 crook 5936: @cindex cursor control
1.26 crook 5937: doc-at-xy
5938: doc-page
5939: doc-s"
5940: doc-c"
5941: doc-char
5942: doc-[char]
5943: doc-sliteral
5944:
5945: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 5946:
5947: @example
1.26 crook 5948: .( text-1)
5949: : my-word
5950: ." text-2" cr
5951: .( text-3)
5952: ;
5953:
5954: ." text-4"
5955:
5956: : my-char
5957: [char] ALPHABET emit
5958: char emit
5959: ;
1.5 anton 5960: @end example
5961:
1.26 crook 5962: When you load this code into Gforth, the following output is generated:
1.5 anton 5963:
1.26 crook 5964: @example
1.30 anton 5965: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 5966: @end example
1.5 anton 5967:
1.26 crook 5968: @itemize @bullet
5969: @item
5970: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
5971: is an immediate word; it behaves in the same way whether it is used inside
5972: or outside a colon definition.
5973: @item
5974: Message @code{text-4} is displayed because of Gforth's added interpretation
5975: semantics for @code{."}.
5976: @item
1.29 crook 5977: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 5978: performs the compilation semantics for @code{."} within the definition of
5979: @code{my-word}.
5980: @end itemize
1.5 anton 5981:
1.26 crook 5982: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 5983:
1.26 crook 5984: @example
1.30 anton 5985: @kbd{my-word @key{RET}} text-2
1.26 crook 5986: ok
1.30 anton 5987: @kbd{my-char fred @key{RET}} Af ok
5988: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 5989: @end example
1.5 anton 5990:
5991: @itemize @bullet
5992: @item
1.26 crook 5993: Message @code{text-2} is displayed because of the run-time behaviour of
5994: @code{."}.
5995: @item
5996: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
5997: on the stack at run-time. @code{emit} always displays the character
5998: when @code{my-char} is executed.
5999: @item
6000: @code{char} parses a string at run-time and the second @code{emit} displays
6001: the first character of the string.
1.5 anton 6002: @item
1.26 crook 6003: If you type @code{see my-char} you can see that @code{[char]} discarded
6004: the text ``LPHABET'' and only compiled the display code for ``A'' into the
6005: definition of @code{my-char}.
1.5 anton 6006: @end itemize
6007:
6008:
6009:
1.26 crook 6010: @node Input, , Displaying characters and strings, Other I/O
6011: @subsection Input
6012: @cindex input
1.28 crook 6013: @cindex I/O - see input
6014: @cindex parsing a string
1.5 anton 6015:
1.27 crook 6016: @xref{String Formats} for ways of storing character strings in memory.
1.5 anton 6017:
1.27 crook 6018: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 6019: @comment then index them
1.27 crook 6020:
6021: doc-key
6022: doc-key?
1.26 crook 6023: doc->number
6024: doc->float
6025: doc-accept
1.27 crook 6026: doc-pad
6027: doc-parse
6028: doc-word
6029: doc-sword
6030: doc-refill
6031: @comment obsolescent words..
6032: doc-convert
1.26 crook 6033: doc-query
6034: doc-expect
1.27 crook 6035: doc-span
1.5 anton 6036:
6037:
6038: @c -------------------------------------------------------------
1.26 crook 6039: @node Programming Tools, Assembler and Code Words, Other I/O, Words
6040: @section Programming Tools
6041: @cindex programming tools
1.12 anton 6042:
6043: @menu
1.26 crook 6044: * Debugging:: Simple and quick.
6045: * Assertions:: Making your programs self-checking.
6046: * Singlestep Debugger:: Executing your program word by word.
1.5 anton 6047: @end menu
6048:
1.26 crook 6049: @node Debugging, Assertions, Programming Tools, Programming Tools
6050: @subsection Debugging
6051: @cindex debugging
1.5 anton 6052:
1.26 crook 6053: Languages with a slow edit/compile/link/test development loop tend to
6054: require sophisticated tracing/stepping debuggers to facilate
6055: productive debugging.
1.5 anton 6056:
1.26 crook 6057: A much better (faster) way in fast-compiling languages is to add
6058: printing code at well-selected places, let the program run, look at
6059: the output, see where things went wrong, add more printing code, etc.,
6060: until the bug is found.
1.5 anton 6061:
1.26 crook 6062: The simple debugging aids provided in @file{debugs.fs}
6063: are meant to support this style of debugging. In addition, there are
6064: words for non-destructively inspecting the stack and memory:
1.5 anton 6065:
1.26 crook 6066: doc-.s
6067: doc-f.s
1.5 anton 6068:
1.29 crook 6069: There is a word @code{.r} but it does @i{not} display the return
1.26 crook 6070: stack! It is used for formatted numeric output.
1.5 anton 6071:
1.26 crook 6072: doc-depth
6073: doc-fdepth
6074: doc-clearstack
6075: doc-?
6076: doc-dump
1.5 anton 6077:
1.26 crook 6078: The word @code{~~} prints debugging information (by default the source
6079: location and the stack contents). It is easy to insert. If you use Emacs
6080: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
6081: query-replace them with nothing). The deferred words
6082: @code{printdebugdata} and @code{printdebugline} control the output of
6083: @code{~~}. The default source location output format works well with
6084: Emacs' compilation mode, so you can step through the program at the
6085: source level using @kbd{C-x `} (the advantage over a stepping debugger
6086: is that you can step in any direction and you know where the crash has
6087: happened or where the strange data has occurred).
1.5 anton 6088:
1.26 crook 6089: The default actions of @code{~~} clobber the contents of the pictured
6090: numeric output string, so you should not use @code{~~}, e.g., between
6091: @code{<#} and @code{#>}.
1.5 anton 6092:
1.26 crook 6093: doc-~~
6094: doc-printdebugdata
6095: doc-printdebugline
1.5 anton 6096:
1.26 crook 6097: doc-see
6098: doc-marker
1.5 anton 6099:
1.26 crook 6100: Here's an example of using @code{marker} at the start of a source file
6101: that you are debugging; it ensures that you only ever have one copy of
6102: the file's definitions compiled at any time:
1.5 anton 6103:
1.26 crook 6104: @example
6105: [IFDEF] my-code
6106: my-code
6107: [ENDIF]
1.5 anton 6108:
1.26 crook 6109: marker my-code
1.28 crook 6110: init-included-files
1.5 anton 6111:
1.26 crook 6112: \ .. definitions start here
6113: \ .
6114: \ .
6115: \ end
6116: @end example
1.5 anton 6117:
6118:
6119:
1.26 crook 6120: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
6121: @subsection Assertions
6122: @cindex assertions
1.5 anton 6123:
1.26 crook 6124: It is a good idea to make your programs self-checking, especially if you
6125: make an assumption that may become invalid during maintenance (for
6126: example, that a certain field of a data structure is never zero). Gforth
1.29 crook 6127: supports @dfn{assertions} for this purpose. They are used like this:
1.23 crook 6128:
1.26 crook 6129: @example
1.29 crook 6130: assert( @i{flag} )
1.26 crook 6131: @end example
1.23 crook 6132:
1.26 crook 6133: The code between @code{assert(} and @code{)} should compute a flag, that
6134: should be true if everything is alright and false otherwise. It should
6135: not change anything else on the stack. The overall stack effect of the
6136: assertion is @code{( -- )}. E.g.
1.23 crook 6137:
1.26 crook 6138: @example
6139: assert( 1 1 + 2 = ) \ what we learn in school
6140: assert( dup 0<> ) \ assert that the top of stack is not zero
6141: assert( false ) \ this code should not be reached
6142: @end example
1.23 crook 6143:
1.26 crook 6144: The need for assertions is different at different times. During
6145: debugging, we want more checking, in production we sometimes care more
6146: for speed. Therefore, assertions can be turned off, i.e., the assertion
6147: becomes a comment. Depending on the importance of an assertion and the
6148: time it takes to check it, you may want to turn off some assertions and
6149: keep others turned on. Gforth provides several levels of assertions for
6150: this purpose:
1.23 crook 6151:
1.26 crook 6152: doc-assert0(
6153: doc-assert1(
6154: doc-assert2(
6155: doc-assert3(
6156: doc-assert(
6157: doc-)
1.23 crook 6158:
1.26 crook 6159: The variable @code{assert-level} specifies the highest assertions that
6160: are turned on. I.e., at the default @code{assert-level} of one,
6161: @code{assert0(} and @code{assert1(} assertions perform checking, while
6162: @code{assert2(} and @code{assert3(} assertions are treated as comments.
6163:
6164: The value of @code{assert-level} is evaluated at compile-time, not at
6165: run-time. Therefore you cannot turn assertions on or off at run-time;
6166: you have to set the @code{assert-level} appropriately before compiling a
6167: piece of code. You can compile different pieces of code at different
6168: @code{assert-level}s (e.g., a trusted library at level 1 and
6169: newly-written code at level 3).
1.23 crook 6170:
1.26 crook 6171: doc-assert-level
1.23 crook 6172:
1.26 crook 6173: If an assertion fails, a message compatible with Emacs' compilation mode
6174: is produced and the execution is aborted (currently with @code{ABORT"}.
6175: If there is interest, we will introduce a special throw code. But if you
6176: intend to @code{catch} a specific condition, using @code{throw} is
6177: probably more appropriate than an assertion).
1.23 crook 6178:
1.26 crook 6179: Definitions in ANS Forth for these assertion words are provided
6180: in @file{compat/assert.fs}.
1.23 crook 6181:
6182:
1.26 crook 6183: @node Singlestep Debugger, , Assertions, Programming Tools
6184: @subsection Singlestep Debugger
6185: @cindex singlestep Debugger
6186: @cindex debugging Singlestep
6187: @cindex @code{dbg}
6188: @cindex @code{BREAK:}
6189: @cindex @code{BREAK"}
1.23 crook 6190:
1.26 crook 6191: When you create a new word there's often the need to check whether it
6192: behaves correctly or not. You can do this by typing @code{dbg
6193: badword}. A debug session might look like this:
1.23 crook 6194:
1.26 crook 6195: @example
6196: : badword 0 DO i . LOOP ; ok
6197: 2 dbg badword
6198: : badword
6199: Scanning code...
1.23 crook 6200:
1.26 crook 6201: Nesting debugger ready!
1.23 crook 6202:
1.26 crook 6203: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
6204: 400D4740 8049F68 DO -> [ 0 ]
6205: 400D4744 804A0C8 i -> [ 1 ] 00000
6206: 400D4748 400C5E60 . -> 0 [ 0 ]
6207: 400D474C 8049D0C LOOP -> [ 0 ]
6208: 400D4744 804A0C8 i -> [ 1 ] 00001
6209: 400D4748 400C5E60 . -> 1 [ 0 ]
6210: 400D474C 8049D0C LOOP -> [ 0 ]
6211: 400D4758 804B384 ; -> ok
6212: @end example
1.23 crook 6213:
1.26 crook 6214: Each line displayed is one step. You always have to hit return to
6215: execute the next word that is displayed. If you don't want to execute
6216: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
6217: an overview what keys are available:
1.23 crook 6218:
1.26 crook 6219: @table @i
1.23 crook 6220:
1.30 anton 6221: @item @key{RET}
1.26 crook 6222: Next; Execute the next word.
1.23 crook 6223:
1.26 crook 6224: @item n
6225: Nest; Single step through next word.
1.5 anton 6226:
1.26 crook 6227: @item u
6228: Unnest; Stop debugging and execute rest of word. If we got to this word
6229: with nest, continue debugging with the calling word.
1.5 anton 6230:
1.26 crook 6231: @item d
6232: Done; Stop debugging and execute rest.
1.5 anton 6233:
1.26 crook 6234: @item s
6235: Stop; Abort immediately.
1.5 anton 6236:
1.26 crook 6237: @end table
1.5 anton 6238:
1.26 crook 6239: Debugging large application with this mechanism is very difficult, because
6240: you have to nest very deeply into the program before the interesting part
6241: begins. This takes a lot of time.
1.5 anton 6242:
1.26 crook 6243: To do it more directly put a @code{BREAK:} command into your source code.
6244: When program execution reaches @code{BREAK:} the single step debugger is
6245: invoked and you have all the features described above.
1.23 crook 6246:
1.26 crook 6247: If you have more than one part to debug it is useful to know where the
6248: program has stopped at the moment. You can do this by the
6249: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
6250: string is typed out when the ``breakpoint'' is reached.
6251:
6252: doc-dbg
6253: doc-BREAK:
6254: doc-BREAK"
6255:
6256:
6257: @c -------------------------------------------------------------
6258: @node Assembler and Code Words, Threading Words, Programming Tools, Words
6259: @section Assembler and Code Words
6260: @cindex assembler
6261: @cindex code words
1.5 anton 6262:
1.26 crook 6263: Gforth provides some words for defining primitives (words written in
1.29 crook 6264: machine code), and for defining the machine-code equivalent of
1.26 crook 6265: @code{DOES>}-based defining words. However, the machine-independent
6266: nature of Gforth poses a few problems: First of all, Gforth runs on
6267: several architectures, so it can provide no standard assembler. What's
6268: worse is that the register allocation not only depends on the processor,
6269: but also on the @code{gcc} version and options used.
1.5 anton 6270:
1.29 crook 6271: The words that Gforth offers encapsulate some system dependences (e.g.,
6272: the header structure), so a system-independent assembler may be used in
1.26 crook 6273: Gforth. If you do not have an assembler, you can compile machine code
1.29 crook 6274: directly with @code{,} and @code{c,}@footnote{This isn't portable,
6275: because these words emit stuff in @i{data} space; it works because
6276: Gforth has unified code/data spaces. Assembler isn't likely to be
6277: portable anyway.}.
1.5 anton 6278:
1.26 crook 6279: doc-assembler
6280: doc-code
6281: doc-end-code
6282: doc-;code
6283: doc-flush-icache
1.5 anton 6284:
1.26 crook 6285: If @code{flush-icache} does not work correctly, @code{code} words
6286: etc. will not work (reliably), either.
1.5 anton 6287:
1.29 crook 6288: The typical usage of these @code{code} words can be shown most easily by
6289: analogy to the equivalent high-level defining words:
6290:
6291: @example
6292: : foo code foo
6293: <high-level Forth words> <assembler>
6294: ; end-code
6295:
6296: : bar : bar
6297: <high-level Forth words> <high-level Forth words>
6298: CREATE CREATE
6299: <high-level Forth words> <high-level Forth words>
6300: DOES> ;code
6301: <high-level Forth words> <assembler>
6302: ; end-code
6303: @end example
6304:
1.26 crook 6305: @code{flush-icache} is always present. The other words are rarely used
6306: and reside in @code{code.fs}, which is usually not loaded. You can load
6307: it with @code{require code.fs}.
1.5 anton 6308:
1.26 crook 6309: @cindex registers of the inner interpreter
6310: In the assembly code you will want to refer to the inner interpreter's
6311: registers (e.g., the data stack pointer) and you may want to use other
6312: registers for temporary storage. Unfortunately, the register allocation
6313: is installation-dependent.
1.5 anton 6314:
1.26 crook 6315: The easiest solution is to use explicit register declarations
6316: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
6317: GNU C Manual}) for all of the inner interpreter's registers: You have to
6318: compile Gforth with @code{-DFORCE_REG} (configure option
6319: @code{--enable-force-reg}) and the appropriate declarations must be
6320: present in the @code{machine.h} file (see @code{mips.h} for an example;
6321: you can find a full list of all declarable register symbols with
6322: @code{grep register engine.c}). If you give explicit registers to all
6323: variables that are declared at the beginning of @code{engine()}, you
6324: should be able to use the other caller-saved registers for temporary
6325: storage. Alternatively, you can use the @code{gcc} option
6326: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
6327: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
6328: (however, this restriction on register allocation may slow Gforth
6329: significantly).
1.5 anton 6330:
1.26 crook 6331: If this solution is not viable (e.g., because @code{gcc} does not allow
6332: you to explicitly declare all the registers you need), you have to find
6333: out by looking at the code where the inner interpreter's registers
6334: reside and which registers can be used for temporary storage. You can
6335: get an assembly listing of the engine's code with @code{make engine.s}.
1.5 anton 6336:
1.26 crook 6337: In any case, it is good practice to abstract your assembly code from the
6338: actual register allocation. E.g., if the data stack pointer resides in
6339: register @code{$17}, create an alias for this register called @code{sp},
6340: and use that in your assembly code.
1.5 anton 6341:
1.26 crook 6342: @cindex code words, portable
6343: Another option for implementing normal and defining words efficiently
6344: is to add the desired functionality to the source of Gforth. For normal
6345: words you just have to edit @file{primitives} (@pxref{Automatic
6346: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
6347: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
6348: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5 anton 6349:
6350:
1.26 crook 6351: @c -------------------------------------------------------------
6352: @node Threading Words, Locals, Assembler and Code Words, Words
6353: @section Threading Words
6354: @cindex threading words
1.5 anton 6355:
1.26 crook 6356: @cindex code address
6357: These words provide access to code addresses and other threading stuff
6358: in Gforth (and, possibly, other interpretive Forths). It more or less
6359: abstracts away the differences between direct and indirect threading
6360: (and, for direct threading, the machine dependences). However, at
6361: present this wordset is still incomplete. It is also pretty low-level;
6362: some day it will hopefully be made unnecessary by an internals wordset
6363: that abstracts implementation details away completely.
1.5 anton 6364:
1.26 crook 6365: doc-threading-method
6366: doc->code-address
6367: doc->does-code
6368: doc-code-address!
6369: doc-does-code!
6370: doc-does-handler!
6371: doc-/does-handler
1.5 anton 6372:
1.26 crook 6373: The code addresses produced by various defining words are produced by
6374: the following words:
1.5 anton 6375:
1.26 crook 6376: doc-docol:
6377: doc-docon:
6378: doc-dovar:
6379: doc-douser:
6380: doc-dodefer:
6381: doc-dofield:
1.5 anton 6382:
1.26 crook 6383: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
6384: with @code{>does-code}. If the word was defined in that way, the value
6385: returned is non-zero and identifies the @code{DOES>} used by the
6386: defining word.
6387: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5 anton 6388:
1.26 crook 6389: @c -------------------------------------------------------------
6390: @node Locals, Structures, Threading Words, Words
6391: @section Locals
6392: @cindex locals
1.5 anton 6393:
1.26 crook 6394: Local variables can make Forth programming more enjoyable and Forth
6395: programs easier to read. Unfortunately, the locals of ANS Forth are
6396: laden with restrictions. Therefore, we provide not only the ANS Forth
6397: locals wordset, but also our own, more powerful locals wordset (we
6398: implemented the ANS Forth locals wordset through our locals wordset).
1.5 anton 6399:
1.26 crook 6400: The ideas in this section have also been published in the paper
6401: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
6402: at EuroForth '94; it is available at
6403: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
1.5 anton 6404:
1.26 crook 6405: @menu
6406: * Gforth locals::
6407: * ANS Forth locals::
6408: @end menu
1.5 anton 6409:
1.26 crook 6410: @node Gforth locals, ANS Forth locals, Locals, Locals
6411: @subsection Gforth locals
6412: @cindex Gforth locals
6413: @cindex locals, Gforth style
1.5 anton 6414:
1.26 crook 6415: Locals can be defined with
1.5 anton 6416:
6417: @example
1.26 crook 6418: @{ local1 local2 ... -- comment @}
6419: @end example
6420: or
6421: @example
6422: @{ local1 local2 ... @}
1.5 anton 6423: @end example
6424:
1.26 crook 6425: E.g.,
1.5 anton 6426: @example
1.26 crook 6427: : max @{ n1 n2 -- n3 @}
6428: n1 n2 > if
6429: n1
6430: else
6431: n2
6432: endif ;
1.5 anton 6433: @end example
6434:
1.26 crook 6435: The similarity of locals definitions with stack comments is intended. A
6436: locals definition often replaces the stack comment of a word. The order
6437: of the locals corresponds to the order in a stack comment and everything
6438: after the @code{--} is really a comment.
1.5 anton 6439:
1.26 crook 6440: This similarity has one disadvantage: It is too easy to confuse locals
6441: declarations with stack comments, causing bugs and making them hard to
6442: find. However, this problem can be avoided by appropriate coding
6443: conventions: Do not use both notations in the same program. If you do,
6444: they should be distinguished using additional means, e.g. by position.
6445:
6446: @cindex types of locals
6447: @cindex locals types
6448: The name of the local may be preceded by a type specifier, e.g.,
6449: @code{F:} for a floating point value:
6450:
6451: @example
6452: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
6453: \ complex multiplication
6454: Ar Br f* Ai Bi f* f-
6455: Ar Bi f* Ai Br f* f+ ;
6456: @end example
6457:
6458: @cindex flavours of locals
6459: @cindex locals flavours
6460: @cindex value-flavoured locals
6461: @cindex variable-flavoured locals
6462: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
6463: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
6464: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
6465: with @code{W:}, @code{D:} etc.) produces its value and can be changed
6466: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
6467: produces its address (which becomes invalid when the variable's scope is
6468: left). E.g., the standard word @code{emit} can be defined in terms of
6469: @code{type} like this:
1.5 anton 6470:
6471: @example
1.26 crook 6472: : emit @{ C^ char* -- @}
6473: char* 1 type ;
1.5 anton 6474: @end example
6475:
1.26 crook 6476: @cindex default type of locals
6477: @cindex locals, default type
6478: A local without type specifier is a @code{W:} local. Both flavours of
6479: locals are initialized with values from the data or FP stack.
1.5 anton 6480:
1.26 crook 6481: Currently there is no way to define locals with user-defined data
6482: structures, but we are working on it.
1.5 anton 6483:
1.26 crook 6484: Gforth allows defining locals everywhere in a colon definition. This
6485: poses the following questions:
1.5 anton 6486:
1.26 crook 6487: @menu
6488: * Where are locals visible by name?::
6489: * How long do locals live?::
6490: * Programming Style::
6491: * Implementation::
6492: @end menu
1.5 anton 6493:
1.26 crook 6494: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
6495: @subsubsection Where are locals visible by name?
6496: @cindex locals visibility
6497: @cindex visibility of locals
6498: @cindex scope of locals
1.5 anton 6499:
1.26 crook 6500: Basically, the answer is that locals are visible where you would expect
6501: it in block-structured languages, and sometimes a little longer. If you
6502: want to restrict the scope of a local, enclose its definition in
6503: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 6504:
1.26 crook 6505: doc-scope
6506: doc-endscope
1.5 anton 6507:
1.26 crook 6508: These words behave like control structure words, so you can use them
6509: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
6510: arbitrary ways.
1.5 anton 6511:
1.26 crook 6512: If you want a more exact answer to the visibility question, here's the
6513: basic principle: A local is visible in all places that can only be
6514: reached through the definition of the local@footnote{In compiler
6515: construction terminology, all places dominated by the definition of the
6516: local.}. In other words, it is not visible in places that can be reached
6517: without going through the definition of the local. E.g., locals defined
6518: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
6519: defined in @code{BEGIN}...@code{UNTIL} are visible after the
6520: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5 anton 6521:
1.26 crook 6522: The reasoning behind this solution is: We want to have the locals
6523: visible as long as it is meaningful. The user can always make the
6524: visibility shorter by using explicit scoping. In a place that can
6525: only be reached through the definition of a local, the meaning of a
6526: local name is clear. In other places it is not: How is the local
6527: initialized at the control flow path that does not contain the
6528: definition? Which local is meant, if the same name is defined twice in
6529: two independent control flow paths?
1.5 anton 6530:
1.26 crook 6531: This should be enough detail for nearly all users, so you can skip the
6532: rest of this section. If you really must know all the gory details and
6533: options, read on.
1.5 anton 6534:
1.26 crook 6535: In order to implement this rule, the compiler has to know which places
6536: are unreachable. It knows this automatically after @code{AHEAD},
6537: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
6538: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
6539: compiler that the control flow never reaches that place. If
6540: @code{UNREACHABLE} is not used where it could, the only consequence is
6541: that the visibility of some locals is more limited than the rule above
6542: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
6543: lie to the compiler), buggy code will be produced.
1.5 anton 6544:
1.26 crook 6545: doc-unreachable
1.5 anton 6546:
1.26 crook 6547: Another problem with this rule is that at @code{BEGIN}, the compiler
6548: does not know which locals will be visible on the incoming
6549: back-edge. All problems discussed in the following are due to this
6550: ignorance of the compiler (we discuss the problems using @code{BEGIN}
6551: loops as examples; the discussion also applies to @code{?DO} and other
6552: loops). Perhaps the most insidious example is:
1.5 anton 6553: @example
1.26 crook 6554: AHEAD
6555: BEGIN
6556: x
6557: [ 1 CS-ROLL ] THEN
6558: @{ x @}
6559: ...
6560: UNTIL
6561: @end example
1.5 anton 6562:
1.26 crook 6563: This should be legal according to the visibility rule. The use of
6564: @code{x} can only be reached through the definition; but that appears
6565: textually below the use.
1.5 anton 6566:
1.26 crook 6567: From this example it is clear that the visibility rules cannot be fully
6568: implemented without major headaches. Our implementation treats common
6569: cases as advertised and the exceptions are treated in a safe way: The
6570: compiler makes a reasonable guess about the locals visible after a
6571: @code{BEGIN}; if it is too pessimistic, the
6572: user will get a spurious error about the local not being defined; if the
6573: compiler is too optimistic, it will notice this later and issue a
6574: warning. In the case above the compiler would complain about @code{x}
6575: being undefined at its use. You can see from the obscure examples in
6576: this section that it takes quite unusual control structures to get the
6577: compiler into trouble, and even then it will often do fine.
1.5 anton 6578:
1.26 crook 6579: If the @code{BEGIN} is reachable from above, the most optimistic guess
6580: is that all locals visible before the @code{BEGIN} will also be
6581: visible after the @code{BEGIN}. This guess is valid for all loops that
6582: are entered only through the @code{BEGIN}, in particular, for normal
6583: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
6584: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
6585: compiler. When the branch to the @code{BEGIN} is finally generated by
6586: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
6587: warns the user if it was too optimistic:
6588: @example
6589: IF
6590: @{ x @}
6591: BEGIN
6592: \ x ?
6593: [ 1 cs-roll ] THEN
6594: ...
6595: UNTIL
1.5 anton 6596: @end example
6597:
1.26 crook 6598: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
6599: optimistically assumes that it lives until the @code{THEN}. It notices
6600: this difference when it compiles the @code{UNTIL} and issues a
6601: warning. The user can avoid the warning, and make sure that @code{x}
6602: is not used in the wrong area by using explicit scoping:
6603: @example
6604: IF
6605: SCOPE
6606: @{ x @}
6607: ENDSCOPE
6608: BEGIN
6609: [ 1 cs-roll ] THEN
6610: ...
6611: UNTIL
6612: @end example
1.5 anton 6613:
1.26 crook 6614: Since the guess is optimistic, there will be no spurious error messages
6615: about undefined locals.
1.5 anton 6616:
1.26 crook 6617: If the @code{BEGIN} is not reachable from above (e.g., after
6618: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
6619: optimistic guess, as the locals visible after the @code{BEGIN} may be
6620: defined later. Therefore, the compiler assumes that no locals are
6621: visible after the @code{BEGIN}. However, the user can use
6622: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
6623: visible at the BEGIN as at the point where the top control-flow stack
6624: item was created.
1.5 anton 6625:
1.26 crook 6626: doc-assume-live
1.5 anton 6627:
1.26 crook 6628: E.g.,
1.5 anton 6629: @example
1.26 crook 6630: @{ x @}
6631: AHEAD
6632: ASSUME-LIVE
6633: BEGIN
6634: x
6635: [ 1 CS-ROLL ] THEN
6636: ...
6637: UNTIL
1.5 anton 6638: @end example
6639:
1.26 crook 6640: Other cases where the locals are defined before the @code{BEGIN} can be
6641: handled by inserting an appropriate @code{CS-ROLL} before the
6642: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
6643: behind the @code{ASSUME-LIVE}).
1.5 anton 6644:
1.26 crook 6645: Cases where locals are defined after the @code{BEGIN} (but should be
6646: visible immediately after the @code{BEGIN}) can only be handled by
6647: rearranging the loop. E.g., the ``most insidious'' example above can be
6648: arranged into:
1.5 anton 6649: @example
1.26 crook 6650: BEGIN
6651: @{ x @}
6652: ... 0=
6653: WHILE
6654: x
6655: REPEAT
1.5 anton 6656: @end example
6657:
1.26 crook 6658: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
6659: @subsubsection How long do locals live?
6660: @cindex locals lifetime
6661: @cindex lifetime of locals
1.5 anton 6662:
1.26 crook 6663: The right answer for the lifetime question would be: A local lives at
6664: least as long as it can be accessed. For a value-flavoured local this
6665: means: until the end of its visibility. However, a variable-flavoured
6666: local could be accessed through its address far beyond its visibility
6667: scope. Ultimately, this would mean that such locals would have to be
6668: garbage collected. Since this entails un-Forth-like implementation
6669: complexities, I adopted the same cowardly solution as some other
6670: languages (e.g., C): The local lives only as long as it is visible;
6671: afterwards its address is invalid (and programs that access it
6672: afterwards are erroneous).
1.5 anton 6673:
1.26 crook 6674: @node Programming Style, Implementation, How long do locals live?, Gforth locals
6675: @subsubsection Programming Style
6676: @cindex locals programming style
6677: @cindex programming style, locals
1.5 anton 6678:
1.26 crook 6679: The freedom to define locals anywhere has the potential to change
6680: programming styles dramatically. In particular, the need to use the
6681: return stack for intermediate storage vanishes. Moreover, all stack
6682: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
6683: determined arguments) can be eliminated: If the stack items are in the
6684: wrong order, just write a locals definition for all of them; then
6685: write the items in the order you want.
1.5 anton 6686:
1.26 crook 6687: This seems a little far-fetched and eliminating stack manipulations is
6688: unlikely to become a conscious programming objective. Still, the number
6689: of stack manipulations will be reduced dramatically if local variables
6690: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
6691: a traditional implementation of @code{max}).
1.5 anton 6692:
1.26 crook 6693: This shows one potential benefit of locals: making Forth programs more
6694: readable. Of course, this benefit will only be realized if the
6695: programmers continue to honour the principle of factoring instead of
6696: using the added latitude to make the words longer.
1.5 anton 6697:
1.26 crook 6698: @cindex single-assignment style for locals
6699: Using @code{TO} can and should be avoided. Without @code{TO},
6700: every value-flavoured local has only a single assignment and many
6701: advantages of functional languages apply to Forth. I.e., programs are
6702: easier to analyse, to optimize and to read: It is clear from the
6703: definition what the local stands for, it does not turn into something
6704: different later.
1.5 anton 6705:
1.26 crook 6706: E.g., a definition using @code{TO} might look like this:
1.5 anton 6707: @example
1.26 crook 6708: : strcmp @{ addr1 u1 addr2 u2 -- n @}
6709: u1 u2 min 0
6710: ?do
6711: addr1 c@@ addr2 c@@ -
6712: ?dup-if
6713: unloop exit
6714: then
6715: addr1 char+ TO addr1
6716: addr2 char+ TO addr2
6717: loop
6718: u1 u2 - ;
1.5 anton 6719: @end example
1.26 crook 6720: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
6721: every loop iteration. @code{strcmp} is a typical example of the
6722: readability problems of using @code{TO}. When you start reading
6723: @code{strcmp}, you think that @code{addr1} refers to the start of the
6724: string. Only near the end of the loop you realize that it is something
6725: else.
1.5 anton 6726:
1.26 crook 6727: This can be avoided by defining two locals at the start of the loop that
6728: are initialized with the right value for the current iteration.
1.5 anton 6729: @example
1.26 crook 6730: : strcmp @{ addr1 u1 addr2 u2 -- n @}
6731: addr1 addr2
6732: u1 u2 min 0
6733: ?do @{ s1 s2 @}
6734: s1 c@@ s2 c@@ -
6735: ?dup-if
6736: unloop exit
6737: then
6738: s1 char+ s2 char+
6739: loop
6740: 2drop
6741: u1 u2 - ;
1.5 anton 6742: @end example
1.26 crook 6743: Here it is clear from the start that @code{s1} has a different value
6744: in every loop iteration.
1.5 anton 6745:
1.26 crook 6746: @node Implementation, , Programming Style, Gforth locals
6747: @subsubsection Implementation
6748: @cindex locals implementation
6749: @cindex implementation of locals
1.5 anton 6750:
1.26 crook 6751: @cindex locals stack
6752: Gforth uses an extra locals stack. The most compelling reason for
6753: this is that the return stack is not float-aligned; using an extra stack
6754: also eliminates the problems and restrictions of using the return stack
6755: as locals stack. Like the other stacks, the locals stack grows toward
6756: lower addresses. A few primitives allow an efficient implementation:
1.5 anton 6757:
1.26 crook 6758: doc-@local#
6759: doc-f@local#
6760: doc-laddr#
6761: doc-lp+!#
6762: doc-lp!
6763: doc->l
6764: doc-f>l
1.5 anton 6765:
1.26 crook 6766: In addition to these primitives, some specializations of these
6767: primitives for commonly occurring inline arguments are provided for
6768: efficiency reasons, e.g., @code{@@local0} as specialization of
6769: @code{@@local#} for the inline argument 0. The following compiling words
6770: compile the right specialized version, or the general version, as
6771: appropriate:
1.6 pazsan 6772:
1.26 crook 6773: doc-compile-@local
6774: doc-compile-f@local
6775: doc-compile-lp+!
1.12 anton 6776:
1.26 crook 6777: Combinations of conditional branches and @code{lp+!#} like
6778: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
6779: is taken) are provided for efficiency and correctness in loops.
1.6 pazsan 6780:
1.26 crook 6781: A special area in the dictionary space is reserved for keeping the
6782: local variable names. @code{@{} switches the dictionary pointer to this
6783: area and @code{@}} switches it back and generates the locals
6784: initializing code. @code{W:} etc.@ are normal defining words. This
6785: special area is cleared at the start of every colon definition.
1.6 pazsan 6786:
1.26 crook 6787: @cindex word list for defining locals
6788: A special feature of Gforth's dictionary is used to implement the
6789: definition of locals without type specifiers: every word list (aka
6790: vocabulary) has its own methods for searching
6791: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
6792: with a special search method: When it is searched for a word, it
6793: actually creates that word using @code{W:}. @code{@{} changes the search
6794: order to first search the word list containing @code{@}}, @code{W:} etc.,
6795: and then the word list for defining locals without type specifiers.
1.12 anton 6796:
1.26 crook 6797: The lifetime rules support a stack discipline within a colon
6798: definition: The lifetime of a local is either nested with other locals
6799: lifetimes or it does not overlap them.
1.6 pazsan 6800:
1.26 crook 6801: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
6802: pointer manipulation is generated. Between control structure words
6803: locals definitions can push locals onto the locals stack. @code{AGAIN}
6804: is the simplest of the other three control flow words. It has to
6805: restore the locals stack depth of the corresponding @code{BEGIN}
6806: before branching. The code looks like this:
6807: @format
6808: @code{lp+!#} current-locals-size @minus{} dest-locals-size
6809: @code{branch} <begin>
6810: @end format
1.6 pazsan 6811:
1.26 crook 6812: @code{UNTIL} is a little more complicated: If it branches back, it
6813: must adjust the stack just like @code{AGAIN}. But if it falls through,
6814: the locals stack must not be changed. The compiler generates the
6815: following code:
6816: @format
6817: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
6818: @end format
6819: The locals stack pointer is only adjusted if the branch is taken.
1.6 pazsan 6820:
1.26 crook 6821: @code{THEN} can produce somewhat inefficient code:
6822: @format
6823: @code{lp+!#} current-locals-size @minus{} orig-locals-size
6824: <orig target>:
6825: @code{lp+!#} orig-locals-size @minus{} new-locals-size
6826: @end format
6827: The second @code{lp+!#} adjusts the locals stack pointer from the
1.29 crook 6828: level at the @i{orig} point to the level after the @code{THEN}. The
1.26 crook 6829: first @code{lp+!#} adjusts the locals stack pointer from the current
6830: level to the level at the orig point, so the complete effect is an
6831: adjustment from the current level to the right level after the
6832: @code{THEN}.
1.6 pazsan 6833:
1.26 crook 6834: @cindex locals information on the control-flow stack
6835: @cindex control-flow stack items, locals information
6836: In a conventional Forth implementation a dest control-flow stack entry
6837: is just the target address and an orig entry is just the address to be
6838: patched. Our locals implementation adds a word list to every orig or dest
6839: item. It is the list of locals visible (or assumed visible) at the point
6840: described by the entry. Our implementation also adds a tag to identify
6841: the kind of entry, in particular to differentiate between live and dead
6842: (reachable and unreachable) orig entries.
1.6 pazsan 6843:
1.26 crook 6844: A few unusual operations have to be performed on locals word lists:
1.6 pazsan 6845:
1.26 crook 6846: doc-common-list
6847: doc-sub-list?
6848: doc-list-size
1.6 pazsan 6849:
1.26 crook 6850: Several features of our locals word list implementation make these
6851: operations easy to implement: The locals word lists are organised as
6852: linked lists; the tails of these lists are shared, if the lists
6853: contain some of the same locals; and the address of a name is greater
6854: than the address of the names behind it in the list.
1.6 pazsan 6855:
1.26 crook 6856: Another important implementation detail is the variable
6857: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
6858: determine if they can be reached directly or only through the branch
6859: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
6860: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
6861: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6 pazsan 6862:
1.26 crook 6863: Counted loops are similar to other loops in most respects, but
6864: @code{LEAVE} requires special attention: It performs basically the same
6865: service as @code{AHEAD}, but it does not create a control-flow stack
6866: entry. Therefore the information has to be stored elsewhere;
6867: traditionally, the information was stored in the target fields of the
6868: branches created by the @code{LEAVE}s, by organizing these fields into a
6869: linked list. Unfortunately, this clever trick does not provide enough
6870: space for storing our extended control flow information. Therefore, we
6871: introduce another stack, the leave stack. It contains the control-flow
6872: stack entries for all unresolved @code{LEAVE}s.
1.6 pazsan 6873:
1.26 crook 6874: Local names are kept until the end of the colon definition, even if
6875: they are no longer visible in any control-flow path. In a few cases
6876: this may lead to increased space needs for the locals name area, but
6877: usually less than reclaiming this space would cost in code size.
1.6 pazsan 6878:
6879:
1.26 crook 6880: @node ANS Forth locals, , Gforth locals, Locals
6881: @subsection ANS Forth locals
6882: @cindex locals, ANS Forth style
1.6 pazsan 6883:
1.26 crook 6884: The ANS Forth locals wordset does not define a syntax for locals, but
6885: words that make it possible to define various syntaxes. One of the
6886: possible syntaxes is a subset of the syntax we used in the Gforth locals
6887: wordset, i.e.:
1.6 pazsan 6888:
6889: @example
1.26 crook 6890: @{ local1 local2 ... -- comment @}
1.6 pazsan 6891: @end example
1.23 crook 6892: @noindent
1.26 crook 6893: or
1.6 pazsan 6894: @example
1.26 crook 6895: @{ local1 local2 ... @}
1.6 pazsan 6896: @end example
6897:
1.26 crook 6898: The order of the locals corresponds to the order in a stack comment. The
6899: restrictions are:
1.6 pazsan 6900:
6901: @itemize @bullet
6902: @item
1.26 crook 6903: Locals can only be cell-sized values (no type specifiers are allowed).
1.6 pazsan 6904: @item
1.26 crook 6905: Locals can be defined only outside control structures.
1.6 pazsan 6906: @item
1.26 crook 6907: Locals can interfere with explicit usage of the return stack. For the
6908: exact (and long) rules, see the standard. If you don't use return stack
6909: accessing words in a definition using locals, you will be all right. The
6910: purpose of this rule is to make locals implementation on the return
6911: stack easier.
1.6 pazsan 6912: @item
1.26 crook 6913: The whole definition must be in one line.
6914: @end itemize
1.6 pazsan 6915:
1.26 crook 6916: Locals defined in this way behave like @code{VALUE}s (@xref{Simple
6917: Defining Words}). I.e., they are initialized from the stack. Using their
6918: name produces their value. Their value can be changed using @code{TO}.
1.6 pazsan 6919:
1.26 crook 6920: Since this syntax is supported by Gforth directly, you need not do
6921: anything to use it. If you want to port a program using this syntax to
6922: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
6923: syntax on the other system.
1.6 pazsan 6924:
1.26 crook 6925: Note that a syntax shown in the standard, section A.13 looks
6926: similar, but is quite different in having the order of locals
6927: reversed. Beware!
1.6 pazsan 6928:
1.26 crook 6929: The ANS Forth locals wordset itself consists of a word:
1.6 pazsan 6930:
1.26 crook 6931: doc-(local)
1.6 pazsan 6932:
1.26 crook 6933: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
6934: awful that we strongly recommend not to use it. We have implemented this
6935: syntax to make porting to Gforth easy, but do not document it here. The
6936: problem with this syntax is that the locals are defined in an order
6937: reversed with respect to the standard stack comment notation, making
6938: programs harder to read, and easier to misread and miswrite. The only
6939: merit of this syntax is that it is easy to implement using the ANS Forth
6940: locals wordset.
1.7 pazsan 6941:
6942:
1.26 crook 6943: @c ----------------------------------------------------------
6944: @node Structures, Object-oriented Forth, Locals, Words
6945: @section Structures
6946: @cindex structures
6947: @cindex records
1.7 pazsan 6948:
1.26 crook 6949: This section presents the structure package that comes with Gforth. A
6950: version of the package implemented in ANS Forth is available in
6951: @file{compat/struct.fs}. This package was inspired by a posting on
6952: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
6953: possibly John Hayes). A version of this section has been published in
6954: ???. Marcel Hendrix provided helpful comments.
1.7 pazsan 6955:
1.26 crook 6956: @menu
6957: * Why explicit structure support?::
6958: * Structure Usage::
6959: * Structure Naming Convention::
6960: * Structure Implementation::
6961: * Structure Glossary::
6962: @end menu
1.7 pazsan 6963:
1.26 crook 6964: @node Why explicit structure support?, Structure Usage, Structures, Structures
6965: @subsection Why explicit structure support?
1.7 pazsan 6966:
1.26 crook 6967: @cindex address arithmetic for structures
6968: @cindex structures using address arithmetic
6969: If we want to use a structure containing several fields, we could simply
6970: reserve memory for it, and access the fields using address arithmetic
1.32 ! anton 6971: (@pxref{Address arithmetic}). As an example, consider a structure with
1.26 crook 6972: the following fields
1.7 pazsan 6973:
1.26 crook 6974: @table @code
6975: @item a
6976: is a float
6977: @item b
6978: is a cell
6979: @item c
6980: is a float
6981: @end table
1.7 pazsan 6982:
1.26 crook 6983: Given the (float-aligned) base address of the structure we get the
6984: address of the field
1.13 pazsan 6985:
1.26 crook 6986: @table @code
6987: @item a
6988: without doing anything further.
6989: @item b
6990: with @code{float+}
6991: @item c
6992: with @code{float+ cell+ faligned}
6993: @end table
1.13 pazsan 6994:
1.26 crook 6995: It is easy to see that this can become quite tiring.
1.13 pazsan 6996:
1.26 crook 6997: Moreover, it is not very readable, because seeing a
6998: @code{cell+} tells us neither which kind of structure is
6999: accessed nor what field is accessed; we have to somehow infer the kind
7000: of structure, and then look up in the documentation, which field of
7001: that structure corresponds to that offset.
1.13 pazsan 7002:
1.26 crook 7003: Finally, this kind of address arithmetic also causes maintenance
7004: troubles: If you add or delete a field somewhere in the middle of the
7005: structure, you have to find and change all computations for the fields
7006: afterwards.
1.13 pazsan 7007:
1.26 crook 7008: So, instead of using @code{cell+} and friends directly, how
7009: about storing the offsets in constants:
1.13 pazsan 7010:
7011: @example
1.26 crook 7012: 0 constant a-offset
7013: 0 float+ constant b-offset
7014: 0 float+ cell+ faligned c-offset
1.13 pazsan 7015: @end example
7016:
1.26 crook 7017: Now we can get the address of field @code{x} with @code{x-offset
7018: +}. This is much better in all respects. Of course, you still
7019: have to change all later offset definitions if you add a field. You can
7020: fix this by declaring the offsets in the following way:
1.13 pazsan 7021:
7022: @example
1.26 crook 7023: 0 constant a-offset
7024: a-offset float+ constant b-offset
7025: b-offset cell+ faligned constant c-offset
1.13 pazsan 7026: @end example
7027:
1.26 crook 7028: Since we always use the offsets with @code{+}, we could use a defining
7029: word @code{cfield} that includes the @code{+} in the action of the
7030: defined word:
1.8 pazsan 7031:
7032: @example
1.26 crook 7033: : cfield ( n "name" -- )
7034: create ,
7035: does> ( name execution: addr1 -- addr2 )
7036: @@ + ;
1.13 pazsan 7037:
1.26 crook 7038: 0 cfield a
7039: 0 a float+ cfield b
7040: 0 b cell+ faligned cfield c
1.13 pazsan 7041: @end example
7042:
1.26 crook 7043: Instead of @code{x-offset +}, we now simply write @code{x}.
7044:
7045: The structure field words now can be used quite nicely. However,
7046: their definition is still a bit cumbersome: We have to repeat the
7047: name, the information about size and alignment is distributed before
7048: and after the field definitions etc. The structure package presented
7049: here addresses these problems.
7050:
7051: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
7052: @subsection Structure Usage
7053: @cindex structure usage
1.13 pazsan 7054:
1.26 crook 7055: @cindex @code{field} usage
7056: @cindex @code{struct} usage
7057: @cindex @code{end-struct} usage
7058: You can define a structure for a (data-less) linked list with:
1.13 pazsan 7059: @example
1.26 crook 7060: struct
7061: cell% field list-next
7062: end-struct list%
1.13 pazsan 7063: @end example
7064:
1.26 crook 7065: With the address of the list node on the stack, you can compute the
7066: address of the field that contains the address of the next node with
7067: @code{list-next}. E.g., you can determine the length of a list
7068: with:
1.13 pazsan 7069:
7070: @example
1.26 crook 7071: : list-length ( list -- n )
7072: \ "list" is a pointer to the first element of a linked list
7073: \ "n" is the length of the list
7074: 0 BEGIN ( list1 n1 )
7075: over
7076: WHILE ( list1 n1 )
7077: 1+ swap list-next @@ swap
7078: REPEAT
7079: nip ;
1.13 pazsan 7080: @end example
7081:
1.26 crook 7082: You can reserve memory for a list node in the dictionary with
7083: @code{list% %allot}, which leaves the address of the list node on the
7084: stack. For the equivalent allocation on the heap you can use @code{list%
7085: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
7086: use @code{list% %allocate}). You can get the the size of a list
7087: node with @code{list% %size} and its alignment with @code{list%
7088: %alignment}.
1.13 pazsan 7089:
1.26 crook 7090: Note that in ANS Forth the body of a @code{create}d word is
7091: @code{aligned} but not necessarily @code{faligned};
7092: therefore, if you do a:
1.13 pazsan 7093: @example
1.26 crook 7094: create @emph{name} foo% %allot
1.8 pazsan 7095: @end example
7096:
1.26 crook 7097: @noindent
7098: then the memory alloted for @code{foo%} is
7099: guaranteed to start at the body of @code{@emph{name}} only if
7100: @code{foo%} contains only character, cell and double fields.
1.20 pazsan 7101:
1.26 crook 7102: @cindex strcutures containing structures
7103: You can include a structure @code{foo%} as a field of
7104: another structure, like this:
1.20 pazsan 7105: @example
1.26 crook 7106: struct
7107: ...
7108: foo% field ...
7109: ...
7110: end-struct ...
1.20 pazsan 7111: @end example
7112:
1.26 crook 7113: @cindex structure extension
7114: @cindex extended records
7115: Instead of starting with an empty structure, you can extend an
7116: existing structure. E.g., a plain linked list without data, as defined
7117: above, is hardly useful; You can extend it to a linked list of integers,
7118: like this:@footnote{This feature is also known as @emph{extended
7119: records}. It is the main innovation in the Oberon language; in other
7120: words, adding this feature to Modula-2 led Wirth to create a new
7121: language, write a new compiler etc. Adding this feature to Forth just
7122: required a few lines of code.}
1.20 pazsan 7123:
7124: @example
1.26 crook 7125: list%
7126: cell% field intlist-int
7127: end-struct intlist%
1.20 pazsan 7128: @end example
7129:
1.26 crook 7130: @code{intlist%} is a structure with two fields:
7131: @code{list-next} and @code{intlist-int}.
1.20 pazsan 7132:
1.26 crook 7133: @cindex structures containing arrays
7134: You can specify an array type containing @emph{n} elements of
7135: type @code{foo%} like this:
1.20 pazsan 7136:
7137: @example
1.26 crook 7138: foo% @emph{n} *
1.20 pazsan 7139: @end example
7140:
1.26 crook 7141: You can use this array type in any place where you can use a normal
7142: type, e.g., when defining a @code{field}, or with
7143: @code{%allot}.
1.20 pazsan 7144:
1.26 crook 7145: @cindex first field optimization
7146: The first field is at the base address of a structure and the word
7147: for this field (e.g., @code{list-next}) actually does not change
7148: the address on the stack. You may be tempted to leave it away in the
7149: interest of run-time and space efficiency. This is not necessary,
7150: because the structure package optimizes this case and compiling such
7151: words does not generate any code. So, in the interest of readability
7152: and maintainability you should include the word for the field when
7153: accessing the field.
1.20 pazsan 7154:
1.26 crook 7155: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
7156: @subsection Structure Naming Convention
7157: @cindex structure naming convention
1.20 pazsan 7158:
1.26 crook 7159: The field names that come to (my) mind are often quite generic, and,
7160: if used, would cause frequent name clashes. E.g., many structures
7161: probably contain a @code{counter} field. The structure names
7162: that come to (my) mind are often also the logical choice for the names
7163: of words that create such a structure.
1.20 pazsan 7164:
1.26 crook 7165: Therefore, I have adopted the following naming conventions:
1.20 pazsan 7166:
1.26 crook 7167: @itemize @bullet
7168: @cindex field naming convention
7169: @item
7170: The names of fields are of the form
7171: @code{@emph{struct}-@emph{field}}, where
7172: @code{@emph{struct}} is the basic name of the structure, and
7173: @code{@emph{field}} is the basic name of the field. You can
7174: think of field words as converting the (address of the)
7175: structure into the (address of the) field.
1.20 pazsan 7176:
1.26 crook 7177: @cindex structure naming convention
7178: @item
7179: The names of structures are of the form
7180: @code{@emph{struct}%}, where
7181: @code{@emph{struct}} is the basic name of the structure.
7182: @end itemize
1.20 pazsan 7183:
1.26 crook 7184: This naming convention does not work that well for fields of extended
7185: structures; e.g., the integer list structure has a field
7186: @code{intlist-int}, but has @code{list-next}, not
7187: @code{intlist-next}.
1.20 pazsan 7188:
1.26 crook 7189: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
7190: @subsection Structure Implementation
7191: @cindex structure implementation
7192: @cindex implementation of structures
1.20 pazsan 7193:
1.26 crook 7194: The central idea in the implementation is to pass the data about the
7195: structure being built on the stack, not in some global
7196: variable. Everything else falls into place naturally once this design
7197: decision is made.
1.20 pazsan 7198:
1.26 crook 7199: The type description on the stack is of the form @emph{align
7200: size}. Keeping the size on the top-of-stack makes dealing with arrays
7201: very simple.
1.20 pazsan 7202:
1.26 crook 7203: @code{field} is a defining word that uses @code{Create}
7204: and @code{DOES>}. The body of the field contains the offset
7205: of the field, and the normal @code{DOES>} action is simply:
1.20 pazsan 7206:
7207: @example
1.26 crook 7208: @ +
1.20 pazsan 7209: @end example
7210:
1.23 crook 7211: @noindent
1.26 crook 7212: i.e., add the offset to the address, giving the stack effect
1.29 crook 7213: @i{addr1 -- addr2} for a field.
1.20 pazsan 7214:
1.26 crook 7215: @cindex first field optimization, implementation
7216: This simple structure is slightly complicated by the optimization
7217: for fields with offset 0, which requires a different
7218: @code{DOES>}-part (because we cannot rely on there being
7219: something on the stack if such a field is invoked during
7220: compilation). Therefore, we put the different @code{DOES>}-parts
7221: in separate words, and decide which one to invoke based on the
7222: offset. For a zero offset, the field is basically a noop; it is
7223: immediate, and therefore no code is generated when it is compiled.
1.20 pazsan 7224:
1.26 crook 7225: @node Structure Glossary, , Structure Implementation, Structures
7226: @subsection Structure Glossary
7227: @cindex structure glossary
1.20 pazsan 7228:
1.26 crook 7229: doc-%align
7230: doc-%alignment
7231: doc-%alloc
7232: doc-%allocate
7233: doc-%allot
7234: doc-cell%
7235: doc-char%
7236: doc-dfloat%
7237: doc-double%
7238: doc-end-struct
7239: doc-field
7240: doc-float%
7241: doc-naligned
7242: doc-sfloat%
7243: doc-%size
7244: doc-struct
1.23 crook 7245:
1.26 crook 7246: @c -------------------------------------------------------------
7247: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
7248: @section Object-oriented Forth
1.20 pazsan 7249:
1.26 crook 7250: Gforth comes with three packages for object-oriented programming:
7251: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
7252: is preloaded, so you have to @code{include} them before use. The most
7253: important differences between these packages (and others) are discussed
7254: in @ref{Comparison with other object models}. All packages are written
7255: in ANS Forth and can be used with any other ANS Forth.
1.20 pazsan 7256:
1.26 crook 7257: @menu
7258: * Why object-oriented programming?::
7259: * Object-Oriented Terminology::
7260: * Objects::
7261: * OOF::
7262: * Mini-OOF::
7263: * Comparison with other object models::
7264: @end menu
1.20 pazsan 7265:
1.23 crook 7266:
1.26 crook 7267: @node Why object-oriented programming?, Object-Oriented Terminology, , Object-oriented Forth
7268: @subsubsection Why object-oriented programming?
7269: @cindex object-oriented programming motivation
7270: @cindex motivation for object-oriented programming
1.23 crook 7271:
1.26 crook 7272: Often we have to deal with several data structures (@emph{objects}),
7273: that have to be treated similarly in some respects, but differently in
7274: others. Graphical objects are the textbook example: circles, triangles,
7275: dinosaurs, icons, and others, and we may want to add more during program
7276: development. We want to apply some operations to any graphical object,
7277: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
7278: has to do something different for every kind of object.
7279: @comment TODO add some other operations eg perimeter, area
7280: @comment and tie in to concrete examples later..
1.23 crook 7281:
1.26 crook 7282: We could implement @code{draw} as a big @code{CASE}
7283: control structure that executes the appropriate code depending on the
7284: kind of object to be drawn. This would be not be very elegant, and,
7285: moreover, we would have to change @code{draw} every time we add
7286: a new kind of graphical object (say, a spaceship).
1.23 crook 7287:
1.26 crook 7288: What we would rather do is: When defining spaceships, we would tell
7289: the system: ``Here's how you @code{draw} a spaceship; you figure
7290: out the rest''.
1.23 crook 7291:
1.26 crook 7292: This is the problem that all systems solve that (rightfully) call
7293: themselves object-oriented; the object-oriented packages presented here
7294: solve this problem (and not much else).
7295: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23 crook 7296:
1.26 crook 7297: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
7298: @subsubsection Object-Oriented Terminology
7299: @cindex object-oriented terminology
7300: @cindex terminology for object-oriented programming
1.23 crook 7301:
1.26 crook 7302: This section is mainly for reference, so you don't have to understand
7303: all of it right away. The terminology is mainly Smalltalk-inspired. In
7304: short:
1.23 crook 7305:
1.26 crook 7306: @table @emph
7307: @cindex class
7308: @item class
7309: a data structure definition with some extras.
1.23 crook 7310:
1.26 crook 7311: @cindex object
7312: @item object
7313: an instance of the data structure described by the class definition.
1.23 crook 7314:
1.26 crook 7315: @cindex instance variables
7316: @item instance variables
7317: fields of the data structure.
1.23 crook 7318:
1.26 crook 7319: @cindex selector
7320: @cindex method selector
7321: @cindex virtual function
7322: @item selector
7323: (or @emph{method selector}) a word (e.g.,
7324: @code{draw}) that performs an operation on a variety of data
7325: structures (classes). A selector describes @emph{what} operation to
7326: perform. In C++ terminology: a (pure) virtual function.
1.23 crook 7327:
1.26 crook 7328: @cindex method
7329: @item method
7330: the concrete definition that performs the operation
7331: described by the selector for a specific class. A method specifies
7332: @emph{how} the operation is performed for a specific class.
1.23 crook 7333:
1.26 crook 7334: @cindex selector invocation
7335: @cindex message send
7336: @cindex invoking a selector
7337: @item selector invocation
7338: a call of a selector. One argument of the call (the TOS (top-of-stack))
7339: is used for determining which method is used. In Smalltalk terminology:
7340: a message (consisting of the selector and the other arguments) is sent
7341: to the object.
1.1 anton 7342:
1.26 crook 7343: @cindex receiving object
7344: @item receiving object
7345: the object used for determining the method executed by a selector
7346: invocation. In the @file{objects.fs} model, it is the object that is on
7347: the TOS when the selector is invoked. (@emph{Receiving} comes from
7348: the Smalltalk @emph{message} terminology.)
1.1 anton 7349:
1.26 crook 7350: @cindex child class
7351: @cindex parent class
7352: @cindex inheritance
7353: @item child class
7354: a class that has (@emph{inherits}) all properties (instance variables,
7355: selectors, methods) from a @emph{parent class}. In Smalltalk
7356: terminology: The subclass inherits from the superclass. In C++
7357: terminology: The derived class inherits from the base class.
1.1 anton 7358:
1.26 crook 7359: @end table
1.21 crook 7360:
1.26 crook 7361: @c If you wonder about the message sending terminology, it comes from
7362: @c a time when each object had it's own task and objects communicated via
7363: @c message passing; eventually the Smalltalk developers realized that
7364: @c they can do most things through simple (indirect) calls. They kept the
7365: @c terminology.
1.1 anton 7366:
7367:
1.26 crook 7368: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
7369: @subsection The @file{objects.fs} model
7370: @cindex objects
7371: @cindex object-oriented programming
1.1 anton 7372:
1.26 crook 7373: @cindex @file{objects.fs}
7374: @cindex @file{oof.fs}
1.1 anton 7375:
1.26 crook 7376: This section describes the @file{objects.fs} package. This material also has been published in @cite{Yet Another Forth Objects Package} by Anton Ertl and appeared in Forth Dimensions 19(2), pages 37--43 (@url{http://www.complang.tuwien.ac.at/forth/objects/objects.html}).
7377: @c McKewan's and Zsoter's packages
1.1 anton 7378:
1.26 crook 7379: This section assumes that you have read @ref{Structures}.
1.1 anton 7380:
1.26 crook 7381: The techniques on which this model is based have been used to implement
7382: the parser generator, Gray, and have also been used in Gforth for
7383: implementing the various flavours of word lists (hashed or not,
7384: case-sensitive or not, special-purpose word lists for locals etc.).
1.1 anton 7385:
7386:
1.26 crook 7387: @menu
7388: * Properties of the Objects model::
7389: * Basic Objects Usage::
7390: * The Objects base class::
7391: * Creating objects::
7392: * Object-Oriented Programming Style::
7393: * Class Binding::
7394: * Method conveniences::
7395: * Classes and Scoping::
7396: * Object Interfaces::
7397: * Objects Implementation::
7398: * Objects Glossary::
7399: @end menu
1.1 anton 7400:
1.26 crook 7401: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
7402: and Bernd Paysan helped me with the related works section.
1.1 anton 7403:
1.26 crook 7404: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
7405: @subsubsection Properties of the @file{objects.fs} model
7406: @cindex @file{objects.fs} properties
1.1 anton 7407:
1.26 crook 7408: @itemize @bullet
7409: @item
7410: It is straightforward to pass objects on the stack. Passing
7411: selectors on the stack is a little less convenient, but possible.
1.1 anton 7412:
1.26 crook 7413: @item
7414: Objects are just data structures in memory, and are referenced by their
7415: address. You can create words for objects with normal defining words
7416: like @code{constant}. Likewise, there is no difference between instance
7417: variables that contain objects and those that contain other data.
1.1 anton 7418:
1.26 crook 7419: @item
7420: Late binding is efficient and easy to use.
1.21 crook 7421:
1.26 crook 7422: @item
7423: It avoids parsing, and thus avoids problems with state-smartness
7424: and reduced extensibility; for convenience there are a few parsing
7425: words, but they have non-parsing counterparts. There are also a few
7426: defining words that parse. This is hard to avoid, because all standard
7427: defining words parse (except @code{:noname}); however, such
7428: words are not as bad as many other parsing words, because they are not
7429: state-smart.
1.21 crook 7430:
1.26 crook 7431: @item
7432: It does not try to incorporate everything. It does a few things and does
7433: them well (IMO). In particular, this model was not designed to support
7434: information hiding (although it has features that may help); you can use
7435: a separate package for achieving this.
1.21 crook 7436:
1.26 crook 7437: @item
7438: It is layered; you don't have to learn and use all features to use this
7439: model. Only a few features are necessary (@xref{Basic Objects Usage},
7440: @xref{The Objects base class}, @xref{Creating objects}.), the others
7441: are optional and independent of each other.
1.21 crook 7442:
1.26 crook 7443: @item
7444: An implementation in ANS Forth is available.
1.21 crook 7445:
1.26 crook 7446: @end itemize
1.21 crook 7447:
7448:
1.26 crook 7449: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
7450: @subsubsection Basic @file{objects.fs} Usage
7451: @cindex basic objects usage
7452: @cindex objects, basic usage
1.21 crook 7453:
1.26 crook 7454: You can define a class for graphical objects like this:
1.21 crook 7455:
1.26 crook 7456: @cindex @code{class} usage
7457: @cindex @code{end-class} usage
7458: @cindex @code{selector} usage
7459: @example
7460: object class \ "object" is the parent class
7461: selector draw ( x y graphical -- )
7462: end-class graphical
7463: @end example
1.21 crook 7464:
1.26 crook 7465: This code defines a class @code{graphical} with an
7466: operation @code{draw}. We can perform the operation
7467: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 7468:
1.26 crook 7469: @example
7470: 100 100 t-rex draw
7471: @end example
1.21 crook 7472:
1.26 crook 7473: @noindent
7474: where @code{t-rex} is a word (say, a constant) that produces a
7475: graphical object.
1.21 crook 7476:
1.29 crook 7477: @comment TODO add a 2nd operation eg perimeter.. and use for
1.26 crook 7478: @comment a concrete example
1.21 crook 7479:
1.26 crook 7480: @cindex abstract class
7481: How do we create a graphical object? With the present definitions,
7482: we cannot create a useful graphical object. The class
7483: @code{graphical} describes graphical objects in general, but not
7484: any concrete graphical object type (C++ users would call it an
7485: @emph{abstract class}); e.g., there is no method for the selector
7486: @code{draw} in the class @code{graphical}.
1.21 crook 7487:
1.26 crook 7488: For concrete graphical objects, we define child classes of the
7489: class @code{graphical}, e.g.:
1.21 crook 7490:
1.26 crook 7491: @cindex @code{overrides} usage
7492: @cindex @code{field} usage in class definition
7493: @example
7494: graphical class \ "graphical" is the parent class
7495: cell% field circle-radius
1.21 crook 7496:
1.26 crook 7497: :noname ( x y circle -- )
7498: circle-radius @@ draw-circle ;
7499: overrides draw
1.21 crook 7500:
1.26 crook 7501: :noname ( n-radius circle -- )
7502: circle-radius ! ;
7503: overrides construct
1.21 crook 7504:
1.26 crook 7505: end-class circle
1.21 crook 7506: @end example
7507:
1.26 crook 7508: Here we define a class @code{circle} as a child of @code{graphical},
7509: with field @code{circle-radius} (which behaves just like a field
7510: (@pxref{Structures}); it defines (using @code{overrides}) new methods
7511: for the selectors @code{draw} and @code{construct} (@code{construct} is
7512: defined in @code{object}, the parent class of @code{graphical}).
1.21 crook 7513:
1.26 crook 7514: Now we can create a circle on the heap (i.e.,
7515: @code{allocate}d memory) with:
1.21 crook 7516:
1.26 crook 7517: @cindex @code{heap-new} usage
1.21 crook 7518: @example
1.26 crook 7519: 50 circle heap-new constant my-circle
7520: @end example
1.21 crook 7521:
1.26 crook 7522: @noindent
7523: @code{heap-new} invokes @code{construct}, thus
7524: initializing the field @code{circle-radius} with 50. We can draw
7525: this new circle at (100,100) with:
1.21 crook 7526:
1.26 crook 7527: @example
7528: 100 100 my-circle draw
1.21 crook 7529: @end example
7530:
1.26 crook 7531: @cindex selector invocation, restrictions
7532: @cindex class definition, restrictions
7533: Note: You can only invoke a selector if the object on the TOS
7534: (the receiving object) belongs to the class where the selector was
7535: defined or one of its descendents; e.g., you can invoke
7536: @code{draw} only for objects belonging to @code{graphical}
7537: or its descendents (e.g., @code{circle}). Immediately before
7538: @code{end-class}, the search order has to be the same as
7539: immediately after @code{class}.
1.21 crook 7540:
1.26 crook 7541: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
7542: @subsubsection The @file{object.fs} base class
7543: @cindex @code{object} class
1.21 crook 7544:
1.26 crook 7545: When you define a class, you have to specify a parent class. So how do
7546: you start defining classes? There is one class available from the start:
7547: @code{object}. It is ancestor for all classes and so is the
7548: only class that has no parent. It has two selectors: @code{construct}
7549: and @code{print}.
1.21 crook 7550:
1.26 crook 7551: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
7552: @subsubsection Creating objects
7553: @cindex creating objects
7554: @cindex object creation
7555: @cindex object allocation options
1.21 crook 7556:
1.26 crook 7557: @cindex @code{heap-new} discussion
7558: @cindex @code{dict-new} discussion
7559: @cindex @code{construct} discussion
7560: You can create and initialize an object of a class on the heap with
7561: @code{heap-new} ( ... class -- object ) and in the dictionary
7562: (allocation with @code{allot}) with @code{dict-new} (
7563: ... class -- object ). Both words invoke @code{construct}, which
7564: consumes the stack items indicated by "..." above.
1.21 crook 7565:
1.26 crook 7566: @cindex @code{init-object} discussion
7567: @cindex @code{class-inst-size} discussion
7568: If you want to allocate memory for an object yourself, you can get its
7569: alignment and size with @code{class-inst-size 2@@} ( class --
7570: align size ). Once you have memory for an object, you can initialize
7571: it with @code{init-object} ( ... class object -- );
7572: @code{construct} does only a part of the necessary work.
1.21 crook 7573:
1.26 crook 7574: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
7575: @subsubsection Object-Oriented Programming Style
7576: @cindex object-oriented programming style
1.21 crook 7577:
1.26 crook 7578: This section is not exhaustive.
1.1 anton 7579:
1.26 crook 7580: @cindex stack effects of selectors
7581: @cindex selectors and stack effects
7582: In general, it is a good idea to ensure that all methods for the
7583: same selector have the same stack effect: when you invoke a selector,
7584: you often have no idea which method will be invoked, so, unless all
7585: methods have the same stack effect, you will not know the stack effect
7586: of the selector invocation.
1.21 crook 7587:
1.26 crook 7588: One exception to this rule is methods for the selector
7589: @code{construct}. We know which method is invoked, because we
7590: specify the class to be constructed at the same place. Actually, I
7591: defined @code{construct} as a selector only to give the users a
7592: convenient way to specify initialization. The way it is used, a
7593: mechanism different from selector invocation would be more natural
7594: (but probably would take more code and more space to explain).
1.21 crook 7595:
1.26 crook 7596: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
7597: @subsubsection Class Binding
7598: @cindex class binding
7599: @cindex early binding
1.21 crook 7600:
1.26 crook 7601: @cindex late binding
7602: Normal selector invocations determine the method at run-time depending
7603: on the class of the receiving object. This run-time selection is called
1.29 crook 7604: @i{late binding}.
1.21 crook 7605:
1.26 crook 7606: Sometimes it's preferable to invoke a different method. For example,
7607: you might want to use the simple method for @code{print}ing
7608: @code{object}s instead of the possibly long-winded @code{print} method
7609: of the receiver class. You can achieve this by replacing the invocation
7610: of @code{print} with:
1.21 crook 7611:
1.26 crook 7612: @cindex @code{[bind]} usage
7613: @example
7614: [bind] object print
1.21 crook 7615: @end example
7616:
1.26 crook 7617: @noindent
7618: in compiled code or:
1.21 crook 7619:
1.26 crook 7620: @cindex @code{bind} usage
1.21 crook 7621: @example
1.26 crook 7622: bind object print
1.21 crook 7623: @end example
7624:
1.26 crook 7625: @cindex class binding, alternative to
7626: @noindent
7627: in interpreted code. Alternatively, you can define the method with a
7628: name (e.g., @code{print-object}), and then invoke it through the
7629: name. Class binding is just a (often more convenient) way to achieve
7630: the same effect; it avoids name clutter and allows you to invoke
7631: methods directly without naming them first.
7632:
7633: @cindex superclass binding
7634: @cindex parent class binding
7635: A frequent use of class binding is this: When we define a method
7636: for a selector, we often want the method to do what the selector does
7637: in the parent class, and a little more. There is a special word for
7638: this purpose: @code{[parent]}; @code{[parent]
7639: @emph{selector}} is equivalent to @code{[bind] @emph{parent
7640: selector}}, where @code{@emph{parent}} is the parent
7641: class of the current class. E.g., a method definition might look like:
1.21 crook 7642:
1.26 crook 7643: @cindex @code{[parent]} usage
1.21 crook 7644: @example
1.26 crook 7645: :noname
7646: dup [parent] foo \ do parent's foo on the receiving object
7647: ... \ do some more
7648: ; overrides foo
1.21 crook 7649: @end example
7650:
1.26 crook 7651: @cindex class binding as optimization
7652: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
7653: March 1997), Andrew McKewan presents class binding as an optimization
7654: technique. I recommend not using it for this purpose unless you are in
7655: an emergency. Late binding is pretty fast with this model anyway, so the
7656: benefit of using class binding is small; the cost of using class binding
7657: where it is not appropriate is reduced maintainability.
1.21 crook 7658:
1.26 crook 7659: While we are at programming style questions: You should bind
7660: selectors only to ancestor classes of the receiving object. E.g., say,
7661: you know that the receiving object is of class @code{foo} or its
7662: descendents; then you should bind only to @code{foo} and its
7663: ancestors.
1.21 crook 7664:
1.26 crook 7665: @node Method conveniences, Classes and Scoping, Class Binding, Objects
7666: @subsubsection Method conveniences
7667: @cindex method conveniences
1.1 anton 7668:
1.26 crook 7669: In a method you usually access the receiving object pretty often. If
7670: you define the method as a plain colon definition (e.g., with
7671: @code{:noname}), you may have to do a lot of stack
7672: gymnastics. To avoid this, you can define the method with @code{m:
7673: ... ;m}. E.g., you could define the method for
7674: @code{draw}ing a @code{circle} with
1.20 pazsan 7675:
1.26 crook 7676: @cindex @code{this} usage
7677: @cindex @code{m:} usage
7678: @cindex @code{;m} usage
7679: @example
7680: m: ( x y circle -- )
7681: ( x y ) this circle-radius @@ draw-circle ;m
7682: @end example
1.20 pazsan 7683:
1.26 crook 7684: @cindex @code{exit} in @code{m: ... ;m}
7685: @cindex @code{exitm} discussion
7686: @cindex @code{catch} in @code{m: ... ;m}
7687: When this method is executed, the receiver object is removed from the
7688: stack; you can access it with @code{this} (admittedly, in this
7689: example the use of @code{m: ... ;m} offers no advantage). Note
7690: that I specify the stack effect for the whole method (i.e. including
7691: the receiver object), not just for the code between @code{m:}
7692: and @code{;m}. You cannot use @code{exit} in
7693: @code{m:...;m}; instead, use
7694: @code{exitm}.@footnote{Moreover, for any word that calls
7695: @code{catch} and was defined before loading
7696: @code{objects.fs}, you have to redefine it like I redefined
7697: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20 pazsan 7698:
1.26 crook 7699: @cindex @code{inst-var} usage
7700: You will frequently use sequences of the form @code{this
7701: @emph{field}} (in the example above: @code{this
7702: circle-radius}). If you use the field only in this way, you can
7703: define it with @code{inst-var} and eliminate the
7704: @code{this} before the field name. E.g., the @code{circle}
7705: class above could also be defined with:
1.20 pazsan 7706:
1.26 crook 7707: @example
7708: graphical class
7709: cell% inst-var radius
1.20 pazsan 7710:
1.26 crook 7711: m: ( x y circle -- )
7712: radius @@ draw-circle ;m
7713: overrides draw
1.20 pazsan 7714:
1.26 crook 7715: m: ( n-radius circle -- )
7716: radius ! ;m
7717: overrides construct
1.12 anton 7718:
1.26 crook 7719: end-class circle
7720: @end example
1.12 anton 7721:
1.26 crook 7722: @code{radius} can only be used in @code{circle} and its
7723: descendent classes and inside @code{m:...;m}.
1.12 anton 7724:
1.26 crook 7725: @cindex @code{inst-value} usage
7726: You can also define fields with @code{inst-value}, which is
7727: to @code{inst-var} what @code{value} is to
7728: @code{variable}. You can change the value of such a field with
7729: @code{[to-inst]}. E.g., we could also define the class
7730: @code{circle} like this:
1.12 anton 7731:
1.26 crook 7732: @example
7733: graphical class
7734: inst-value radius
1.12 anton 7735:
1.26 crook 7736: m: ( x y circle -- )
7737: radius draw-circle ;m
7738: overrides draw
1.12 anton 7739:
1.26 crook 7740: m: ( n-radius circle -- )
7741: [to-inst] radius ;m
7742: overrides construct
1.21 crook 7743:
1.26 crook 7744: end-class circle
1.12 anton 7745: @end example
7746:
7747:
1.26 crook 7748: @node Classes and Scoping, Object Interfaces, Method conveniences, Objects
7749: @subsubsection Classes and Scoping
7750: @cindex classes and scoping
7751: @cindex scoping and classes
1.12 anton 7752:
1.26 crook 7753: Inheritance is frequent, unlike structure extension. This exacerbates
7754: the problem with the field name convention (@pxref{Structure Naming
7755: Convention}): One always has to remember in which class the field was
7756: originally defined; changing a part of the class structure would require
7757: changes for renaming in otherwise unaffected code.
1.12 anton 7758:
1.26 crook 7759: @cindex @code{inst-var} visibility
7760: @cindex @code{inst-value} visibility
7761: To solve this problem, I added a scoping mechanism (which was not in my
7762: original charter): A field defined with @code{inst-var} (or
7763: @code{inst-value}) is visible only in the class where it is defined and in
7764: the descendent classes of this class. Using such fields only makes
7765: sense in @code{m:}-defined methods in these classes anyway.
1.12 anton 7766:
1.26 crook 7767: This scoping mechanism allows us to use the unadorned field name,
7768: because name clashes with unrelated words become much less likely.
1.12 anton 7769:
1.26 crook 7770: @cindex @code{protected} discussion
7771: @cindex @code{private} discussion
7772: Once we have this mechanism, we can also use it for controlling the
7773: visibility of other words: All words defined after
7774: @code{protected} are visible only in the current class and its
7775: descendents. @code{public} restores the compilation
7776: (i.e. @code{current}) word list that was in effect before. If you
7777: have several @code{protected}s without an intervening
7778: @code{public} or @code{set-current}, @code{public}
7779: will restore the compilation word list in effect before the first of
7780: these @code{protected}s.
1.12 anton 7781:
1.26 crook 7782: @node Object Interfaces, Objects Implementation, Classes and Scoping, Objects
7783: @subsubsection Object Interfaces
7784: @cindex object interfaces
7785: @cindex interfaces for objects
1.12 anton 7786:
1.26 crook 7787: In this model you can only call selectors defined in the class of the
7788: receiving objects or in one of its ancestors. If you call a selector
7789: with a receiving object that is not in one of these classes, the
7790: result is undefined; if you are lucky, the program crashes
7791: immediately.
1.12 anton 7792:
1.26 crook 7793: @cindex selectors common to hardly-related classes
7794: Now consider the case when you want to have a selector (or several)
7795: available in two classes: You would have to add the selector to a
7796: common ancestor class, in the worst case to @code{object}. You
7797: may not want to do this, e.g., because someone else is responsible for
7798: this ancestor class.
1.12 anton 7799:
1.26 crook 7800: The solution for this problem is interfaces. An interface is a
7801: collection of selectors. If a class implements an interface, the
7802: selectors become available to the class and its descendents. A class
7803: can implement an unlimited number of interfaces. For the problem
7804: discussed above, we would define an interface for the selector(s), and
7805: both classes would implement the interface.
1.12 anton 7806:
1.26 crook 7807: As an example, consider an interface @code{storage} for
7808: writing objects to disk and getting them back, and a class
7809: @code{foo} that implements it. The code would look like this:
1.12 anton 7810:
1.26 crook 7811: @cindex @code{interface} usage
7812: @cindex @code{end-interface} usage
7813: @cindex @code{implementation} usage
7814: @example
7815: interface
7816: selector write ( file object -- )
7817: selector read1 ( file object -- )
7818: end-interface storage
1.12 anton 7819:
1.26 crook 7820: bar class
7821: storage implementation
1.12 anton 7822:
1.26 crook 7823: ... overrides write
7824: ... overrides read
7825: ...
7826: end-class foo
1.12 anton 7827: @end example
7828:
1.26 crook 7829: @noindent
1.29 crook 7830: (I would add a word @code{read} @i{( file -- object )} that uses
1.26 crook 7831: @code{read1} internally, but that's beyond the point illustrated
7832: here.)
1.12 anton 7833:
1.26 crook 7834: Note that you cannot use @code{protected} in an interface; and
7835: of course you cannot define fields.
1.12 anton 7836:
1.26 crook 7837: In the Neon model, all selectors are available for all classes;
7838: therefore it does not need interfaces. The price you pay in this model
7839: is slower late binding, and therefore, added complexity to avoid late
7840: binding.
1.12 anton 7841:
1.26 crook 7842: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
7843: @subsubsection @file{objects.fs} Implementation
7844: @cindex @file{objects.fs} implementation
1.12 anton 7845:
1.26 crook 7846: @cindex @code{object-map} discussion
7847: An object is a piece of memory, like one of the data structures
7848: described with @code{struct...end-struct}. It has a field
7849: @code{object-map} that points to the method map for the object's
7850: class.
1.12 anton 7851:
1.26 crook 7852: @cindex method map
7853: @cindex virtual function table
7854: The @emph{method map}@footnote{This is Self terminology; in C++
7855: terminology: virtual function table.} is an array that contains the
1.29 crook 7856: execution tokens (@i{xt}s) of the methods for the object's class. Each
1.26 crook 7857: selector contains an offset into a method map.
1.12 anton 7858:
1.26 crook 7859: @cindex @code{selector} implementation, class
7860: @code{selector} is a defining word that uses
7861: @code{CREATE} and @code{DOES>}. The body of the
7862: selector contains the offset; the @code{does>} action for a
7863: class selector is, basically:
1.21 crook 7864:
1.26 crook 7865: @example
7866: ( object addr ) @@ over object-map @@ + @@ execute
7867: @end example
1.12 anton 7868:
1.26 crook 7869: Since @code{object-map} is the first field of the object, it
7870: does not generate any code. As you can see, calling a selector has a
7871: small, constant cost.
1.12 anton 7872:
1.26 crook 7873: @cindex @code{current-interface} discussion
7874: @cindex class implementation and representation
7875: A class is basically a @code{struct} combined with a method
7876: map. During the class definition the alignment and size of the class
7877: are passed on the stack, just as with @code{struct}s, so
7878: @code{field} can also be used for defining class
7879: fields. However, passing more items on the stack would be
7880: inconvenient, so @code{class} builds a data structure in memory,
7881: which is accessed through the variable
7882: @code{current-interface}. After its definition is complete, the
7883: class is represented on the stack by a pointer (e.g., as parameter for
7884: a child class definition).
1.1 anton 7885:
1.26 crook 7886: A new class starts off with the alignment and size of its parent,
7887: and a copy of the parent's method map. Defining new fields extends the
7888: size and alignment; likewise, defining new selectors extends the
1.29 crook 7889: method map. @code{overrides} just stores a new @i{xt} in the method
1.26 crook 7890: map at the offset given by the selector.
1.20 pazsan 7891:
1.26 crook 7892: @cindex class binding, implementation
1.29 crook 7893: Class binding just gets the @i{xt} at the offset given by the selector
1.26 crook 7894: from the class's method map and @code{compile,}s (in the case of
7895: @code{[bind]}) it.
1.21 crook 7896:
1.26 crook 7897: @cindex @code{this} implementation
7898: @cindex @code{catch} and @code{this}
7899: @cindex @code{this} and @code{catch}
7900: I implemented @code{this} as a @code{value}. At the
7901: start of an @code{m:...;m} method the old @code{this} is
7902: stored to the return stack and restored at the end; and the object on
7903: the TOS is stored @code{TO this}. This technique has one
7904: disadvantage: If the user does not leave the method via
7905: @code{;m}, but via @code{throw} or @code{exit},
7906: @code{this} is not restored (and @code{exit} may
7907: crash). To deal with the @code{throw} problem, I have redefined
7908: @code{catch} to save and restore @code{this}; the same
7909: should be done with any word that can catch an exception. As for
7910: @code{exit}, I simply forbid it (as a replacement, there is
7911: @code{exitm}).
1.21 crook 7912:
1.26 crook 7913: @cindex @code{inst-var} implementation
7914: @code{inst-var} is just the same as @code{field}, with
7915: a different @code{DOES>} action:
7916: @example
7917: @@ this +
7918: @end example
7919: Similar for @code{inst-value}.
1.21 crook 7920:
1.26 crook 7921: @cindex class scoping implementation
7922: Each class also has a word list that contains the words defined with
7923: @code{inst-var} and @code{inst-value}, and its protected
7924: words. It also has a pointer to its parent. @code{class} pushes
7925: the word lists of the class and all its ancestors onto the search order stack,
7926: and @code{end-class} drops them.
1.21 crook 7927:
1.26 crook 7928: @cindex interface implementation
7929: An interface is like a class without fields, parent and protected
7930: words; i.e., it just has a method map. If a class implements an
7931: interface, its method map contains a pointer to the method map of the
7932: interface. The positive offsets in the map are reserved for class
7933: methods, therefore interface map pointers have negative
7934: offsets. Interfaces have offsets that are unique throughout the
7935: system, unlike class selectors, whose offsets are only unique for the
7936: classes where the selector is available (invokable).
1.21 crook 7937:
1.26 crook 7938: This structure means that interface selectors have to perform one
7939: indirection more than class selectors to find their method. Their body
7940: contains the interface map pointer offset in the class method map, and
7941: the method offset in the interface method map. The
7942: @code{does>} action for an interface selector is, basically:
1.21 crook 7943:
7944: @example
1.26 crook 7945: ( object selector-body )
7946: 2dup selector-interface @@ ( object selector-body object interface-offset )
7947: swap object-map @@ + @@ ( object selector-body map )
7948: swap selector-offset @@ + @@ execute
1.21 crook 7949: @end example
7950:
1.26 crook 7951: where @code{object-map} and @code{selector-offset} are
7952: first fields and generate no code.
7953:
7954: As a concrete example, consider the following code:
1.21 crook 7955:
1.26 crook 7956: @example
7957: interface
7958: selector if1sel1
7959: selector if1sel2
7960: end-interface if1
1.21 crook 7961:
1.26 crook 7962: object class
7963: if1 implementation
7964: selector cl1sel1
7965: cell% inst-var cl1iv1
1.21 crook 7966:
1.26 crook 7967: ' m1 overrides construct
7968: ' m2 overrides if1sel1
7969: ' m3 overrides if1sel2
7970: ' m4 overrides cl1sel2
7971: end-class cl1
1.21 crook 7972:
1.26 crook 7973: create obj1 object dict-new drop
7974: create obj2 cl1 dict-new drop
7975: @end example
1.21 crook 7976:
1.26 crook 7977: The data structure created by this code (including the data structure
7978: for @code{object}) is shown in the <a
7979: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.29 crook 7980: @comment TODO add this diagram..
1.21 crook 7981:
1.26 crook 7982: @node Objects Glossary, , Objects Implementation, Objects
7983: @subsubsection @file{objects.fs} Glossary
7984: @cindex @file{objects.fs} Glossary
1.21 crook 7985:
1.26 crook 7986: doc---objects-bind
7987: doc---objects-<bind>
7988: doc---objects-bind'
7989: doc---objects-[bind]
7990: doc---objects-class
7991: doc---objects-class->map
7992: doc---objects-class-inst-size
7993: doc---objects-class-override!
7994: doc---objects-construct
7995: doc---objects-current'
7996: doc---objects-[current]
7997: doc---objects-current-interface
7998: doc---objects-dict-new
7999: doc---objects-drop-order
8000: doc---objects-end-class
8001: doc---objects-end-class-noname
8002: doc---objects-end-interface
8003: doc---objects-end-interface-noname
8004: doc---objects-exitm
8005: doc---objects-heap-new
8006: doc---objects-implementation
8007: doc---objects-init-object
8008: doc---objects-inst-value
8009: doc---objects-inst-var
8010: doc---objects-interface
8011: doc---objects-;m
8012: doc---objects-m:
8013: doc---objects-method
8014: doc---objects-object
8015: doc---objects-overrides
8016: doc---objects-[parent]
8017: doc---objects-print
8018: doc---objects-protected
8019: doc---objects-public
8020: doc---objects-push-order
8021: doc---objects-selector
8022: doc---objects-this
8023: doc---objects-<to-inst>
8024: doc---objects-[to-inst]
8025: doc---objects-to-this
8026: doc---objects-xt-new
1.21 crook 8027:
1.26 crook 8028: @c -------------------------------------------------------------
8029: @node OOF, Mini-OOF, Objects, Object-oriented Forth
8030: @subsection The @file{oof.fs} model
8031: @cindex oof
8032: @cindex object-oriented programming
1.21 crook 8033:
1.26 crook 8034: @cindex @file{objects.fs}
8035: @cindex @file{oof.fs}
1.21 crook 8036:
1.26 crook 8037: This section describes the @file{oof.fs} package.
1.21 crook 8038:
1.26 crook 8039: The package described in this section has been used in bigFORTH since 1991, and
8040: used for two large applications: a chromatographic system used to
8041: create new medicaments, and a graphic user interface library (MINOS).
1.21 crook 8042:
1.26 crook 8043: You can find a description (in German) of @file{oof.fs} in @cite{Object
8044: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
8045: 10(2), 1994.
1.21 crook 8046:
1.26 crook 8047: @menu
8048: * Properties of the OOF model::
8049: * Basic OOF Usage::
8050: * The OOF base class::
8051: * Class Declaration::
8052: * Class Implementation::
8053: @end menu
1.21 crook 8054:
1.26 crook 8055: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
8056: @subsubsection Properties of the @file{oof.fs} model
8057: @cindex @file{oof.fs} properties
1.21 crook 8058:
1.26 crook 8059: @itemize @bullet
8060: @item
8061: This model combines object oriented programming with information
8062: hiding. It helps you writing large application, where scoping is
8063: necessary, because it provides class-oriented scoping.
1.21 crook 8064:
1.26 crook 8065: @item
8066: Named objects, object pointers, and object arrays can be created,
8067: selector invocation uses the ``object selector'' syntax. Selector invocation
8068: to objects and/or selectors on the stack is a bit less convenient, but
8069: possible.
1.21 crook 8070:
1.26 crook 8071: @item
8072: Selector invocation and instance variable usage of the active object is
8073: straightforward, since both make use of the active object.
1.21 crook 8074:
1.26 crook 8075: @item
8076: Late binding is efficient and easy to use.
1.21 crook 8077:
1.26 crook 8078: @item
8079: State-smart objects parse selectors. However, extensibility is provided
8080: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21 crook 8081:
8082: @item
1.26 crook 8083: An implementation in ANS Forth is available.
8084:
1.21 crook 8085: @end itemize
8086:
8087:
1.26 crook 8088: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
8089: @subsubsection Basic @file{oof.fs} Usage
8090: @cindex @file{oof.fs} usage
8091:
8092: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21 crook 8093:
1.26 crook 8094: You can define a class for graphical objects like this:
1.21 crook 8095:
1.26 crook 8096: @cindex @code{class} usage
8097: @cindex @code{class;} usage
8098: @cindex @code{method} usage
8099: @example
8100: object class graphical \ "object" is the parent class
8101: method draw ( x y graphical -- )
8102: class;
8103: @end example
1.21 crook 8104:
1.26 crook 8105: This code defines a class @code{graphical} with an
8106: operation @code{draw}. We can perform the operation
8107: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 8108:
1.26 crook 8109: @example
8110: 100 100 t-rex draw
8111: @end example
1.21 crook 8112:
1.26 crook 8113: @noindent
8114: where @code{t-rex} is an object or object pointer, created with e.g.
8115: @code{graphical : t-rex}.
1.21 crook 8116:
1.26 crook 8117: @cindex abstract class
8118: How do we create a graphical object? With the present definitions,
8119: we cannot create a useful graphical object. The class
8120: @code{graphical} describes graphical objects in general, but not
8121: any concrete graphical object type (C++ users would call it an
8122: @emph{abstract class}); e.g., there is no method for the selector
8123: @code{draw} in the class @code{graphical}.
1.21 crook 8124:
1.26 crook 8125: For concrete graphical objects, we define child classes of the
8126: class @code{graphical}, e.g.:
1.21 crook 8127:
8128: @example
1.26 crook 8129: graphical class circle \ "graphical" is the parent class
8130: cell var circle-radius
8131: how:
8132: : draw ( x y -- )
8133: circle-radius @@ draw-circle ;
8134:
8135: : init ( n-radius -- (
8136: circle-radius ! ;
8137: class;
8138: @end example
8139:
8140: Here we define a class @code{circle} as a child of @code{graphical},
8141: with a field @code{circle-radius}; it defines new methods for the
8142: selectors @code{draw} and @code{init} (@code{init} is defined in
8143: @code{object}, the parent class of @code{graphical}).
1.21 crook 8144:
1.26 crook 8145: Now we can create a circle in the dictionary with:
1.21 crook 8146:
1.26 crook 8147: @example
8148: 50 circle : my-circle
1.21 crook 8149: @end example
8150:
1.26 crook 8151: @noindent
8152: @code{:} invokes @code{init}, thus initializing the field
8153: @code{circle-radius} with 50. We can draw this new circle at (100,100)
8154: with:
1.21 crook 8155:
8156: @example
1.26 crook 8157: 100 100 my-circle draw
1.21 crook 8158: @end example
8159:
1.26 crook 8160: @cindex selector invocation, restrictions
8161: @cindex class definition, restrictions
8162: Note: You can only invoke a selector if the receiving object belongs to
8163: the class where the selector was defined or one of its descendents;
8164: e.g., you can invoke @code{draw} only for objects belonging to
8165: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
8166: mechanism will check if you try to invoke a selector that is not
8167: defined in this class hierarchy, so you'll get an error at compilation
8168: time.
8169:
8170:
8171: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
8172: @subsubsection The @file{oof.fs} base class
8173: @cindex @file{oof.fs} base class
8174:
8175: When you define a class, you have to specify a parent class. So how do
8176: you start defining classes? There is one class available from the start:
8177: @code{object}. You have to use it as ancestor for all classes. It is the
8178: only class that has no parent. Classes are also objects, except that
8179: they don't have instance variables; class manipulation such as
8180: inheritance or changing definitions of a class is handled through
8181: selectors of the class @code{object}.
8182:
8183: @code{object} provides a number of selectors:
8184:
1.21 crook 8185: @itemize @bullet
8186: @item
1.26 crook 8187: @code{class} for subclassing, @code{definitions} to add definitions
8188: later on, and @code{class?} to get type informations (is the class a
8189: subclass of the class passed on the stack?).
8190: doc---object-class
8191: doc---object-definitions
8192: doc---object-class?
8193:
1.21 crook 8194: @item
1.26 crook 8195: @code{init} and @code{dispose} as constructor and destructor of the
8196: object. @code{init} is invocated after the object's memory is allocated,
8197: while @code{dispose} also handles deallocation. Thus if you redefine
8198: @code{dispose}, you have to call the parent's dispose with @code{super
8199: dispose}, too.
8200: doc---object-init
8201: doc---object-dispose
8202:
1.21 crook 8203: @item
1.26 crook 8204: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
8205: @code{[]} to create named and unnamed objects and object arrays or
8206: object pointers.
8207: doc---object-new
8208: doc---object-new[]
8209: doc---object-:
8210: doc---object-ptr
8211: doc---object-asptr
8212: doc---object-[]
1.21 crook 8213:
1.26 crook 8214: @item
8215: @code{::} and @code{super} for explicit scoping. You should use explicit
8216: scoping only for super classes or classes with the same set of instance
8217: variables. Explicitly-scoped selectors use early binding.
8218: doc---object-::
8219: doc---object-super
1.21 crook 8220:
1.26 crook 8221: @item
8222: @code{self} to get the address of the object
8223: doc---object-self
1.21 crook 8224:
8225: @item
1.26 crook 8226: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
8227: pointers and instance defers.
8228: doc---object-bind
8229: doc---object-bound
8230: doc---object-link
8231: doc---object-is
8232:
1.21 crook 8233: @item
1.26 crook 8234: @code{'} to obtain selector tokens, @code{send} to invocate selectors
8235: form the stack, and @code{postpone} to generate selector invocation code.
8236: doc---object-'
8237: doc---object-postpone
8238:
1.21 crook 8239: @item
1.26 crook 8240: @code{with} and @code{endwith} to select the active object from the
8241: stack, and enable its scope. Using @code{with} and @code{endwith}
8242: also allows you to create code using selector @code{postpone} without being
8243: trapped by the state-smart objects.
8244: doc---object-with
8245: doc---object-endwith
8246:
1.21 crook 8247: @end itemize
8248:
1.26 crook 8249: @node Class Declaration, Class Implementation, The OOF base class, OOF
8250: @subsubsection Class Declaration
8251: @cindex class declaration
8252:
8253: @itemize @bullet
8254: @item
8255: Instance variables
8256: doc---oof-var
1.21 crook 8257:
1.26 crook 8258: @item
8259: Object pointers
8260: doc---oof-ptr
8261: doc---oof-asptr
1.21 crook 8262:
1.26 crook 8263: @item
8264: Instance defers
8265: doc---oof-defer
1.21 crook 8266:
1.26 crook 8267: @item
8268: Method selectors
8269: doc---oof-early
8270: doc---oof-method
1.21 crook 8271:
1.26 crook 8272: @item
8273: Class-wide variables
8274: doc---oof-static
1.21 crook 8275:
1.26 crook 8276: @item
8277: End declaration
8278: doc---oof-how:
8279: doc---oof-class;
1.21 crook 8280:
1.26 crook 8281: @end itemize
1.21 crook 8282:
1.26 crook 8283: @c -------------------------------------------------------------
8284: @node Class Implementation, , Class Declaration, OOF
8285: @subsubsection Class Implementation
8286: @cindex class implementation
1.21 crook 8287:
1.26 crook 8288: @c -------------------------------------------------------------
8289: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
8290: @subsection The @file{mini-oof.fs} model
8291: @cindex mini-oof
1.1 anton 8292:
1.26 crook 8293: Gforth's third object oriented Forth package is a 12-liner. It uses a
8294: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
8295: and reduces to the bare minimum of features. This is based on a posting
8296: of Bernd Paysan in comp.arch.
1.1 anton 8297:
8298: @menu
1.26 crook 8299: * Basic Mini-OOF Usage::
8300: * Mini-OOF Example::
8301: * Mini-OOF Implementation::
1.1 anton 8302: @end menu
8303:
1.26 crook 8304: @c -------------------------------------------------------------
8305: @node Basic Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
8306: @subsubsection Basic @file{mini-oof.fs} Usage
8307: @cindex mini-oof usage
1.1 anton 8308:
1.28 crook 8309: There is a base class (@code{class}, which allocates one cell for the
8310: object pointer) plus seven other words: to define a method, a variable,
8311: a class; to end a class, to resolve binding, to allocate an object and
8312: to compile a class method.
1.26 crook 8313: @comment TODO better description of the last one
1.1 anton 8314:
1.26 crook 8315: doc-object
8316: doc-method
8317: doc-var
8318: doc-class
8319: doc-end-class
8320: doc-defines
8321: doc-new
8322: doc-::
1.1 anton 8323:
1.21 crook 8324:
1.26 crook 8325: @c -------------------------------------------------------------
8326: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
8327: @subsubsection Mini-OOF Example
8328: @cindex mini-oof example
1.21 crook 8329:
1.26 crook 8330: A short example shows how to use this package. This example, in slightly
8331: extended form, is supplied as @file{moof-exm.fs}
1.29 crook 8332: @comment TODO could flesh this out with some comments from the Forthwrite article
1.21 crook 8333:
1.26 crook 8334: @example
8335: object class
8336: method init
8337: method draw
8338: end-class graphical
8339: @end example
1.21 crook 8340:
1.26 crook 8341: This code defines a class @code{graphical} with an
8342: operation @code{draw}. We can perform the operation
8343: @code{draw} on any @code{graphical} object, e.g.:
1.1 anton 8344:
1.26 crook 8345: @example
8346: 100 100 t-rex draw
8347: @end example
1.1 anton 8348:
1.26 crook 8349: where @code{t-rex} is an object or object pointer, created with e.g.
8350: @code{graphical new Constant t-rex}.
1.1 anton 8351:
1.26 crook 8352: For concrete graphical objects, we define child classes of the
8353: class @code{graphical}, e.g.:
1.21 crook 8354:
8355: @example
1.26 crook 8356: graphical class
8357: cell var circle-radius
8358: end-class circle \ "graphical" is the parent class
1.21 crook 8359:
1.26 crook 8360: :noname ( x y -- )
8361: circle-radius @@ draw-circle ; circle defines draw
8362: :noname ( r -- )
8363: circle-radius ! ; circle defines init
1.21 crook 8364: @end example
8365:
1.26 crook 8366: There is no implicit init method, so we have to define one. The creation
8367: code of the object now has to call init explicitely.
1.21 crook 8368:
1.26 crook 8369: @example
8370: circle new Constant my-circle
8371: 50 my-circle init
8372: @end example
1.21 crook 8373:
1.26 crook 8374: It is also possible to add a function to create named objects with
8375: automatic call of @code{init}, given that all objects have @code{init}
8376: on the same place:
1.1 anton 8377:
8378: @example
1.26 crook 8379: : new: ( .. o "name" -- )
8380: new dup Constant init ;
8381: 80 circle new: large-circle
1.1 anton 8382: @end example
8383:
1.26 crook 8384: We can draw this new circle at (100,100) with:
1.1 anton 8385:
8386: @example
1.26 crook 8387: 100 100 my-circle draw
1.1 anton 8388: @end example
8389:
1.26 crook 8390: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
8391: @subsubsection @file{mini-oof.fs} Implementation
1.1 anton 8392:
1.26 crook 8393: Object-oriented systems with late binding typically use a
8394: ``vtable''-approach: the first variable in each object is a pointer to a
8395: table, which contains the methods as function pointers. The vtable
8396: may also contain other information.
1.1 anton 8397:
1.26 crook 8398: So first, let's declare methods:
1.1 anton 8399:
1.26 crook 8400: @example
8401: : method ( m v -- m' v ) Create over , swap cell+ swap
8402: DOES> ( ... o -- ... ) @ over @ + @ execute ;
8403: @end example
1.1 anton 8404:
1.26 crook 8405: During method declaration, the number of methods and instance
8406: variables is on the stack (in address units). @code{method} creates
8407: one method and increments the method number. To execute a method, it
8408: takes the object, fetches the vtable pointer, adds the offset, and
1.29 crook 8409: executes the @i{xt} stored there. Each method takes the object it is
1.26 crook 8410: invoked from as top of stack parameter. The method itself should
8411: consume that object.
1.1 anton 8412:
1.26 crook 8413: Now, we also have to declare instance variables
1.21 crook 8414:
1.26 crook 8415: @example
8416: : var ( m v size -- m v' ) Create over , +
8417: DOES> ( o -- addr ) @ + ;
8418: @end example
1.21 crook 8419:
1.26 crook 8420: As before, a word is created with the current offset. Instance
8421: variables can have different sizes (cells, floats, doubles, chars), so
8422: all we do is take the size and add it to the offset. If your machine
8423: has alignment restrictions, put the proper @code{aligned} or
8424: @code{faligned} before the variable, to adjust the variable
8425: offset. That's why it is on the top of stack.
1.2 jwilke 8426:
1.26 crook 8427: We need a starting point (the base object) and some syntactic sugar:
1.21 crook 8428:
1.26 crook 8429: @example
8430: Create object 1 cells , 2 cells ,
8431: : class ( class -- class methods vars ) dup 2@ ;
8432: @end example
1.21 crook 8433:
1.26 crook 8434: For inheritance, the vtable of the parent object has to be
8435: copied when a new, derived class is declared. This gives all the
8436: methods of the parent class, which can be overridden, though.
1.21 crook 8437:
1.2 jwilke 8438: @example
1.26 crook 8439: : end-class ( class methods vars -- )
8440: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
8441: cell+ dup cell+ r> rot @ 2 cells /string move ;
8442: @end example
8443:
8444: The first line creates the vtable, initialized with
8445: @code{noop}s. The second line is the inheritance mechanism, it
8446: copies the xts from the parent vtable.
1.2 jwilke 8447:
1.26 crook 8448: We still have no way to define new methods, let's do that now:
1.2 jwilke 8449:
1.26 crook 8450: @example
8451: : defines ( xt class -- ) ' >body @ + ! ;
1.2 jwilke 8452: @end example
8453:
1.26 crook 8454: To allocate a new object, we need a word, too:
1.2 jwilke 8455:
1.26 crook 8456: @example
8457: : new ( class -- o ) here over @ allot swap over ! ;
8458: @end example
1.2 jwilke 8459:
1.26 crook 8460: Sometimes derived classes want to access the method of the
8461: parent object. There are two ways to achieve this with Mini-OOF:
8462: first, you could use named words, and second, you could look up the
8463: vtable of the parent object.
1.2 jwilke 8464:
1.26 crook 8465: @example
8466: : :: ( class "name" -- ) ' >body @ + @ compile, ;
8467: @end example
1.2 jwilke 8468:
8469:
1.26 crook 8470: Nothing can be more confusing than a good example, so here is
8471: one. First let's declare a text object (called
8472: @code{button}), that stores text and position:
1.2 jwilke 8473:
1.26 crook 8474: @example
8475: object class
8476: cell var text
8477: cell var len
8478: cell var x
8479: cell var y
8480: method init
8481: method draw
8482: end-class button
8483: @end example
1.2 jwilke 8484:
1.26 crook 8485: @noindent
8486: Now, implement the two methods, @code{draw} and @code{init}:
1.2 jwilke 8487:
1.26 crook 8488: @example
8489: :noname ( o -- )
8490: >r r@ x @ r@ y @ at-xy r@ text @ r> len @ type ;
8491: button defines draw
8492: :noname ( addr u o -- )
8493: >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
8494: button defines init
8495: @end example
1.2 jwilke 8496:
1.26 crook 8497: @noindent
8498: To demonstrate inheritance, we define a class @code{bold-button}, with no
8499: new data and no new methods:
1.2 jwilke 8500:
1.26 crook 8501: @example
8502: button class
8503: end-class bold-button
1.1 anton 8504:
1.26 crook 8505: : bold 27 emit ." [1m" ;
8506: : normal 27 emit ." [0m" ;
8507: @end example
1.1 anton 8508:
1.26 crook 8509: @noindent
8510: The class @code{bold-button} has a different draw method to
8511: @code{button}, but the new method is defined in terms of the draw method
8512: for @code{button}:
1.1 anton 8513:
1.26 crook 8514: @example
8515: :noname bold [ button :: draw ] normal ; bold-button defines draw
8516: @end example
1.1 anton 8517:
1.26 crook 8518: @noindent
8519: Finally, create two objects and apply methods:
1.1 anton 8520:
1.26 crook 8521: @example
8522: button new Constant foo
8523: s" thin foo" foo init
8524: page
8525: foo draw
8526: bold-button new Constant bar
8527: s" fat bar" bar init
8528: 1 bar y !
8529: bar draw
8530: @end example
1.1 anton 8531:
8532:
1.26 crook 8533: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
8534: @subsubsection Comparison with other object models
8535: @cindex comparison of object models
8536: @cindex object models, comparison
1.1 anton 8537:
1.26 crook 8538: Many object-oriented Forth extensions have been proposed (@cite{A survey
8539: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
8540: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
8541: relation of the object models described here to two well-known and two
8542: closely-related (by the use of method maps) models.
1.1 anton 8543:
1.26 crook 8544: @cindex Neon model
8545: The most popular model currently seems to be the Neon model (see
8546: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
8547: 1997) by Andrew McKewan) but this model has a number of limitations
8548: @footnote{A longer version of this critique can be
8549: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
8550: Dimensions, May 1997) by Anton Ertl.}:
1.1 anton 8551:
1.26 crook 8552: @itemize @bullet
8553: @item
8554: It uses a @code{@emph{selector
8555: object}} syntax, which makes it unnatural to pass objects on the
8556: stack.
1.1 anton 8557:
1.26 crook 8558: @item
8559: It requires that the selector parses the input stream (at
8560: compile time); this leads to reduced extensibility and to bugs that are+
8561: hard to find.
1.1 anton 8562:
1.26 crook 8563: @item
8564: It allows using every selector to every object;
8565: this eliminates the need for classes, but makes it harder to create
8566: efficient implementations.
8567: @end itemize
1.1 anton 8568:
1.26 crook 8569: @cindex Pountain's object-oriented model
8570: Another well-known publication is @cite{Object-Oriented Forth} (Academic
8571: Press, London, 1987) by Dick Pountain. However, it is not really about
8572: object-oriented programming, because it hardly deals with late
8573: binding. Instead, it focuses on features like information hiding and
8574: overloading that are characteristic of modular languages like Ada (83).
1.1 anton 8575:
1.26 crook 8576: @cindex Zsoter's object-oriented model
8577: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1) 1996, pages 31-35)
8578: Andras Zsoter describes a model that makes heavy use of an active object
8579: (like @code{this} in @file{objects.fs}): The active object is not only
8580: used for accessing all fields, but also specifies the receiving object
8581: of every selector invocation; you have to change the active object
8582: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
8583: changes more or less implicitly at @code{m: ... ;m}. Such a change at
8584: the method entry point is unnecessary with the Zsoter's model, because
8585: the receiving object is the active object already. On the other hand, the explicit
8586: change is absolutely necessary in that model, because otherwise no one
8587: could ever change the active object. An ANS Forth implementation of this
8588: model is available at @url{http://www.forth.org/fig/oopf.html}.
1.1 anton 8589:
1.26 crook 8590: @cindex @file{oof.fs}, differences to other models
8591: The @file{oof.fs} model combines information hiding and overloading
8592: resolution (by keeping names in various word lists) with object-oriented
8593: programming. It sets the active object implicitly on method entry, but
8594: also allows explicit changing (with @code{>o...o>} or with
8595: @code{with...endwith}). It uses parsing and state-smart objects and
8596: classes for resolving overloading and for early binding: the object or
8597: class parses the selector and determines the method from this. If the
8598: selector is not parsed by an object or class, it performs a call to the
8599: selector for the active object (late binding), like Zsoter's model.
8600: Fields are always accessed through the active object. The big
8601: disadvantage of this model is the parsing and the state-smartness, which
8602: reduces extensibility and increases the opportunities for subtle bugs;
8603: essentially, you are only safe if you never tick or @code{postpone} an
8604: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1 anton 8605:
1.26 crook 8606: @cindex @file{mini-oof.fs}, differences to other models
8607: The @file{mini-oof.fs} model is quite similar to a very stripped-down version of
8608: the @file{objects.fs} model, but syntactically it is a mixture of the @file{objects.fs} and
8609: @file{oof.fs} models.
1.1 anton 8610:
1.26 crook 8611: @c -------------------------------------------------------------
8612: @node Passing Commands to the OS, Miscellaneous Words, Object-oriented Forth, Words
1.21 crook 8613: @section Passing Commands to the Operating System
8614: @cindex operating system - passing commands
8615: @cindex shell commands
8616:
8617: Gforth allows you to pass an arbitrary string to the host operating
8618: system shell (if such a thing exists) for execution.
8619:
8620: doc-sh
8621: doc-system
8622: doc-$?
1.23 crook 8623: doc-getenv
1.21 crook 8624:
1.26 crook 8625: @c -------------------------------------------------------------
1.21 crook 8626: @node Miscellaneous Words, , Passing Commands to the OS, Words
8627: @section Miscellaneous Words
8628: @cindex miscellaneous words
8629:
1.29 crook 8630: @comment TODO find homes for these
8631:
1.26 crook 8632: These section lists the ANS Forth words that are not documented
1.21 crook 8633: elsewhere in this manual. Ultimately, they all need proper homes.
8634:
8635: doc-ms
8636: doc-time&date
1.27 crook 8637:
1.21 crook 8638: doc-[compile]
8639:
1.26 crook 8640: The following ANS Forth words are not currently supported by Gforth
1.27 crook 8641: (@pxref{ANS conformance}):
1.21 crook 8642:
8643: @code{EDITOR}
8644: @code{EKEY}
8645: @code{EKEY>CHAR}
8646: @code{EKEY?}
8647: @code{EMIT?}
8648: @code{FORGET}
8649:
1.24 anton 8650: @c ******************************************************************
8651: @node Error messages, Tools, Words, Top
8652: @chapter Error messages
8653: @cindex error messages
8654: @cindex backtrace
8655:
8656: A typical Gforth error message looks like this:
8657:
8658: @example
8659: in file included from :-1
8660: in file included from ./yyy.fs:1
8661: ./xxx.fs:4: Invalid memory address
8662: bar
8663: ^^^
1.25 anton 8664: $400E664C @@
8665: $400E6664 foo
1.24 anton 8666: @end example
8667:
8668: The message identifying the error is @code{Invalid memory address}. The
8669: error happened when text-interpreting line 4 of the file
8670: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
8671: word on the line where the error happened, is pointed out (with
8672: @code{^^^}).
8673:
8674: The file containing the error was included in line 1 of @file{./yyy.fs},
8675: and @file{yyy.fs} was included from a non-file (in this case, by giving
8676: @file{yyy.fs} as command-line parameter to Gforth).
8677:
8678: At the end of the error message you find a return stack dump that can be
8679: interpreted as a backtrace (possibly empty). On top you find the top of
8680: the return stack when the @code{throw} happened, and at the bottom you
8681: find the return stack entry just above the return stack of the topmost
8682: text interpreter.
8683:
8684: To the right of most return stack entries you see a guess for the word
8685: that pushed that return stack entry as its return address. This gives a
8686: backtrace. In our case we see that @code{bar} called @code{foo}, and
8687: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
8688: address} exception).
8689:
8690: Note that the backtrace is not perfect: We don't know which return stack
8691: entries are return addresses (so we may get false positives); and in
8692: some cases (e.g., for @code{abort"}) we cannot determine from the return
8693: address the word that pushed the return address, so for some return
8694: addresses you see no names in the return stack dump.
1.25 anton 8695:
8696: @cindex @code{catch} and backtraces
8697: The return stack dump represents the return stack at the time when a
8698: specific @code{throw} was executed. In programs that make use of
8699: @code{catch}, it is not necessarily clear which @code{throw} should be
8700: used for the return stack dump (e.g., consider one @code{throw} that
8701: indicates an error, which is caught, and during recovery another error
8702: happens; which @code{throw} should be used for the stack dump). Gforth
8703: presents the return stack dump for the first @code{throw} after the last
8704: executed (not returned-to) @code{catch}; this works well in the usual
8705: case.
8706:
8707: @cindex @code{gforth-fast} and backtraces
8708: @cindex @code{gforth-fast}, difference from @code{gforth}
8709: @cindex backtraces with @code{gforth-fast}
8710: @cindex return stack dump with @code{gforth-fast}
8711: @code{gforth} is able to do a return stack dump for throws generated
8712: from primitives (e.g., invalid memory address, stack empty etc.);
8713: @code{gforth-fast} is only able to do a return stack dump from a
8714: directly called @code{throw} (including @code{abort} etc.). This is the
1.30 anton 8715: only difference (apart from a speed factor of between 1.15 (K6-2) and
8716: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}. Given an
8717: exception caused by a primitive in @code{gforth-fast}, you will
8718: typically see no return stack dump at all; however, if the exception is
8719: caught by @code{catch} (e.g., for restoring some state), and then
8720: @code{throw}n again, the return stack dump will be for the first such
8721: @code{throw}.
1.2 jwilke 8722:
1.5 anton 8723: @c ******************************************************************
1.24 anton 8724: @node Tools, ANS conformance, Error messages, Top
1.1 anton 8725: @chapter Tools
8726:
8727: @menu
8728: * ANS Report:: Report the words used, sorted by wordset.
8729: @end menu
8730:
8731: See also @ref{Emacs and Gforth}.
8732:
8733: @node ANS Report, , Tools, Tools
8734: @section @file{ans-report.fs}: Report the words used, sorted by wordset
8735: @cindex @file{ans-report.fs}
8736: @cindex report the words used in your program
8737: @cindex words used in your program
8738:
8739: If you want to label a Forth program as ANS Forth Program, you must
8740: document which wordsets the program uses; for extension wordsets, it is
8741: helpful to list the words the program requires from these wordsets
8742: (because Forth systems are allowed to provide only some words of them).
8743:
8744: The @file{ans-report.fs} tool makes it easy for you to determine which
8745: words from which wordset and which non-ANS words your application
8746: uses. You simply have to include @file{ans-report.fs} before loading the
8747: program you want to check. After loading your program, you can get the
8748: report with @code{print-ans-report}. A typical use is to run this as
8749: batch job like this:
8750: @example
8751: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
8752: @end example
8753:
8754: The output looks like this (for @file{compat/control.fs}):
8755: @example
8756: The program uses the following words
8757: from CORE :
8758: : POSTPONE THEN ; immediate ?dup IF 0=
8759: from BLOCK-EXT :
8760: \
8761: from FILE :
8762: (
8763: @end example
8764:
8765: @subsection Caveats
8766:
8767: Note that @file{ans-report.fs} just checks which words are used, not whether
8768: they are used in an ANS Forth conforming way!
8769:
8770: Some words are defined in several wordsets in the
8771: standard. @file{ans-report.fs} reports them for only one of the
8772: wordsets, and not necessarily the one you expect. It depends on usage
8773: which wordset is the right one to specify. E.g., if you only use the
8774: compilation semantics of @code{S"}, it is a Core word; if you also use
8775: its interpretation semantics, it is a File word.
8776:
8777: @c ******************************************************************
8778: @node ANS conformance, Model, Tools, Top
8779: @chapter ANS conformance
8780: @cindex ANS conformance of Gforth
8781:
8782: To the best of our knowledge, Gforth is an
8783:
8784: ANS Forth System
8785: @itemize @bullet
8786: @item providing the Core Extensions word set
8787: @item providing the Block word set
8788: @item providing the Block Extensions word set
8789: @item providing the Double-Number word set
8790: @item providing the Double-Number Extensions word set
8791: @item providing the Exception word set
8792: @item providing the Exception Extensions word set
8793: @item providing the Facility word set
8794: @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
8795: @item providing the File Access word set
8796: @item providing the File Access Extensions word set
8797: @item providing the Floating-Point word set
8798: @item providing the Floating-Point Extensions word set
8799: @item providing the Locals word set
8800: @item providing the Locals Extensions word set
8801: @item providing the Memory-Allocation word set
8802: @item providing the Memory-Allocation Extensions word set (that one's easy)
8803: @item providing the Programming-Tools word set
8804: @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
8805: @item providing the Search-Order word set
8806: @item providing the Search-Order Extensions word set
8807: @item providing the String word set
8808: @item providing the String Extensions word set (another easy one)
8809: @end itemize
8810:
8811: @cindex system documentation
8812: In addition, ANS Forth systems are required to document certain
8813: implementation choices. This chapter tries to meet these
8814: requirements. In many cases it gives a way to ask the system for the
8815: information instead of providing the information directly, in
8816: particular, if the information depends on the processor, the operating
8817: system or the installation options chosen, or if they are likely to
8818: change during the maintenance of Gforth.
8819:
8820: @comment The framework for the rest has been taken from pfe.
8821:
8822: @menu
8823: * The Core Words::
8824: * The optional Block word set::
8825: * The optional Double Number word set::
8826: * The optional Exception word set::
8827: * The optional Facility word set::
8828: * The optional File-Access word set::
8829: * The optional Floating-Point word set::
8830: * The optional Locals word set::
8831: * The optional Memory-Allocation word set::
8832: * The optional Programming-Tools word set::
8833: * The optional Search-Order word set::
8834: @end menu
8835:
8836:
8837: @c =====================================================================
8838: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
8839: @comment node-name, next, previous, up
8840: @section The Core Words
8841: @c =====================================================================
8842: @cindex core words, system documentation
8843: @cindex system documentation, core words
8844:
8845: @menu
8846: * core-idef:: Implementation Defined Options
8847: * core-ambcond:: Ambiguous Conditions
8848: * core-other:: Other System Documentation
8849: @end menu
8850:
8851: @c ---------------------------------------------------------------------
8852: @node core-idef, core-ambcond, The Core Words, The Core Words
8853: @subsection Implementation Defined Options
8854: @c ---------------------------------------------------------------------
8855: @cindex core words, implementation-defined options
8856: @cindex implementation-defined options, core words
8857:
8858:
8859: @table @i
8860: @item (Cell) aligned addresses:
8861: @cindex cell-aligned addresses
8862: @cindex aligned addresses
8863: processor-dependent. Gforth's alignment words perform natural alignment
8864: (e.g., an address aligned for a datum of size 8 is divisible by
8865: 8). Unaligned accesses usually result in a @code{-23 THROW}.
8866:
8867: @item @code{EMIT} and non-graphic characters:
8868: @cindex @code{EMIT} and non-graphic characters
8869: @cindex non-graphic characters and @code{EMIT}
8870: The character is output using the C library function (actually, macro)
8871: @code{putc}.
8872:
8873: @item character editing of @code{ACCEPT} and @code{EXPECT}:
8874: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
8875: @cindex editing in @code{ACCEPT} and @code{EXPECT}
8876: @cindex @code{ACCEPT}, editing
8877: @cindex @code{EXPECT}, editing
8878: This is modeled on the GNU readline library (@pxref{Readline
8879: Interaction, , Command Line Editing, readline, The GNU Readline
8880: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
8881: producing a full word completion every time you type it (instead of
1.28 crook 8882: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 8883:
8884: @item character set:
8885: @cindex character set
8886: The character set of your computer and display device. Gforth is
8887: 8-bit-clean (but some other component in your system may make trouble).
8888:
8889: @item Character-aligned address requirements:
8890: @cindex character-aligned address requirements
8891: installation-dependent. Currently a character is represented by a C
8892: @code{unsigned char}; in the future we might switch to @code{wchar_t}
8893: (Comments on that requested).
8894:
8895: @item character-set extensions and matching of names:
8896: @cindex character-set extensions and matching of names
1.26 crook 8897: @cindex case-sensitivity for name lookup
8898: @cindex name lookup, case-sensitivity
8899: @cindex locale and case-sensitivity
1.21 crook 8900: Any character except the ASCII NUL character can be used in a
1.1 anton 8901: name. Matching is case-insensitive (except in @code{TABLE}s). The
8902: matching is performed using the C function @code{strncasecmp}, whose
8903: function is probably influenced by the locale. E.g., the @code{C} locale
8904: does not know about accents and umlauts, so they are matched
8905: case-sensitively in that locale. For portability reasons it is best to
8906: write programs such that they work in the @code{C} locale. Then one can
8907: use libraries written by a Polish programmer (who might use words
8908: containing ISO Latin-2 encoded characters) and by a French programmer
8909: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
8910: funny results for some of the words (which ones, depends on the font you
8911: are using)). Also, the locale you prefer may not be available in other
8912: operating systems. Hopefully, Unicode will solve these problems one day.
8913:
8914: @item conditions under which control characters match a space delimiter:
8915: @cindex space delimiters
8916: @cindex control characters as delimiters
8917: If @code{WORD} is called with the space character as a delimiter, all
8918: white-space characters (as identified by the C macro @code{isspace()})
8919: are delimiters. @code{PARSE}, on the other hand, treats space like other
8920: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
8921: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
8922: interpreter (aka text interpreter) by default, treats all white-space
8923: characters as delimiters.
8924:
1.26 crook 8925: @item format of the control-flow stack:
8926: @cindex control-flow stack, format
8927: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 8928: stack item in cells is given by the constant @code{cs-item-size}. At the
8929: time of this writing, an item consists of a (pointer to a) locals list
8930: (third), an address in the code (second), and a tag for identifying the
8931: item (TOS). The following tags are used: @code{defstart},
8932: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
8933: @code{scopestart}.
8934:
8935: @item conversion of digits > 35
8936: @cindex digits > 35
8937: The characters @code{[\]^_'} are the digits with the decimal value
8938: 36@minus{}41. There is no way to input many of the larger digits.
8939:
8940: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
8941: @cindex @code{EXPECT}, display after end of input
8942: @cindex @code{ACCEPT}, display after end of input
8943: The cursor is moved to the end of the entered string. If the input is
8944: terminated using the @kbd{Return} key, a space is typed.
8945:
8946: @item exception abort sequence of @code{ABORT"}:
8947: @cindex exception abort sequence of @code{ABORT"}
8948: @cindex @code{ABORT"}, exception abort sequence
8949: The error string is stored into the variable @code{"error} and a
8950: @code{-2 throw} is performed.
8951:
8952: @item input line terminator:
8953: @cindex input line terminator
8954: @cindex line terminator on input
1.26 crook 8955: @cindex newline character on input
1.1 anton 8956: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
8957: lines. One of these characters is typically produced when you type the
8958: @kbd{Enter} or @kbd{Return} key.
8959:
8960: @item maximum size of a counted string:
8961: @cindex maximum size of a counted string
8962: @cindex counted string, maximum size
8963: @code{s" /counted-string" environment? drop .}. Currently 255 characters
8964: on all ports, but this may change.
8965:
8966: @item maximum size of a parsed string:
8967: @cindex maximum size of a parsed string
8968: @cindex parsed string, maximum size
8969: Given by the constant @code{/line}. Currently 255 characters.
8970:
8971: @item maximum size of a definition name, in characters:
8972: @cindex maximum size of a definition name, in characters
8973: @cindex name, maximum length
8974: 31
8975:
8976: @item maximum string length for @code{ENVIRONMENT?}, in characters:
8977: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
8978: @cindex @code{ENVIRONMENT?} string length, maximum
8979: 31
8980:
8981: @item method of selecting the user input device:
8982: @cindex user input device, method of selecting
8983: The user input device is the standard input. There is currently no way to
8984: change it from within Gforth. However, the input can typically be
8985: redirected in the command line that starts Gforth.
8986:
8987: @item method of selecting the user output device:
8988: @cindex user output device, method of selecting
8989: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 8990: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
8991: output when the user output device is a terminal, otherwise the output
8992: is buffered.
1.1 anton 8993:
8994: @item methods of dictionary compilation:
8995: What are we expected to document here?
8996:
8997: @item number of bits in one address unit:
8998: @cindex number of bits in one address unit
8999: @cindex address unit, size in bits
9000: @code{s" address-units-bits" environment? drop .}. 8 in all current
9001: ports.
9002:
9003: @item number representation and arithmetic:
9004: @cindex number representation and arithmetic
9005: Processor-dependent. Binary two's complement on all current ports.
9006:
9007: @item ranges for integer types:
9008: @cindex ranges for integer types
9009: @cindex integer types, ranges
9010: Installation-dependent. Make environmental queries for @code{MAX-N},
9011: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
9012: unsigned (and positive) types is 0. The lower bound for signed types on
9013: two's complement and one's complement machines machines can be computed
9014: by adding 1 to the upper bound.
9015:
9016: @item read-only data space regions:
9017: @cindex read-only data space regions
9018: @cindex data-space, read-only regions
9019: The whole Forth data space is writable.
9020:
9021: @item size of buffer at @code{WORD}:
9022: @cindex size of buffer at @code{WORD}
9023: @cindex @code{WORD} buffer size
9024: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
9025: shared with the pictured numeric output string. If overwriting
9026: @code{PAD} is acceptable, it is as large as the remaining dictionary
9027: space, although only as much can be sensibly used as fits in a counted
9028: string.
9029:
9030: @item size of one cell in address units:
9031: @cindex cell size
9032: @code{1 cells .}.
9033:
9034: @item size of one character in address units:
9035: @cindex char size
9036: @code{1 chars .}. 1 on all current ports.
9037:
9038: @item size of the keyboard terminal buffer:
9039: @cindex size of the keyboard terminal buffer
9040: @cindex terminal buffer, size
9041: Varies. You can determine the size at a specific time using @code{lp@@
9042: tib - .}. It is shared with the locals stack and TIBs of files that
9043: include the current file. You can change the amount of space for TIBs
9044: and locals stack at Gforth startup with the command line option
9045: @code{-l}.
9046:
9047: @item size of the pictured numeric output buffer:
9048: @cindex size of the pictured numeric output buffer
9049: @cindex pictured numeric output buffer, size
9050: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
9051: shared with @code{WORD}.
9052:
9053: @item size of the scratch area returned by @code{PAD}:
9054: @cindex size of the scratch area returned by @code{PAD}
9055: @cindex @code{PAD} size
9056: The remainder of dictionary space. @code{unused pad here - - .}.
9057:
9058: @item system case-sensitivity characteristics:
9059: @cindex case-sensitivity characteristics
1.26 crook 9060: Dictionary searches are case-insensitive (except in
1.1 anton 9061: @code{TABLE}s). However, as explained above under @i{character-set
9062: extensions}, the matching for non-ASCII characters is determined by the
9063: locale you are using. In the default @code{C} locale all non-ASCII
9064: characters are matched case-sensitively.
9065:
9066: @item system prompt:
9067: @cindex system prompt
9068: @cindex prompt
9069: @code{ ok} in interpret state, @code{ compiled} in compile state.
9070:
9071: @item division rounding:
9072: @cindex division rounding
9073: installation dependent. @code{s" floored" environment? drop .}. We leave
9074: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
9075: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
9076:
9077: @item values of @code{STATE} when true:
9078: @cindex @code{STATE} values
9079: -1.
9080:
9081: @item values returned after arithmetic overflow:
9082: On two's complement machines, arithmetic is performed modulo
9083: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
9084: arithmetic (with appropriate mapping for signed types). Division by zero
9085: typically results in a @code{-55 throw} (Floating-point unidentified
9086: fault), although a @code{-10 throw} (divide by zero) would be more
9087: appropriate.
9088:
9089: @item whether the current definition can be found after @t{DOES>}:
9090: @cindex @t{DOES>}, visibility of current definition
9091: No.
9092:
9093: @end table
9094:
9095: @c ---------------------------------------------------------------------
9096: @node core-ambcond, core-other, core-idef, The Core Words
9097: @subsection Ambiguous conditions
9098: @c ---------------------------------------------------------------------
9099: @cindex core words, ambiguous conditions
9100: @cindex ambiguous conditions, core words
9101:
9102: @table @i
9103:
9104: @item a name is neither a word nor a number:
9105: @cindex name not found
1.26 crook 9106: @cindex undefined word
1.1 anton 9107: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
9108: preserves the data and FP stack, so you don't lose more work than
9109: necessary.
9110:
9111: @item a definition name exceeds the maximum length allowed:
1.26 crook 9112: @cindex word name too long
1.1 anton 9113: @code{-19 throw} (Word name too long)
9114:
9115: @item addressing a region not inside the various data spaces of the forth system:
9116: @cindex Invalid memory address
1.32 ! anton 9117: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 9118: typically readable. Accessing other addresses gives results dependent on
9119: the operating system. On decent systems: @code{-9 throw} (Invalid memory
9120: address).
9121:
9122: @item argument type incompatible with parameter:
1.26 crook 9123: @cindex argument type mismatch
1.1 anton 9124: This is usually not caught. Some words perform checks, e.g., the control
9125: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
9126: mismatch).
9127:
9128: @item attempting to obtain the execution token of a word with undefined execution semantics:
9129: @cindex Interpreting a compile-only word, for @code{'} etc.
9130: @cindex execution token of words with undefined execution semantics
9131: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
9132: get an execution token for @code{compile-only-error} (which performs a
9133: @code{-14 throw} when executed).
9134:
9135: @item dividing by zero:
9136: @cindex dividing by zero
9137: @cindex floating point unidentified fault, integer division
1.24 anton 9138: On better platforms, this produces a @code{-10 throw} (Division by
9139: zero); on other systems, this typically results in a @code{-55 throw}
9140: (Floating-point unidentified fault).
1.1 anton 9141:
9142: @item insufficient data stack or return stack space:
9143: @cindex insufficient data stack or return stack space
9144: @cindex stack overflow
1.26 crook 9145: @cindex address alignment exception, stack overflow
1.1 anton 9146: @cindex Invalid memory address, stack overflow
9147: Depending on the operating system, the installation, and the invocation
9148: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 9149: it is not checked. If it is checked, you typically get a @code{-3 throw}
9150: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
9151: throw} (Invalid memory address) (depending on the platform and how you
9152: achieved the overflow) as soon as the overflow happens. If it is not
9153: checked, overflows typically result in mysterious illegal memory
9154: accesses, producing @code{-9 throw} (Invalid memory address) or
9155: @code{-23 throw} (Address alignment exception); they might also destroy
9156: the internal data structure of @code{ALLOCATE} and friends, resulting in
9157: various errors in these words.
1.1 anton 9158:
9159: @item insufficient space for loop control parameters:
9160: @cindex insufficient space for loop control parameters
9161: like other return stack overflows.
9162:
9163: @item insufficient space in the dictionary:
9164: @cindex insufficient space in the dictionary
9165: @cindex dictionary overflow
1.12 anton 9166: If you try to allot (either directly with @code{allot}, or indirectly
9167: with @code{,}, @code{create} etc.) more memory than available in the
9168: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
9169: to access memory beyond the end of the dictionary, the results are
9170: similar to stack overflows.
1.1 anton 9171:
9172: @item interpreting a word with undefined interpretation semantics:
9173: @cindex interpreting a word with undefined interpretation semantics
9174: @cindex Interpreting a compile-only word
9175: For some words, we have defined interpretation semantics. For the
9176: others: @code{-14 throw} (Interpreting a compile-only word).
9177:
9178: @item modifying the contents of the input buffer or a string literal:
9179: @cindex modifying the contents of the input buffer or a string literal
9180: These are located in writable memory and can be modified.
9181:
9182: @item overflow of the pictured numeric output string:
9183: @cindex overflow of the pictured numeric output string
9184: @cindex pictured numeric output string, overflow
1.24 anton 9185: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 9186:
9187: @item parsed string overflow:
9188: @cindex parsed string overflow
9189: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
9190:
9191: @item producing a result out of range:
9192: @cindex result out of range
9193: On two's complement machines, arithmetic is performed modulo
9194: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
9195: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 9196: typically results in a @code{-10 throw} (divide by zero) or @code{-55
9197: throw} (floating point unidentified fault). @code{convert} and
9198: @code{>number} currently overflow silently.
1.1 anton 9199:
9200: @item reading from an empty data or return stack:
9201: @cindex stack empty
9202: @cindex stack underflow
1.24 anton 9203: @cindex return stack underflow
1.1 anton 9204: The data stack is checked by the outer (aka text) interpreter after
9205: every word executed. If it has underflowed, a @code{-4 throw} (Stack
9206: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 9207: depending on operating system, installation, and invocation. If they are
9208: caught by a check, they typically result in @code{-4 throw} (Stack
9209: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
9210: (Invalid memory address), depending on the platform and which stack
9211: underflows and by how much. Note that even if the system uses checking
9212: (through the MMU), your program may have to underflow by a significant
9213: number of stack items to trigger the reaction (the reason for this is
9214: that the MMU, and therefore the checking, works with a page-size
9215: granularity). If there is no checking, the symptoms resulting from an
9216: underflow are similar to those from an overflow. Unbalanced return
9217: stack errors result in a variaty of symptoms, including @code{-9 throw}
9218: (Invalid memory address) and Illegal Instruction (typically @code{-260
9219: throw}).
1.1 anton 9220:
9221: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
9222: @cindex unexpected end of the input buffer
9223: @cindex zero-length string as a name
9224: @cindex Attempt to use zero-length string as a name
9225: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
9226: use zero-length string as a name). Words like @code{'} probably will not
9227: find what they search. Note that it is possible to create zero-length
9228: names with @code{nextname} (should it not?).
9229:
9230: @item @code{>IN} greater than input buffer:
9231: @cindex @code{>IN} greater than input buffer
9232: The next invocation of a parsing word returns a string with length 0.
9233:
9234: @item @code{RECURSE} appears after @code{DOES>}:
9235: @cindex @code{RECURSE} appears after @code{DOES>}
9236: Compiles a recursive call to the defining word, not to the defined word.
9237:
9238: @item argument input source different than current input source for @code{RESTORE-INPUT}:
9239: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 9240: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 9241: @cindex @code{RESTORE-INPUT}, Argument type mismatch
9242: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
9243: the end of the file was reached), its source-id may be
9244: reused. Therefore, restoring an input source specification referencing a
9245: closed file may lead to unpredictable results instead of a @code{-12
9246: THROW}.
9247:
9248: In the future, Gforth may be able to restore input source specifications
9249: from other than the current input source.
9250:
9251: @item data space containing definitions gets de-allocated:
9252: @cindex data space containing definitions gets de-allocated
9253: Deallocation with @code{allot} is not checked. This typically results in
9254: memory access faults or execution of illegal instructions.
9255:
9256: @item data space read/write with incorrect alignment:
9257: @cindex data space read/write with incorrect alignment
9258: @cindex alignment faults
1.26 crook 9259: @cindex address alignment exception
1.1 anton 9260: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 9261: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 9262: alignment turned on, incorrect alignment results in a @code{-9 throw}
9263: (Invalid memory address). There are reportedly some processors with
1.12 anton 9264: alignment restrictions that do not report violations.
1.1 anton 9265:
9266: @item data space pointer not properly aligned, @code{,}, @code{C,}:
9267: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
9268: Like other alignment errors.
9269:
9270: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
9271: Like other stack underflows.
9272:
9273: @item loop control parameters not available:
9274: @cindex loop control parameters not available
9275: Not checked. The counted loop words simply assume that the top of return
9276: stack items are loop control parameters and behave accordingly.
9277:
9278: @item most recent definition does not have a name (@code{IMMEDIATE}):
9279: @cindex most recent definition does not have a name (@code{IMMEDIATE})
9280: @cindex last word was headerless
9281: @code{abort" last word was headerless"}.
9282:
9283: @item name not defined by @code{VALUE} used by @code{TO}:
9284: @cindex name not defined by @code{VALUE} used by @code{TO}
9285: @cindex @code{TO} on non-@code{VALUE}s
9286: @cindex Invalid name argument, @code{TO}
9287: @code{-32 throw} (Invalid name argument) (unless name is a local or was
9288: defined by @code{CONSTANT}; in the latter case it just changes the constant).
9289:
9290: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
9291: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 9292: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 9293: @code{-13 throw} (Undefined word)
9294:
9295: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
9296: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
9297: Gforth behaves as if they were of the same type. I.e., you can predict
9298: the behaviour by interpreting all parameters as, e.g., signed.
9299:
9300: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
9301: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
9302: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
9303: compilation semantics of @code{TO}.
9304:
9305: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 9306: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 9307: @cindex @code{WORD}, string overflow
9308: Not checked. The string will be ok, but the count will, of course,
9309: contain only the least significant bits of the length.
9310:
9311: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
9312: @cindex @code{LSHIFT}, large shift counts
9313: @cindex @code{RSHIFT}, large shift counts
9314: Processor-dependent. Typical behaviours are returning 0 and using only
9315: the low bits of the shift count.
9316:
9317: @item word not defined via @code{CREATE}:
9318: @cindex @code{>BODY} of non-@code{CREATE}d words
9319: @code{>BODY} produces the PFA of the word no matter how it was defined.
9320:
9321: @cindex @code{DOES>} of non-@code{CREATE}d words
9322: @code{DOES>} changes the execution semantics of the last defined word no
9323: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
9324: @code{CREATE , DOES>}.
9325:
9326: @item words improperly used outside @code{<#} and @code{#>}:
9327: Not checked. As usual, you can expect memory faults.
9328:
9329: @end table
9330:
9331:
9332: @c ---------------------------------------------------------------------
9333: @node core-other, , core-ambcond, The Core Words
9334: @subsection Other system documentation
9335: @c ---------------------------------------------------------------------
9336: @cindex other system documentation, core words
9337: @cindex core words, other system documentation
9338:
9339: @table @i
9340: @item nonstandard words using @code{PAD}:
9341: @cindex @code{PAD} use by nonstandard words
9342: None.
9343:
9344: @item operator's terminal facilities available:
9345: @cindex operator's terminal facilities available
9346: After processing the command line, Gforth goes into interactive mode,
9347: and you can give commands to Gforth interactively. The actual facilities
9348: available depend on how you invoke Gforth.
9349:
9350: @item program data space available:
9351: @cindex program data space available
9352: @cindex data space available
9353: @code{UNUSED .} gives the remaining dictionary space. The total
9354: dictionary space can be specified with the @code{-m} switch
9355: (@pxref{Invoking Gforth}) when Gforth starts up.
9356:
9357: @item return stack space available:
9358: @cindex return stack space available
9359: You can compute the total return stack space in cells with
9360: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
9361: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
9362:
9363: @item stack space available:
9364: @cindex stack space available
9365: You can compute the total data stack space in cells with
9366: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
9367: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
9368:
9369: @item system dictionary space required, in address units:
9370: @cindex system dictionary space required, in address units
9371: Type @code{here forthstart - .} after startup. At the time of this
9372: writing, this gives 80080 (bytes) on a 32-bit system.
9373: @end table
9374:
9375:
9376: @c =====================================================================
9377: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
9378: @section The optional Block word set
9379: @c =====================================================================
9380: @cindex system documentation, block words
9381: @cindex block words, system documentation
9382:
9383: @menu
9384: * block-idef:: Implementation Defined Options
9385: * block-ambcond:: Ambiguous Conditions
9386: * block-other:: Other System Documentation
9387: @end menu
9388:
9389:
9390: @c ---------------------------------------------------------------------
9391: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
9392: @subsection Implementation Defined Options
9393: @c ---------------------------------------------------------------------
9394: @cindex implementation-defined options, block words
9395: @cindex block words, implementation-defined options
9396:
9397: @table @i
9398: @item the format for display by @code{LIST}:
9399: @cindex @code{LIST} display format
9400: First the screen number is displayed, then 16 lines of 64 characters,
9401: each line preceded by the line number.
9402:
9403: @item the length of a line affected by @code{\}:
9404: @cindex length of a line affected by @code{\}
9405: @cindex @code{\}, line length in blocks
9406: 64 characters.
9407: @end table
9408:
9409:
9410: @c ---------------------------------------------------------------------
9411: @node block-ambcond, block-other, block-idef, The optional Block word set
9412: @subsection Ambiguous conditions
9413: @c ---------------------------------------------------------------------
9414: @cindex block words, ambiguous conditions
9415: @cindex ambiguous conditions, block words
9416:
9417: @table @i
9418: @item correct block read was not possible:
9419: @cindex block read not possible
9420: Typically results in a @code{throw} of some OS-derived value (between
9421: -512 and -2048). If the blocks file was just not long enough, blanks are
9422: supplied for the missing portion.
9423:
9424: @item I/O exception in block transfer:
9425: @cindex I/O exception in block transfer
9426: @cindex block transfer, I/O exception
9427: Typically results in a @code{throw} of some OS-derived value (between
9428: -512 and -2048).
9429:
9430: @item invalid block number:
9431: @cindex invalid block number
9432: @cindex block number invalid
9433: @code{-35 throw} (Invalid block number)
9434:
9435: @item a program directly alters the contents of @code{BLK}:
9436: @cindex @code{BLK}, altering @code{BLK}
9437: The input stream is switched to that other block, at the same
9438: position. If the storing to @code{BLK} happens when interpreting
9439: non-block input, the system will get quite confused when the block ends.
9440:
9441: @item no current block buffer for @code{UPDATE}:
9442: @cindex @code{UPDATE}, no current block buffer
9443: @code{UPDATE} has no effect.
9444:
9445: @end table
9446:
9447: @c ---------------------------------------------------------------------
9448: @node block-other, , block-ambcond, The optional Block word set
9449: @subsection Other system documentation
9450: @c ---------------------------------------------------------------------
9451: @cindex other system documentation, block words
9452: @cindex block words, other system documentation
9453:
9454: @table @i
9455: @item any restrictions a multiprogramming system places on the use of buffer addresses:
9456: No restrictions (yet).
9457:
9458: @item the number of blocks available for source and data:
9459: depends on your disk space.
9460:
9461: @end table
9462:
9463:
9464: @c =====================================================================
9465: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
9466: @section The optional Double Number word set
9467: @c =====================================================================
9468: @cindex system documentation, double words
9469: @cindex double words, system documentation
9470:
9471: @menu
9472: * double-ambcond:: Ambiguous Conditions
9473: @end menu
9474:
9475:
9476: @c ---------------------------------------------------------------------
9477: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
9478: @subsection Ambiguous conditions
9479: @c ---------------------------------------------------------------------
9480: @cindex double words, ambiguous conditions
9481: @cindex ambiguous conditions, double words
9482:
9483: @table @i
1.29 crook 9484: @item @i{d} outside of range of @i{n} in @code{D>S}:
9485: @cindex @code{D>S}, @i{d} out of range of @i{n}
9486: The least significant cell of @i{d} is produced.
1.1 anton 9487:
9488: @end table
9489:
9490:
9491: @c =====================================================================
9492: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
9493: @section The optional Exception word set
9494: @c =====================================================================
9495: @cindex system documentation, exception words
9496: @cindex exception words, system documentation
9497:
9498: @menu
9499: * exception-idef:: Implementation Defined Options
9500: @end menu
9501:
9502:
9503: @c ---------------------------------------------------------------------
9504: @node exception-idef, , The optional Exception word set, The optional Exception word set
9505: @subsection Implementation Defined Options
9506: @c ---------------------------------------------------------------------
9507: @cindex implementation-defined options, exception words
9508: @cindex exception words, implementation-defined options
9509:
9510: @table @i
9511: @item @code{THROW}-codes used in the system:
9512: @cindex @code{THROW}-codes used in the system
9513: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 9514: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 9515: codes -512@minus{}-2047 are used for OS errors (for file and memory
9516: allocation operations). The mapping from OS error numbers to throw codes
9517: is -512@minus{}@code{errno}. One side effect of this mapping is that
9518: undefined OS errors produce a message with a strange number; e.g.,
9519: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
9520: @end table
9521:
9522: @c =====================================================================
9523: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
9524: @section The optional Facility word set
9525: @c =====================================================================
9526: @cindex system documentation, facility words
9527: @cindex facility words, system documentation
9528:
9529: @menu
9530: * facility-idef:: Implementation Defined Options
9531: * facility-ambcond:: Ambiguous Conditions
9532: @end menu
9533:
9534:
9535: @c ---------------------------------------------------------------------
9536: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
9537: @subsection Implementation Defined Options
9538: @c ---------------------------------------------------------------------
9539: @cindex implementation-defined options, facility words
9540: @cindex facility words, implementation-defined options
9541:
9542: @table @i
9543: @item encoding of keyboard events (@code{EKEY}):
9544: @cindex keyboard events, encoding in @code{EKEY}
9545: @cindex @code{EKEY}, encoding of keyboard events
9546: Not yet implemented.
9547:
9548: @item duration of a system clock tick:
9549: @cindex duration of a system clock tick
9550: @cindex clock tick duration
9551: System dependent. With respect to @code{MS}, the time is specified in
9552: microseconds. How well the OS and the hardware implement this, is
9553: another question.
9554:
9555: @item repeatability to be expected from the execution of @code{MS}:
9556: @cindex repeatability to be expected from the execution of @code{MS}
9557: @cindex @code{MS}, repeatability to be expected
9558: System dependent. On Unix, a lot depends on load. If the system is
9559: lightly loaded, and the delay is short enough that Gforth does not get
9560: swapped out, the performance should be acceptable. Under MS-DOS and
9561: other single-tasking systems, it should be good.
9562:
9563: @end table
9564:
9565:
9566: @c ---------------------------------------------------------------------
9567: @node facility-ambcond, , facility-idef, The optional Facility word set
9568: @subsection Ambiguous conditions
9569: @c ---------------------------------------------------------------------
9570: @cindex facility words, ambiguous conditions
9571: @cindex ambiguous conditions, facility words
9572:
9573: @table @i
9574: @item @code{AT-XY} can't be performed on user output device:
9575: @cindex @code{AT-XY} can't be performed on user output device
9576: Largely terminal dependent. No range checks are done on the arguments.
9577: No errors are reported. You may see some garbage appearing, you may see
9578: simply nothing happen.
9579:
9580: @end table
9581:
9582:
9583: @c =====================================================================
9584: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
9585: @section The optional File-Access word set
9586: @c =====================================================================
9587: @cindex system documentation, file words
9588: @cindex file words, system documentation
9589:
9590: @menu
9591: * file-idef:: Implementation Defined Options
9592: * file-ambcond:: Ambiguous Conditions
9593: @end menu
9594:
9595: @c ---------------------------------------------------------------------
9596: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
9597: @subsection Implementation Defined Options
9598: @c ---------------------------------------------------------------------
9599: @cindex implementation-defined options, file words
9600: @cindex file words, implementation-defined options
9601:
9602: @table @i
9603: @item file access methods used:
9604: @cindex file access methods used
9605: @code{R/O}, @code{R/W} and @code{BIN} work as you would
9606: expect. @code{W/O} translates into the C file opening mode @code{w} (or
9607: @code{wb}): The file is cleared, if it exists, and created, if it does
9608: not (with both @code{open-file} and @code{create-file}). Under Unix
9609: @code{create-file} creates a file with 666 permissions modified by your
9610: umask.
9611:
9612: @item file exceptions:
9613: @cindex file exceptions
9614: The file words do not raise exceptions (except, perhaps, memory access
9615: faults when you pass illegal addresses or file-ids).
9616:
9617: @item file line terminator:
9618: @cindex file line terminator
9619: System-dependent. Gforth uses C's newline character as line
9620: terminator. What the actual character code(s) of this are is
9621: system-dependent.
9622:
9623: @item file name format:
9624: @cindex file name format
9625: System dependent. Gforth just uses the file name format of your OS.
9626:
9627: @item information returned by @code{FILE-STATUS}:
9628: @cindex @code{FILE-STATUS}, returned information
9629: @code{FILE-STATUS} returns the most powerful file access mode allowed
9630: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
9631: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
9632: along with the returned mode.
9633:
9634: @item input file state after an exception when including source:
9635: @cindex exception when including source
9636: All files that are left via the exception are closed.
9637:
1.29 crook 9638: @item @i{ior} values and meaning:
9639: @cindex @i{ior} values and meaning
9640: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 9641: intended as throw codes. They typically are in the range
9642: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 9643: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 9644:
9645: @item maximum depth of file input nesting:
9646: @cindex maximum depth of file input nesting
9647: @cindex file input nesting, maximum depth
9648: limited by the amount of return stack, locals/TIB stack, and the number
9649: of open files available. This should not give you troubles.
9650:
9651: @item maximum size of input line:
9652: @cindex maximum size of input line
9653: @cindex input line size, maximum
9654: @code{/line}. Currently 255.
9655:
9656: @item methods of mapping block ranges to files:
9657: @cindex mapping block ranges to files
9658: @cindex files containing blocks
9659: @cindex blocks in files
9660: By default, blocks are accessed in the file @file{blocks.fb} in the
9661: current working directory. The file can be switched with @code{USE}.
9662:
9663: @item number of string buffers provided by @code{S"}:
9664: @cindex @code{S"}, number of string buffers
9665: 1
9666:
9667: @item size of string buffer used by @code{S"}:
9668: @cindex @code{S"}, size of string buffer
9669: @code{/line}. currently 255.
9670:
9671: @end table
9672:
9673: @c ---------------------------------------------------------------------
9674: @node file-ambcond, , file-idef, The optional File-Access word set
9675: @subsection Ambiguous conditions
9676: @c ---------------------------------------------------------------------
9677: @cindex file words, ambiguous conditions
9678: @cindex ambiguous conditions, file words
9679:
9680: @table @i
9681: @item attempting to position a file outside its boundaries:
9682: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
9683: @code{REPOSITION-FILE} is performed as usual: Afterwards,
9684: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
9685:
9686: @item attempting to read from file positions not yet written:
9687: @cindex reading from file positions not yet written
9688: End-of-file, i.e., zero characters are read and no error is reported.
9689:
1.29 crook 9690: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
9691: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 9692: An appropriate exception may be thrown, but a memory fault or other
9693: problem is more probable.
9694:
1.29 crook 9695: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
9696: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
9697: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
9698: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 9699: thrown.
9700:
9701: @item named file cannot be opened (@code{INCLUDED}):
9702: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 9703: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 9704:
9705: @item requesting an unmapped block number:
9706: @cindex unmapped block numbers
9707: There are no unmapped legal block numbers. On some operating systems,
9708: writing a block with a large number may overflow the file system and
9709: have an error message as consequence.
9710:
9711: @item using @code{source-id} when @code{blk} is non-zero:
9712: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
9713: @code{source-id} performs its function. Typically it will give the id of
9714: the source which loaded the block. (Better ideas?)
9715:
9716: @end table
9717:
9718:
9719: @c =====================================================================
9720: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
9721: @section The optional Floating-Point word set
9722: @c =====================================================================
9723: @cindex system documentation, floating-point words
9724: @cindex floating-point words, system documentation
9725:
9726: @menu
9727: * floating-idef:: Implementation Defined Options
9728: * floating-ambcond:: Ambiguous Conditions
9729: @end menu
9730:
9731:
9732: @c ---------------------------------------------------------------------
9733: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
9734: @subsection Implementation Defined Options
9735: @c ---------------------------------------------------------------------
9736: @cindex implementation-defined options, floating-point words
9737: @cindex floating-point words, implementation-defined options
9738:
9739: @table @i
9740: @item format and range of floating point numbers:
9741: @cindex format and range of floating point numbers
9742: @cindex floating point numbers, format and range
9743: System-dependent; the @code{double} type of C.
9744:
1.29 crook 9745: @item results of @code{REPRESENT} when @i{float} is out of range:
9746: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 9747: System dependent; @code{REPRESENT} is implemented using the C library
9748: function @code{ecvt()} and inherits its behaviour in this respect.
9749:
9750: @item rounding or truncation of floating-point numbers:
9751: @cindex rounding of floating-point numbers
9752: @cindex truncation of floating-point numbers
9753: @cindex floating-point numbers, rounding or truncation
9754: System dependent; the rounding behaviour is inherited from the hosting C
9755: compiler. IEEE-FP-based (i.e., most) systems by default round to
9756: nearest, and break ties by rounding to even (i.e., such that the last
9757: bit of the mantissa is 0).
9758:
9759: @item size of floating-point stack:
9760: @cindex floating-point stack size
9761: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
9762: the floating-point stack (in floats). You can specify this on startup
9763: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
9764:
9765: @item width of floating-point stack:
9766: @cindex floating-point stack width
9767: @code{1 floats}.
9768:
9769: @end table
9770:
9771:
9772: @c ---------------------------------------------------------------------
9773: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
9774: @subsection Ambiguous conditions
9775: @c ---------------------------------------------------------------------
9776: @cindex floating-point words, ambiguous conditions
9777: @cindex ambiguous conditions, floating-point words
9778:
9779: @table @i
9780: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
9781: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
9782: System-dependent. Typically results in a @code{-23 THROW} like other
9783: alignment violations.
9784:
9785: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
9786: @cindex @code{f@@} used with an address that is not float aligned
9787: @cindex @code{f!} used with an address that is not float aligned
9788: System-dependent. Typically results in a @code{-23 THROW} like other
9789: alignment violations.
9790:
9791: @item floating-point result out of range:
9792: @cindex floating-point result out of range
9793: System-dependent. Can result in a @code{-55 THROW} (Floating-point
9794: unidentified fault), or can produce a special value representing, e.g.,
9795: Infinity.
9796:
9797: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
9798: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
9799: System-dependent. Typically results in an alignment fault like other
9800: alignment violations.
9801:
9802: @item @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
9803: @cindex @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
9804: The floating-point number is converted into decimal nonetheless.
9805:
9806: @item Both arguments are equal to zero (@code{FATAN2}):
9807: @cindex @code{FATAN2}, both arguments are equal to zero
9808: System-dependent. @code{FATAN2} is implemented using the C library
9809: function @code{atan2()}.
9810:
1.29 crook 9811: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
9812: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
9813: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 9814: because of small errors and the tan will be a very large (or very small)
9815: but finite number.
9816:
1.29 crook 9817: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
9818: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 9819: The result is rounded to the nearest float.
9820:
9821: @item dividing by zero:
9822: @cindex dividing by zero, floating-point
9823: @cindex floating-point dividing by zero
9824: @cindex floating-point unidentified fault, FP divide-by-zero
9825: @code{-55 throw} (Floating-point unidentified fault)
9826:
9827: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
9828: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
9829: System dependent. On IEEE-FP based systems the number is converted into
9830: an infinity.
9831:
1.29 crook 9832: @item @i{float}<1 (@code{FACOSH}):
9833: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 9834: @cindex floating-point unidentified fault, @code{FACOSH}
9835: @code{-55 throw} (Floating-point unidentified fault)
9836:
1.29 crook 9837: @item @i{float}=<-1 (@code{FLNP1}):
9838: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 9839: @cindex floating-point unidentified fault, @code{FLNP1}
9840: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29 crook 9841: negative infinity is typically produced for @i{float}=-1.
1.1 anton 9842:
1.29 crook 9843: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
9844: @cindex @code{FLN}, @i{float}=<0
9845: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 9846: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
9847: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29 crook 9848: negative infinity is typically produced for @i{float}=0.
1.1 anton 9849:
1.29 crook 9850: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
9851: @cindex @code{FASINH}, @i{float}<0
9852: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 9853: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
9854: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
9855: produces values for these inputs on my Linux box (Bug in the C library?)
9856:
1.29 crook 9857: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
9858: @cindex @code{FACOS}, |@i{float}|>1
9859: @cindex @code{FASIN}, |@i{float}|>1
9860: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 9861: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
9862: @code{-55 throw} (Floating-point unidentified fault).
9863:
1.29 crook 9864: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
9865: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 9866: @cindex floating-point unidentified fault, @code{F>D}
9867: @code{-55 throw} (Floating-point unidentified fault).
9868:
9869: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
9870: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
9871: This does not happen.
9872: @end table
9873:
9874: @c =====================================================================
9875: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
9876: @section The optional Locals word set
9877: @c =====================================================================
9878: @cindex system documentation, locals words
9879: @cindex locals words, system documentation
9880:
9881: @menu
9882: * locals-idef:: Implementation Defined Options
9883: * locals-ambcond:: Ambiguous Conditions
9884: @end menu
9885:
9886:
9887: @c ---------------------------------------------------------------------
9888: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
9889: @subsection Implementation Defined Options
9890: @c ---------------------------------------------------------------------
9891: @cindex implementation-defined options, locals words
9892: @cindex locals words, implementation-defined options
9893:
9894: @table @i
9895: @item maximum number of locals in a definition:
9896: @cindex maximum number of locals in a definition
9897: @cindex locals, maximum number in a definition
9898: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
9899: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
9900: characters. The number of locals in a definition is bounded by the size
9901: of locals-buffer, which contains the names of the locals.
9902:
9903: @end table
9904:
9905:
9906: @c ---------------------------------------------------------------------
9907: @node locals-ambcond, , locals-idef, The optional Locals word set
9908: @subsection Ambiguous conditions
9909: @c ---------------------------------------------------------------------
9910: @cindex locals words, ambiguous conditions
9911: @cindex ambiguous conditions, locals words
9912:
9913: @table @i
9914: @item executing a named local in interpretation state:
9915: @cindex local in interpretation state
9916: @cindex Interpreting a compile-only word, for a local
9917: Locals have no interpretation semantics. If you try to perform the
9918: interpretation semantics, you will get a @code{-14 throw} somewhere
9919: (Interpreting a compile-only word). If you perform the compilation
9920: semantics, the locals access will be compiled (irrespective of state).
9921:
1.29 crook 9922: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 9923: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
9924: @cindex @code{TO} on non-@code{VALUE}s and non-locals
9925: @cindex Invalid name argument, @code{TO}
9926: @code{-32 throw} (Invalid name argument)
9927:
9928: @end table
9929:
9930:
9931: @c =====================================================================
9932: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
9933: @section The optional Memory-Allocation word set
9934: @c =====================================================================
9935: @cindex system documentation, memory-allocation words
9936: @cindex memory-allocation words, system documentation
9937:
9938: @menu
9939: * memory-idef:: Implementation Defined Options
9940: @end menu
9941:
9942:
9943: @c ---------------------------------------------------------------------
9944: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
9945: @subsection Implementation Defined Options
9946: @c ---------------------------------------------------------------------
9947: @cindex implementation-defined options, memory-allocation words
9948: @cindex memory-allocation words, implementation-defined options
9949:
9950: @table @i
1.29 crook 9951: @item values and meaning of @i{ior}:
9952: @cindex @i{ior} values and meaning
9953: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 9954: intended as throw codes. They typically are in the range
9955: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 9956: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 9957:
9958: @end table
9959:
9960: @c =====================================================================
9961: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
9962: @section The optional Programming-Tools word set
9963: @c =====================================================================
9964: @cindex system documentation, programming-tools words
9965: @cindex programming-tools words, system documentation
9966:
9967: @menu
9968: * programming-idef:: Implementation Defined Options
9969: * programming-ambcond:: Ambiguous Conditions
9970: @end menu
9971:
9972:
9973: @c ---------------------------------------------------------------------
9974: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
9975: @subsection Implementation Defined Options
9976: @c ---------------------------------------------------------------------
9977: @cindex implementation-defined options, programming-tools words
9978: @cindex programming-tools words, implementation-defined options
9979:
9980: @table @i
9981: @item ending sequence for input following @code{;CODE} and @code{CODE}:
9982: @cindex @code{;CODE} ending sequence
9983: @cindex @code{CODE} ending sequence
9984: @code{END-CODE}
9985:
9986: @item manner of processing input following @code{;CODE} and @code{CODE}:
9987: @cindex @code{;CODE}, processing input
9988: @cindex @code{CODE}, processing input
9989: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
9990: the input is processed by the text interpreter, (starting) in interpret
9991: state.
9992:
9993: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
9994: @cindex @code{ASSEMBLER}, search order capability
9995: The ANS Forth search order word set.
9996:
9997: @item source and format of display by @code{SEE}:
9998: @cindex @code{SEE}, source and format of output
9999: The source for @code{see} is the intermediate code used by the inner
10000: interpreter. The current @code{see} tries to output Forth source code
10001: as well as possible.
10002:
10003: @end table
10004:
10005: @c ---------------------------------------------------------------------
10006: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
10007: @subsection Ambiguous conditions
10008: @c ---------------------------------------------------------------------
10009: @cindex programming-tools words, ambiguous conditions
10010: @cindex ambiguous conditions, programming-tools words
10011:
10012: @table @i
10013:
1.21 crook 10014: @item deleting the compilation word list (@code{FORGET}):
10015: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 10016: Not implemented (yet).
10017:
1.29 crook 10018: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
10019: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
10020: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 10021: @cindex control-flow stack underflow
10022: This typically results in an @code{abort"} with a descriptive error
10023: message (may change into a @code{-22 throw} (Control structure mismatch)
10024: in the future). You may also get a memory access error. If you are
10025: unlucky, this ambiguous condition is not caught.
10026:
1.29 crook 10027: @item @i{name} can't be found (@code{FORGET}):
10028: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 10029: Not implemented (yet).
10030:
1.29 crook 10031: @item @i{name} not defined via @code{CREATE}:
10032: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 10033: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
10034: the execution semantics of the last defined word no matter how it was
10035: defined.
10036:
10037: @item @code{POSTPONE} applied to @code{[IF]}:
10038: @cindex @code{POSTPONE} applied to @code{[IF]}
10039: @cindex @code{[IF]} and @code{POSTPONE}
10040: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
10041: equivalent to @code{[IF]}.
10042:
10043: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
10044: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
10045: Continue in the same state of conditional compilation in the next outer
10046: input source. Currently there is no warning to the user about this.
10047:
10048: @item removing a needed definition (@code{FORGET}):
10049: @cindex @code{FORGET}, removing a needed definition
10050: Not implemented (yet).
10051:
10052: @end table
10053:
10054:
10055: @c =====================================================================
10056: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
10057: @section The optional Search-Order word set
10058: @c =====================================================================
10059: @cindex system documentation, search-order words
10060: @cindex search-order words, system documentation
10061:
10062: @menu
10063: * search-idef:: Implementation Defined Options
10064: * search-ambcond:: Ambiguous Conditions
10065: @end menu
10066:
10067:
10068: @c ---------------------------------------------------------------------
10069: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
10070: @subsection Implementation Defined Options
10071: @c ---------------------------------------------------------------------
10072: @cindex implementation-defined options, search-order words
10073: @cindex search-order words, implementation-defined options
10074:
10075: @table @i
10076: @item maximum number of word lists in search order:
10077: @cindex maximum number of word lists in search order
10078: @cindex search order, maximum depth
10079: @code{s" wordlists" environment? drop .}. Currently 16.
10080:
10081: @item minimum search order:
10082: @cindex minimum search order
10083: @cindex search order, minimum
10084: @code{root root}.
10085:
10086: @end table
10087:
10088: @c ---------------------------------------------------------------------
10089: @node search-ambcond, , search-idef, The optional Search-Order word set
10090: @subsection Ambiguous conditions
10091: @c ---------------------------------------------------------------------
10092: @cindex search-order words, ambiguous conditions
10093: @cindex ambiguous conditions, search-order words
10094:
10095: @table @i
1.21 crook 10096: @item changing the compilation word list (during compilation):
10097: @cindex changing the compilation word list (during compilation)
10098: @cindex compilation word list, change before definition ends
10099: The word is entered into the word list that was the compilation word list
1.1 anton 10100: at the start of the definition. Any changes to the name field (e.g.,
10101: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
10102: are applied to the latest defined word (as reported by @code{last} or
1.21 crook 10103: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1 anton 10104:
10105: @item search order empty (@code{previous}):
10106: @cindex @code{previous}, search order empty
1.26 crook 10107: @cindex vocstack empty, @code{previous}
1.1 anton 10108: @code{abort" Vocstack empty"}.
10109:
10110: @item too many word lists in search order (@code{also}):
10111: @cindex @code{also}, too many word lists in search order
1.26 crook 10112: @cindex vocstack full, @code{also}
1.1 anton 10113: @code{abort" Vocstack full"}.
10114:
10115: @end table
10116:
10117: @c ***************************************************************
10118: @node Model, Integrating Gforth, ANS conformance, Top
10119: @chapter Model
10120:
10121: This chapter has yet to be written. It will contain information, on
10122: which internal structures you can rely.
10123:
10124: @c ***************************************************************
10125: @node Integrating Gforth, Emacs and Gforth, Model, Top
10126: @chapter Integrating Gforth into C programs
10127:
10128: This is not yet implemented.
10129:
10130: Several people like to use Forth as scripting language for applications
10131: that are otherwise written in C, C++, or some other language.
10132:
10133: The Forth system ATLAST provides facilities for embedding it into
10134: applications; unfortunately it has several disadvantages: most
10135: importantly, it is not based on ANS Forth, and it is apparently dead
10136: (i.e., not developed further and not supported). The facilities
1.21 crook 10137: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 10138: making the switch should not be hard.
10139:
10140: We also tried to design the interface such that it can easily be
10141: implemented by other Forth systems, so that we may one day arrive at a
10142: standardized interface. Such a standard interface would allow you to
10143: replace the Forth system without having to rewrite C code.
10144:
10145: You embed the Gforth interpreter by linking with the library
10146: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
10147: global symbols in this library that belong to the interface, have the
10148: prefix @code{forth_}. (Global symbols that are used internally have the
10149: prefix @code{gforth_}).
10150:
10151: You can include the declarations of Forth types and the functions and
10152: variables of the interface with @code{#include <forth.h>}.
10153:
10154: Types.
10155:
10156: Variables.
10157:
10158: Data and FP Stack pointer. Area sizes.
10159:
10160: functions.
10161:
10162: forth_init(imagefile)
10163: forth_evaluate(string) exceptions?
10164: forth_goto(address) (or forth_execute(xt)?)
10165: forth_continue() (a corountining mechanism)
10166:
10167: Adding primitives.
10168:
10169: No checking.
10170:
10171: Signals?
10172:
10173: Accessing the Stacks
10174:
1.26 crook 10175: @c ******************************************************************
1.1 anton 10176: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
10177: @chapter Emacs and Gforth
10178: @cindex Emacs and Gforth
10179:
10180: @cindex @file{gforth.el}
10181: @cindex @file{forth.el}
10182: @cindex Rydqvist, Goran
10183: @cindex comment editing commands
10184: @cindex @code{\}, editing with Emacs
10185: @cindex debug tracer editing commands
10186: @cindex @code{~~}, removal with Emacs
10187: @cindex Forth mode in Emacs
10188: Gforth comes with @file{gforth.el}, an improved version of
10189: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 10190: improvements are:
10191:
10192: @itemize @bullet
10193: @item
10194: A better (but still not perfect) handling of indentation.
10195: @item
10196: Comment paragraph filling (@kbd{M-q})
10197: @item
10198: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
10199: @item
10200: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
10201: @end itemize
10202:
10203: I left the stuff I do not use alone, even though some of it only makes
10204: sense for TILE. To get a description of these features, enter Forth mode
10205: and type @kbd{C-h m}.
1.1 anton 10206:
10207: @cindex source location of error or debugging output in Emacs
10208: @cindex error output, finding the source location in Emacs
10209: @cindex debugging output, finding the source location in Emacs
10210: In addition, Gforth supports Emacs quite well: The source code locations
10211: given in error messages, debugging output (from @code{~~}) and failed
10212: assertion messages are in the right format for Emacs' compilation mode
10213: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
10214: Manual}) so the source location corresponding to an error or other
10215: message is only a few keystrokes away (@kbd{C-x `} for the next error,
10216: @kbd{C-c C-c} for the error under the cursor).
10217:
10218: @cindex @file{TAGS} file
10219: @cindex @file{etags.fs}
10220: @cindex viewing the source of a word in Emacs
1.26 crook 10221: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file will
10222: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 10223: contains the definitions of all words defined afterwards. You can then
10224: find the source for a word using @kbd{M-.}. Note that emacs can use
10225: several tags files at the same time (e.g., one for the Gforth sources
10226: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
10227: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
10228: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
10229: @file{/usr/local/share/gforth/0.2.0/TAGS}).
10230:
10231: @cindex @file{.emacs}
10232: To get all these benefits, add the following lines to your @file{.emacs}
10233: file:
10234:
10235: @example
10236: (autoload 'forth-mode "gforth.el")
10237: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
10238: @end example
10239:
1.26 crook 10240: @c ******************************************************************
1.1 anton 10241: @node Image Files, Engine, Emacs and Gforth, Top
10242: @chapter Image Files
1.26 crook 10243: @cindex image file
10244: @cindex @file{.fi} files
1.1 anton 10245: @cindex precompiled Forth code
10246: @cindex dictionary in persistent form
10247: @cindex persistent form of dictionary
10248:
10249: An image file is a file containing an image of the Forth dictionary,
10250: i.e., compiled Forth code and data residing in the dictionary. By
10251: convention, we use the extension @code{.fi} for image files.
10252:
10253: @menu
1.18 anton 10254: * Image Licensing Issues:: Distribution terms for images.
10255: * Image File Background:: Why have image files?
1.29 crook 10256: * Non-Relocatable Image Files:: don't always work.
1.18 anton 10257: * Data-Relocatable Image Files:: are better.
1.29 crook 10258: * Fully Relocatable Image Files:: better yet.
1.18 anton 10259: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 10260: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 10261: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 10262: @end menu
10263:
1.18 anton 10264: @node Image Licensing Issues, Image File Background, Image Files, Image Files
10265: @section Image Licensing Issues
10266: @cindex license for images
10267: @cindex image license
10268:
10269: An image created with @code{gforthmi} (@pxref{gforthmi}) or
10270: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
10271: original image; i.e., according to copyright law it is a derived work of
10272: the original image.
10273:
10274: Since Gforth is distributed under the GNU GPL, the newly created image
10275: falls under the GNU GPL, too. In particular, this means that if you
10276: distribute the image, you have to make all of the sources for the image
10277: available, including those you wrote. For details see @ref{License, ,
10278: GNU General Public License (Section 3)}.
10279:
10280: If you create an image with @code{cross} (@pxref{cross.fs}), the image
10281: contains only code compiled from the sources you gave it; if none of
10282: these sources is under the GPL, the terms discussed above do not apply
10283: to the image. However, if your image needs an engine (a gforth binary)
10284: that is under the GPL, you should make sure that you distribute both in
10285: a way that is at most a @emph{mere aggregation}, if you don't want the
10286: terms of the GPL to apply to the image.
10287:
10288: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 10289: @section Image File Background
10290: @cindex image file background
10291:
10292: Our Forth system consists not only of primitives, but also of
10293: definitions written in Forth. Since the Forth compiler itself belongs to
10294: those definitions, it is not possible to start the system with the
10295: primitives and the Forth source alone. Therefore we provide the Forth
1.26 crook 10296: code as an image file in nearly executable form. When Gforth starts up,
10297: a C routine loads the image file into memory, optionally relocates the
10298: addresses, then sets up the memory (stacks etc.) according to
10299: information in the image file, and (finally) starts executing Forth
10300: code.
1.1 anton 10301:
10302: The image file variants represent different compromises between the
10303: goals of making it easy to generate image files and making them
10304: portable.
10305:
10306: @cindex relocation at run-time
1.26 crook 10307: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 10308: run-time. This avoids many of the complications discussed below (image
10309: files are data relocatable without further ado), but costs performance
10310: (one addition per memory access).
10311:
10312: @cindex relocation at load-time
1.26 crook 10313: By contrast, the Gforth loader performs relocation at image load time. The
10314: loader also has to replace tokens that represent primitive calls with the
1.1 anton 10315: appropriate code-field addresses (or code addresses in the case of
10316: direct threading).
10317:
10318: There are three kinds of image files, with different degrees of
10319: relocatability: non-relocatable, data-relocatable, and fully relocatable
10320: image files.
10321:
10322: @cindex image file loader
10323: @cindex relocating loader
10324: @cindex loader for image files
10325: These image file variants have several restrictions in common; they are
10326: caused by the design of the image file loader:
10327:
10328: @itemize @bullet
10329: @item
10330: There is only one segment; in particular, this means, that an image file
10331: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 10332: them). The contents of the stacks are not represented, either.
1.1 anton 10333:
10334: @item
10335: The only kinds of relocation supported are: adding the same offset to
10336: all cells that represent data addresses; and replacing special tokens
10337: with code addresses or with pieces of machine code.
10338:
10339: If any complex computations involving addresses are performed, the
10340: results cannot be represented in the image file. Several applications that
10341: use such computations come to mind:
10342: @itemize @minus
10343: @item
10344: Hashing addresses (or data structures which contain addresses) for table
10345: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
10346: purpose, you will have no problem, because the hash tables are
10347: recomputed automatically when the system is started. If you use your own
10348: hash tables, you will have to do something similar.
10349:
10350: @item
10351: There's a cute implementation of doubly-linked lists that uses
10352: @code{XOR}ed addresses. You could represent such lists as singly-linked
10353: in the image file, and restore the doubly-linked representation on
10354: startup.@footnote{In my opinion, though, you should think thrice before
10355: using a doubly-linked list (whatever implementation).}
10356:
10357: @item
10358: The code addresses of run-time routines like @code{docol:} cannot be
10359: represented in the image file (because their tokens would be replaced by
10360: machine code in direct threaded implementations). As a workaround,
10361: compute these addresses at run-time with @code{>code-address} from the
10362: executions tokens of appropriate words (see the definitions of
10363: @code{docol:} and friends in @file{kernel.fs}).
10364:
10365: @item
10366: On many architectures addresses are represented in machine code in some
10367: shifted or mangled form. You cannot put @code{CODE} words that contain
10368: absolute addresses in this form in a relocatable image file. Workarounds
10369: are representing the address in some relative form (e.g., relative to
10370: the CFA, which is present in some register), or loading the address from
10371: a place where it is stored in a non-mangled form.
10372: @end itemize
10373: @end itemize
10374:
10375: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
10376: @section Non-Relocatable Image Files
10377: @cindex non-relocatable image files
1.26 crook 10378: @cindex image file, non-relocatable
1.1 anton 10379:
10380: These files are simple memory dumps of the dictionary. They are specific
10381: to the executable (i.e., @file{gforth} file) they were created
10382: with. What's worse, they are specific to the place on which the
10383: dictionary resided when the image was created. Now, there is no
10384: guarantee that the dictionary will reside at the same place the next
10385: time you start Gforth, so there's no guarantee that a non-relocatable
10386: image will work the next time (Gforth will complain instead of crashing,
10387: though).
10388:
10389: You can create a non-relocatable image file with
10390:
10391: doc-savesystem
10392:
10393: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
10394: @section Data-Relocatable Image Files
10395: @cindex data-relocatable image files
1.26 crook 10396: @cindex image file, data-relocatable
1.1 anton 10397:
10398: These files contain relocatable data addresses, but fixed code addresses
10399: (instead of tokens). They are specific to the executable (i.e.,
10400: @file{gforth} file) they were created with. For direct threading on some
10401: architectures (e.g., the i386), data-relocatable images do not work. You
10402: get a data-relocatable image, if you use @file{gforthmi} with a
10403: Gforth binary that is not doubly indirect threaded (@pxref{Fully
10404: Relocatable Image Files}).
10405:
10406: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
10407: @section Fully Relocatable Image Files
10408: @cindex fully relocatable image files
1.26 crook 10409: @cindex image file, fully relocatable
1.1 anton 10410:
10411: @cindex @file{kern*.fi}, relocatability
10412: @cindex @file{gforth.fi}, relocatability
10413: These image files have relocatable data addresses, and tokens for code
10414: addresses. They can be used with different binaries (e.g., with and
10415: without debugging) on the same machine, and even across machines with
10416: the same data formats (byte order, cell size, floating point
10417: format). However, they are usually specific to the version of Gforth
10418: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
10419: are fully relocatable.
10420:
10421: There are two ways to create a fully relocatable image file:
10422:
10423: @menu
1.29 crook 10424: * gforthmi:: The normal way
1.1 anton 10425: * cross.fs:: The hard way
10426: @end menu
10427:
10428: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
10429: @subsection @file{gforthmi}
10430: @cindex @file{comp-i.fs}
10431: @cindex @file{gforthmi}
10432:
10433: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 10434: image @i{file} that contains everything you would load by invoking
10435: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 10436: @example
1.29 crook 10437: gforthmi @i{file} @i{options}
1.1 anton 10438: @end example
10439:
10440: E.g., if you want to create an image @file{asm.fi} that has the file
10441: @file{asm.fs} loaded in addition to the usual stuff, you could do it
10442: like this:
10443:
10444: @example
10445: gforthmi asm.fi asm.fs
10446: @end example
10447:
1.27 crook 10448: @file{gforthmi} is implemented as a sh script and works like this: It
10449: produces two non-relocatable images for different addresses and then
10450: compares them. Its output reflects this: first you see the output (if
10451: any) of the two Gforth invocations that produce the nonrelocatable image
10452: files, then you see the output of the comparing program: It displays the
10453: offset used for data addresses and the offset used for code addresses;
1.1 anton 10454: moreover, for each cell that cannot be represented correctly in the
10455: image files, it displays a line like the following one:
10456:
10457: @example
10458: 78DC BFFFFA50 BFFFFA40
10459: @end example
10460:
10461: This means that at offset $78dc from @code{forthstart}, one input image
10462: contains $bffffa50, and the other contains $bffffa40. Since these cells
10463: cannot be represented correctly in the output image, you should examine
10464: these places in the dictionary and verify that these cells are dead
10465: (i.e., not read before they are written).
10466:
1.27 crook 10467: If you type @file{gforthmi} with no arguments, it prints some usage
10468: instructions.
10469:
1.1 anton 10470: @cindex @code{savesystem} during @file{gforthmi}
10471: @cindex @code{bye} during @file{gforthmi}
10472: @cindex doubly indirect threaded code
10473: @cindex environment variable @code{GFORTHD}
10474: @cindex @code{GFORTHD} environment variable
10475: @cindex @code{gforth-ditc}
1.29 crook 10476: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 10477: words @code{savesystem} and @code{bye} must be visible. A special doubly
10478: indirect threaded version of the @file{gforth} executable is used for
10479: creating the nonrelocatable images; you can pass the exact filename of
10480: this executable through the environment variable @code{GFORTHD}
10481: (default: @file{gforth-ditc}); if you pass a version that is not doubly
10482: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 10483: data-relocatable image (because there is no code address offset). The
10484: normal @file{gforth} executable is used for creating the relocatable
10485: image; you can pass the exact filename of this executable through the
10486: environment variable @code{GFORTH}.
1.1 anton 10487:
10488: @node cross.fs, , gforthmi, Fully Relocatable Image Files
10489: @subsection @file{cross.fs}
10490: @cindex @file{cross.fs}
10491: @cindex cross-compiler
10492: @cindex metacompiler
10493:
10494: You can also use @code{cross}, a batch compiler that accepts a Forth-like
10495: programming language. This @code{cross} language has to be documented
10496: yet.
10497:
10498: @cindex target compiler
10499: @code{cross} also allows you to create image files for machines with
10500: different data sizes and data formats than the one used for generating
10501: the image file. You can also use it to create an application image that
10502: does not contain a Forth compiler. These features are bought with
10503: restrictions and inconveniences in programming. E.g., addresses have to
10504: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
10505: order to make the code relocatable.
10506:
10507:
10508: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
10509: @section Stack and Dictionary Sizes
10510: @cindex image file, stack and dictionary sizes
10511: @cindex dictionary size default
10512: @cindex stack size default
10513:
10514: If you invoke Gforth with a command line flag for the size
10515: (@pxref{Invoking Gforth}), the size you specify is stored in the
10516: dictionary. If you save the dictionary with @code{savesystem} or create
10517: an image with @file{gforthmi}, this size will become the default
10518: for the resulting image file. E.g., the following will create a
1.21 crook 10519: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 10520:
10521: @example
10522: gforthmi gforth.fi -m 1M
10523: @end example
10524:
10525: In other words, if you want to set the default size for the dictionary
10526: and the stacks of an image, just invoke @file{gforthmi} with the
10527: appropriate options when creating the image.
10528:
10529: @cindex stack size, cache-friendly
10530: Note: For cache-friendly behaviour (i.e., good performance), you should
10531: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
10532: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
10533: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
10534:
10535: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
10536: @section Running Image Files
10537: @cindex running image files
10538: @cindex invoking image files
10539: @cindex image file invocation
10540:
10541: @cindex -i, invoke image file
10542: @cindex --image file, invoke image file
1.29 crook 10543: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 10544: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
10545: @example
1.29 crook 10546: gforth -i @i{image}
1.1 anton 10547: @end example
10548:
10549: @cindex executable image file
1.26 crook 10550: @cindex image file, executable
1.1 anton 10551: If your operating system supports starting scripts with a line of the
10552: form @code{#! ...}, you just have to type the image file name to start
10553: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 10554: just a convention). I.e., to run Gforth with the image file @i{image},
10555: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 10556: This works because every @code{.fi} file starts with a line of this
10557: format:
10558:
10559: @example
10560: #! /usr/local/bin/gforth-0.4.0 -i
10561: @end example
10562:
10563: The file and pathname for the Gforth engine specified on this line is
10564: the specific Gforth executable that it was built against; i.e. the value
10565: of the environment variable @code{GFORTH} at the time that
10566: @file{gforthmi} was executed.
1.1 anton 10567:
1.27 crook 10568: You can make use of the same shell capability to make a Forth source
10569: file into an executable. For example, if you place this text in a file:
1.26 crook 10570:
10571: @example
10572: #! /usr/local/bin/gforth
10573:
10574: ." Hello, world" CR
10575: bye
10576: @end example
10577:
10578: @noindent
1.27 crook 10579: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 10580: directly from the command line. The sequence @code{#!} is used in two
10581: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 10582: system@footnote{The Unix kernel actually recognises two types of files:
10583: executable files and files of data, where the data is processed by an
10584: interpreter that is specified on the ``interpreter line'' -- the first
10585: line of the file, starting with the sequence #!. There may be a small
10586: limit (e.g., 32) on the number of characters that may be specified on
10587: the interpreter line.} secondly it is treated as a comment character by
10588: Gforth. Because of the second usage, a space is required between
10589: @code{#!} and the path to the executable.
1.27 crook 10590:
10591: The disadvantage of this latter technique, compared with using
10592: @file{gforthmi}, is that it is slower; the Forth source code is compiled
10593: on-the-fly, each time the program is invoked.
10594:
1.26 crook 10595: @comment TODO describe the #! magic with reference to the Power Tools book.
10596:
1.1 anton 10597: doc-#!
10598:
10599: @node Modifying the Startup Sequence, , Running Image Files, Image Files
10600: @section Modifying the Startup Sequence
10601: @cindex startup sequence for image file
10602: @cindex image file initialization sequence
10603: @cindex initialization sequence of image file
10604:
10605: You can add your own initialization to the startup sequence through the
1.26 crook 10606: deferred word @code{'cold}. @code{'cold} is invoked just before the
10607: image-specific command line processing (by default, loading files and
10608: evaluating (@code{-e}) strings) starts.
1.1 anton 10609:
10610: A sequence for adding your initialization usually looks like this:
10611:
10612: @example
10613: :noname
10614: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
10615: ... \ your stuff
10616: ; IS 'cold
10617: @end example
10618:
10619: @cindex turnkey image files
1.26 crook 10620: @cindex image file, turnkey applications
1.1 anton 10621: You can make a turnkey image by letting @code{'cold} execute a word
10622: (your turnkey application) that never returns; instead, it exits Gforth
10623: via @code{bye} or @code{throw}.
10624:
10625: @cindex command-line arguments, access
10626: @cindex arguments on the command line, access
10627: You can access the (image-specific) command-line arguments through the
1.26 crook 10628: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1 anton 10629: access to @code{argv}.
10630:
1.26 crook 10631: If @code{'cold} exits normally, Gforth processes the command-line
10632: arguments as files to be loaded and strings to be evaluated. Therefore,
10633: @code{'cold} should remove the arguments it has used in this case.
10634:
10635: doc-'cold
1.1 anton 10636: doc-argc
10637: doc-argv
10638: doc-arg
10639:
10640:
10641: @c ******************************************************************
1.13 pazsan 10642: @node Engine, Binding to System Library, Image Files, Top
1.1 anton 10643: @chapter Engine
10644: @cindex engine
10645: @cindex virtual machine
10646:
1.26 crook 10647: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 10648: may be helpful for finding your way in the Gforth sources.
10649:
10650: The ideas in this section have also been published in the papers
10651: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
10652: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
10653: Ertl, presented at EuroForth '93; the latter is available at
10654: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
10655:
10656: @menu
10657: * Portability::
10658: * Threading::
10659: * Primitives::
10660: * Performance::
10661: @end menu
10662:
10663: @node Portability, Threading, Engine, Engine
10664: @section Portability
10665: @cindex engine portability
10666:
1.26 crook 10667: An important goal of the Gforth Project is availability across a wide
10668: range of personal machines. fig-Forth, and, to a lesser extent, F83,
10669: achieved this goal by manually coding the engine in assembly language
10670: for several then-popular processors. This approach is very
10671: labor-intensive and the results are short-lived due to progress in
10672: computer architecture.
1.1 anton 10673:
10674: @cindex C, using C for the engine
10675: Others have avoided this problem by coding in C, e.g., Mitch Bradley
10676: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
10677: particularly popular for UNIX-based Forths due to the large variety of
10678: architectures of UNIX machines. Unfortunately an implementation in C
10679: does not mix well with the goals of efficiency and with using
10680: traditional techniques: Indirect or direct threading cannot be expressed
10681: in C, and switch threading, the fastest technique available in C, is
10682: significantly slower. Another problem with C is that it is very
10683: cumbersome to express double integer arithmetic.
10684:
10685: @cindex GNU C for the engine
10686: @cindex long long
10687: Fortunately, there is a portable language that does not have these
10688: limitations: GNU C, the version of C processed by the GNU C compiler
10689: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
10690: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
10691: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
10692: threading possible, its @code{long long} type (@pxref{Long Long, ,
10693: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
10694: double numbers@footnote{Unfortunately, long longs are not implemented
10695: properly on all machines (e.g., on alpha-osf1, long longs are only 64
10696: bits, the same size as longs (and pointers), but they should be twice as
1.4 anton 10697: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1 anton 10698: C Manual}). So, we had to implement doubles in C after all. Still, on
10699: most machines we can use long longs and achieve better performance than
10700: with the emulation package.}. GNU C is available for free on all
10701: important (and many unimportant) UNIX machines, VMS, 80386s running
10702: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
10703: on all these machines.
10704:
10705: Writing in a portable language has the reputation of producing code that
10706: is slower than assembly. For our Forth engine we repeatedly looked at
10707: the code produced by the compiler and eliminated most compiler-induced
10708: inefficiencies by appropriate changes in the source code.
10709:
10710: @cindex explicit register declarations
10711: @cindex --enable-force-reg, configuration flag
10712: @cindex -DFORCE_REG
10713: However, register allocation cannot be portably influenced by the
10714: programmer, leading to some inefficiencies on register-starved
10715: machines. We use explicit register declarations (@pxref{Explicit Reg
10716: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
10717: improve the speed on some machines. They are turned on by using the
10718: configuration flag @code{--enable-force-reg} (@code{gcc} switch
10719: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
10720: machine, but also on the compiler version: On some machines some
10721: compiler versions produce incorrect code when certain explicit register
10722: declarations are used. So by default @code{-DFORCE_REG} is not used.
10723:
10724: @node Threading, Primitives, Portability, Engine
10725: @section Threading
10726: @cindex inner interpreter implementation
10727: @cindex threaded code implementation
10728:
10729: @cindex labels as values
10730: GNU C's labels as values extension (available since @code{gcc-2.0},
10731: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 10732: makes it possible to take the address of @i{label} by writing
10733: @code{&&@i{label}}. This address can then be used in a statement like
10734: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 10735: @code{goto x}.
10736:
1.26 crook 10737: @cindex @code{NEXT}, indirect threaded
1.1 anton 10738: @cindex indirect threaded inner interpreter
10739: @cindex inner interpreter, indirect threaded
1.26 crook 10740: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 10741: @example
10742: cfa = *ip++;
10743: ca = *cfa;
10744: goto *ca;
10745: @end example
10746: @cindex instruction pointer
10747: For those unfamiliar with the names: @code{ip} is the Forth instruction
10748: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
10749: execution token and points to the code field of the next word to be
10750: executed; The @code{ca} (code address) fetched from there points to some
10751: executable code, e.g., a primitive or the colon definition handler
10752: @code{docol}.
10753:
1.26 crook 10754: @cindex @code{NEXT}, direct threaded
1.1 anton 10755: @cindex direct threaded inner interpreter
10756: @cindex inner interpreter, direct threaded
10757: Direct threading is even simpler:
10758: @example
10759: ca = *ip++;
10760: goto *ca;
10761: @end example
10762:
10763: Of course we have packaged the whole thing neatly in macros called
1.26 crook 10764: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 10765:
10766: @menu
10767: * Scheduling::
10768: * Direct or Indirect Threaded?::
10769: * DOES>::
10770: @end menu
10771:
10772: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
10773: @subsection Scheduling
10774: @cindex inner interpreter optimization
10775:
10776: There is a little complication: Pipelined and superscalar processors,
10777: i.e., RISC and some modern CISC machines can process independent
10778: instructions while waiting for the results of an instruction. The
10779: compiler usually reorders (schedules) the instructions in a way that
10780: achieves good usage of these delay slots. However, on our first tries
10781: the compiler did not do well on scheduling primitives. E.g., for
10782: @code{+} implemented as
10783: @example
10784: n=sp[0]+sp[1];
10785: sp++;
10786: sp[0]=n;
10787: NEXT;
10788: @end example
1.26 crook 10789: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1 anton 10790: scheduling. After a little thought the problem becomes clear: The
1.21 crook 10791: compiler cannot know that @code{sp} and @code{ip} point to different
10792: addresses (and the version of @code{gcc} we used would not know it even
10793: if it was possible), so it could not move the load of the cfa above the
10794: store to the TOS. Indeed the pointers could be the same, if code on or
10795: very near the top of stack were executed. In the interest of speed we
10796: chose to forbid this probably unused ``feature'' and helped the compiler
1.26 crook 10797: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21 crook 10798: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1 anton 10799: @example
10800: n=sp[0]+sp[1];
10801: sp++;
10802: NEXT_P1;
10803: sp[0]=n;
10804: NEXT_P2;
10805: @end example
10806: This can be scheduled optimally by the compiler.
10807:
10808: This division can be turned off with the switch @code{-DCISC_NEXT}. This
10809: switch is on by default on machines that do not profit from scheduling
10810: (e.g., the 80386), in order to preserve registers.
10811:
10812: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
10813: @subsection Direct or Indirect Threaded?
10814: @cindex threading, direct or indirect?
10815:
10816: @cindex -DDIRECT_THREADED
10817: Both! After packaging the nasty details in macro definitions we
10818: realized that we could switch between direct and indirect threading by
10819: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
10820: defining a few machine-specific macros for the direct-threading case.
10821: On the Forth level we also offer access words that hide the
10822: differences between the threading methods (@pxref{Threading Words}).
10823:
10824: Indirect threading is implemented completely machine-independently.
10825: Direct threading needs routines for creating jumps to the executable
1.21 crook 10826: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
10827: machine-dependent, but they do not amount to many source lines. Therefore,
10828: even porting direct threading to a new machine requires little effort.
1.1 anton 10829:
10830: @cindex --enable-indirect-threaded, configuration flag
10831: @cindex --enable-direct-threaded, configuration flag
10832: The default threading method is machine-dependent. You can enforce a
10833: specific threading method when building Gforth with the configuration
10834: flag @code{--enable-direct-threaded} or
10835: @code{--enable-indirect-threaded}. Note that direct threading is not
10836: supported on all machines.
10837:
10838: @node DOES>, , Direct or Indirect Threaded?, Threading
10839: @subsection DOES>
10840: @cindex @code{DOES>} implementation
10841:
1.26 crook 10842: @cindex @code{dodoes} routine
10843: @cindex @code{DOES>}-code
1.1 anton 10844: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
10845: the chunk of code executed by every word defined by a
10846: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
10847: the Forth code to be executed, i.e. the code after the
1.26 crook 10848: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1 anton 10849:
1.21 crook 10850: In fig-Forth the code field points directly to the @code{dodoes} and the
1.26 crook 10851: @code{DOES>}code address is stored in the cell after the code address (i.e. at
1.29 crook 10852: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1 anton 10853: the Forth-79 and all later standards, because in fig-Forth this address
10854: lies in the body (which is illegal in these standards). However, by
10855: making the code field larger for all words this solution becomes legal
10856: again. We use this approach for the indirect threaded version and for
10857: direct threading on some machines. Leaving a cell unused in most words
10858: is a bit wasteful, but on the machines we are targeting this is hardly a
10859: problem. The other reason for having a code field size of two cells is
10860: to avoid having different image files for direct and indirect threaded
10861: systems (direct threaded systems require two-cell code fields on many
10862: machines).
10863:
1.26 crook 10864: @cindex @code{DOES>}-handler
1.1 anton 10865: The other approach is that the code field points or jumps to the cell
1.26 crook 10866: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
10867: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
10868: @code{DOES>}-code address by computing the code address, i.e., the address of
1.1 anton 10869: the jump to dodoes, and add the length of that jump field. A variant of
10870: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
10871: return address (which can be found in the return register on RISCs) is
1.26 crook 10872: the @code{DOES>}-code address. Since the two cells available in the code field
1.1 anton 10873: are used up by the jump to the code address in direct threading on many
10874: architectures, we use this approach for direct threading on these
10875: architectures. We did not want to add another cell to the code field.
10876:
10877: @node Primitives, Performance, Threading, Engine
10878: @section Primitives
10879: @cindex primitives, implementation
10880: @cindex virtual machine instructions, implementation
10881:
10882: @menu
10883: * Automatic Generation::
10884: * TOS Optimization::
10885: * Produced code::
10886: @end menu
10887:
10888: @node Automatic Generation, TOS Optimization, Primitives, Primitives
10889: @subsection Automatic Generation
10890: @cindex primitives, automatic generation
10891:
10892: @cindex @file{prims2x.fs}
10893: Since the primitives are implemented in a portable language, there is no
10894: longer any need to minimize the number of primitives. On the contrary,
10895: having many primitives has an advantage: speed. In order to reduce the
10896: number of errors in primitives and to make programming them easier, we
10897: provide a tool, the primitive generator (@file{prims2x.fs}), that
10898: automatically generates most (and sometimes all) of the C code for a
10899: primitive from the stack effect notation. The source for a primitive
10900: has the following form:
10901:
10902: @cindex primitive source format
10903: @format
1.29 crook 10904: @i{Forth-name} @i{stack-effect} @i{category} [@i{pronounc.}]
10905: [@code{""}@i{glossary entry}@code{""}]
10906: @i{C code}
1.1 anton 10907: [@code{:}
1.29 crook 10908: @i{Forth code}]
1.1 anton 10909: @end format
10910:
10911: The items in brackets are optional. The category and glossary fields
10912: are there for generating the documentation, the Forth code is there
10913: for manual implementations on machines without GNU C. E.g., the source
10914: for the primitive @code{+} is:
10915: @example
10916: + n1 n2 -- n core plus
10917: n = n1+n2;
10918: @end example
10919:
10920: This looks like a specification, but in fact @code{n = n1+n2} is C
10921: code. Our primitive generation tool extracts a lot of information from
10922: the stack effect notations@footnote{We use a one-stack notation, even
10923: though we have separate data and floating-point stacks; The separate
10924: notation can be generated easily from the unified notation.}: The number
10925: of items popped from and pushed on the stack, their type, and by what
10926: name they are referred to in the C code. It then generates a C code
10927: prelude and postlude for each primitive. The final C code for @code{+}
10928: looks like this:
10929:
10930: @example
10931: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
10932: /* */ /* documentation */
10933: @{
10934: DEF_CA /* definition of variable ca (indirect threading) */
10935: Cell n1; /* definitions of variables */
10936: Cell n2;
10937: Cell n;
10938: n1 = (Cell) sp[1]; /* input */
10939: n2 = (Cell) TOS;
10940: sp += 1; /* stack adjustment */
10941: NAME("+") /* debugging output (with -DDEBUG) */
10942: @{
10943: n = n1+n2; /* C code taken from the source */
10944: @}
10945: NEXT_P1; /* NEXT part 1 */
10946: TOS = (Cell)n; /* output */
10947: NEXT_P2; /* NEXT part 2 */
10948: @}
10949: @end example
10950:
10951: This looks long and inefficient, but the GNU C compiler optimizes quite
10952: well and produces optimal code for @code{+} on, e.g., the R3000 and the
10953: HP RISC machines: Defining the @code{n}s does not produce any code, and
10954: using them as intermediate storage also adds no cost.
10955:
1.26 crook 10956: There are also other optimizations that are not illustrated by this
10957: example: assignments between simple variables are usually for free (copy
1.1 anton 10958: propagation). If one of the stack items is not used by the primitive
10959: (e.g. in @code{drop}), the compiler eliminates the load from the stack
10960: (dead code elimination). On the other hand, there are some things that
10961: the compiler does not do, therefore they are performed by
10962: @file{prims2x.fs}: The compiler does not optimize code away that stores
10963: a stack item to the place where it just came from (e.g., @code{over}).
10964:
10965: While programming a primitive is usually easy, there are a few cases
10966: where the programmer has to take the actions of the generator into
10967: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 10968: fall through to @code{NEXT}.
1.1 anton 10969:
10970: @node TOS Optimization, Produced code, Automatic Generation, Primitives
10971: @subsection TOS Optimization
10972: @cindex TOS optimization for primitives
10973: @cindex primitives, keeping the TOS in a register
10974:
10975: An important optimization for stack machine emulators, e.g., Forth
10976: engines, is keeping one or more of the top stack items in
1.29 crook 10977: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
10978: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 10979: @itemize @bullet
10980: @item
1.29 crook 10981: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 10982: due to fewer loads from and stores to the stack.
1.29 crook 10983: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
10984: @i{y<n}, due to additional moves between registers.
1.1 anton 10985: @end itemize
10986:
10987: @cindex -DUSE_TOS
10988: @cindex -DUSE_NO_TOS
10989: In particular, keeping one item in a register is never a disadvantage,
10990: if there are enough registers. Keeping two items in registers is a
10991: disadvantage for frequent words like @code{?branch}, constants,
10992: variables, literals and @code{i}. Therefore our generator only produces
10993: code that keeps zero or one items in registers. The generated C code
10994: covers both cases; the selection between these alternatives is made at
10995: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
10996: code for @code{+} is just a simple variable name in the one-item case,
10997: otherwise it is a macro that expands into @code{sp[0]}. Note that the
10998: GNU C compiler tries to keep simple variables like @code{TOS} in
10999: registers, and it usually succeeds, if there are enough registers.
11000:
11001: @cindex -DUSE_FTOS
11002: @cindex -DUSE_NO_FTOS
11003: The primitive generator performs the TOS optimization for the
11004: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
11005: operations the benefit of this optimization is even larger:
11006: floating-point operations take quite long on most processors, but can be
11007: performed in parallel with other operations as long as their results are
11008: not used. If the FP-TOS is kept in a register, this works. If
11009: it is kept on the stack, i.e., in memory, the store into memory has to
11010: wait for the result of the floating-point operation, lengthening the
11011: execution time of the primitive considerably.
11012:
11013: The TOS optimization makes the automatic generation of primitives a
11014: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
11015: @code{TOS} is not sufficient. There are some special cases to
11016: consider:
11017: @itemize @bullet
11018: @item In the case of @code{dup ( w -- w w )} the generator must not
11019: eliminate the store to the original location of the item on the stack,
11020: if the TOS optimization is turned on.
11021: @item Primitives with stack effects of the form @code{--}
1.29 crook 11022: @i{out1}...@i{outy} must store the TOS to the stack at the start.
11023: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 11024: must load the TOS from the stack at the end. But for the null stack
11025: effect @code{--} no stores or loads should be generated.
11026: @end itemize
11027:
11028: @node Produced code, , TOS Optimization, Primitives
11029: @subsection Produced code
11030: @cindex primitives, assembly code listing
11031:
11032: @cindex @file{engine.s}
11033: To see what assembly code is produced for the primitives on your machine
11034: with your compiler and your flag settings, type @code{make engine.s} and
11035: look at the resulting file @file{engine.s}.
11036:
11037: @node Performance, , Primitives, Engine
11038: @section Performance
11039: @cindex performance of some Forth interpreters
11040: @cindex engine performance
11041: @cindex benchmarking Forth systems
11042: @cindex Gforth performance
11043:
11044: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
11045: impossible to write a significantly faster engine.
11046:
11047: On register-starved machines like the 386 architecture processors
11048: improvements are possible, because @code{gcc} does not utilize the
11049: registers as well as a human, even with explicit register declarations;
11050: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
11051: and hand-tuned it for the 486; this system is 1.19 times faster on the
11052: Sieve benchmark on a 486DX2/66 than Gforth compiled with
11053: @code{gcc-2.6.3} with @code{-DFORCE_REG}.
11054:
11055: @cindex Win32Forth performance
11056: @cindex NT Forth performance
11057: @cindex eforth performance
11058: @cindex ThisForth performance
11059: @cindex PFE performance
11060: @cindex TILE performance
11061: However, this potential advantage of assembly language implementations
11062: is not necessarily realized in complete Forth systems: We compared
11063: Gforth (direct threaded, compiled with @code{gcc-2.6.3} and
11064: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
11065: 1994) and Eforth (with and without peephole (aka pinhole) optimization
11066: of the threaded code); all these systems were written in assembly
11067: language. We also compared Gforth with three systems written in C:
11068: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
11069: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21 crook 11070: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
11071: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1 anton 11072: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
11073: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
11074: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
11075: 486DX2/66 with similar memory performance under Windows NT. Marcel
11076: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
11077: added the peephole optimizer, ran the benchmarks and reported the
11078: results.
11079:
11080: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
11081: matrix multiplication come from the Stanford integer benchmarks and have
11082: been translated into Forth by Martin Fraeman; we used the versions
11083: included in the TILE Forth package, but with bigger data set sizes; and
11084: a recursive Fibonacci number computation for benchmarking calling
11085: performance. The following table shows the time taken for the benchmarks
11086: scaled by the time taken by Gforth (in other words, it shows the speedup
11087: factor that Gforth achieved over the other systems).
11088:
11089: @example
11090: relative Win32- NT eforth This-
11091: time Gforth Forth Forth eforth +opt PFE Forth TILE
11092: sieve 1.00 1.39 1.14 1.39 0.85 1.58 3.18 8.58
11093: bubble 1.00 1.31 1.41 1.48 0.88 1.50 3.88
11094: matmul 1.00 1.47 1.35 1.46 0.74 1.58 4.09
11095: fib 1.00 1.52 1.34 1.22 0.86 1.74 2.99 4.30
11096: @end example
11097:
1.26 crook 11098: You may be quite surprised by the good performance of Gforth when
11099: compared with systems written in assembly language. One important reason
11100: for the disappointing performance of these other systems is probably
11101: that they are not written optimally for the 486 (e.g., they use the
11102: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
11103: but costly method for relocating the Forth image: like @code{cforth}, it
11104: computes the actual addresses at run time, resulting in two address
11105: computations per @code{NEXT} (@pxref{Image File Background}).
11106:
11107: Only Eforth with the peephole optimizer has a performance that is
11108: comparable to Gforth. The speedups achieved with peephole optimization
11109: of threaded code are quite remarkable. Adding a peephole optimizer to
11110: Gforth should cause similar speedups.
1.1 anton 11111:
11112: The speedup of Gforth over PFE, ThisForth and TILE can be easily
11113: explained with the self-imposed restriction of the latter systems to
11114: standard C, which makes efficient threading impossible (however, the
1.4 anton 11115: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 11116: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
11117: Moreover, current C compilers have a hard time optimizing other aspects
11118: of the ThisForth and the TILE source.
11119:
1.26 crook 11120: The performance of Gforth on 386 architecture processors varies widely
11121: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
11122: allocate any of the virtual machine registers into real machine
11123: registers by itself and would not work correctly with explicit register
11124: declarations, giving a 1.3 times slower engine (on a 486DX2/66 running
11125: the Sieve) than the one measured above.
1.1 anton 11126:
1.26 crook 11127: Note that there have been several releases of Win32Forth since the
11128: release presented here, so the results presented above may have little
1.1 anton 11129: predictive value for the performance of Win32Forth today.
11130:
11131: @cindex @file{Benchres}
11132: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
11133: Maierhofer (presented at EuroForth '95), an indirect threaded version of
11134: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
11135: version of Gforth is 2%@minus{}8% slower on a 486 than the direct
11136: threaded version used here. The paper available at
11137: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
11138: it also contains numbers for some native code systems. You can find a
11139: newer version of these measurements at
11140: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
11141: find numbers for Gforth on various machines in @file{Benchres}.
11142:
1.26 crook 11143: @c ******************************************************************
1.13 pazsan 11144: @node Binding to System Library, Cross Compiler, Engine, Top
1.14 pazsan 11145: @chapter Binding to System Library
1.13 pazsan 11146:
11147: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14 pazsan 11148: @chapter Cross Compiler
1.13 pazsan 11149:
11150: Cross Compiler
11151:
11152: @menu
11153: * Using the Cross Compiler::
11154: * How the Cross Compiler Works::
11155: @end menu
11156:
1.21 crook 11157: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 11158: @section Using the Cross Compiler
1.13 pazsan 11159:
1.21 crook 11160: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 11161: @section How the Cross Compiler Works
1.13 pazsan 11162:
11163: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 11164: @appendix Bugs
1.1 anton 11165: @cindex bug reporting
11166:
1.21 crook 11167: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 11168:
11169: If you find a bug, please send a bug report to
1.21 crook 11170: @email{bug-gforth@@gnu.ai.mit.edu}. A bug report should include this
11171: information:
11172:
11173: @itemize @bullet
11174: @item
11175: The Gforth version used (it is announced at the start of an
11176: interactive Gforth session).
11177: @item
11178: The machine and operating system (on Unix
11179: systems @code{uname -a} will report this information).
11180: @item
11181: The installation options (send the file @file{config.status}).
11182: @item
11183: A complete list of changes (if any) you (or your installer) have made to the
11184: Gforth sources.
11185: @item
11186: A program (or a sequence of keyboard commands) that reproduces the bug.
11187: @item
11188: A description of what you think constitutes the buggy behaviour.
11189: @end itemize
1.1 anton 11190:
11191: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
11192: to Report Bugs, gcc.info, GNU C Manual}.
11193:
11194:
1.21 crook 11195: @node Origin, Forth-related information, Bugs, Top
11196: @appendix Authors and Ancestors of Gforth
1.1 anton 11197:
11198: @section Authors and Contributors
11199: @cindex authors of Gforth
11200: @cindex contributors to Gforth
11201:
11202: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
11203: Ertl. The third major author was Jens Wilke. Lennart Benschop (who was
11204: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
11205: with their continuous feedback. Lennart Benshop contributed
11206: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
11207: support for calling C libraries. Helpful comments also came from Paul
11208: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.12 anton 11209: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
11210: release of Gforth-0.2.1 there were also helpful comments from many
11211: others; thank you all, sorry for not listing you here (but digging
1.23 crook 11212: through my mailbox to extract your names is on my to-do list). Since the
11213: release of Gforth-0.4.0 Neal Crook worked on the manual.
1.1 anton 11214:
11215: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
11216: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 11217: was developed across the Internet, and its authors did not meet
1.20 pazsan 11218: physically for the first 4 years of development.
1.1 anton 11219:
11220: @section Pedigree
1.26 crook 11221: @cindex pedigree of Gforth
1.1 anton 11222:
1.20 pazsan 11223: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1 anton 11224: Dirk Zoller) will cross-fertilize each other. Of course, a significant
11225: part of the design of Gforth was prescribed by ANS Forth.
11226:
1.20 pazsan 11227: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 11228: 32 bit native code version of VolksForth for the Atari ST, written
11229: mostly by Dietrich Weineck.
11230:
11231: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
11232: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
11233: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
11234:
11235: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
11236: Forth-83 standard. !! Pedigree? When?
11237:
11238: A team led by Bill Ragsdale implemented fig-Forth on many processors in
11239: 1979. Robert Selzer and Bill Ragsdale developed the original
11240: implementation of fig-Forth for the 6502 based on microForth.
11241:
11242: The principal architect of microForth was Dean Sanderson. microForth was
11243: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
11244: the 1802, and subsequently implemented on the 8080, the 6800 and the
11245: Z80.
11246:
11247: All earlier Forth systems were custom-made, usually by Charles Moore,
11248: who discovered (as he puts it) Forth during the late 60s. The first full
11249: Forth existed in 1971.
11250:
11251: A part of the information in this section comes from @cite{The Evolution
11252: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
11253: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
11254: Notices 28(3), 1993. You can find more historical and genealogical
11255: information about Forth there.
11256:
1.21 crook 11257: @node Forth-related information, Word Index, Origin, Top
11258: @appendix Other Forth-related information
11259: @cindex Forth-related information
11260:
11261: @menu
11262: * Internet resources::
11263: * Books::
11264: * The Forth Interest Group::
11265: * Conferences::
11266: @end menu
11267:
11268:
11269: @node Internet resources, Books, Forth-related information, Forth-related information
11270: @section Internet resources
1.26 crook 11271: @cindex internet resources
1.21 crook 11272:
11273: @cindex comp.lang.forth
11274: @cindex frequently asked questions
11275: There is an active newsgroup (comp.lang.forth) discussing Forth and
11276: Forth-related issues. A frequently-asked-questions (FAQ) list
11277: is posted to the newsgroup regulary, and archived at these sites:
11278:
11279: @itemize @bullet
11280: @item
11281: @url{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
11282: @item
11283: @url{ftp://ftp.forth.org/pub/Forth/FAQ/}
11284: @end itemize
11285:
11286: The FAQ list should be considered mandatory reading before posting to
11287: the newsgroup.
11288:
11289: Here are some other web sites holding Forth-related material:
11290:
11291: @itemize @bullet
11292: @item
11293: @url{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
11294: @item
11295: @url{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
11296: @item
11297: @url{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
11298: @item
11299: @url{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
11300: Research page, including links to the Journal of Forth Application and
11301: Research (JFAR) and a searchable Forth bibliography.
11302: @end itemize
11303:
11304:
11305: @node Books, The Forth Interest Group, Internet resources, Forth-related information
11306: @section Books
1.26 crook 11307: @cindex books on Forth
1.21 crook 11308:
11309: As the Standard is relatively new, there are not many books out yet. It
11310: is not recommended to learn Forth by using Gforth and a book that is not
11311: written for ANS Forth, as you will not know your mistakes from the
11312: deviations of the book. However, books based on the Forth-83 standard
11313: should be ok, because ANS Forth is primarily an extension of Forth-83.
11314:
11315: @cindex standard document for ANS Forth
11316: @cindex ANS Forth document
11317: The definite reference if you want to write ANS Forth programs is, of
1.26 crook 11318: course, the ANS Forth document. It is available in printed form from the
1.21 crook 11319: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
11320: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
11321: $200. You can also get it from Global Engineering Documents (Tel.: USA
11322: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
11323:
11324: @cite{dpANS6}, the last draft of the standard, which was then submitted
11325: to ANSI for publication is available electronically and for free in some
11326: MS Word format, and it has been converted to HTML
11327: (@url{http://www.taygeta.com/forth/dpans.html}; this is my favourite
11328: format); this HTML version also includes the answers to Requests for
11329: Interpretation (RFIs). Some pointers to these versions can be found
11330: through @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
11331:
1.26 crook 11332: @cindex introductory book on Forth
11333: @cindex book on Forth, introductory
1.21 crook 11334: @cindex Woehr, Jack: @cite{Forth: The New Model}
11335: @cindex @cite{Forth: The new model} (book)
11336: @cite{Forth: The New Model} by Jack Woehr (Prentice-Hall, 1993) is an
11337: introductory book based on a draft version of the standard. It does not
11338: cover the whole standard. It also contains interesting background
11339: information (Jack Woehr was in the ANS Forth Technical Committee). It is
11340: not appropriate for complete newbies, but programmers experienced in
11341: other languages should find it ok.
11342:
11343: @cindex Conklin, Edward K., and Elizabeth Rather: @cite{Forth Programmer's Handbook}
11344: @cindex Rather, Elizabeth and Edward K. Conklin: @cite{Forth Programmer's Handbook}
11345: @cindex @cite{Forth Programmer's Handbook} (book)
11346: @cite{Forth Programmer's Handbook} by Edward K. Conklin, Elizabeth
11347: D. Rather and the technical staff of Forth, Inc. (Forth, Inc., 1997;
11348: ISBN 0-9662156-0-5) contains little introductory material. The majority
11349: of the book is similar to @ref{Words}, but the book covers most of the
11350: standard words and some non-standard words (whereas this manual is
11351: quite incomplete). In addition, the book contains a chapter on
11352: programming style. The major drawback of this book is that it usually
11353: does not identify what is standard and what is specific to the Forth
11354: system described in the book (probably one of Forth, Inc.'s systems).
11355: Fortunately, many of the non-standard programming practices described in
11356: the book work in Gforth, too. Still, this drawback makes the book
11357: hardly more useful than a pre-ANS book.
11358:
11359: @node The Forth Interest Group, Conferences, Books, Forth-related information
11360: @section The Forth Interest Group
11361: @cindex Forth interest group (FIG)
11362:
11363: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26 crook 11364: member-supported organisation. It publishes a regular magazine,
11365: @var{FORTH Dimensions}, and offers other benefits of membership. You can
11366: contact the FIG through their office email address:
11367: @email{office@@forth.org} or by visiting their web site at
11368: @url{http://www.forth.org/}. This web site also includes links to FIG
11369: chapters in other countries and American cities
1.21 crook 11370: (@url{http://www.forth.org/chapters.html}).
11371:
11372: @node Conferences, , The Forth Interest Group, Forth-related information
11373: @section Conferences
11374: @cindex Conferences
11375:
11376: There are several regular conferences related to Forth. They are all
1.26 crook 11377: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
11378: news group:
1.21 crook 11379:
11380: @itemize @bullet
11381: @item
11382: FORML -- the Forth modification laboratory convenes every year near
11383: Monterey, California.
11384: @item
11385: The Rochester Forth Conference -- an annual conference traditionally
11386: held in Rochester, New York.
11387: @item
11388: EuroForth -- this European conference takes place annually.
11389: @end itemize
11390:
11391:
11392: @node Word Index, Concept Index, Forth-related information, Top
1.1 anton 11393: @unnumbered Word Index
11394:
1.26 crook 11395: This index is a list of Forth words that have ``glossary'' entries
11396: within this manual. Each word is listed with its stack effect and
11397: wordset.
1.1 anton 11398:
11399: @printindex fn
11400:
11401: @node Concept Index, , Word Index, Top
11402: @unnumbered Concept and Word Index
11403:
1.26 crook 11404: Not all entries listed in this index are present verbatim in the
11405: text. This index also duplicates, in abbreviated form, all of the words
11406: listed in the Word Index (only the names are listed for the words here).
1.1 anton 11407:
11408: @printindex cp
11409:
11410: @contents
11411: @bye
11412:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>