Annotation of gforth/doc/gforth.ds, revision 1.30
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:
159: * Invoking Gforth::
160: * Leaving Gforth::
161: * Command-line editing::
162: * Upper and lower case::
163: * Environment variables::
164: * Gforth Files::
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.12 anton 209: * Mixed precision:: operations with single and double-cell integers
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.27 crook 222: * Reserving Data Space::
1.12 anton 223: * Memory Access::
1.27 crook 224: * Address Arithmetic::
225: * Memory Blocks::
226: * Dynamic Allocation::
1.12 anton 227:
228: Control Structures
229:
230: * Selection::
231: * Simple Loops::
232: * Counted Loops::
233: * Arbitrary control structures::
234: * Calls and returns::
235: * Exception Handling::
236:
237: Defining Words
238:
239: * Simple Defining Words::
240: * Colon Definitions::
241: * User-defined Defining Words::
242: * Supplying names::
243: * Interpretation and Compilation Semantics::
244:
1.21 crook 245: The Text Interpreter
246:
1.29 crook 247: * Input Sources::
1.21 crook 248: * Number Conversion::
249: * Interpret/Compile states::
250: * Literals::
251: * Interpreter Directives::
252:
1.26 crook 253: Word Lists
254:
255: * Why use word lists?::
256: * Word list examples::
257:
258: Files
259:
260: * Forth source files::
261: * General files::
262: * Search Paths::
263: * Forth Search Paths::
264: * General Search Paths::
265:
266: Other I/O
267:
268: * Simple numeric output::
269: * Formatted numeric output::
270: * String Formats::
271: * Displaying characters and strings::
272: * Input::
273:
274: Programming Tools
275:
276: * Debugging:: Simple and quick.
277: * Assertions:: Making your programs self-checking.
278: * Singlestep Debugger:: Executing your program word by word.
279:
280: Locals
281:
282: * Gforth locals::
283: * ANS Forth locals::
284:
285: Gforth locals
286:
287: * Where are locals visible by name?::
288: * How long do locals live?::
289: * Programming Style::
290: * Implementation::
291:
1.12 anton 292: Structures
293:
294: * Why explicit structure support?::
295: * Structure Usage::
296: * Structure Naming Convention::
297: * Structure Implementation::
298: * Structure Glossary::
299:
300: Object-oriented Forth
301:
1.24 anton 302: * Why object-oriented programming?::
303: * Object-Oriented Terminology::
304: * Objects::
305: * OOF::
306: * Mini-OOF::
1.23 crook 307: * Comparison with other object models::
1.12 anton 308:
1.24 anton 309: The @file{objects.fs} model
1.12 anton 310:
311: * Properties of the Objects model::
312: * Basic Objects Usage::
1.23 crook 313: * The Objects base class::
1.12 anton 314: * Creating objects::
315: * Object-Oriented Programming Style::
316: * Class Binding::
317: * Method conveniences::
318: * Classes and Scoping::
319: * Object Interfaces::
320: * Objects Implementation::
321: * Objects Glossary::
322:
1.24 anton 323: The @file{oof.fs} model
1.12 anton 324:
325: * Properties of the OOF model::
326: * Basic OOF Usage::
1.23 crook 327: * The OOF base class::
1.12 anton 328: * Class Declaration::
329: * Class Implementation::
330:
1.24 anton 331: The @file{mini-oof.fs} model
1.23 crook 332:
333: * Basic Mini-OOF Usage::
334: * Mini-OOF Example::
335: * Mini-OOF Implementation::
336:
1.12 anton 337: Tools
338:
339: * ANS Report:: Report the words used, sorted by wordset.
340:
341: ANS conformance
342:
343: * The Core Words::
344: * The optional Block word set::
345: * The optional Double Number word set::
346: * The optional Exception word set::
347: * The optional Facility word set::
348: * The optional File-Access word set::
349: * The optional Floating-Point word set::
350: * The optional Locals word set::
351: * The optional Memory-Allocation word set::
352: * The optional Programming-Tools word set::
353: * The optional Search-Order word set::
354:
355: The Core Words
356:
357: * core-idef:: Implementation Defined Options
358: * core-ambcond:: Ambiguous Conditions
359: * core-other:: Other System Documentation
360:
361: The optional Block word set
362:
363: * block-idef:: Implementation Defined Options
364: * block-ambcond:: Ambiguous Conditions
365: * block-other:: Other System Documentation
366:
367: The optional Double Number word set
368:
369: * double-ambcond:: Ambiguous Conditions
370:
371: The optional Exception word set
372:
373: * exception-idef:: Implementation Defined Options
374:
375: The optional Facility word set
376:
377: * facility-idef:: Implementation Defined Options
378: * facility-ambcond:: Ambiguous Conditions
379:
380: The optional File-Access word set
381:
382: * file-idef:: Implementation Defined Options
383: * file-ambcond:: Ambiguous Conditions
384:
385: The optional Floating-Point word set
386:
387: * floating-idef:: Implementation Defined Options
388: * floating-ambcond:: Ambiguous Conditions
389:
390: The optional Locals word set
391:
392: * locals-idef:: Implementation Defined Options
393: * locals-ambcond:: Ambiguous Conditions
394:
395: The optional Memory-Allocation word set
396:
397: * memory-idef:: Implementation Defined Options
398:
399: The optional Programming-Tools word set
400:
401: * programming-idef:: Implementation Defined Options
402: * programming-ambcond:: Ambiguous Conditions
403:
404: The optional Search-Order word set
405:
406: * search-idef:: Implementation Defined Options
407: * search-ambcond:: Ambiguous Conditions
408:
409: Image Files
410:
1.24 anton 411: * Image Licensing Issues:: Distribution terms for images.
412: * Image File Background:: Why have image files?
413: * Non-Relocatable Image Files:: don't always work.
414: * Data-Relocatable Image Files:: are better.
1.12 anton 415: * Fully Relocatable Image Files:: better yet.
1.24 anton 416: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
417: * Running Image Files:: @code{gforth -i @var{file}} or @var{file}.
418: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 419:
420: Fully Relocatable Image Files
421:
1.27 crook 422: * gforthmi:: The normal way
1.12 anton 423: * cross.fs:: The hard way
424:
425: Engine
426:
427: * Portability::
428: * Threading::
429: * Primitives::
430: * Performance::
431:
432: Threading
433:
434: * Scheduling::
435: * Direct or Indirect Threaded?::
436: * DOES>::
437:
438: Primitives
439:
440: * Automatic Generation::
441: * TOS Optimization::
442: * Produced code::
1.13 pazsan 443:
444: Cross Compiler
445:
446: * Using the Cross Compiler::
447: * How the Cross Compiler Works::
448:
1.24 anton 449: Other Forth-related information
1.21 crook 450:
451: * Internet resources::
452: * Books::
453: * The Forth Interest Group::
454: * Conferences::
455:
1.24 anton 456: @end detailmenu
1.1 anton 457: @end menu
458:
1.26 crook 459: @node License, Goals, Top, Top
1.1 anton 460: @unnumbered GNU GENERAL PUBLIC LICENSE
461: @center Version 2, June 1991
462:
463: @display
464: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
465: 675 Mass Ave, Cambridge, MA 02139, USA
466:
467: Everyone is permitted to copy and distribute verbatim copies
468: of this license document, but changing it is not allowed.
469: @end display
470:
471: @unnumberedsec Preamble
472:
473: The licenses for most software are designed to take away your
474: freedom to share and change it. By contrast, the GNU General Public
475: License is intended to guarantee your freedom to share and change free
476: software---to make sure the software is free for all its users. This
477: General Public License applies to most of the Free Software
478: Foundation's software and to any other program whose authors commit to
479: using it. (Some other Free Software Foundation software is covered by
480: the GNU Library General Public License instead.) You can apply it to
481: your programs, too.
482:
483: When we speak of free software, we are referring to freedom, not
484: price. Our General Public Licenses are designed to make sure that you
485: have the freedom to distribute copies of free software (and charge for
486: this service if you wish), that you receive source code or can get it
487: if you want it, that you can change the software or use pieces of it
488: in new free programs; and that you know you can do these things.
489:
490: To protect your rights, we need to make restrictions that forbid
491: anyone to deny you these rights or to ask you to surrender the rights.
492: These restrictions translate to certain responsibilities for you if you
493: distribute copies of the software, or if you modify it.
494:
495: For example, if you distribute copies of such a program, whether
496: gratis or for a fee, you must give the recipients all the rights that
497: you have. You must make sure that they, too, receive or can get the
498: source code. And you must show them these terms so they know their
499: rights.
500:
501: We protect your rights with two steps: (1) copyright the software, and
502: (2) offer you this license which gives you legal permission to copy,
503: distribute and/or modify the software.
504:
505: Also, for each author's protection and ours, we want to make certain
506: that everyone understands that there is no warranty for this free
507: software. If the software is modified by someone else and passed on, we
508: want its recipients to know that what they have is not the original, so
509: that any problems introduced by others will not reflect on the original
510: authors' reputations.
511:
512: Finally, any free program is threatened constantly by software
513: patents. We wish to avoid the danger that redistributors of a free
514: program will individually obtain patent licenses, in effect making the
515: program proprietary. To prevent this, we have made it clear that any
516: patent must be licensed for everyone's free use or not licensed at all.
517:
518: The precise terms and conditions for copying, distribution and
519: modification follow.
520:
521: @iftex
522: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
523: @end iftex
524: @ifinfo
525: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
526: @end ifinfo
527:
528: @enumerate 0
529: @item
530: This License applies to any program or other work which contains
531: a notice placed by the copyright holder saying it may be distributed
532: under the terms of this General Public License. The ``Program'', below,
533: refers to any such program or work, and a ``work based on the Program''
534: means either the Program or any derivative work under copyright law:
535: that is to say, a work containing the Program or a portion of it,
536: either verbatim or with modifications and/or translated into another
537: language. (Hereinafter, translation is included without limitation in
538: the term ``modification''.) Each licensee is addressed as ``you''.
539:
540: Activities other than copying, distribution and modification are not
541: covered by this License; they are outside its scope. The act of
542: running the Program is not restricted, and the output from the Program
543: is covered only if its contents constitute a work based on the
544: Program (independent of having been made by running the Program).
545: Whether that is true depends on what the Program does.
546:
547: @item
548: You may copy and distribute verbatim copies of the Program's
549: source code as you receive it, in any medium, provided that you
550: conspicuously and appropriately publish on each copy an appropriate
551: copyright notice and disclaimer of warranty; keep intact all the
552: notices that refer to this License and to the absence of any warranty;
553: and give any other recipients of the Program a copy of this License
554: along with the Program.
555:
556: You may charge a fee for the physical act of transferring a copy, and
557: you may at your option offer warranty protection in exchange for a fee.
558:
559: @item
560: You may modify your copy or copies of the Program or any portion
561: of it, thus forming a work based on the Program, and copy and
562: distribute such modifications or work under the terms of Section 1
563: above, provided that you also meet all of these conditions:
564:
565: @enumerate a
566: @item
567: You must cause the modified files to carry prominent notices
568: stating that you changed the files and the date of any change.
569:
570: @item
571: You must cause any work that you distribute or publish, that in
572: whole or in part contains or is derived from the Program or any
573: part thereof, to be licensed as a whole at no charge to all third
574: parties under the terms of this License.
575:
576: @item
577: If the modified program normally reads commands interactively
578: when run, you must cause it, when started running for such
579: interactive use in the most ordinary way, to print or display an
580: announcement including an appropriate copyright notice and a
581: notice that there is no warranty (or else, saying that you provide
582: a warranty) and that users may redistribute the program under
583: these conditions, and telling the user how to view a copy of this
584: License. (Exception: if the Program itself is interactive but
585: does not normally print such an announcement, your work based on
586: the Program is not required to print an announcement.)
587: @end enumerate
588:
589: These requirements apply to the modified work as a whole. If
590: identifiable sections of that work are not derived from the Program,
591: and can be reasonably considered independent and separate works in
592: themselves, then this License, and its terms, do not apply to those
593: sections when you distribute them as separate works. But when you
594: distribute the same sections as part of a whole which is a work based
595: on the Program, the distribution of the whole must be on the terms of
596: this License, whose permissions for other licensees extend to the
597: entire whole, and thus to each and every part regardless of who wrote it.
598:
599: Thus, it is not the intent of this section to claim rights or contest
600: your rights to work written entirely by you; rather, the intent is to
601: exercise the right to control the distribution of derivative or
602: collective works based on the Program.
603:
604: In addition, mere aggregation of another work not based on the Program
605: with the Program (or with a work based on the Program) on a volume of
606: a storage or distribution medium does not bring the other work under
607: the scope of this License.
608:
609: @item
610: You may copy and distribute the Program (or a work based on it,
611: under Section 2) in object code or executable form under the terms of
612: Sections 1 and 2 above provided that you also do one of the following:
613:
614: @enumerate a
615: @item
616: Accompany it with the complete corresponding machine-readable
617: source code, which must be distributed under the terms of Sections
618: 1 and 2 above on a medium customarily used for software interchange; or,
619:
620: @item
621: Accompany it with a written offer, valid for at least three
622: years, to give any third party, for a charge no more than your
623: cost of physically performing source distribution, a complete
624: machine-readable copy of the corresponding source code, to be
625: distributed under the terms of Sections 1 and 2 above on a medium
626: customarily used for software interchange; or,
627:
628: @item
629: Accompany it with the information you received as to the offer
630: to distribute corresponding source code. (This alternative is
631: allowed only for noncommercial distribution and only if you
632: received the program in object code or executable form with such
633: an offer, in accord with Subsection b above.)
634: @end enumerate
635:
636: The source code for a work means the preferred form of the work for
637: making modifications to it. For an executable work, complete source
638: code means all the source code for all modules it contains, plus any
639: associated interface definition files, plus the scripts used to
640: control compilation and installation of the executable. However, as a
641: special exception, the source code distributed need not include
642: anything that is normally distributed (in either source or binary
643: form) with the major components (compiler, kernel, and so on) of the
644: operating system on which the executable runs, unless that component
645: itself accompanies the executable.
646:
647: If distribution of executable or object code is made by offering
648: access to copy from a designated place, then offering equivalent
649: access to copy the source code from the same place counts as
650: distribution of the source code, even though third parties are not
651: compelled to copy the source along with the object code.
652:
653: @item
654: You may not copy, modify, sublicense, or distribute the Program
655: except as expressly provided under this License. Any attempt
656: otherwise to copy, modify, sublicense or distribute the Program is
657: void, and will automatically terminate your rights under this License.
658: However, parties who have received copies, or rights, from you under
659: this License will not have their licenses terminated so long as such
660: parties remain in full compliance.
661:
662: @item
663: You are not required to accept this License, since you have not
664: signed it. However, nothing else grants you permission to modify or
665: distribute the Program or its derivative works. These actions are
666: prohibited by law if you do not accept this License. Therefore, by
667: modifying or distributing the Program (or any work based on the
668: Program), you indicate your acceptance of this License to do so, and
669: all its terms and conditions for copying, distributing or modifying
670: the Program or works based on it.
671:
672: @item
673: Each time you redistribute the Program (or any work based on the
674: Program), the recipient automatically receives a license from the
675: original licensor to copy, distribute or modify the Program subject to
676: these terms and conditions. You may not impose any further
677: restrictions on the recipients' exercise of the rights granted herein.
678: You are not responsible for enforcing compliance by third parties to
679: this License.
680:
681: @item
682: If, as a consequence of a court judgment or allegation of patent
683: infringement or for any other reason (not limited to patent issues),
684: conditions are imposed on you (whether by court order, agreement or
685: otherwise) that contradict the conditions of this License, they do not
686: excuse you from the conditions of this License. If you cannot
687: distribute so as to satisfy simultaneously your obligations under this
688: License and any other pertinent obligations, then as a consequence you
689: may not distribute the Program at all. For example, if a patent
690: license would not permit royalty-free redistribution of the Program by
691: all those who receive copies directly or indirectly through you, then
692: the only way you could satisfy both it and this License would be to
693: refrain entirely from distribution of the Program.
694:
695: If any portion of this section is held invalid or unenforceable under
696: any particular circumstance, the balance of the section is intended to
697: apply and the section as a whole is intended to apply in other
698: circumstances.
699:
700: It is not the purpose of this section to induce you to infringe any
701: patents or other property right claims or to contest validity of any
702: such claims; this section has the sole purpose of protecting the
703: integrity of the free software distribution system, which is
704: implemented by public license practices. Many people have made
705: generous contributions to the wide range of software distributed
706: through that system in reliance on consistent application of that
707: system; it is up to the author/donor to decide if he or she is willing
708: to distribute software through any other system and a licensee cannot
709: impose that choice.
710:
711: This section is intended to make thoroughly clear what is believed to
712: be a consequence of the rest of this License.
713:
714: @item
715: If the distribution and/or use of the Program is restricted in
716: certain countries either by patents or by copyrighted interfaces, the
717: original copyright holder who places the Program under this License
718: may add an explicit geographical distribution limitation excluding
719: those countries, so that distribution is permitted only in or among
720: countries not thus excluded. In such case, this License incorporates
721: the limitation as if written in the body of this License.
722:
723: @item
724: The Free Software Foundation may publish revised and/or new versions
725: of the General Public License from time to time. Such new versions will
726: be similar in spirit to the present version, but may differ in detail to
727: address new problems or concerns.
728:
729: Each version is given a distinguishing version number. If the Program
730: specifies a version number of this License which applies to it and ``any
731: later version'', you have the option of following the terms and conditions
732: either of that version or of any later version published by the Free
733: Software Foundation. If the Program does not specify a version number of
734: this License, you may choose any version ever published by the Free Software
735: Foundation.
736:
737: @item
738: If you wish to incorporate parts of the Program into other free
739: programs whose distribution conditions are different, write to the author
740: to ask for permission. For software which is copyrighted by the Free
741: Software Foundation, write to the Free Software Foundation; we sometimes
742: make exceptions for this. Our decision will be guided by the two goals
743: of preserving the free status of all derivatives of our free software and
744: of promoting the sharing and reuse of software generally.
745:
746: @iftex
747: @heading NO WARRANTY
748: @end iftex
749: @ifinfo
750: @center NO WARRANTY
751: @end ifinfo
752:
753: @item
754: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
755: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
756: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
757: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
758: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
759: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
760: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
761: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
762: REPAIR OR CORRECTION.
763:
764: @item
765: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
766: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
767: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
768: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
769: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
770: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
771: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
772: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
773: POSSIBILITY OF SUCH DAMAGES.
774: @end enumerate
775:
776: @iftex
777: @heading END OF TERMS AND CONDITIONS
778: @end iftex
779: @ifinfo
780: @center END OF TERMS AND CONDITIONS
781: @end ifinfo
782:
783: @page
784: @unnumberedsec How to Apply These Terms to Your New Programs
785:
786: If you develop a new program, and you want it to be of the greatest
787: possible use to the public, the best way to achieve this is to make it
788: free software which everyone can redistribute and change under these terms.
789:
790: To do so, attach the following notices to the program. It is safest
791: to attach them to the start of each source file to most effectively
792: convey the exclusion of warranty; and each file should have at least
793: the ``copyright'' line and a pointer to where the full notice is found.
794:
795: @smallexample
796: @var{one line to give the program's name and a brief idea of what it does.}
797: Copyright (C) 19@var{yy} @var{name of author}
798:
799: This program is free software; you can redistribute it and/or modify
800: it under the terms of the GNU General Public License as published by
801: the Free Software Foundation; either version 2 of the License, or
802: (at your option) any later version.
803:
804: This program is distributed in the hope that it will be useful,
805: but WITHOUT ANY WARRANTY; without even the implied warranty of
806: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
807: GNU General Public License for more details.
808:
809: You should have received a copy of the GNU General Public License
810: along with this program; if not, write to the Free Software
811: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
812: @end smallexample
813:
814: Also add information on how to contact you by electronic and paper mail.
815:
816: If the program is interactive, make it output a short notice like this
817: when it starts in an interactive mode:
818:
819: @smallexample
820: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
821: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
822: type `show w'.
823: This is free software, and you are welcome to redistribute it
824: under certain conditions; type `show c' for details.
825: @end smallexample
826:
827: The hypothetical commands @samp{show w} and @samp{show c} should show
828: the appropriate parts of the General Public License. Of course, the
829: commands you use may be called something other than @samp{show w} and
830: @samp{show c}; they could even be mouse-clicks or menu items---whatever
831: suits your program.
832:
833: You should also get your employer (if you work as a programmer) or your
834: school, if any, to sign a ``copyright disclaimer'' for the program, if
835: necessary. Here is a sample; alter the names:
836:
837: @smallexample
838: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
839: `Gnomovision' (which makes passes at compilers) written by James Hacker.
840:
841: @var{signature of Ty Coon}, 1 April 1989
842: Ty Coon, President of Vice
843: @end smallexample
844:
845: This General Public License does not permit incorporating your program into
846: proprietary programs. If your program is a subroutine library, you may
847: consider it more useful to permit linking proprietary applications with the
848: library. If this is what you want to do, use the GNU Library General
849: Public License instead of this License.
850:
851: @iftex
852: @unnumbered Preface
853: @cindex Preface
1.21 crook 854: This manual documents Gforth. Some introductory material is provided for
855: readers who are unfamiliar with Forth or who are migrating to Gforth
856: from other Forth compilers. However, this manual is primarily a
857: reference manual.
1.1 anton 858: @end iftex
859:
1.28 crook 860: @comment TODO much more blurb here.
1.26 crook 861:
862: @c ******************************************************************
1.29 crook 863: @node Goals, Gforth Environment, License, Top
1.26 crook 864: @comment node-name, next, previous, up
865: @chapter Goals of Gforth
866: @cindex goals of the Gforth project
867: The goal of the Gforth Project is to develop a standard model for
868: ANS Forth. This can be split into several subgoals:
869:
870: @itemize @bullet
871: @item
872: Gforth should conform to the ANS Forth Standard.
873: @item
874: It should be a model, i.e. it should define all the
875: implementation-dependent things.
876: @item
877: It should become standard, i.e. widely accepted and used. This goal
878: is the most difficult one.
879: @end itemize
880:
881: To achieve these goals Gforth should be
882: @itemize @bullet
883: @item
884: Similar to previous models (fig-Forth, F83)
885: @item
886: Powerful. It should provide for all the things that are considered
887: necessary today and even some that are not yet considered necessary.
888: @item
889: Efficient. It should not get the reputation of being exceptionally
890: slow.
891: @item
892: Free.
893: @item
894: Available on many machines/easy to port.
895: @end itemize
896:
897: Have we achieved these goals? Gforth conforms to the ANS Forth
898: standard. It may be considered a model, but we have not yet documented
899: which parts of the model are stable and which parts we are likely to
900: change. It certainly has not yet become a de facto standard, but it
901: appears to be quite popular. It has some similarities to and some
902: differences from previous models. It has some powerful features, but not
903: yet everything that we envisioned. We certainly have achieved our
904: execution speed goals (@pxref{Performance}). It is free and available
905: on many machines.
906:
907: @menu
908: * Gforth Extensions Sinful?::
909: @end menu
910:
911: @node Gforth Extensions Sinful?, , Goals, Goals
912: @comment node-name, next, previous, up
913: @section Is it a Sin to use Gforth Extensions?
914: @cindex Gforth extensions
915:
916: If you've been paying attention, you will have realised that there is an
917: ANS (American National Standard) for Forth. As you read through the rest
1.29 crook 918: of this manual, you will see documentation for @i{Standard} words, and
919: documentation for some appealing Gforth @i{extensions}. You might ask
920: yourself the question: @i{``Given that there is a standard, would I be
1.26 crook 921: committing a sin to use (non-Standard) Gforth extensions?''}
922:
923: The answer to that question is somewhat pragmatic and somewhat
924: philosophical. Consider these points:
925:
926: @itemize @bullet
927: @item
928: A number of the Gforth extensions can be implemented in ANS Forth using
929: files provided in the @file{compat/} directory. These are mentioned in
930: the text in passing.
931: @item
932: Forth has a rich historical precedent for programmers taking advantage
933: of implementation-dependent features of their tools (for example,
934: relying on a knowledge of the dictionary structure). Sometimes these
935: techniques are necessary to extract every last bit of performance from
936: the hardware, sometimes they are just a programming shorthand.
937: @item
938: The best way to break the rules is to know what the rules are. To learn
939: the rules, there is no substitute for studying the text of the Standard
940: itself. In particular, Appendix A of the Standard (@var{Rationale})
941: provides a valuable insight into the thought processes of the technical
942: committee.
943: @item
944: The best reason to break a rule is because you have to; because it's
945: more productive to do that, because it makes your code run fast enough
946: or because you can see no Standard way to achieve what you want to
947: achieve.
948: @end itemize
949:
950: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
951: analyse your program and determine what non-Standard definitions it
952: relies upon.
953:
1.29 crook 954:
1.26 crook 955: @c ******************************************************************
1.29 crook 956: @node Gforth Environment, Introduction, Goals, Top
957: @chapter Gforth Environment
958: @cindex Gforth environment
1.21 crook 959:
1.29 crook 960: Note: ultimately, the gforth man page will be auto-generated from the
961: material in this chapter.
1.21 crook 962:
963: @menu
1.29 crook 964: * Invoking Gforth:: Getting in
965: * Leaving Gforth:: Getting out
966: * Command-line editing::
967: * Upper and lower case::
968: * Environment variables:: ..that affect how Gforth starts up
969: * Gforth Files:: What gets installed and where
1.21 crook 970: @end menu
971:
1.30 ! anton 972: @xref{Image Files} for related information about the creation of images.
1.29 crook 973:
1.21 crook 974: @comment ----------------------------------------------
1.29 crook 975: @node Invoking Gforth, Leaving Gforth, ,Gforth Environment
976: @section Invoking Gforth
977: @cindex invoking Gforth
978: @cindex running Gforth
979: @cindex command-line options
980: @cindex options on the command line
981: @cindex flags on the command line
1.21 crook 982:
1.30 ! anton 983: Gforth is made up of two parts; an executable ``engine'' (named
! 984: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
! 985: will usually just say @code{gforth} -- this automatically loads the
! 986: default image file @file{gforth.fi}. In many other cases the default
! 987: Gforth image will be invoked like this:
1.21 crook 988: @example
1.30 ! anton 989: gforth [file | -e forth-code] ...
1.21 crook 990: @end example
1.29 crook 991: @noindent
992: This interprets the contents of the files and the Forth code in the order they
993: are given.
1.21 crook 994:
1.30 ! anton 995: In addition to the @file{gforth} engine, there is also an engine called
! 996: @file{gforth-fast}, which is faster, but gives less informative error
! 997: messages (@pxref{Error messages}).
! 998:
1.29 crook 999: In general, the command line looks like this:
1.21 crook 1000:
1001: @example
1.30 ! anton 1002: gforth[-fast] [engine options] [image options]
1.21 crook 1003: @end example
1004:
1.30 ! anton 1005: The engine options must come before the rest of the command
1.29 crook 1006: line. They are:
1.26 crook 1007:
1.29 crook 1008: @table @code
1009: @cindex -i, command-line option
1010: @cindex --image-file, command-line option
1011: @item --image-file @i{file}
1012: @itemx -i @i{file}
1013: Loads the Forth image @i{file} instead of the default
1014: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 1015:
1.29 crook 1016: @cindex --path, command-line option
1017: @cindex -p, command-line option
1018: @item --path @i{path}
1019: @itemx -p @i{path}
1020: Uses @i{path} for searching the image file and Forth source code files
1021: instead of the default in the environment variable @code{GFORTHPATH} or
1022: the path specified at installation time (e.g.,
1023: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
1024: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 1025:
1.29 crook 1026: @cindex --dictionary-size, command-line option
1027: @cindex -m, command-line option
1028: @cindex @i{size} parameters for command-line options
1029: @cindex size of the dictionary and the stacks
1030: @item --dictionary-size @i{size}
1031: @itemx -m @i{size}
1032: Allocate @i{size} space for the Forth dictionary space instead of
1033: using the default specified in the image (typically 256K). The
1034: @i{size} specification for this and subsequent options consists of
1035: an integer and a unit (e.g.,
1036: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
1037: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
1038: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
1039: @code{e} is used.
1.21 crook 1040:
1.29 crook 1041: @cindex --data-stack-size, command-line option
1042: @cindex -d, command-line option
1043: @item --data-stack-size @i{size}
1044: @itemx -d @i{size}
1045: Allocate @i{size} space for the data stack instead of using the
1046: default specified in the image (typically 16K).
1.21 crook 1047:
1.29 crook 1048: @cindex --return-stack-size, command-line option
1049: @cindex -r, command-line option
1050: @item --return-stack-size @i{size}
1051: @itemx -r @i{size}
1052: Allocate @i{size} space for the return stack instead of using the
1053: default specified in the image (typically 15K).
1.21 crook 1054:
1.29 crook 1055: @cindex --fp-stack-size, command-line option
1056: @cindex -f, command-line option
1057: @item --fp-stack-size @i{size}
1058: @itemx -f @i{size}
1059: Allocate @i{size} space for the floating point stack instead of
1060: using the default specified in the image (typically 15.5K). In this case
1061: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 1062:
1.29 crook 1063: @cindex --locals-stack-size, command-line option
1064: @cindex -l, command-line option
1065: @item --locals-stack-size @i{size}
1066: @itemx -l @i{size}
1067: Allocate @i{size} space for the locals stack instead of using the
1068: default specified in the image (typically 14.5K).
1.21 crook 1069:
1.29 crook 1070: @cindex -h, command-line option
1071: @cindex --help, command-line option
1072: @item --help
1073: @itemx -h
1074: Print a message about the command-line options
1.21 crook 1075:
1.29 crook 1076: @cindex -v, command-line option
1077: @cindex --version, command-line option
1078: @item --version
1079: @itemx -v
1080: Print version and exit
1.21 crook 1081:
1.29 crook 1082: @cindex --debug, command-line option
1083: @item --debug
1084: Print some information useful for debugging on startup.
1.21 crook 1085:
1.29 crook 1086: @cindex --offset-image, command-line option
1087: @item --offset-image
1088: Start the dictionary at a slightly different position than would be used
1089: otherwise (useful for creating data-relocatable images,
1090: @pxref{Data-Relocatable Image Files}).
1.21 crook 1091:
1.29 crook 1092: @cindex --no-offset-im, command-line option
1093: @item --no-offset-im
1094: Start the dictionary at the normal position.
1.21 crook 1095:
1.29 crook 1096: @cindex --clear-dictionary, command-line option
1097: @item --clear-dictionary
1098: Initialize all bytes in the dictionary to 0 before loading the image
1099: (@pxref{Data-Relocatable Image Files}).
1100:
1101: @cindex --die-on-signal, command-line-option
1102: @item --die-on-signal
1103: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
1104: or the segmentation violation SIGSEGV) by translating it into a Forth
1105: @code{THROW}. With this option, Gforth exits if it receives such a
1106: signal. This option is useful when the engine and/or the image might be
1107: severely broken (such that it causes another signal before recovering
1108: from the first); this option avoids endless loops in such cases.
1109: @end table
1110:
1111: @cindex loading files at startup
1112: @cindex executing code on startup
1113: @cindex batch processing with Gforth
1114: As explained above, the image-specific command-line arguments for the
1115: default image @file{gforth.fi} consist of a sequence of filenames and
1116: @code{-e @var{forth-code}} options that are interpreted in the sequence
1117: in which they are given. The @code{-e @var{forth-code}} or
1118: @code{--evaluate @var{forth-code}} option evaluates the Forth
1119: code. This option takes only one argument; if you want to evaluate more
1120: Forth words, you have to quote them or use @code{-e} several times. To exit
1121: after processing the command line (instead of entering interactive mode)
1122: append @code{-e bye} to the command line.
1123:
1124: @cindex versions, invoking other versions of Gforth
1125: If you have several versions of Gforth installed, @code{gforth} will
1126: invoke the version that was installed last. @code{gforth-@i{version}}
1127: invokes a specific version. You may want to use the option
1128: @code{--path}, if your environment contains the variable
1129: @code{GFORTHPATH}.
1130:
1131: Not yet implemented:
1132: On startup the system first executes the system initialization file
1133: (unless the option @code{--no-init-file} is given; note that the system
1134: resulting from using this option may not be ANS Forth conformant). Then
1135: the user initialization file @file{.gforth.fs} is executed, unless the
1136: option @code{--no-rc} is given; this file is first searched in @file{.},
1137: then in @file{~}, then in the normal path (see above).
1.21 crook 1138:
1139:
1140:
1.29 crook 1141: @comment ----------------------------------------------
1142: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
1143: @section Leaving Gforth
1144: @cindex Gforth - leaving
1145: @cindex leaving Gforth
1.21 crook 1146:
1.30 ! anton 1147: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
! 1148: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
! 1149: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
! 1150: data are discarded. @xref{Image Files} for ways of saving the state of
! 1151: the system before leaving Gforth.
1.21 crook 1152:
1.29 crook 1153: doc-bye
1.21 crook 1154:
1.29 crook 1155: @comment ----------------------------------------------
1156: @node Command-line editing, Upper and lower case,Leaving Gforth,Gforth Environment
1157: @section Command-line editing
1158: @cindex command-line editing
1.21 crook 1159:
1.29 crook 1160: Gforth maintains a history file that records every line that you type to
1161: the text interpreter. This file is preserved between sessions, and is
1162: used to provide a command-line recall facility; if you type ctrl-P
1163: repeatedly you can recall successively older commands from this (or
1164: previous) session(s). The full list of command-line editing facilities is:
1.21 crook 1165:
1.30 ! anton 1166: @comment use @table? - anton
1.21 crook 1167: @itemize @bullet
1168: @item
1.30 ! anton 1169: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
1.29 crook 1170: commands from the history buffer.
1171: @item
1.30 ! anton 1172: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
1.29 crook 1173: from the history buffer.
1174: @item
1.30 ! anton 1175: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
1.29 crook 1176: @item
1.30 ! anton 1177: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
1.29 crook 1178: @item
1.30 ! anton 1179: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
1.29 crook 1180: closing up the line.
1181: @item
1.30 ! anton 1182: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
1.29 crook 1183: @item
1.30 ! anton 1184: @kbd{Ctrl-a} to move the cursor to the start of the line.
1.21 crook 1185: @item
1.30 ! anton 1186: @kbd{Ctrl-e} to move the cursor to the end of the line.
1.21 crook 1187: @item
1.30 ! anton 1188: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
1.29 crook 1189: line.
1.21 crook 1190: @item
1.30 ! anton 1191: @key{TAB} to step through all possible full-word completions of the word
1.29 crook 1192: currently being typed.
1.21 crook 1193: @item
1.30 ! anton 1194: @kbd{Ctrl-d} at the start of the line to terminate Gforth (gracefully,
! 1195: using @code{bye}).
1.21 crook 1196: @end itemize
1197:
1.29 crook 1198: When editing, displayable characters are inserted to the left of the
1199: cursor position; the line is always in ``insert'' (as opposed to
1200: ``overstrike'') mode.
1201:
1202: @cindex history file
1203: @cindex @file{.gforth-history}
1204: On Unix systems, the history file is @file{~/.gforth-history} by
1205: default@footnote{i.e. it is stored in the user's home directory.}. You
1206: can find out the name and location of your history file using:
1207:
1208: @example
1209: history-file type \ Unix-class systems
1.21 crook 1210:
1.29 crook 1211: history-file type \ Other systems
1212: history-dir type
1.21 crook 1213: @end example
1214:
1.29 crook 1215: If you enter long definitions by hand, you can use a text editor to
1216: paste them out of the history file into a Forth source file for reuse at
1217: a later time.
1218:
1219: Gforth never trims the size of the history file, so you should do this
1220: periodically, if necessary.
1221:
1222: @comment this is all defined in history.fs
1223:
1224:
1225:
1226: @comment ----------------------------------------------
1227: @node Upper and lower case, Environment variables,Command-line editing,Gforth Environment
1228: @section Upper and lower case
1229: @cindex case-sensitivity
1230: @cindex upper and lower case
1231:
1232: Gforth is case-insensitive, so you can enter definitions and invoke
1233: Standard words using upper, lower or mixed case (however,
1234: @pxref{core-idef, Implementation-defined options, Implementation-defined
1235: options}).
1236:
1.30 ! anton 1237: ANS Forth only @i{requires} implementations to recognise Standard words
! 1238: when they are typed entirely in upper case. Therefore, a Standard
! 1239: program must use upper case for all Standard words. You can use whatever
! 1240: case you like for words that you define, but in a standard program you
! 1241: have to use the words in the same case that you defined them.
! 1242:
! 1243: Gforth supports case sensitivity through @code{table}s (case-sensitive
! 1244: wordlists, @pxref{Word Lists}).
! 1245:
! 1246: Two people have asked how to convert Gforth to case sensitivity; while
! 1247: we think this is a bad idea, you can change all wordlists into tables
! 1248: like this:
1.29 crook 1249:
1.30 ! anton 1250: @example
! 1251: ' table-find forth-wordlist wordlist-map @ !
! 1252: @end example
! 1253:
! 1254: Note that you now have to type the predefined words in the same case
! 1255: that we defined them, which are varying. You may want to convert them
! 1256: to your favourite case before doing this operation (I won't explain how,
! 1257: because if you are even contemplating to do this, you'd better have
! 1258: enough knowledge of Forth systems to know this already).
1.29 crook 1259:
1260: @comment ----------------------------------------------
1261: @node Environment variables, Gforth Files, Upper and lower case,Gforth Environment
1262: @section Environment variables
1263: @cindex environment variables
1.21 crook 1264:
1.29 crook 1265: Gforth uses these environment variables:
1.21 crook 1266:
1.29 crook 1267: @itemize @bullet
1268: @item
1269: @cindex GFORTHHIST - environment variable
1270: GFORTHHIST - (Unix systems only) specifies the directory in which to
1271: open/create the history file, @file{.gforth-history}. Default:
1272: @code{$HOME}.
1.21 crook 1273:
1.29 crook 1274: @item
1275: @cindex GFORTHPATH - environment variable
1276: GFORTHPATH - specifies the path used when searching for the gforth image file and
1277: for Forth source-code files.
1.21 crook 1278:
1.29 crook 1279: @item
1280: @cindex GFORTH - environment variable
1281: GFORTH - used by @file{gforthmi} @xref{gforthmi}.
1.26 crook 1282:
1.29 crook 1283: @item
1284: @cindex GFORTHD - environment variable
1285: GFORTHD - used by @file{gforthmi} @xref{gforthmi}.
1.21 crook 1286:
1.29 crook 1287: @item
1288: @cindex TMP, TEMP - environment variable
1289: TMP, TEMP - (non-Unix systems only) used as a potential location for the
1290: history file.
1291: @end itemize
1.21 crook 1292:
1.29 crook 1293: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1294: @comment mentioning these.
1.21 crook 1295:
1.29 crook 1296: All the Gforth environment variables default to sensible values if they
1297: are not set.
1.21 crook 1298:
1299:
1.29 crook 1300: @comment ----------------------------------------------
1301: @node Gforth Files, ,Environment variables,Gforth Environment
1302: @section Gforth files
1303: @cindex Gforth files
1.21 crook 1304:
1.30 ! anton 1305: When you Gforth on a Unix system in the default places, it installs
! 1306: files in these locations:
1.21 crook 1307:
1.26 crook 1308: @itemize @bullet
1309: @item
1.29 crook 1310: @file{/usr/local/bin/gforth}
1311: @item
1312: @file{/usr/local/bin/gforthmi}
1313: @item
1314: @file{/usr/local/man/man1/gforth.1} - man page.
1315: @item
1316: @file{/usr/local/info} - the Info version of this manual.
1317: @item
1.30 ! anton 1318: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1.29 crook 1319: @item
1320: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1.26 crook 1321: @item
1.30 ! anton 1322: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1.26 crook 1323: @item
1.30 ! anton 1324: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1.26 crook 1325: @end itemize
1.21 crook 1326:
1.30 ! anton 1327: You can select different places for installation by using
! 1328: @code{configure} options (listed with @code{configure --help}).
1.21 crook 1329:
1.29 crook 1330: @c ******************************************************************
1331: @node Introduction, Words, Gforth Environment, Top
1332: @comment node-name, next, previous, up
1333: @chapter An Introduction to ANS Forth
1334: @cindex Forth - an introduction
1.21 crook 1335:
1.29 crook 1336: The primary purpose of this manual is to document Gforth. However, since
1337: Forth is not a widely-known language and there is a lack of up-to-date
1338: teaching material, it seems worthwhile to provide some introductory
1339: material. @xref{Forth-related information} for other sources of Forth-related
1340: information.
1.21 crook 1341:
1.29 crook 1342: The examples in this section should work on any ANS Forth; the
1343: output shown was produced using Gforth. Each example attempts to
1344: reproduce the exact output that Gforth produces. If you try out the
1345: examples (and you should), what you should type is shown @kbd{like this}
1346: and Gforth's response is shown @code{like this}. The single exception is
1.30 ! anton 1347: that, where the example shows @key{RET} it means that you should
1.29 crook 1348: press the ``carriage return'' key. Unfortunately, some output formats for
1349: this manual cannot show the difference between @kbd{this} and
1350: @code{this} which will make trying out the examples harder (but not
1351: impossible).
1.21 crook 1352:
1.29 crook 1353: Forth is an unusual language. It provides an interactive development
1354: environment which includes both an interpreter and compiler. Forth
1355: programming style encourages you to break a problem down into many
1356: @cindex factoring
1357: small fragments (@dfn{factoring}), and then to develop and test each
1358: fragment interactively. Forth advocates assert that breaking the
1359: edit-compile-test cycle used by conventional programming languages can
1360: lead to great productivity improvements.
1.21 crook 1361:
1.29 crook 1362: @menu
1363: * Introducing the Text Interpreter::
1364: * Stacks and Postfix notation::
1365: * Your first definition::
1366: * How does that work?::
1367: * Forth is written in Forth::
1368: * Review - elements of a Forth system::
1369: * Where to go next::
1370: * Exercises::
1371: @end menu
1.21 crook 1372:
1.29 crook 1373: @comment ----------------------------------------------
1374: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
1375: @section Introducing the Text Interpreter
1376: @cindex text interpreter
1377: @cindex outer interpreter
1.21 crook 1378:
1.30 ! anton 1379: @c IMO this is too detailed and the pace is too slow for
! 1380: @c an introduction. If you know German, take a look at
! 1381: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
! 1382: @c to see how I do it - anton
! 1383:
1.29 crook 1384: When you invoke the Forth image, you will see a startup banner printed
1385: and nothing else (if you have Gforth installed on your system, try
1.30 ! anton 1386: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 1387: its command line interpreter, which is called the @dfn{Text Interpreter}
1388: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.30 ! anton 1389: about the text interpreter as you read through this chapter, but
! 1390: @pxref{The Text Interpreter} for more detail).
1.21 crook 1391:
1.29 crook 1392: Although it's not obvious, Forth is actually waiting for your
1.30 ! anton 1393: input. Type a number and press the @key{RET} key:
1.21 crook 1394:
1.26 crook 1395: @example
1.30 ! anton 1396: @kbd{45@key{RET}} ok
1.26 crook 1397: @end example
1.21 crook 1398:
1.29 crook 1399: Rather than give you a prompt to invite you to input something, the text
1400: interpreter prints a status message @i{after} it has processed a line
1401: of input. The status message in this case (``@code{ ok}'' followed by
1402: carriage-return) indicates that the text interpreter was able to process
1403: all of your input successfully. Now type something illegal:
1404:
1405: @example
1.30 ! anton 1406: @kbd{qwer341@key{RET}}
1.29 crook 1407: :1: Undefined word
1408: qwer341
1409: ^^^^^^^
1410: $400D2BA8 Bounce
1411: $400DBDA8 no.extensions
1412: @end example
1.23 crook 1413:
1.29 crook 1414: The exact text, other than the ``Undefined word'' may differ slightly on
1415: your system, but the effect is the same; when the text interpreter
1416: detects an error, it discards any remaining text on a line, resets
1.30 ! anton 1417: certain internal state and prints an error message. @xref{Error
! 1418: messages} for a detailed description of error messages.
1.23 crook 1419:
1.29 crook 1420: The text interpreter waits for you to press carriage-return, and then
1421: processes your input line. Starting at the beginning of the line, it
1422: breaks the line into groups of characters separated by spaces. For each
1423: group of characters in turn, it makes two attempts to do something:
1.23 crook 1424:
1.29 crook 1425: @itemize @bullet
1426: @item
1427: It tries to treat it as a command. It does this by searching a @dfn{name
1428: dictionary}. If the group of characters matches an entry in the name
1429: dictionary, the name dictionary provides the text interpreter with
1430: information that allows the text interpreter perform some actions. In
1431: Forth jargon, we say that the group
1432: @cindex word
1433: @cindex definition
1434: @cindex execution token
1435: @cindex xt
1436: of characters names a @dfn{word}, that the dictionary search returns an
1437: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
1438: word, and that the text interpreter executes the xt. Often, the terms
1439: @dfn{word} and @dfn{definition} are used interchangeably.
1440: @item
1441: If the text interpreter fails to find a match in the name dictionary, it
1442: tries to treat the group of characters as a number in the current number
1443: base (when you start up Forth, the current number base is base 10). If
1444: the group of characters legitimately represents a number, the text
1445: interpreter pushes the number onto a stack (we'll learn more about that
1446: in the next section).
1447: @end itemize
1.23 crook 1448:
1.29 crook 1449: If the text interpreter is unable to do either of these things with any
1450: group of characters, it discards the group of characters and the rest of
1451: the line, then prints an error message. If the text interpreter reaches
1452: the end of the line without error, it prints the status message ``@code{ ok}''
1453: followed by carriage-return.
1.21 crook 1454:
1.29 crook 1455: This is the simplest command we can give to the text interpreter:
1.23 crook 1456:
1457: @example
1.30 ! anton 1458: @key{RET} ok
1.23 crook 1459: @end example
1.21 crook 1460:
1.29 crook 1461: The text interpreter did everything we asked it to do (nothing) without
1462: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
1463: command:
1.21 crook 1464:
1.23 crook 1465: @example
1.30 ! anton 1466: @kbd{12 dup fred dup@key{RET}}
1.29 crook 1467: :1: Undefined word
1468: 12 dup fred dup
1469: ^^^^
1470: $400D2BA8 Bounce
1471: $400DBDA8 no.extensions
1.23 crook 1472: @end example
1.21 crook 1473:
1.29 crook 1474: When you press the carriage-return key, the text interpreter starts to
1475: work its way along the line:
1.21 crook 1476:
1.29 crook 1477: @itemize @bullet
1478: @item
1479: When it gets to the space after the @code{2}, it takes the group of
1480: characters @code{12} and looks them up in the name
1481: dictionary@footnote{We can't tell if it found them or not, but assume
1482: for now that it did not}. There is no match for this group of characters
1483: in the name dictionary, so it tries to treat them as a number. It is
1484: able to do this successfully, so it puts the number, 12, ``on the stack''
1485: (whatever that means).
1486: @item
1487: The text interpreter resumes scanning the line and gets the next group
1488: of characters, @code{dup}. It looks it up in the name dictionary and
1489: (you'll have to take my word for this) finds it, and executes the word
1490: @code{dup} (whatever that means).
1491: @item
1492: Once again, the text interpreter resumes scanning the line and gets the
1493: group of characters @code{fred}. It looks them up in the name
1494: dictionary, but can't find them. It tries to treat them as a number, but
1495: they don't represent any legal number.
1496: @end itemize
1.21 crook 1497:
1.29 crook 1498: At this point, the text interpreter gives up and prints an error
1499: message. The error message shows exactly how far the text interpreter
1500: got in processing the line. In particular, it shows that the text
1501: interpreter made no attempt to do anything with the final character
1502: group, @code{dup}, even though we have good reason to believe that the
1503: text interpreter would have no problem looking that word up and
1504: executing it a second time.
1.21 crook 1505:
1506:
1.29 crook 1507: @comment ----------------------------------------------
1508: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
1509: @section Stacks, postfix notation and parameter passing
1510: @cindex text interpreter
1511: @cindex outer interpreter
1.21 crook 1512:
1.29 crook 1513: In procedural programming languages (like C and Pascal), the
1514: building-block of programs is the @dfn{function} or @dfn{procedure}. These
1515: functions or procedures are called with @dfn{explicit parameters}. For
1516: example, in C we might write:
1.21 crook 1517:
1.23 crook 1518: @example
1.29 crook 1519: total = total + new_volume(length,height,depth);
1.23 crook 1520: @end example
1.21 crook 1521:
1.23 crook 1522: @noindent
1.29 crook 1523: where new_volume is a function-call to another piece of code, and total,
1524: length, height and depth are all variables. length, height and depth are
1525: parameters to the function-call.
1.21 crook 1526:
1.29 crook 1527: In Forth, the equivalent of the function or procedure is the
1528: @dfn{definition} and parameters are implicitly passed between
1529: definitions using a shared stack that is visible to the
1530: programmer. Although Forth does support variables, the existence of the
1531: stack means that they are used far less often than in most other
1532: programming languages. When the text interpreter encounters a number, it
1533: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 ! anton 1534: actual number is implementation-dependent ...) and the particular stack
1.29 crook 1535: used for any operation is implied unambiguously by the operation being
1536: performed. The stack used for all integer operations is called the @dfn{data
1537: stack} and, since this is the stack used most commonly, references to
1538: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 1539:
1.29 crook 1540: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 1541:
1.23 crook 1542: @example
1.30 ! anton 1543: @kbd{1 2 3@key{RET}} ok
1.23 crook 1544: @end example
1.21 crook 1545:
1.29 crook 1546: Then this instructs the text interpreter to placed three numbers on the
1547: (data) stack. An analogy for the behaviour of the stack is to take a
1548: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
1549: the table. The 3 was the last card onto the pile (``last-in'') and if
1550: you take a card off the pile then, unless you're prepared to fiddle a
1551: bit, the card that you take off will be the 3 (``first-out''). The
1552: number that will be first-out of the stack is called the @dfn{top of
1553: stack}, which
1554: @cindex TOS definition
1555: is often abbreviated to @dfn{TOS}.
1.21 crook 1556:
1.29 crook 1557: To understand how parameters are passed in Forth, consider the
1558: behaviour of the definition @code{+} (pronounced ``plus''). You will not
1559: be surprised to learn that this definition performs addition. More
1560: precisely, it adds two number together and produces a result. Where does
1561: it get the two numbers from? It takes the top two numbers off the
1562: stack. Where does it place the result? On the stack. You can act-out the
1563: behaviour of @code{+} with your playing cards like this:
1.21 crook 1564:
1565: @itemize @bullet
1566: @item
1.29 crook 1567: Pick up two cards from the stack on the table
1.21 crook 1568: @item
1.29 crook 1569: Stare at them intently and ask yourself ``what @i{is} the sum of these two
1570: numbers''
1.21 crook 1571: @item
1.29 crook 1572: Decide that the answer is 5
1.21 crook 1573: @item
1.29 crook 1574: Shuffle the two cards back into the pack and find a 5
1.21 crook 1575: @item
1.29 crook 1576: Put a 5 on the remaining ace that's on the table.
1.21 crook 1577: @end itemize
1578:
1.29 crook 1579: If you don't have a pack of cards handy but you do have Forth running,
1580: you can use the definition @code{.s} to show the current state of the stack,
1581: without affecting the stack. Type:
1.21 crook 1582:
1583: @example
1.30 ! anton 1584: @kbd{clearstack 1 2 3@key{RET}} ok
! 1585: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 1586: @end example
1587:
1.29 crook 1588: The text interpreter looks up the word @code{clearstack} and executes
1589: it; it tidies up the stack and removes any entries that may have been
1590: left on it by earlier examples. The text interpreter pushes each of the
1591: three numbers in turn onto the stack. Finally, the text interpreter
1592: looks up the word @code{.s} and executes it. The effect of executing
1593: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
1594: followed by a list of all the items on the stack; the item on the far
1595: right-hand side is the TOS.
1.21 crook 1596:
1.29 crook 1597: You can now type:
1.21 crook 1598:
1.29 crook 1599: @example
1.30 ! anton 1600: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 1601: @end example
1.21 crook 1602:
1.29 crook 1603: @noindent
1604: which is correct; there are now 2 items on the stack and the result of
1605: the addition is 5.
1.23 crook 1606:
1.29 crook 1607: If you're playing with cards, try doing a second addition: pick up the
1608: two cards, work out that their sum is 6, shuffle them into the pack,
1609: look for a 6 and place that on the table. You now have just one item on
1610: the stack. What happens if you try to do a third addition? Pick up the
1611: first card, pick up the second card -- ah! There is no second card. This
1612: is called a @dfn{stack underflow} and consitutes an error. If you try to
1613: do the same thing with Forth it will report an error (probably a Stack
1614: Underflow or an Invalid Memory Address error).
1.23 crook 1615:
1.29 crook 1616: The opposite situation to a stack underflow is a @dfn{stack overflow},
1617: which simply accepts that there is a finite amount of storage space
1618: reserved for the stack. To stretch the playing card analogy, if you had
1619: enough packs of cards and you piled the cards up on the table, you would
1620: eventually be unable to add another card; you'd hit the ceiling. Gforth
1621: allows you to set the maximum size of the stacks. In general, the only
1622: time that you will get a stack overflow is because a definition has a
1623: bug in it and is generating data on the stack uncontrollably.
1.23 crook 1624:
1.29 crook 1625: There's one final use for the playing card analogy. If you model your
1626: stack using a pack of playing cards, the maximum number of items on
1627: your stack will be 52 (I assume you didn't use the Joker). The maximum
1628: @i{value} of any item on the stack is 13 (the King). In fact, the only
1629: possible numbers are positive integer numbers 1 through 13; you can't
1630: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
1631: think about some of the cards, you can accommodate different
1632: numbers. For example, you could think of the Jack as representing 0,
1633: the Queen as representing -1 and the King as representing -2. Your
1634: *range* remains unchanged (you can still only represent a total of 13
1635: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 1636:
1.29 crook 1637: In that analogy, the limit was the amount of information that a single
1638: stack entry could hold, and Forth has a similar limit. In Forth, the
1639: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
1640: implementation dependent and affects the maximum value that a stack
1641: entry can hold. A Standard Forth provides a cell size of at least
1642: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 1643:
1.29 crook 1644: Forth does not do any type checking for you, so you are free to
1645: manipulate and combine stack items in any way you wish. A convenient way
1646: of treating stack items is as 2's complement signed integers, and that
1647: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 1648:
1.29 crook 1649: @example
1.30 ! anton 1650: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 1651: @end example
1.21 crook 1652:
1.29 crook 1653: If you use numbers and definitions like @code{+} in order to turn Forth
1654: into a great big pocket calculator, you will realise that it's rather
1655: different from a normal calculator. Rather than typing 2 + 3 = you had
1656: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
1657: result). The terminology used to describe this difference is to say that
1658: your calculator uses @dfn{Infix Notation} (parameters and operators are
1659: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
1660: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 1661:
1.29 crook 1662: Whilst postfix notation might look confusing to begin with, it has
1663: several important advantages:
1.21 crook 1664:
1.23 crook 1665: @itemize @bullet
1666: @item
1.29 crook 1667: it is unambiguous
1.23 crook 1668: @item
1.29 crook 1669: it is more concise
1.23 crook 1670: @item
1.29 crook 1671: it fits naturally with a stack-based system
1.23 crook 1672: @end itemize
1.21 crook 1673:
1.29 crook 1674: To examine these claims in more detail, consider these sums:
1.21 crook 1675:
1.29 crook 1676: @example
1677: 6 + 5 * 4 =
1678: 4 * 5 + 6 =
1679: @end example
1.21 crook 1680:
1.29 crook 1681: If you're just learning maths or your maths is very rusty, you will
1682: probably come up with the answer 44 for the first and 26 for the
1683: second. If you are a bit of a whizz at maths you will remember the
1684: @i{convention} that multiplication takes precendence over addition, and
1685: you'd come up with the answer 26 both times. To explain the answer 26
1686: to someone who got the answer 44, you'd probably rewrite the first sum
1687: like this:
1.21 crook 1688:
1.29 crook 1689: @example
1690: 6 + (5 * 4) =
1691: @end example
1.21 crook 1692:
1.29 crook 1693: If what you really wanted was to perform the addition before the
1694: multiplication, you would have to use parentheses to force it.
1.21 crook 1695:
1.29 crook 1696: If you did the first two sums on a pocket calculator you would probably
1697: get the right answers, unless you were very cautious and entered them using
1698: these keystroke sequences:
1.21 crook 1699:
1.29 crook 1700: 6 + 5 = * 4 =
1701: 4 * 5 = + 6 =
1.21 crook 1702:
1.29 crook 1703: Postfix notation is unambiguous because the order that the operators
1704: are applied is always explicit; that also means that parentheses are
1705: never required. The operators are @i{active} (the act of quoting the
1706: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 1707:
1.29 crook 1708: The sum 6 + 5 * 4 can be written (in postfix notation) in two
1709: equivalent ways:
1.26 crook 1710:
1711: @example
1.29 crook 1712: 6 5 4 * + or:
1713: 5 4 * 6 +
1.26 crook 1714: @end example
1.23 crook 1715:
1.29 crook 1716: An important thing that you should notice about this notation is that
1717: the @i{order} of the numbers does not change; if you want to subtract
1718: 2 from 10 you type @code{10 2 -}.
1.1 anton 1719:
1.29 crook 1720: The reason that Forth uses postfix notation is very simple to explain: it
1721: makes the implementation extremely simple, and it follows naturally from
1722: using the stack as a mechanism for passing parameters. Another way of
1723: thinking about this is to realise that all Forth definitions are
1724: @i{active}; they execute as they are encountered by the text
1725: interpreter. The result of this is that the syntax of Forth is trivially
1726: simple.
1.1 anton 1727:
1728:
1729:
1.29 crook 1730: @comment ----------------------------------------------
1731: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
1732: @section Your first Forth definition
1733: @cindex first definition
1.1 anton 1734:
1.29 crook 1735: Until now, the examples we've seen have been trivial; we've just been
1736: using Forth as a bigger-than-pocket calculator. Also, each calculation
1737: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
1738: again@footnote{That's not quite true. If you press the up-arrow key on
1739: your keyboard you should be able to scroll back to any earlier command,
1740: edit it and re-enter it.} In this section we'll see how to add new
1741: words to Forth's vocabulary.
1.1 anton 1742:
1.29 crook 1743: The easiest way to create a new word is to use a @dfn{colon
1744: definition}. We'll define a few and try them out before worrying too
1745: much about how they work. Try typing in these examples; be careful to
1746: copy the spaces accurately:
1.1 anton 1747:
1.29 crook 1748: @example
1749: : add-two 2 + . ;
1750: : greet ." Hello and welcome" ;
1751: : demo 5 add-two ;
1752: @end example
1.1 anton 1753:
1.29 crook 1754: @noindent
1755: Now try them out:
1.1 anton 1756:
1.29 crook 1757: @example
1.30 ! anton 1758: @kbd{greet@key{RET}} Hello and welcome ok
! 1759: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
! 1760: @kbd{4 add-two@key{RET}} 6 ok
! 1761: @kbd{demo@key{RET}} 7 ok
! 1762: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 1763: @end example
1.1 anton 1764:
1.29 crook 1765: The first new thing that we've introduced here is the pair of words
1766: @code{:} and @code{;}. These are used to start and terminate a new
1767: definition, respectively. The first word after the @code{:} is the name
1768: for the new definition.
1.1 anton 1769:
1.29 crook 1770: As you can see from the examples, a definition is built up of words that
1771: have already been defined; Forth makes no distinction between
1772: definitions that existed when you started the system up, and those that
1773: you define yourself.
1.1 anton 1774:
1.29 crook 1775: The examples also introduce the words @code{.} (dot), @code{."}
1776: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
1777: the stack and displays it. It's like @code{.s} except that it only
1778: displays the top item of the stack and it is destructive; after it has
1779: executed, the number is no longer on the stack. There is always one
1780: space printed after the number, and no spaces before it. Dot-quote
1781: defines a string (a sequence of characters) that will be printed when
1782: the word is executed. The string can contain any printable characters
1783: except @code{"}. A @code{"} has a special function; it is not a Forth
1784: word but it acts as a delimiter (the way that delimiters work is
1785: described in the next section). Finally, @code{dup} duplicates the value
1786: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 1787:
1.29 crook 1788: We already know that the text interpreter searches through the
1789: dictionary to locate names. If you've followed the examples earlier, you
1790: will already have a definition called @code{add-two}. Lets try modifying
1791: it by typing in a new definition:
1.1 anton 1792:
1.29 crook 1793: @example
1.30 ! anton 1794: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 1795: @end example
1.5 anton 1796:
1.29 crook 1797: Forth recognised that we were defining a word that already exists, and
1798: printed a message to warn us of that fact. Let's try out the new
1799: definition:
1.5 anton 1800:
1.29 crook 1801: @example
1.30 ! anton 1802: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 1803: @end example
1.1 anton 1804:
1.29 crook 1805: @noindent
1806: All that we've actually done here, though, is to create a new
1807: definition, with a particular name. The fact that there was already a
1808: definition with the same name did not make any difference to the way
1809: that the new definition was created (except that Forth printed a warning
1810: message). The old definition of add-two still exists (try @code{demo}
1811: again to see that this is true). Any new definition will use the new
1812: definition of @code{add-two}, but old definitions continue to use the
1813: version that already existed at the time that they were @code{compiled}.
1.1 anton 1814:
1.29 crook 1815: Before you go on to the next section, try defining and redefining some
1816: words of your own.
1.1 anton 1817:
1.29 crook 1818: @comment ----------------------------------------------
1819: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
1820: @section How does that work?
1821: @cindex parsing words
1.1 anton 1822:
1.30 ! anton 1823: @c That's pretty deep (IMO way too deep) for an introduction. - anton
! 1824:
! 1825: @c Is it a good idea to talk about the interpretation semantics of a
! 1826: @c number? We don't have an xt to go along with it. - anton
! 1827:
! 1828: @c Now that I have eliminated execution semantics, I wonder if it would not
! 1829: @c be better to keep them (or add run-time semantics), to make it easier to
! 1830: @c explain what compilation semantics usually does. - anton
! 1831:
1.29 crook 1832: Now we're going to take another look at the definition of @code{add-two}
1833: from the previous section. From our knowledge of the way that the text
1834: interpreter works, we would have expected this result when we tried to
1835: define @code{add-two}:
1.21 crook 1836:
1.29 crook 1837: @example
1.30 ! anton 1838: @kbd{: add-two 2 + . " ;@key{RET}}
1.29 crook 1839: ^^^^^^^
1840: Error: Undefined word
1841: @end example
1.28 crook 1842:
1.29 crook 1843: The reason that this didn't happen is bound up in the way that @code{:}
1844: works. The word @code{:} does two special things. The first special
1845: thing that it does prevents the text interpreter from ever seeing the
1846: characters @code{add-two}. The text interpreter uses a variable called
1847: @cindex modifying >IN
1848: @code{>IN} (pronounced ''to-in'') to keep track of where it is in the
1849: input line. When it encounters the word @code{:} it behaves in exactly
1850: the same way as it does for any other word; it looks it up in the name
1851: dictionary, finds its xt and executes it. When @code{:} executes, it
1852: looks at the input buffer, finds the word @code{add-two} and advances the
1853: value of @code{>IN} to point past it. It then does some other stuff
1854: associated with creating the new definition (including creating an entry
1855: for @code{add-two} in the name dictionary). When the execution of @code{:}
1856: completes, control returns to the text interpreter, which is oblivious
1857: to the fact that it has been tricked into ignoring part of the input
1858: line.
1.21 crook 1859:
1.29 crook 1860: @cindex parsing words
1861: Words like @code{:} -- words that advance the value of @code{>IN} and so
1862: prevent the text interpreter from acting on the whole of the input line
1863: -- are called @dfn{parsing words}.
1.21 crook 1864:
1.29 crook 1865: @cindex @code{state} - effect on the text interpreter
1866: @cindex text interpreter - effect of state
1867: The second special thing that @code{:} does is change the value of a
1868: variable called @code{state}, which affects the way that the text
1869: interpreter behaves. When Gforth starts up, @code{state} has the value
1870: 0, and the text interpreter is said to be @dfn{interpreting}. During a
1871: colon definition (started with @code{:}), @code{state} is set to -1 and
1872: the text interpreter is said to be @dfn{compiling}. The word @code{;}
1873: ends the definition -- one of the things that it does is to change the
1874: value of @code{state} back to 0.
1.21 crook 1875:
1.29 crook 1876: We have already seen how the text interpreter behaves when it is
1877: interpreting; it looks for each character sequence in the dictionary,
1878: finds its xt and executes it, or it converts it to a number and pushes
1879: it onto the stack, or it fails to do either and generates an error.
1.21 crook 1880:
1.29 crook 1881: When the text interpreter is compiling, its behaviour is slightly
1882: different; it still looks for each character sequence in the dictionary
1.30 ! anton 1883: and finds it, or converts it to a number, or fails to do either and
! 1884: generates an error. But instead of the execution token of a word it
! 1885: finds and executes the compilation token. For most words executing the
! 1886: compilation token results in laying down (@dfn{compiling}) the execution
! 1887: token, i.e., some magic to make that xt or number get executed or pushed
! 1888: at a later time; at the time that @code{add-two} is
! 1889: @dfn{executed}. Therefore, when you execute @code{add-two} its
! 1890: @dfn{run-time effect} is exactly the same as if you had typed @code{2 +
! 1891: .} outside of a definition, and pressed carriage-return.
1.28 crook 1892:
1.30 ! anton 1893: In Forth, every word or number can be described in terms of two
1.29 crook 1894: properties:
1.28 crook 1895:
1896: @itemize @bullet
1897: @item
1.30 ! anton 1898: Its @dfn{interpretation semantics}, represented by the execution token.
1.28 crook 1899: @item
1.30 ! anton 1900: Its @dfn{compilation semantics}, represented by the compilation token.
1.29 crook 1901: @end itemize
1902:
1.30 ! anton 1903: The value of @code{state} determines whether the text interpreter will
! 1904: use the compilation or interpretation semantics of a word or number that
! 1905: it encounters.
1.29 crook 1906:
1907: @itemize @bullet
1.28 crook 1908: @item
1.29 crook 1909: @cindex interpretation semantics
1910: When the text interpreter encounters a word or number in @dfn{interpret}
1911: state, it performs the @dfn{interpretation semantics} of the word or
1912: number.
1.28 crook 1913: @item
1.29 crook 1914: @cindex compilation semantics
1915: When the text interpreter encounters a word or number in @dfn{compile}
1916: state, it performs the @dfn{compilation semantics} of the word or
1917: number.
1918: @end itemize
1919:
1920: @noindent
1921: Numbers are always treated in a fixed way:
1922:
1923: @itemize @bullet
1.28 crook 1924: @item
1.30 ! anton 1925: When the number is @dfn{interpreted}, its behaviour is to push the number onto the stack.
1.28 crook 1926: @item
1.30 ! anton 1927: When the number is @dfn{compiled}, a piece of code is appended to the
! 1928: current definition that pushes the number when it runs. (In other words,
! 1929: the compilation semantics of a number are to postpone its interpretation
! 1930: semantics until the run-time of the definition that it is being compiled
! 1931: into.)
1.29 crook 1932: @end itemize
1933:
1934: The behaviour of a word is not so regular, but most have @i{default
1.30 ! anton 1935: compilation semantics} which means that they behave like this:
1.29 crook 1936:
1937: @itemize @bullet
1.28 crook 1938: @item
1.30 ! anton 1939: The @dfn{interpretation semantics} of the word are to do something useful.
! 1940: @item
1.29 crook 1941: The @dfn{compilation semantics} of the word are to append its
1.30 ! anton 1942: @dfn{interpretation semantics} to the current definition (so that its
! 1943: run-time behaviour is to do something useful).
1.28 crook 1944: @end itemize
1945:
1.30 ! anton 1946: @cindex immediate words
1.29 crook 1947: The actual behaviour of any particular word depends upon the way in
1948: which it was defined. When the text interpreter finds the word in the
1949: name dictionary, it not only retrieves the xt for the word, it also
1950: retrieves some flags: the @dfn{compile-only} flag and the @dfn{immediate
1951: flag}. The compile-only flag indicates that the word has no
1.30 ! anton 1952: interpretation semantics (the run-time behaviour for the default
! 1953: compilation semantics is not affected by this flag, however); any
! 1954: attempt to interpret a word that has the compile-only flag set will
! 1955: generate an error (for example, @code{IF} has no interpretation
! 1956: semantics). The immediate flag changes the compilation semantics of the
! 1957: word; if it is set, the compilation semantics are equal to the
! 1958: interpretation semantics (again ignoring the compile-only flag). it. In
! 1959: other words, these so-called @dfn{immediate} words behave like this:
1.29 crook 1960:
1961: @itemize @bullet
1962: @item
1.30 ! anton 1963: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 1964: @item
1.30 ! anton 1965: The @dfn{compilation semantics} of the word are to do something useful
! 1966: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 1967: @end itemize
1.28 crook 1968:
1.29 crook 1969: This example shows the difference between an immediate and a
1970: non-immediate word:
1.28 crook 1971:
1.29 crook 1972: @example
1973: : show-state state @@ . ;
1974: : show-state-now show-state ; immediate
1975: : word1 show-state ;
1976: : word2 show-state-now ;
1.28 crook 1977: @end example
1.23 crook 1978:
1.29 crook 1979: The word @code{immediate} after the definition of @code{show-state-now}
1980: makes that word an immediate word. These definitions introduce a new
1981: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
1982: variable, and leaves it on the stack. Therefore, the behaviour of
1983: @code{show-state} is to print a number that represents the current value
1984: of @code{state}.
1.28 crook 1985:
1.29 crook 1986: When you execute @code{word1}, it prints the number 0, indicating that
1987: the system is interpreting. When the text interpreter compiled the
1988: definition of @code{word1}, it encountered @code{show-state} whose
1.30 ! anton 1989: compilation semantics are to append its interpretation semantics to the
1.29 crook 1990: current definition. When you execute @code{word1}, it performs the
1.30 ! anton 1991: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 1992: (and therefore @code{show-state}) are executed, the system is
1993: interpreting.
1.28 crook 1994:
1.30 ! anton 1995: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 1996: you should have seen the number -1 printed, followed by ``@code{
1997: ok}''. When the text interpreter compiled the definition of
1998: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 ! anton 1999: whose compilation semantics are therefore to perform its interpretation
1.29 crook 2000: semantics. It is executed straight away (even before the text
2001: interpreter has moved on to process another group of characters; the
2002: @code{;} in this example). The effect of executing it are to display the
2003: value of @code{state} @i{at the time that the definition of}
2004: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
2005: system is compiling at this time. If you execute @code{word2} it does
2006: nothing at all.
1.28 crook 2007:
1.29 crook 2008: @cindex @code{."}, how it works
2009: Before leaving the subject of immediate words, consider the behaviour of
2010: @code{."} in the definition of @code{greet}, in the previous
2011: section. This word is both a parsing word and an immediate word. Notice
2012: that there is a space between @code{."} and the start of the text
2013: @code{Hello and welcome}, but that there is no space between the last
2014: letter of @code{welcome} and the @code{"} character. The reason for this
2015: is that @code{."} is a Forth word; it must have a space after it so that
2016: the text interpreter can identify it. The @code{"} is not a Forth word;
2017: it is a @dfn{delimiter}. The examples earlier show that, when the string
2018: is displayed, there is neither a space before the @code{H} nor after the
2019: @code{e}. Since @code{."} is an immediate word, it executes at the time
2020: that @code{greet} is defined. When it executes, its behaviour is to
2021: search forward in the input line looking for the delimiter. When it
2022: finds the delimiter, it updates @code{>IN} to point past the
2023: delimiter. It also compiles some magic code into the definition of
2024: @code{greet}; the xt of a run-time routine that prints a text string. It
2025: compiles the string @code{Hello and welcome} into memory so that it is
2026: available to be printed later. When the text interpreter gains control,
2027: the next word it finds in the input stream is @code{;} and so it
2028: terminates the definition of @code{greet}.
1.28 crook 2029:
2030:
2031: @comment ----------------------------------------------
1.29 crook 2032: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
2033: @section Forth is written in Forth
2034: @cindex structure of Forth programs
2035:
2036: When you start up a Forth compiler, a large number of definitions
2037: already exist. In Forth, you develop a new application using bottom-up
2038: programming techniques to create new definitions that are defined in
2039: terms of existing definitions. As you create each definition you can
2040: test and debug it interactively.
2041:
2042: If you have tried out the examples in this section, you will probably
2043: have typed them in by hand; when you leave Gforth, your definitions will
2044: be lost. You can avoid this by using a text editor to enter Forth source
2045: code into a file, and then loading code from the file using
2046: @code{include} (@xref{Forth source files}). A Forth source file is
2047: processed by the text interpreter, just as though you had typed it in by
2048: hand@footnote{Actually, there are some subtle differences -- see
2049: @ref{The Text Interpreter}.}.
2050:
2051: Gforth also supports the traditional Forth alternative to using text
2052: files for program entry (@xref{Blocks}).
1.28 crook 2053:
1.29 crook 2054: In common with many, if not most, Forth compilers, most of Gforth is
2055: actually written in Forth. All of the @file{.fs} files in the
2056: installation directory@footnote{For example,
1.30 ! anton 2057: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 2058: study to see examples of Forth programming.
1.28 crook 2059:
1.29 crook 2060: Gforth maintains a history file that records every line that you type to
2061: the text interpreter. This file is preserved between sessions, and is
2062: used to provide a command-line recall facility. If you enter long
2063: definitions by hand, you can use a text editor to paste them out of the
2064: history file into a Forth source file for reuse at a later time
2065: (@pxref{Command-line editing} for more information).
1.28 crook 2066:
2067:
2068: @comment ----------------------------------------------
1.29 crook 2069: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
2070: @section Review - elements of a Forth system
2071: @cindex elements of a Forth system
1.28 crook 2072:
1.29 crook 2073: To summarise this chapter:
1.28 crook 2074:
2075: @itemize @bullet
2076: @item
1.29 crook 2077: Forth programs use @dfn{factoring} to break a problem down into small
2078: fragments called @dfn{words} or @dfn{definitions}.
2079: @item
2080: Forth program development is an interactive process.
2081: @item
2082: The main command loop that accepts input, and controls both
2083: interpretation and compilation, is called the @dfn{text interpreter}
2084: (also known as the @dfn{outer interpreter}).
2085: @item
2086: Forth has a very simple syntax, consisting of words and numbers
2087: separated by spaces or carriage-return characters. Any additional syntax
2088: is imposed by @dfn{parsing words}.
2089: @item
2090: Forth uses a stack to pass parameters between words. As a result, it
2091: uses postfix notation.
2092: @item
2093: To use a word that has previously been defined, the text interpreter
2094: searches for the word in the @dfn{name dictionary}.
2095: @item
1.30 ! anton 2096: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 2097: @item
1.29 crook 2098: The text interpreter uses the value of @code{state} to select between
2099: the use of the @dfn{interpretation semantics} and the @dfn{compilation
2100: semantics} of a word that it encounters.
1.28 crook 2101: @item
1.30 ! anton 2102: The relationship between the @dfn{interpretation semantics} and
! 2103: @dfn{compilation semantics} for a word
1.29 crook 2104: depend upon the way in which the word was defined (for example, whether
2105: it is an @dfn{immediate} word).
1.28 crook 2106: @item
1.29 crook 2107: Forth definitions can be implemented in Forth (called @dfn{high-level
2108: definitions}) or in some other way (usually a lower-level language and
2109: as a result often called @dfn{low-level definitions}, @dfn{code
2110: definitions} or @dfn{primitives}).
1.28 crook 2111: @item
1.29 crook 2112: Many Forth systems are implemented mainly in Forth.
1.28 crook 2113: @end itemize
2114:
2115:
1.29 crook 2116: @comment ----------------------------------------------
2117: @node Where to go next,Exercises,Review - elements of a Forth system, Introduction
2118: @section Where To Go Next
2119: @cindex where to go next
1.28 crook 2120:
1.29 crook 2121: Amazing as it may seem, if you have read (and understood) this far, you
2122: know almost all the fundamentals about the inner workings of a Forth
2123: system. You certainly know enough to be able to read and understand the
2124: rest of this manual and the ANS Forth document, to learn more about the
2125: facilities that Forth in general and Gforth in particular provide. Even
2126: scarier, you know almost enough to implement your own Forth system.
1.30 ! anton 2127: However, that's not a good idea just yet... better to try writing some
1.29 crook 2128: programs in Gforth.
1.28 crook 2129:
1.29 crook 2130: Forth has such a rich vocabulary that it can be hard to know where to
2131: start in learning it. This section suggests a few sets of words that are
2132: enough to write small but useful programs. Use the word index in this
2133: document to learn more about each word, then try it out and try to write
2134: small definitions using it. Start by experimenting with these words:
1.28 crook 2135:
2136: @itemize @bullet
2137: @item
1.29 crook 2138: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
2139: @item
2140: Comparison: @code{MIN MAX =}
2141: @item
2142: Logic: @code{AND OR XOR NOT}
2143: @item
2144: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 2145: @item
1.29 crook 2146: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 2147: @item
1.29 crook 2148: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 2149: @item
1.29 crook 2150: Defining words: @code{: ; CREATE}
1.28 crook 2151: @item
1.29 crook 2152: Memory allocation words: @code{ALLOT ,}
1.28 crook 2153: @item
1.29 crook 2154: Tools: @code{SEE WORDS .S MARKER}
2155: @end itemize
2156:
2157: When you have mastered those, go on to:
2158:
2159: @itemize @bullet
1.28 crook 2160: @item
1.29 crook 2161: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 2162: @item
1.29 crook 2163: Memory access: @code{@@ !}
1.28 crook 2164: @end itemize
1.23 crook 2165:
1.29 crook 2166: When you have mastered these, there's nothing for it but to read through
2167: the whole of this manual and find out what you've missed.
2168:
2169: @comment ----------------------------------------------
2170: @node Exercises, ,Where to go next, Introduction
2171: @section Exercises
2172: @cindex exercises
2173:
2174: TODO: provide a set of programming excercises linked into the stuff done
2175: already and into other sections of the manual. Provide solutions to all
2176: the exercises in a .fs file in the distribution.
2177:
2178: @c Get some inspiration from Starting Forth and Kelly&Spies.
2179:
2180: @c excercises:
2181: @c 1. take inches and convert to feet and inches.
2182: @c 2. take temperature and convert from fahrenheight to celcius;
2183: @c may need to care about symmetric vs floored??
2184: @c 3. take input line and do character substitution
2185: @c to encipher or decipher
2186: @c 4. as above but work on a file for in and out
2187: @c 5. take input line and convert to pig-latin
2188: @c
2189: @c thing of sets of things to exercise then come up with
2190: @c problems that need those things.
2191:
2192:
1.26 crook 2193: @c ******************************************************************
1.29 crook 2194: @node Words, Error messages, Introduction, Top
1.1 anton 2195: @chapter Forth Words
1.26 crook 2196: @cindex words
1.1 anton 2197:
2198: @menu
2199: * Notation::
1.21 crook 2200: * Comments::
2201: * Boolean Flags::
1.1 anton 2202: * Arithmetic::
2203: * Stack Manipulation::
1.5 anton 2204: * Memory::
1.1 anton 2205: * Control Structures::
2206: * Defining Words::
1.21 crook 2207: * The Text Interpreter::
1.12 anton 2208: * Tokens for Words::
1.21 crook 2209: * Word Lists::
2210: * Environmental Queries::
1.12 anton 2211: * Files::
2212: * Blocks::
2213: * Other I/O::
2214: * Programming Tools::
2215: * Assembler and Code Words::
2216: * Threading Words::
1.26 crook 2217: * Locals::
2218: * Structures::
2219: * Object-oriented Forth::
1.21 crook 2220: * Passing Commands to the OS::
2221: * Miscellaneous Words::
1.1 anton 2222: @end menu
2223:
1.21 crook 2224: @node Notation, Comments, Words, Words
1.1 anton 2225: @section Notation
2226: @cindex notation of glossary entries
2227: @cindex format of glossary entries
2228: @cindex glossary notation format
2229: @cindex word glossary entry format
2230:
2231: The Forth words are described in this section in the glossary notation
2232: that has become a de-facto standard for Forth texts, i.e.,
2233:
2234: @format
1.29 crook 2235: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 2236: @end format
1.29 crook 2237: @i{Description}
1.1 anton 2238:
2239: @table @var
2240: @item word
1.28 crook 2241: The name of the word.
1.1 anton 2242:
2243: @item Stack effect
2244: @cindex stack effect
1.29 crook 2245: The stack effect is written in the notation @code{@i{before} --
2246: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 2247: stack entries before and after the execution of the word. The rest of
2248: the stack is not touched by the word. The top of stack is rightmost,
2249: i.e., a stack sequence is written as it is typed in. Note that Gforth
2250: uses a separate floating point stack, but a unified stack
1.29 crook 2251: notation. Also, return stack effects are not shown in @i{stack
2252: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 2253: the type and/or the function of the item. See below for a discussion of
2254: the types.
2255:
2256: All words have two stack effects: A compile-time stack effect and a
2257: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 2258: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 2259: this standard behaviour, or the word does other unusual things at
2260: compile time, both stack effects are shown; otherwise only the run-time
2261: stack effect is shown.
2262:
2263: @cindex pronounciation of words
2264: @item pronunciation
2265: How the word is pronounced.
2266:
2267: @cindex wordset
2268: @item wordset
1.21 crook 2269: The ANS Forth standard is divided into several word sets. A standard
2270: system need not support all of them. Therefore, in theory, the fewer
2271: word sets your program uses the more portable it will be. However, we
2272: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 2273: all word sets. Words that are not defined in ANS Forth have
1.21 crook 2274: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 2275: describes words that will work in future releases of Gforth;
2276: @code{gforth-internal} words are more volatile. Environmental query
2277: strings are also displayed like words; you can recognize them by the
1.21 crook 2278: @code{environment} in the word set field.
1.1 anton 2279:
2280: @item Description
2281: A description of the behaviour of the word.
2282: @end table
2283:
2284: @cindex types of stack items
2285: @cindex stack item types
2286: The type of a stack item is specified by the character(s) the name
2287: starts with:
2288:
2289: @table @code
2290: @item f
2291: @cindex @code{f}, stack item type
2292: Boolean flags, i.e. @code{false} or @code{true}.
2293: @item c
2294: @cindex @code{c}, stack item type
2295: Char
2296: @item w
2297: @cindex @code{w}, stack item type
2298: Cell, can contain an integer or an address
2299: @item n
2300: @cindex @code{n}, stack item type
2301: signed integer
2302: @item u
2303: @cindex @code{u}, stack item type
2304: unsigned integer
2305: @item d
2306: @cindex @code{d}, stack item type
2307: double sized signed integer
2308: @item ud
2309: @cindex @code{ud}, stack item type
2310: double sized unsigned integer
2311: @item r
2312: @cindex @code{r}, stack item type
2313: Float (on the FP stack)
1.21 crook 2314: @item a-
1.1 anton 2315: @cindex @code{a_}, stack item type
2316: Cell-aligned address
1.21 crook 2317: @item c-
1.1 anton 2318: @cindex @code{c_}, stack item type
2319: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 2320: @item f-
1.1 anton 2321: @cindex @code{f_}, stack item type
2322: Float-aligned address
1.21 crook 2323: @item df-
1.1 anton 2324: @cindex @code{df_}, stack item type
2325: Address aligned for IEEE double precision float
1.21 crook 2326: @item sf-
1.1 anton 2327: @cindex @code{sf_}, stack item type
2328: Address aligned for IEEE single precision float
2329: @item xt
2330: @cindex @code{xt}, stack item type
2331: Execution token, same size as Cell
2332: @item wid
2333: @cindex @code{wid}, stack item type
1.21 crook 2334: Word list ID, same size as Cell
1.1 anton 2335: @item f83name
2336: @cindex @code{f83name}, stack item type
2337: Pointer to a name structure
2338: @item "
2339: @cindex @code{"}, stack item type
1.12 anton 2340: string in the input stream (not on the stack). The terminating character
2341: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 2342: quotes.
2343: @end table
2344:
1.21 crook 2345: @node Comments, Boolean Flags, Notation, Words
2346: @section Comments
1.26 crook 2347: @cindex comments
1.21 crook 2348:
1.29 crook 2349: Forth supports two styles of comment; the traditional @i{in-line} comment,
2350: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 2351:
1.23 crook 2352: doc-(
1.21 crook 2353: doc-\
1.23 crook 2354: doc-\G
1.21 crook 2355:
2356: @node Boolean Flags, Arithmetic, Comments, Words
2357: @section Boolean Flags
1.26 crook 2358: @cindex Boolean flags
1.21 crook 2359:
2360: A Boolean flag is cell-sized. A cell with all bits clear represents the
2361: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 2362: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 2363: a cell that has @i{any} bit set as @code{true}.
1.21 crook 2364:
2365: doc-true
2366: doc-false
1.29 crook 2367: doc-on
2368: doc-off
1.21 crook 2369:
2370: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 2371: @section Arithmetic
2372: @cindex arithmetic words
2373:
2374: @cindex division with potentially negative operands
2375: Forth arithmetic is not checked, i.e., you will not hear about integer
2376: overflow on addition or multiplication, you may hear about division by
2377: zero if you are lucky. The operator is written after the operands, but
2378: the operands are still in the original order. I.e., the infix @code{2-1}
2379: corresponds to @code{2 1 -}. Forth offers a variety of division
2380: operators. If you perform division with potentially negative operands,
2381: you do not want to use @code{/} or @code{/mod} with its undefined
2382: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
2383: former, @pxref{Mixed precision}).
1.26 crook 2384: @comment TODO discuss the different division forms and the std approach
1.1 anton 2385:
2386: @menu
2387: * Single precision::
2388: * Bitwise operations::
1.21 crook 2389: * Double precision:: Double-cell integer arithmetic
2390: * Numeric comparison::
1.29 crook 2391: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 2392: * Floating Point::
2393: @end menu
2394:
2395: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
2396: @subsection Single precision
2397: @cindex single precision arithmetic words
2398:
1.21 crook 2399: By default, numbers in Forth are single-precision integers that are 1
1.26 crook 2400: cell in size. They can be signed or unsigned, depending upon how you
1.21 crook 2401: treat them. @xref{Number Conversion} for the rules used by the text
2402: interpreter for recognising single-precision integers.
2403:
1.1 anton 2404: doc-+
1.21 crook 2405: doc-1+
1.1 anton 2406: doc--
1.21 crook 2407: doc-1-
1.1 anton 2408: doc-*
2409: doc-/
2410: doc-mod
2411: doc-/mod
2412: doc-negate
2413: doc-abs
2414: doc-min
2415: doc-max
1.21 crook 2416: doc-d>s
1.27 crook 2417: doc-floored
1.1 anton 2418:
1.21 crook 2419: @node Bitwise operations, Double precision, Single precision, Arithmetic
1.1 anton 2420: @subsection Bitwise operations
2421: @cindex bitwise operation words
2422:
2423: doc-and
2424: doc-or
2425: doc-xor
2426: doc-invert
1.21 crook 2427: doc-lshift
2428: doc-rshift
1.1 anton 2429: doc-2*
1.21 crook 2430: doc-d2*
1.1 anton 2431: doc-2/
1.21 crook 2432: doc-d2/
2433:
2434: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
2435: @subsection Double precision
2436: @cindex double precision arithmetic words
2437:
2438: @xref{Number Conversion} for the rules used by the text interpreter for
2439: recognising double-precision integers.
2440:
2441: A double precision number is represented by a cell pair, with the most
1.26 crook 2442: significant digit at the TOS. It is trivial to convert an unsigned
2443: single to an (unsigned) double; simply push a @code{0} onto the
2444: TOS. Since numbers are represented by Gforth using 2's complement
2445: arithmetic, converting a signed single to a (signed) double requires
2446: sign-extension across the most significant digit. This can be achieved
2447: using @code{s>d}. The moral of the story is that you cannot convert a
2448: number without knowing whether it represents an unsigned or a
2449: signed number.
1.21 crook 2450:
2451: doc-s>d
2452: doc-d+
2453: doc-d-
2454: doc-dnegate
2455: doc-dabs
2456: doc-dmin
2457: doc-dmax
2458:
2459: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
2460: @subsection Numeric comparison
2461: @cindex numeric comparison words
2462:
1.28 crook 2463: doc-<
2464: doc-<=
2465: doc-<>
2466: doc-=
2467: doc->
2468: doc->=
2469:
1.21 crook 2470: doc-0<
1.23 crook 2471: doc-0<=
1.21 crook 2472: doc-0<>
2473: doc-0=
1.23 crook 2474: doc-0>
2475: doc-0>=
1.28 crook 2476:
2477: doc-u<
2478: doc-u<=
1.30 ! anton 2479: @comment TODO why u<> and u= ... they are the same as <> and =
1.28 crook 2480: doc-u<>
2481: doc-u=
2482: doc-u>
2483: doc-u>=
2484:
2485: doc-within
2486:
2487: doc-d<
2488: doc-d<=
2489: doc-d<>
2490: doc-d=
2491: doc-d>
2492: doc-d>=
1.23 crook 2493:
1.21 crook 2494: doc-d0<
1.23 crook 2495: doc-d0<=
2496: doc-d0<>
1.21 crook 2497: doc-d0=
1.23 crook 2498: doc-d0>
2499: doc-d0>=
2500:
1.21 crook 2501: doc-du<
1.28 crook 2502: doc-du<=
2503: doc-du<>
2504: doc-du=
2505: doc-du>
2506: doc-du>=
1.1 anton 2507:
1.21 crook 2508: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 2509: @subsection Mixed precision
2510: @cindex mixed precision arithmetic words
2511:
2512: doc-m+
2513: doc-*/
2514: doc-*/mod
2515: doc-m*
2516: doc-um*
2517: doc-m*/
2518: doc-um/mod
2519: doc-fm/mod
2520: doc-sm/rem
2521:
1.21 crook 2522: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 2523: @subsection Floating Point
2524: @cindex floating point arithmetic words
2525:
1.21 crook 2526: @xref{Number Conversion} for the rules used by the text interpreter for
2527: recognising floating-point numbers.
1.1 anton 2528:
2529: @cindex angles in trigonometric operations
2530: @cindex trigonometric operations
2531: Angles in floating point operations are given in radians (a full circle
1.26 crook 2532: has 2 pi radians). Gforth has a separate floating point
2533: stack, but the documentation uses the unified notation.
1.1 anton 2534:
2535: @cindex floating-point arithmetic, pitfalls
2536: Floating point numbers have a number of unpleasant surprises for the
2537: unwary (e.g., floating point addition is not associative) and even a few
2538: for the wary. You should not use them unless you know what you are doing
2539: or you don't care that the results you get are totally bogus. If you
2540: want to learn about the problems of floating point numbers (and how to
2541: avoid them), you might start with @cite{David Goldberg, What Every
2542: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
1.17 anton 2543: Computing Surveys 23(1):5@minus{}48, March 1991}
2544: (@url{http://www.validgh.com/goldberg/paper.ps}).
1.1 anton 2545:
1.21 crook 2546: doc-d>f
2547: doc-f>d
1.1 anton 2548: doc-f+
2549: doc-f-
2550: doc-f*
2551: doc-f/
2552: doc-fnegate
2553: doc-fabs
2554: doc-fmax
2555: doc-fmin
2556: doc-floor
2557: doc-fround
2558: doc-f**
2559: doc-fsqrt
2560: doc-fexp
2561: doc-fexpm1
2562: doc-fln
2563: doc-flnp1
2564: doc-flog
2565: doc-falog
2566: doc-fsin
2567: doc-fcos
2568: doc-fsincos
2569: doc-ftan
2570: doc-fasin
2571: doc-facos
2572: doc-fatan
2573: doc-fatan2
2574: doc-fsinh
2575: doc-fcosh
2576: doc-ftanh
2577: doc-fasinh
2578: doc-facosh
2579: doc-fatanh
1.21 crook 2580: doc-pi
1.28 crook 2581:
1.21 crook 2582: doc-f0<
1.28 crook 2583: doc-f0<=
2584: doc-f0<>
1.21 crook 2585: doc-f0=
1.28 crook 2586: doc-f0>
2587: doc-f0>=
2588:
1.21 crook 2589: doc-f<
2590: doc-f<=
2591: doc-f<>
2592: doc-f=
2593: doc-f>
2594: doc-f>=
1.28 crook 2595:
1.21 crook 2596: doc-f2*
2597: doc-f2/
2598: doc-1/f
2599: doc-f~
2600: doc-precision
2601: doc-set-precision
1.1 anton 2602:
2603: @node Stack Manipulation, Memory, Arithmetic, Words
2604: @section Stack Manipulation
2605: @cindex stack manipulation words
2606:
2607: @cindex floating-point stack in the standard
1.21 crook 2608: Gforth maintains a number of separate stacks:
2609:
1.29 crook 2610: @cindex data stack
2611: @cindex parameter stack
1.21 crook 2612: @itemize @bullet
2613: @item
1.29 crook 2614: A data stack (also known as the @dfn{parameter stack}) -- for
2615: characters, cells, addresses, and double cells.
1.21 crook 2616:
1.29 crook 2617: @cindex floating-point stack
1.21 crook 2618: @item
2619: A floating point stack -- for floating point numbers.
2620:
1.29 crook 2621: @cindex return stack
1.21 crook 2622: @item
2623: A return stack -- for storing the return addresses of colon
2624: definitions and other data.
2625:
1.29 crook 2626: @cindex locals stack
1.21 crook 2627: @item
2628: A locals stack for storing local variables.
2629: @end itemize
2630:
2631: Whilst every sane Forth has a separate floating-point stack, it is not
2632: strictly required; an ANS Forth system could theoretically keep
2633: floating-point numbers on the data stack. As an additional difficulty,
2634: you don't know how many cells a floating-point number takes. It is
2635: reportedly possible to write words in a way that they work also for a
2636: unified stack model, but we do not recommend trying it. Instead, just
2637: say that your program has an environmental dependency on a separate
2638: floating-point stack.
2639:
2640: doc-floating-stack
1.1 anton 2641:
2642: @cindex return stack and locals
2643: @cindex locals and return stack
1.21 crook 2644: A Forth system is allowed to keep local variables on the
1.1 anton 2645: return stack. This is reasonable, as local variables usually eliminate
2646: the need to use the return stack explicitly. So, if you want to produce
1.21 crook 2647: a standard compliant program and you are using local variables in a
2648: word, forget about return stack manipulations in that word (refer to the
1.1 anton 2649: standard document for the exact rules).
2650:
2651: @menu
2652: * Data stack::
2653: * Floating point stack::
2654: * Return stack::
2655: * Locals stack::
2656: * Stack pointer manipulation::
2657: @end menu
2658:
2659: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
2660: @subsection Data stack
2661: @cindex data stack manipulation words
2662: @cindex stack manipulations words, data stack
2663:
2664: doc-drop
2665: doc-nip
2666: doc-dup
2667: doc-over
2668: doc-tuck
2669: doc-swap
1.21 crook 2670: doc-pick
1.1 anton 2671: doc-rot
2672: doc--rot
2673: doc-?dup
2674: doc-roll
2675: doc-2drop
2676: doc-2nip
2677: doc-2dup
2678: doc-2over
2679: doc-2tuck
2680: doc-2swap
2681: doc-2rot
2682:
2683: @node Floating point stack, Return stack, Data stack, Stack Manipulation
2684: @subsection Floating point stack
2685: @cindex floating-point stack manipulation words
2686: @cindex stack manipulation words, floating-point stack
2687:
2688: doc-fdrop
2689: doc-fnip
2690: doc-fdup
2691: doc-fover
2692: doc-ftuck
2693: doc-fswap
1.21 crook 2694: doc-fpick
1.1 anton 2695: doc-frot
2696:
2697: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
2698: @subsection Return stack
2699: @cindex return stack manipulation words
2700: @cindex stack manipulation words, return stack
2701:
2702: doc->r
2703: doc-r>
2704: doc-r@
2705: doc-rdrop
2706: doc-2>r
2707: doc-2r>
2708: doc-2r@
2709: doc-2rdrop
2710:
2711: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
2712: @subsection Locals stack
2713:
1.26 crook 2714: @comment TODO
1.21 crook 2715:
1.1 anton 2716: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
2717: @subsection Stack pointer manipulation
2718: @cindex stack pointer manipulation words
2719:
1.21 crook 2720: doc-sp0
2721: doc-s0
1.1 anton 2722: doc-sp@
2723: doc-sp!
1.21 crook 2724: doc-fp0
1.1 anton 2725: doc-fp@
2726: doc-fp!
1.21 crook 2727: doc-rp0
2728: doc-r0
1.1 anton 2729: doc-rp@
2730: doc-rp!
1.21 crook 2731: doc-lp0
2732: doc-l0
1.1 anton 2733: doc-lp@
2734: doc-lp!
2735:
2736: @node Memory, Control Structures, Stack Manipulation, Words
2737: @section Memory
1.26 crook 2738: @cindex memory words
1.1 anton 2739:
1.27 crook 2740: @cindex dictionary
2741: Forth definitions are organised in memory structures that are
1.29 crook 2742: collectively called the @dfn{dictionary}. The dictionary can be
1.27 crook 2743: considered as three logical memory regions:
2744:
2745: @itemize @bullet
2746: @item
2747: @cindex code space
2748: @cindex code dictionary
1.29 crook 2749: Code space, also known as the @dfn{code dictionary}.
1.27 crook 2750: @item
2751: @cindex name space
2752: @cindex name dictionary
1.29 crook 2753: Name space, also known as the @dfn{name dictionary}@footnote{Sometimes,
2754: the term @dfn{dictionary} is used simply to refer to the name
1.27 crook 2755: dictionary, because it is the one region that is used for looking up
2756: names, just as you would in a conventional dictionary.}.
2757: @item
2758: @cindex data space
2759: Data space
2760: @end itemize
2761:
1.29 crook 2762: When you create a colon definition, the text interpreter compiles the
2763: code for the definition into the code dictionary and compiles the name
1.27 crook 2764: of the definition into the name dictionary, together with other
2765: information about the definition (such as its execution token).
2766:
2767: When you create a variable, the execution of @code{variable} will
2768: compile some code, assign once cell in data space, and compile the name
2769: of the variable into the name dictionary.
2770:
2771: @cindex memory regions - relationship between them
2772: ANS Forth does not specify the relationship between the three memory
2773: regions, and specifies that a Standard program must not access code or
2774: data space directly -- it may only access data space directly. In
2775: addition, the Standard defines what relationships you may and may not
2776: rely on when allocating regions in data space. These constraints are
2777: simply a reflection of the many diverse techniques that are used to
2778: implement Forth systems; understanding and following the requirements of
2779: the Standard allows you to write portable programs -- programs that run
2780: in the same way on any of these diverse systems. Another way of looking
2781: at this is to say that ANS Forth was designed to permit compliant Forth
2782: systems to be implemented in many diverse ways.
2783:
2784: @cindex memory regions - how they are assigned
1.29 crook 2785: Here are some examples of ways in which name, code and data spaces
2786: might be assigned in different Forth implementations:
1.27 crook 2787:
2788: @itemize @bullet
2789: @item
2790: For a Forth system that runs from RAM under a general-purpose operating
2791: system, it can be convenient to interleave name, code and data spaces in
2792: a single contiguous memory region. This organisation can be
2793: memory-efficient (for example, because the relationship between the name
2794: dictionary entry and the associated code dictionary entry can be
2795: implicit, rather than requiring an explicit memory pointer to reference
2796: from the name dictionary and the code dictionary). This is the
2797: organisation used by Gforth, as this example@footnote{The addresses
2798: in the example have been truncated to fit it onto the page, and the
2799: addresses and data shown will not match the output from your system} shows:
2800: @example
2801: hex
2802: variable fred 123456 fred !
2803: variable jim abcd jim !
2804: : foo + / - ;
2805: ' fred 10 - 50 dump
2806: ..80: 5C 46 0E 40 84 66 72 65 - 64 20 20 20 20 20 20 20 \F.@.fred
2807: ..90: D0 9B 04 08 00 00 00 00 - 56 34 12 00 80 46 0E 40 ........V4...F.@
2808: ..A0: 83 6A 69 6D 20 20 20 20 - D0 9B 04 08 00 00 00 00 .jim ........
2809: ..B0: CD AB 00 00 9C 46 0E 40 - 83 66 6F 6F 20 20 20 20 .....F.@.foo
2810: ..C0: 80 9B 04 08 00 00 00 00 - E4 2E 05 08 0C 2F 05 08 ............./..
2811: @end example
2812:
2813: @item
2814: For a high-performance system running on a modern RISC processor with a
2815: modified Harvard architecture (one that has a unified main memory but
2816: separate instruction and data caches), it is desirable to separate
2817: processor instructions from processor data. This encourages a high cache
2818: density and therefore a high cache hit rate. The Forth code dictionary
2819: is not necessarily made up entirely of processor instructions; its
2820: nature is dependent upon the Forth implementation.
2821:
2822: @item
2823: A Forth compiler that runs on a segmented 8086 processor could be
2824: designed to interleave the name, code and data spaces within a single
2825: 64Kbyte segment. A more common implementation choice is to use a
2826: separate 64Kbyte segment for each region, which provides more memory
2827: overall but provides an address map in which only the data space is
2828: accessible.
2829:
2830: @item
2831: Microprocessors exist that run Forth (or many of the primitives required
2832: to implement the Forth virtual machine efficiently) directly. On these
2833: processors, the relationship between name, code and data spaces may be
2834: imposed as a side-effect of the microarchitecture of the processor.
2835:
2836: @item
2837: A Forth compiler that executes from ROM on an embedded system needs its
2838: data space separated from the name and code spaces so that the data
2839: space can be mapped to a RAM area.
2840:
2841: @item
2842: A Forth compiler that runs on an embedded system may have a requirement
2843: for a small memory footprint. On such a system it can be useful to
2844: separate the name space from the data and code spaces; once the
2845: application has been compiled, the name dictionary is no longer
2846: required@footnote{more strictly speaking, most applications can be
2847: designed so that this is the case}. The name dictionary can be deleted
1.29 crook 2848: entirely, or could be stored in memory on a remote @i{host} system for
1.27 crook 2849: debug and development purposes. In the latter case, the compiler running
1.29 crook 2850: on the @i{target} system could implement a protocol across a
1.27 crook 2851: communication link that would allow it to interrogate the name dictionary.
2852: @end itemize
2853:
1.1 anton 2854: @menu
1.27 crook 2855: * Reserving Data Space::
2856: * Memory Access::
2857: * Address Arithmetic::
2858: * Memory Blocks::
2859: * Dynamic Allocation::
1.1 anton 2860: @end menu
2861:
1.27 crook 2862:
2863: @node Reserving Data Space, Memory Access, Memory, Memory
2864: @subsection Reserving Data Space
2865: @cindex reserving data space
2866: @cindex data space - reserving some
2867:
2868: @cindex data space pointer - contiguous regions
1.29 crook 2869: Data space may be reserved as individual chars or cells or in contiguous
2870: regions. These are the rules for reserving contiguous regions in a
2871: Standard (i.e., portable) way:
1.27 crook 2872: @itemize @bullet
2873: @item
2874: The value of the data-space pointer, @code{here}, always defines the
2875: beginning of a contiguous region of data space.
2876:
2877: @item
2878: @code{CREATE} establishes the beginning of a contiguous region of data
2879: space (the @code{CREATE}d definition returns the initial address of the
2880: region).
2881:
2882: @item
1.29 crook 2883: @code{variable} does @i{not} establish the beginning of a contiguous
1.27 crook 2884: region in data space; @code{variable} followed by @code{allot} is not
2885: guaranteed to allocate data space region that is contiguous with the
2886: storage allocated by @code{variable}. Instead, use @code{create} --
2887: @xref{Simple Defining Words} for examples.
2888:
2889: @item
2890: Successive calls to @code{allot}, @code{,} (comma), @code{2,} (2-comma),
2891: @code{c,} (c-comma) and @code{align} reserve a single contiguous region
2892: in data space. The contiguity of the region is interrupted by compiling
2893: (or removing) definitions from the dictionary.
2894:
2895: @item
2896: The most recently reserved contiguous region may be released by calling
2897: @code{allot} with a negative argument, provided that the region has not
2898: been interrupted by compiling (or removing) definitions from the
2899: dictionary.
2900: @end itemize
2901:
1.29 crook 2902: @cindex data space pointer - alignment
2903: These factors affect the alignment of @code{here}, the data
2904: space pointer:
2905:
2906: @itemize @bullet
2907: @item
2908: If the data-space pointer is aligned@footnote{In ANS Forth-speak,
2909: @i{aligned} implictly means @code{CELL}-aligned.} before an
2910: @code{allot}, and a whole number of characters are reserved or released, it
2911: will remain aligned after the @code{allot}.
2912:
2913: @item
2914: If the data-space pointer is character-aligned before an @code{allot},
2915: and a whole number of cells are reserved or released, it will remain
2916: character-aligned after the @code{allot}.
2917:
2918: @item
2919: The initial contents of data space reserved using @code{allot} is
2920: undefined.
2921:
2922: @item
2923: Definitions created by @code{create}, @code{variable}, @code{2variable}
2924: return aligned addresses.
2925:
2926: @item
2927: After a definition is compiled or @code{align} is executed, the data
2928: space pointer is guaranteed to be aligned.
2929: @end itemize
2930:
1.27 crook 2931: doc-here
2932: doc-unused
2933: doc-allot
2934: doc-c,
1.29 crook 2935: doc-f,
1.27 crook 2936: doc-,
2937: doc-2,
1.29 crook 2938: @cindex user space
2939: doc-udp
2940: doc-uallot
1.27 crook 2941:
2942:
2943: @node Memory Access, Address Arithmetic, Reserving Data Space, Memory
1.1 anton 2944: @subsection Memory Access
2945: @cindex memory access words
2946:
2947: doc-@
2948: doc-!
2949: doc-+!
2950: doc-c@
2951: doc-c!
2952: doc-2@
2953: doc-2!
2954: doc-f@
2955: doc-f!
2956: doc-sf@
2957: doc-sf!
2958: doc-df@
2959: doc-df!
2960:
1.27 crook 2961: @node Address Arithmetic, Memory Blocks, Memory Access, Memory
2962: @subsection Address Arithmetic
1.1 anton 2963: @cindex address arithmetic words
2964:
2965: ANS Forth does not specify the sizes of the data types. Instead, it
2966: offers a number of words for computing sizes and doing address
1.29 crook 2967: arithmetic. Address arithmetic is performed in terms of address units
2968: (aus); on most systems the address unit is one byte. Note that a
2969: character may have more than one au, so @code{chars} is no noop (on
2970: systems where it is a noop, it compiles to nothing).
1.1 anton 2971:
2972: @cindex alignment of addresses for types
2973: ANS Forth also defines words for aligning addresses for specific
2974: types. Many computers require that accesses to specific data types
2975: must only occur at specific addresses; e.g., that cells may only be
2976: accessed at addresses divisible by 4. Even if a machine allows unaligned
2977: accesses, it can usually perform aligned accesses faster.
2978:
2979: For the performance-conscious: alignment operations are usually only
2980: necessary during the definition of a data structure, not during the
2981: (more frequent) accesses to it.
2982:
2983: ANS Forth defines no words for character-aligning addresses. This is not
2984: an oversight, but reflects the fact that addresses that are not
2985: char-aligned have no use in the standard and therefore will not be
2986: created.
2987:
2988: @cindex @code{CREATE} and alignment
1.29 crook 2989: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 2990: are cell-aligned; in addition, Gforth guarantees that these addresses
2991: are aligned for all purposes.
2992:
1.26 crook 2993: Note that the ANS Forth word @code{char} has nothing to do with address
2994: arithmetic.
1.1 anton 2995:
2996: doc-chars
2997: doc-char+
2998: doc-cells
2999: doc-cell+
3000: doc-cell
3001: doc-align
3002: doc-aligned
3003: doc-floats
3004: doc-float+
3005: doc-float
3006: doc-falign
3007: doc-faligned
3008: doc-sfloats
3009: doc-sfloat+
3010: doc-sfalign
3011: doc-sfaligned
3012: doc-dfloats
3013: doc-dfloat+
3014: doc-dfalign
3015: doc-dfaligned
3016: doc-maxalign
3017: doc-maxaligned
3018: doc-cfalign
3019: doc-cfaligned
3020: doc-address-unit-bits
3021:
1.27 crook 3022: @node Memory Blocks, Dynamic Allocation, Address Arithmetic, Memory
1.1 anton 3023: @subsection Memory Blocks
3024: @cindex memory block words
1.27 crook 3025: @cindex character strings - moving and copying
3026:
3027: Memory blocks often represent character strings; @xref{String Formats}
3028: for ways of storing character strings in memory. @xref{Displaying
3029: characters and strings} for other string-processing words.
1.1 anton 3030:
1.21 crook 3031: Some of these words work on address units (increments of @code{CELL}),
3032: and expect a @code{CELL}-aligned address. Others work on character units
3033: (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
3034: address. Choose the correct operation depending upon your data type. If
3035: you are moving a block of memory (for example, a region reserved by
3036: @code{allot}) it is safe to use @code{move}, and it should be faster
3037: than using @code{cmove}. If you are moving (for example) a string
3038: compiled using @code{S"}, it is not portable to use @code{move}; the
3039: alignment of the string in memory could change, and the relationship
3040: between @code{CELL} and @code{CHAR} could change.
3041:
3042: When copying characters between overlapping memory regions, choose
3043: carefully between @code{cmove} and @code{cmove>}.
3044:
1.29 crook 3045: You can only use any of these words @i{portably} to access data space.
1.21 crook 3046:
1.27 crook 3047: @comment TODO - think the naming of the arguments is wrong for move
1.29 crook 3048: @comment well, really it seems to be the Standard that's wrong; it
3049: @comment describes MOVE as a word that requires a CELL-aligned source
3050: @comment and destination address but a xtranfer count that need not
3051: @comment be a multiple of CELL.
1.1 anton 3052: doc-move
3053: doc-erase
3054: doc-cmove
3055: doc-cmove>
3056: doc-fill
3057: doc-blank
1.21 crook 3058: doc-compare
3059: doc-search
1.27 crook 3060: doc--trailing
3061: doc-/string
3062:
3063: @comment TODO examples
3064:
3065: @node Dynamic Allocation, ,Memory Blocks, Memory
3066: @subsection Dynamic Allocation of Memory
3067: @cindex dynamic allocation of memory
3068: @cindex memory-allocation word set
3069:
3070: The ANS Forth memory-allocation word set allows memory regions to be
3071: dynamically assigned, resized and released without affecting the data
3072: space pointer. In Gforth, these words are implemented using
3073: the standard C library calls malloc(), free() and resize().
3074:
3075: doc-allocate
3076: doc-free
3077: doc-resize
3078:
1.1 anton 3079:
1.26 crook 3080: @node Control Structures, Defining Words, Memory, Words
1.1 anton 3081: @section Control Structures
3082: @cindex control structures
3083:
3084: Control structures in Forth cannot be used in interpret state, only in
1.29 crook 3085: compile state@footnote{To be precise, they have no interpretation
3086: semantics (@pxref{Interpretation and Compilation Semantics}).}, i.e., in
1.1 anton 3087: a colon definition. We do not like this limitation, but have not seen a
3088: satisfying way around it yet, although many schemes have been proposed.
3089:
3090: @menu
1.29 crook 3091: * Selection:: IF.. ELSE.. ENDIF
3092: * Simple Loops:: BEGIN..
3093: * Counted Loops:: DO
3094: * Arbitrary control structures::
3095: * Calls and returns::
1.1 anton 3096: * Exception Handling::
3097: @end menu
3098:
3099: @node Selection, Simple Loops, Control Structures, Control Structures
3100: @subsection Selection
3101: @cindex selection control structures
3102: @cindex control structures for selection
3103:
3104: @cindex @code{IF} control structure
3105: @example
1.29 crook 3106: @i{flag}
1.1 anton 3107: IF
1.29 crook 3108: @i{code}
1.1 anton 3109: ENDIF
3110: @end example
1.21 crook 3111: @noindent
1.1 anton 3112: or
3113: @example
1.29 crook 3114: @i{flag}
1.1 anton 3115: IF
1.29 crook 3116: @i{code1}
1.1 anton 3117: ELSE
1.29 crook 3118: @i{code2}
1.1 anton 3119: ENDIF
3120: @end example
3121:
3122: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
3123: standard, and @code{ENDIF} is not, although it is quite popular. We
3124: recommend using @code{ENDIF}, because it is less confusing for people
3125: who also know other languages (and is not prone to reinforcing negative
3126: prejudices against Forth in these people). Adding @code{ENDIF} to a
3127: system that only supplies @code{THEN} is simple:
3128: @example
1.21 crook 3129: : ENDIF POSTPONE THEN ; immediate
1.1 anton 3130: @end example
3131:
3132: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
3133: (adv.)} has the following meanings:
3134: @quotation
3135: ... 2b: following next after in order ... 3d: as a necessary consequence
3136: (if you were there, then you saw them).
3137: @end quotation
3138: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
3139: and many other programming languages has the meaning 3d.]
3140:
1.21 crook 3141: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 3142: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 3143: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 3144: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
3145: @file{compat/control.fs}.
3146:
3147: @cindex @code{CASE} control structure
3148: @example
1.29 crook 3149: @i{n}
1.1 anton 3150: CASE
1.29 crook 3151: @i{n1} OF @i{code1} ENDOF
3152: @i{n2} OF @i{code2} ENDOF
1.1 anton 3153: @dots{}
3154: ENDCASE
3155: @end example
3156:
1.29 crook 3157: Executes the first @i{codei}, where the @i{ni} is equal to
3158: @i{n}. A default case can be added by simply writing the code after
3159: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
1.1 anton 3160: but must not consume it.
3161:
3162: @node Simple Loops, Counted Loops, Selection, Control Structures
3163: @subsection Simple Loops
3164: @cindex simple loops
3165: @cindex loops without count
3166:
3167: @cindex @code{WHILE} loop
3168: @example
3169: BEGIN
1.29 crook 3170: @i{code1}
3171: @i{flag}
1.1 anton 3172: WHILE
1.29 crook 3173: @i{code2}
1.1 anton 3174: REPEAT
3175: @end example
3176:
1.29 crook 3177: @i{code1} is executed and @i{flag} is computed. If it is true,
3178: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 3179: false, execution continues after the @code{REPEAT}.
3180:
3181: @cindex @code{UNTIL} loop
3182: @example
3183: BEGIN
1.29 crook 3184: @i{code}
3185: @i{flag}
1.1 anton 3186: UNTIL
3187: @end example
3188:
1.29 crook 3189: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 3190:
3191: @cindex endless loop
3192: @cindex loops, endless
3193: @example
3194: BEGIN
1.29 crook 3195: @i{code}
1.1 anton 3196: AGAIN
3197: @end example
3198:
3199: This is an endless loop.
3200:
3201: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
3202: @subsection Counted Loops
3203: @cindex counted loops
3204: @cindex loops, counted
3205: @cindex @code{DO} loops
3206:
3207: The basic counted loop is:
3208: @example
1.29 crook 3209: @i{limit} @i{start}
1.1 anton 3210: ?DO
1.29 crook 3211: @i{body}
1.1 anton 3212: LOOP
3213: @end example
3214:
1.29 crook 3215: This performs one iteration for every integer, starting from @i{start}
3216: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 3217: accessed with @code{i}. For example, the loop:
1.1 anton 3218: @example
3219: 10 0 ?DO
3220: i .
3221: LOOP
3222: @end example
1.21 crook 3223: @noindent
3224: prints @code{0 1 2 3 4 5 6 7 8 9}
3225:
1.1 anton 3226: The index of the innermost loop can be accessed with @code{i}, the index
3227: of the next loop with @code{j}, and the index of the third loop with
3228: @code{k}.
3229:
3230: doc-i
3231: doc-j
3232: doc-k
3233:
3234: The loop control data are kept on the return stack, so there are some
1.21 crook 3235: restrictions on mixing return stack accesses and counted loop words. In
3236: particuler, if you put values on the return stack outside the loop, you
3237: cannot read them inside the loop@footnote{well, not in a way that is
3238: portable.}. If you put values on the return stack within a loop, you
3239: have to remove them before the end of the loop and before accessing the
3240: index of the loop.
1.1 anton 3241:
3242: There are several variations on the counted loop:
3243:
1.21 crook 3244: @itemize @bullet
3245: @item
3246: @code{LEAVE} leaves the innermost counted loop immediately; execution
3247: continues after the associated @code{LOOP} or @code{NEXT}. For example:
3248:
3249: @example
3250: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
3251: @end example
3252: prints @code{0 1 2 3}
3253:
1.1 anton 3254:
1.21 crook 3255: @item
3256: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
3257: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
3258: return stack so @code{EXIT} can get to its return address. For example:
3259:
3260: @example
3261: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
3262: @end example
3263: prints @code{0 1 2 3}
3264:
3265:
3266: @item
1.29 crook 3267: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 3268: (and @code{LOOP} iterates until they become equal by wrap-around
3269: arithmetic). This behaviour is usually not what you want. Therefore,
3270: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 3271: @code{?DO}), which do not enter the loop if @i{start} is greater than
3272: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 3273: unsigned loop parameters.
3274:
1.21 crook 3275: @item
3276: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
3277: the loop, independent of the loop parameters. Do not use @code{DO}, even
3278: if you know that the loop is entered in any case. Such knowledge tends
3279: to become invalid during maintenance of a program, and then the
3280: @code{DO} will make trouble.
3281:
3282: @item
1.29 crook 3283: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
3284: index by @i{n} instead of by 1. The loop is terminated when the border
3285: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 3286:
1.21 crook 3287: @example
3288: 4 0 +DO i . 2 +LOOP
3289: @end example
3290: @noindent
3291: prints @code{0 2}
3292:
3293: @example
3294: 4 1 +DO i . 2 +LOOP
3295: @end example
3296: @noindent
3297: prints @code{1 3}
1.1 anton 3298:
3299:
3300: @cindex negative increment for counted loops
3301: @cindex counted loops with negative increment
1.29 crook 3302: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 3303:
1.21 crook 3304: @example
3305: -1 0 ?DO i . -1 +LOOP
3306: @end example
3307: @noindent
3308: prints @code{0 -1}
1.1 anton 3309:
1.21 crook 3310: @example
3311: 0 0 ?DO i . -1 +LOOP
3312: @end example
3313: prints nothing.
1.1 anton 3314:
1.29 crook 3315: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
3316: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
3317: index by @i{u} each iteration. The loop is terminated when the border
3318: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 3319: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
3320:
1.21 crook 3321: @example
3322: -2 0 -DO i . 1 -LOOP
3323: @end example
3324: @noindent
3325: prints @code{0 -1}
1.1 anton 3326:
1.21 crook 3327: @example
3328: -1 0 -DO i . 1 -LOOP
3329: @end example
3330: @noindent
3331: prints @code{0}
3332:
3333: @example
3334: 0 0 -DO i . 1 -LOOP
3335: @end example
3336: @noindent
3337: prints nothing.
1.1 anton 3338:
1.21 crook 3339: @end itemize
1.1 anton 3340:
3341: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 3342: @code{-LOOP} are not defined in ANS Forth. However, an implementation
3343: for these words that uses only standard words is provided in
3344: @file{compat/loops.fs}.
1.1 anton 3345:
3346:
3347: @cindex @code{FOR} loops
1.26 crook 3348: Another counted loop is:
1.1 anton 3349: @example
1.29 crook 3350: @i{n}
1.1 anton 3351: FOR
1.29 crook 3352: @i{body}
1.1 anton 3353: NEXT
3354: @end example
3355: This is the preferred loop of native code compiler writers who are too
1.26 crook 3356: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 3357: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
3358: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 3359: Forth systems may behave differently, even if they support @code{FOR}
3360: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 3361:
3362: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
3363: @subsection Arbitrary control structures
3364: @cindex control structures, user-defined
3365:
3366: @cindex control-flow stack
3367: ANS Forth permits and supports using control structures in a non-nested
3368: way. Information about incomplete control structures is stored on the
3369: control-flow stack. This stack may be implemented on the Forth data
3370: stack, and this is what we have done in Gforth.
3371:
3372: @cindex @code{orig}, control-flow stack item
3373: @cindex @code{dest}, control-flow stack item
3374: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
3375: entry represents a backward branch target. A few words are the basis for
3376: building any control structure possible (except control structures that
3377: need storage, like calls, coroutines, and backtracking).
3378:
3379: doc-if
3380: doc-ahead
3381: doc-then
3382: doc-begin
3383: doc-until
3384: doc-again
3385: doc-cs-pick
3386: doc-cs-roll
3387:
1.21 crook 3388: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
3389: manipulate the control-flow stack in a portable way. Without them, you
3390: would need to know how many stack items are occupied by a control-flow
3391: entry (many systems use one cell. In Gforth they currently take three,
3392: but this may change in the future).
3393:
1.1 anton 3394: Some standard control structure words are built from these words:
3395:
3396: doc-else
3397: doc-while
3398: doc-repeat
3399:
3400: Gforth adds some more control-structure words:
3401:
3402: doc-endif
3403: doc-?dup-if
3404: doc-?dup-0=-if
3405:
3406: Counted loop words constitute a separate group of words:
3407:
3408: doc-?do
3409: doc-+do
3410: doc-u+do
3411: doc--do
3412: doc-u-do
3413: doc-do
3414: doc-for
3415: doc-loop
3416: doc-+loop
3417: doc--loop
3418: doc-next
3419: doc-leave
3420: doc-?leave
3421: doc-unloop
3422: doc-done
3423:
1.21 crook 3424: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
3425: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 3426: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
3427: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
3428: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
3429: resolved (by using one of the loop-ending words or @code{DONE}).
3430:
1.26 crook 3431: Another group of control structure words are:
1.1 anton 3432:
3433: doc-case
3434: doc-endcase
3435: doc-of
3436: doc-endof
3437:
1.21 crook 3438: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
3439: @code{CS-ROLL}.
1.1 anton 3440:
3441: @subsubsection Programming Style
3442:
3443: In order to ensure readability we recommend that you do not create
3444: arbitrary control structures directly, but define new control structure
3445: words for the control structure you want and use these words in your
1.26 crook 3446: program. For example, instead of writing:
1.1 anton 3447:
3448: @example
1.26 crook 3449: BEGIN
1.1 anton 3450: ...
1.26 crook 3451: IF [ 1 CS-ROLL ]
1.1 anton 3452: ...
1.26 crook 3453: AGAIN THEN
1.1 anton 3454: @end example
3455:
1.21 crook 3456: @noindent
1.1 anton 3457: we recommend defining control structure words, e.g.,
3458:
3459: @example
1.26 crook 3460: : WHILE ( DEST -- ORIG DEST )
3461: POSTPONE IF
3462: 1 CS-ROLL ; immediate
3463:
3464: : REPEAT ( orig dest -- )
3465: POSTPONE AGAIN
3466: POSTPONE THEN ; immediate
1.1 anton 3467: @end example
3468:
1.21 crook 3469: @noindent
1.1 anton 3470: and then using these to create the control structure:
3471:
3472: @example
1.26 crook 3473: BEGIN
1.1 anton 3474: ...
1.26 crook 3475: WHILE
1.1 anton 3476: ...
1.26 crook 3477: REPEAT
1.1 anton 3478: @end example
3479:
3480: That's much easier to read, isn't it? Of course, @code{REPEAT} and
3481: @code{WHILE} are predefined, so in this example it would not be
3482: necessary to define them.
3483:
3484: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
3485: @subsection Calls and returns
3486: @cindex calling a definition
3487: @cindex returning from a definition
3488:
1.3 anton 3489: @cindex recursive definitions
3490: A definition can be called simply be writing the name of the definition
1.26 crook 3491: to be called. Normally a definition is invisible during its own
1.3 anton 3492: definition. If you want to write a directly recursive definition, you
1.26 crook 3493: can use @code{recursive} to make the current definition visible, or
3494: @code{recurse} to call the current definition directly.
1.3 anton 3495:
3496: doc-recursive
3497: doc-recurse
3498:
1.21 crook 3499: @comment TODO add example of the two recursion methods
1.12 anton 3500: @quotation
3501: @progstyle
3502: I prefer using @code{recursive} to @code{recurse}, because calling the
3503: definition by name is more descriptive (if the name is well-chosen) than
3504: the somewhat cryptic @code{recurse}. E.g., in a quicksort
3505: implementation, it is much better to read (and think) ``now sort the
3506: partitions'' than to read ``now do a recursive call''.
3507: @end quotation
1.3 anton 3508:
1.29 crook 3509: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 3510:
3511: @example
1.28 crook 3512: Defer foo
1.3 anton 3513:
3514: : bar ( ... -- ... )
3515: ... foo ... ;
3516:
3517: :noname ( ... -- ... )
3518: ... bar ... ;
3519: IS foo
3520: @end example
3521:
1.26 crook 3522: The current definition returns control to the calling definition when
1.29 crook 3523: the end of the definition is reached or @code{EXIT} is
3524: encountered. Deferred words are discussed in more detail in @ref{Simple
3525: Defining Words}.
1.1 anton 3526:
3527: doc-exit
3528: doc-;s
3529:
3530: @node Exception Handling, , Calls and returns, Control Structures
3531: @subsection Exception Handling
1.26 crook 3532: @cindex exceptions
1.1 anton 3533:
1.26 crook 3534: If your program detects a fatal error condition, the simplest action
3535: that it can take is to @code{quit}. This resets the return stack and
3536: restarts the text interpreter, but does not print any error message.
1.21 crook 3537:
1.26 crook 3538: The next stage in severity is to execute @code{abort}, which has the
3539: same effect as @code{quit}, with the addition that it resets the data
3540: stack.
1.1 anton 3541:
1.26 crook 3542: A slightly more sophisticated approach is use use @code{abort"}, which
3543: compiles a string to be used as an error message and does a conditional
3544: @code{abort} at run-time. For example:
1.1 anton 3545:
1.26 crook 3546: @example
1.30 ! anton 3547: @kbd{: checker abort" That flag was true" ." A false flag" ;@key{RET}} ok
! 3548: @kbd{0 checker@key{RET}} A false flag ok
! 3549: @kbd{1 checker@key{RET}}
1.26 crook 3550: :1: That flag was true
3551: 1 checker
3552: ^^^^^^^
3553: $400D1648 throw
3554: $400E4660
3555: @end example
1.1 anton 3556:
1.26 crook 3557: These simple techniques allow a program to react to a fatal error
3558: condition, but they are not exactly user-friendly. The ANS Forth
3559: Exception word set provides the pair of words @code{throw} and
3560: @code{catch}, which can be used to provide sophisticated error-handling.
1.1 anton 3561:
1.26 crook 3562: @code{catch} has a similar behaviour to @code{execute}, in that it takes
1.29 crook 3563: an @i{xt} as a parameter and starts execution of the xt. However,
1.26 crook 3564: before passing control to the xt, @code{catch} pushes an
1.29 crook 3565: @dfn{exception frame} onto the @dfn{exception stack}. This exception
1.26 crook 3566: frame is used to restore the system to a known state if a detected error
3567: occurs during the execution of the xt. A typical way to use @code{catch}
3568: would be:
1.1 anton 3569:
1.26 crook 3570: @example
3571: ... ['] foo catch IF ...
3572: @end example
1.1 anton 3573:
1.26 crook 3574: Whilst @code{foo} executes, it can call other words to any level of
3575: nesting, as usual. If @code{foo} (and all the words that it calls)
3576: execute successfully, control will ultimately passes to the word following
3577: the @code{catch}, and there will be a @code{true} flag (0) at
3578: TOS. However, if any word detects an error, it can terminate the
3579: execution of @code{foo} by pushing an error code onto the stack and then
3580: performing a @code{throw}. The execution of @code{throw} will pass
3581: control to the word following the @code{catch}, but this time the TOS
3582: will hold the error code. Therefore, the @code{IF} in the example
3583: can be used to determine whether @code{foo} executed successfully.
1.1 anton 3584:
1.26 crook 3585: This simple example shows how you can use @code{throw} and @code{catch}
3586: to ``take over'' exception handling from the system:
1.1 anton 3587: @example
1.26 crook 3588: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
1.1 anton 3589: @end example
3590:
1.26 crook 3591: The next example is more sophisticated and shows a multi-level
3592: @code{throw} and @code{catch}. To understand this example, start at the
3593: definition of @code{top-level} and work backwards:
3594:
1.1 anton 3595: @example
1.26 crook 3596: : lowest-level ( -- c )
3597: key dup 27 = if
3598: 1 throw \ ESCAPE key pressed
3599: else
3600: ." lowest-level successfull" CR
3601: then
3602: ;
3603:
3604: : lower-level ( -- c )
3605: lowest-level
3606: \ at this level consider a CTRL-U to be a fatal error
3607: dup 21 = if \ CTRL-U
3608: 2 throw
3609: else
3610: ." lower-level successfull" CR
3611: then
3612: ;
3613:
3614: : low-level ( -- c )
3615: ['] lower-level catch
3616: ?dup if
3617: \ error occurred - do we recognise it?
3618: dup 1 = if
3619: \ ESCAPE key pressed.. pretend it was an E
3620: [char] E
3621: else throw \ propogate the error upwards
3622: then
3623: then
3624: ." low-level successfull" CR
3625: ;
3626:
3627: : top-level ( -- )
3628: CR ['] low-level catch \ CATCH is used like EXECUTE
3629: ?dup if \ error occurred..
3630: ." Error " . ." occurred - contact your supplier"
3631: else
3632: ." The '" emit ." ' key was pressed" CR
3633: then
3634: ;
1.1 anton 3635: @end example
3636:
1.26 crook 3637: The ANS Forth document assigns @code{throw} codes thus:
1.1 anton 3638:
1.26 crook 3639: @itemize @bullet
3640: @item
3641: codes in the range -1 -- -255 are reserved to be assigned by the
3642: Standard. Assignments for codes in the range -1 -- -58 are currently
3643: documented in the Standard. In particular, @code{-1 throw} is equivalent
3644: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
3645: @item
3646: codes in the range -256 -- -4095 are reserved to be assigned by the system.
3647: @item
3648: all other codes may be assigned by programs.
3649: @end itemize
1.1 anton 3650:
1.26 crook 3651: Gforth provides the word @code{exception} as a mechanism for assigning
3652: system throw codes to applications. This allows multiple applications to
3653: co-exist in memory without any clash of @code{throw} codes. A definition
3654: of @code{exception} in ANS Forth is provided in
3655: @file{compat/exception.fs}.
1.1 anton 3656:
1.26 crook 3657: doc-quit
3658: doc-abort
3659: doc-abort"
1.1 anton 3660:
1.26 crook 3661: doc-catch
1.29 crook 3662: doc-throw
3663: doc---exception-exception
3664:
3665:
3666: @c -------------------------------------------------------------
3667: @node Defining Words, The Text Interpreter, Control Structures, Words
3668: @section Defining Words
3669: @cindex defining words
3670:
3671: @menu
3672: * Simple Defining Words:: Variables, values and constants
3673: * Colon Definitions::
3674: * User-defined Defining Words::
3675: * Supplying names::
3676: * Interpretation and Compilation Semantics::
3677: @end menu
3678:
3679: @node Simple Defining Words, Colon Definitions, Defining Words, Defining Words
3680: @subsection Simple Defining Words
3681: @cindex simple defining words
3682: @cindex defining words, simple
3683:
3684: Defining words are used to create new entries in the dictionary. The
3685: simplest defining word is @code{CREATE}. @code{CREATE} is used like
3686: this:
3687:
3688: @example
3689: CREATE new-word1
3690: @end example
3691:
3692: @code{CREATE} is a parsing word that generates a dictionary entry for
3693: @code{new-word1}. When @code{new-word1} is executed, all that it does is
3694: leave an address on the stack. The address represents the value of
3695: the data space pointer (@code{HERE}) at the time that @code{new-word1}
3696: was defined. Therefore, @code{CREATE} is a way of associating a name
3697: with the address of a region of memory.
3698:
3699: By extending this example to reserve some memory in data space, we end
3700: up with a @i{variable}. Here are two different ways to do it:
3701:
3702: @example
3703: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
3704: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
3705: @end example
3706:
3707: The variable can be examined and modified using @code{@@} (``fetch'') and
3708: @code{!} (``store'') like this:
3709:
3710: @example
3711: new-word2 @@ . \ get address, fetch from it and display
3712: 1234 new-word2 ! \ new value, get address, store to it
3713: @end example
3714:
3715: As a final refinement, the whole code sequence can be wrapped up in a
3716: defining word (pre-empting the subject of the next section), making it
3717: easier to create new variables:
3718:
3719: @example
3720: : myvariable ( "name" -- a-addr ) CREATE 1 cells allot ;
3721:
3722: myvariable foo
3723: myvariable joe
3724:
3725: 45 3 * foo ! \ set foo to 135
3726: 1234 joe ! \ set joe to 1234
3727: 3 joe +! \ increment joe by 3.. to 1237
3728: @end example
3729:
3730: Not surprisingly, there is no need to define @code{myvariable}, since
3731: Forth already has a definition @code{Variable}. It behaves in exactly
3732: the same way as @code{myvariable} but it is implemented in an optimised
3733: way. Forth also provides @code{2Variable} and @code{fvariable} for
3734: double and floating-point variables, respectively.
3735:
3736: @cindex arrays
3737: A similar mechanism can be used to create arrays. For example, an
3738: 80-character text input buffer:
3739:
3740: @example
3741: CREATE text-buf 80 chars allot
3742:
3743: text-buf 0 chars c@@ \ the 1st character (offset 0)
3744: text-buf 3 chars c@@ \ the 4th character (offset 3)
3745: @end example
3746:
3747: You can build arbitrarily complex data structures by allocating
3748: appropriate areas of memory. @xref{Structures} for further discussions
3749: of this, and to learn about some Gforth tools that make it easier.
3750:
3751: @cindex user variables
3752: @cindex user space
3753: The defining word @code{User} behaves in the same way as @code{Variable}.
3754: The difference is that it reserves space in @i{user (data) space} rather
3755: than normal data space. In a Forth system that has a multi-tasker, each
3756: task has its own set of user variables.
3757:
3758: @comment TODO is that stuff about user variables strictly correct? Is it
3759: @comment just terminal tasks that have user variables?
3760: @comment should document tasker.fs (with some examples) elsewhere
3761: @comment in this manual, then expand on user space and user variables.
3762:
3763: After @code{CREATE} and @code{Variable}s, the next defining word to
3764: consider is @code{Constant}. @code{Constant} allows you to declare a
3765: fixed value and refer to it by name. For example:
3766:
3767: @example
3768: 12 Constant INCHES-PER-FOOT
3769: 3E+08 fconstant SPEED-O-LIGHT
3770: @end example
3771:
3772: A @code{Variable} can be both read and written, so its run-time
3773: behaviour is to supply an address through which its current value can be
3774: manipulated. In contrast, the value of a @code{Constant} cannot be
3775: changed once it has been declared@footnote{Well, often it can be -- but
3776: not in a Standard, portable way. It's safer to use a @code{Value} (read
3777: on).} so it's not necessary to supply the address -- it is more
3778: efficient to return the value of the constant directly. That's exactly
3779: what happens; the run-time effect of a constant is to put its value on
3780: the top of the stack (@ref{User-defined Defining Words} describes one
3781: way of implementing @code{Constant}).
3782:
3783: Gforth also provides @code{2Constant} and @code{fconstant} for defining
3784: double and floating-point constants, respectively.
3785:
3786: Constants in Forth behave differently from their equivalents in other
3787: programming languages. In other languages, a constant (such as an EQU in
3788: assembler or a #define in C) only exists at compile-time; in the
3789: executable program the constant has been translated into an absolute
3790: number and, unless you are using a symbolic debugger, it's impossible to
3791: know what abstract thing that number represents. In Forth a constant has
3792: an entry in the name dictionary and remains there after the code that
3793: uses it has been defined. In fact, it must remain in the dictionary
3794: since it has run-time duties to perform. For example:
3795:
3796: @example
3797: 12 Constant INCHES-PER-FOOT
3798: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
3799: @end example
3800:
3801: @cindex in-lining of constants
3802: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
3803: associated with the constant @code{INCHES-PER-FOOT}. If you use
3804: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
3805: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
3806: attempt to optimise constants by in-lining them where they are used. You
3807: can force Gforth to in-line a constant like this:
3808:
3809: @example
3810: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
3811: @end example
3812:
3813: If you use @code{see} to decompile @i{this} version of
3814: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
3815: longer present. @xref{Interpret/Compile states} and @xref{Literals}
3816: explain to this works.
3817:
3818: In-lining constants in this way might improve execution time
3819: fractionally, and can ensure that a constant is now only referenced at
3820: compile-time. However, the definition of the constant still remains in
3821: the dictionary. Some Forth compilers provide a mechanism for controlling
3822: a second dictionary for holding transient words such that this second
3823: dictionary can be deleted later in order to recover memory
3824: space. However, there is no standard way of doing this.
3825:
3826: One aspect of constants and variables that can sometimes be confusing is
3827: that they have different stack effects; one returns its value whilst the
3828: other returns the address of its value. The defining word @code{Value}
3829: provides an alternative to @code{Variable}, and has the same stack
3830: effect as a constant. A @code{Value} needs an additional word, @code{TO}
3831: to allow its value to be changed. Here are some examples:
3832:
3833: @example
3834: 12 Value APPLES \ a Value is initialised when it is declared.. like a
3835: \ constant but unlike a variable
3836: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
3837: APPLES \ puts 34 on the top of the stack.
3838: @end example
3839:
3840: The defining word @code{Defer} allows you to define a word by name
3841: without defining its behaviour; the definition of its behaviour is
3842: deferred. Here are two situation where this can be useful:
3843:
3844: @itemize @bullet
3845: @item
3846: Where you want to allow the behaviour of a word to be altered later, and
3847: for all precompiled references to the word to change when its behaviour
3848: is changed.
3849: @item
3850: For mutual recursion; @xref{Calls and returns}.
3851: @end itemize
3852:
3853: In the following example, @code{foo} always invokes the version of
3854: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
3855: always invokes the version that prints ``@code{Hello}''. There is no way
3856: of getting @code{foo} to use the later version without re-ordering the
3857: source code and recompilng it.
3858:
3859: @example
3860: : greet ." Good morning" ;
3861: : foo ... greet ... ;
3862: : greet ." Hello" ;
3863: : bar ... greet ... ;
3864: @end example
3865:
3866: This problem can be solved by defining @code{greet} as a @code{Defer}red
3867: word. The behaviour of a @code{Defer}red word can be defined and
3868: redefined at any time by using @code{IS} to associate the xt of a
3869: previously-defined word with it. The previous example becomes:
3870:
3871: @example
3872: Defer greet
3873: : foo ... greet ... ;
3874: : bar ... greet ... ;
3875: : greet1 ." Good morning" ;
3876: : greet2 ." Hello" ;
3877: ' greet2 IS greet \ make greet behave like greet2
3878: @end example
3879:
3880: A deferred word can only inherit default semantics from the xt (because
3881: that is all that an xt can represent -- @pxref{Tokens for Words} for
3882: more discussion of this). However, the semantics of the deferred word
3883: itself can be modified at the time that it is defined. For example:
3884:
3885: @example
3886: : bar .... ; compile-only
3887: Defer fred immediate
3888: Defer jim
3889:
3890: ' bar IS jim \ jim has default semantics
3891: ' bar IS fred \ fred is immediate
3892: @end example
1.1 anton 3893:
1.29 crook 3894: The defining word @code{Alias} allows you to define a word by name that
3895: has the same behaviour as some other word. Here are two situation where
3896: this can be useful:
1.1 anton 3897:
1.29 crook 3898: @itemize @bullet
3899: @item
3900: When you want access to a word's definition from a different word list
3901: (for an example of this, see the definition of the @code{Root} word list
3902: in the Gforth source).
3903: @item
3904: When you want to create a synonym; a definition that can be known by
3905: either of two names (for example, @code{THEN} and @code{ENDIF} are
3906: aliases).
3907: @end itemize
1.1 anton 3908:
1.29 crook 3909: The word whose behaviour the alias is to inherit is represented by an
3910: xt. Therefore, the alias can only inherits default semantics from its
3911: ancestor. The semantics of the alias itself can be modified at the time
3912: that it is defined. For example:
1.1 anton 3913:
1.29 crook 3914: @example
3915: : foo ... ; immediate
1.1 anton 3916:
1.29 crook 3917: ' foo Alias bar \ bar is not an immediate word
3918: ' foo Alias fooby immediate \ fooby is an immediate word
3919: @end example
1.26 crook 3920:
1.29 crook 3921: Words that are aliases have the same xt. Their semantics can differ
3922: because the rules about a word's semantics are stored in the name
3923: dictionary, and the aliases each have their own dictionary entry. It
3924: follows that words that are aliases have different name tokens and may
3925: have the same or different compilation tokens. Once again, see
3926: @ref{Tokens for Words} for more discussions of this.
1.27 crook 3927:
1.29 crook 3928: doc-create
1.26 crook 3929: doc-variable
3930: doc-2variable
3931: doc-fvariable
3932: doc-user
1.29 crook 3933: doc-constant
3934: doc-2constant
3935: doc-fconstant
1.26 crook 3936: doc-value
3937: doc-to
3938: doc-defer
3939: doc-is
1.29 crook 3940: doc-alias
3941: @comment TODO document these: what's defers <is> [is]
3942: doc-what's
1.28 crook 3943: doc-defers
1.26 crook 3944:
3945: Definitions in ANS Forth for @code{defer}, @code{<is>} and
3946: @code{[is]} are provided in @file{compat/defer.fs}.
1.29 crook 3947:
1.1 anton 3948:
1.26 crook 3949: @node Colon Definitions, User-defined Defining Words, Simple Defining Words, Defining Words
3950: @subsection Colon Definitions
3951: @cindex colon definitions
1.1 anton 3952:
1.26 crook 3953: @example
3954: : name ( ... -- ... )
3955: word1 word2 word3 ;
3956: @end example
1.1 anton 3957:
1.29 crook 3958: @noindent
3959: Creates a word called @code{name} that, upon execution, executes
1.26 crook 3960: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.1 anton 3961:
1.29 crook 3962: The explanation above is somewhat superficial. @xref{Your first
3963: definition} for simple examples of colon definitions, then
3964: @xref{Interpretation and Compilation Semantics} for an in-depth
3965: discussion of some of the issues involved.
1.26 crook 3966:
3967: doc-:
3968: doc-;
1.1 anton 3969:
1.26 crook 3970: @node User-defined Defining Words, Supplying names, Colon Definitions, Defining Words
3971: @subsection User-defined Defining Words
3972: @cindex user-defined defining words
3973: @cindex defining words, user-defined
1.1 anton 3974:
1.29 crook 3975: You can create a new defining word by wrapping defining-time code around
3976: an existing defining word and putting the sequence in a colon
3977: definition. For example, suppose that you have a word @code{stats} that
3978: gathers statistics about colon definitions given the @i{xt} of the
3979: definition, and you want every colon definition in your application to
3980: make a call to @code{stats}. You can define and use a new version of
3981: @code{:} like this:
3982:
3983: @example
3984: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
3985: ... ; \ other code
3986:
3987: : my: : lastxt postpone literal ['] stats compile, ;
3988:
3989: my: foo + - ;
3990: @end example
3991:
3992: When @code{foo} is defined using @code{my:} these steps occur:
3993:
3994: @itemize @bullet
3995: @item
3996: @code{my:} is executed.
3997: @item
3998: The @code{:} within the definition (the one between @code{my:} and
3999: @code{lastxt}) is executed, and does just what it always does; it parses
4000: the input stream for a name, builds a dictionary header for the name
4001: @code{foo} and switches @code{state} from interpret to compile.
4002: @item
4003: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
4004: being defined -- @code{foo} -- onto the stack.
4005: @item
4006: The code that was produced by @code{postpone literal} is executed; this
4007: causes the value on the stack to be compiled as a literal in the code
4008: area of @code{foo}.
4009: @item
4010: The code @code{['] stats} compiles a literal into the definition of
4011: @code{my:}. When @code{compile,} is executed, that literal -- the
4012: execution token for @code{stats} -- is layed down in the code area of
4013: @code{foo} , following the literal@footnote{Strictly speaking, the
4014: mechanism that @code{compile,} uses to convert an @i{xt} into something
4015: in the code area is implementation-dependent. A threaded implementation
4016: might spit out the execution token directly whilst another
4017: implementation might spit out a native code sequence.}.
4018: @item
4019: At this point, the execution of @code{my:} is complete, and control
4020: returns to the text interpreter. The text interpreter is in compile
4021: state, so subsequent text @code{+ -} is compiled into the definition of
4022: @code{foo} and the @code{;} terminates the definition as always.
4023: @end itemize
4024:
4025: You can use @code{see} to decompile a word that was defined using
4026: @code{my:} and see how it is different from a normal @code{:}
4027: definition. For example:
4028:
4029: @example
4030: : bar + - ; \ like foo but using : rather than my:
4031: see bar
4032: : bar
4033: + - ;
4034: see foo
4035: : foo
4036: 107645672 stats + - ;
4037:
4038: \ use ' stats . to show that 107645672 is the xt for stats
4039: @end example
4040:
4041:
4042: Rather than edit your application's source code to change every @code{:}
4043: to a @code{my:}, use a deferred word:
4044:
4045: @example
4046: : real: : ; \ retain access to the original
4047: defer : \ redefine as a deferred word
4048: ' my: IS : \ use special version of :
4049: \
4050: \ load application here
4051: \
4052: ' real: IS : \ go back to the original
4053: @end example
4054:
4055: You can use techniques like this to make new defining words in terms of
4056: @i{any} existing defining word.
1.1 anton 4057:
4058:
1.29 crook 4059: @cindex defining defining words
1.26 crook 4060: @cindex @code{CREATE} ... @code{DOES>}
4061: If you want the words defined with your defining words to behave
4062: differently from words defined with standard defining words, you can
4063: write your defining word like this:
1.1 anton 4064:
4065: @example
1.26 crook 4066: : def-word ( "name" -- )
1.29 crook 4067: CREATE @i{code1}
1.26 crook 4068: DOES> ( ... -- ... )
1.29 crook 4069: @i{code2} ;
1.26 crook 4070:
4071: def-word name
1.1 anton 4072: @end example
4073:
1.29 crook 4074: @cindex child words
4075: This fragment defines a @dfn{defining word} @code{def-word} and then
4076: executes it. When @code{def-word} executes, it @code{CREATE}s a new
4077: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
4078: is not executed at this time. The word @code{name} is sometimes called a
4079: @dfn{child} of @code{def-word}.
4080:
4081: When you execute @code{name}, the address of the body of @code{name} is
4082: put on the data stack and @i{code2} is executed (the address of the body
4083: of @code{name} is the address @code{HERE} returns immediately after the
4084: @code{CREATE}).
4085:
4086: @cindex atavism in child words
4087: You can use @code{def-word} to define a set of child word that behave
4088: differently, though atavistically; they all have a common run-time
4089: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
4090: builds a data area in the body of the child word. The structure of the
4091: data is common to all children of @code{def-word}, but the data values
4092: are specific -- and private -- to each child word. When a child word is
4093: executed, the address of its private data area is passed as a parameter
4094: on TOS to be used and manipulated@footnote{It is legitimate both to read
4095: and write to this data area.} by @i{code2}.
4096:
4097: The two fragments of code that make up the defining words act (are
4098: executed) at two completely separate times:
1.1 anton 4099:
1.29 crook 4100: @itemize @bullet
4101: @item
4102: At @i{define time}, the defining word executes @i{code1} to generate a
4103: child word
4104: @item
4105: At @i{child execution time}, when a child word is invoked, @i{code2}
4106: is executed, using parameters (data) that are private and specific to
4107: the child word.
4108: @end itemize
4109:
4110: @c NAC I think this is a really bad example, because it diminishes
4111: @c rather than emphasising the fact that some important stuff happens
4112: @c at define time, and other important stuff happens at child-invocation
4113: @c time, and that those two times are potentially very different.
4114: @c
4115: @c In other words, if you make the following definitions:
4116: @c @example
4117: @c : def-word1 ( "name" -- )
4118: @c CREATE @i{code1} ;
4119: @c
4120: @c : action1 ( ... -- ... )
4121: @c @i{code2} ;
4122: @c
4123: @c def-word1 name1
4124: @c @end example
4125: @c
4126: @c Using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 4127:
1.29 crook 4128: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 4129:
1.1 anton 4130: @example
1.29 crook 4131: : CONSTANT ( w "name" -- )
4132: CREATE ,
1.26 crook 4133: DOES> ( -- w )
4134: @@ ;
1.1 anton 4135: @end example
4136:
1.29 crook 4137: @comment There is a beautiful description of how this works and what
4138: @comment it does in the Forthwrite 100th edition.. as well as an elegant
4139: @comment commentary on the Counting Fruits problem.
4140:
4141: When you create a constant with @code{5 CONSTANT five}, a set of
4142: define-time actions take place; first a new word @code{five} is created,
4143: then the value 5 is laid down in the body of @code{five} with
4144: @code{,}. When @code{five} is invoked, the address of the body is put on
4145: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
4146: no code of its own; it simply contains a data field and a pointer to the
4147: code that follows @code{DOES>} in its defining word. That makes words
4148: created in this way very compact.
4149:
4150: The final example in this section is intended to remind you that space
4151: reserved in @code{CREATE}d words is @i{data} space and therefore can be
4152: both read and written by a Standard program@footnote{Exercise: use this
4153: example as a starting point for your own implementation of @code{Value}
4154: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
4155: @code{[']}.}:
4156:
4157: @example
4158: : foo ( "name" -- )
4159: CREATE -1 ,
4160: DOES> ( -- )
4161: @@ .;
4162:
4163: foo first-word
4164: foo second-word
4165:
4166: 123 ' first-word >BODY !
4167: @end example
4168:
4169: If @code{first-word} had been a @code{CREATE}d word, we could simply
4170: have executed it to get the address of its data field. However, since it
4171: was defined to have @code{DOES>} actions, its execution semantics are to
4172: perform those @code{DOES>} actions. To get the address of its data field
4173: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
4174: translate the xt into the address of the data field. When you execute
4175: @code{first-word}, it will display @code{123}. When you execute
4176: @code{second-word} it will display @code{-1}.
1.26 crook 4177:
4178: @cindex stack effect of @code{DOES>}-parts
4179: @cindex @code{DOES>}-parts, stack effect
1.29 crook 4180: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 4181: the stack effect of the defined words, not the stack effect of the
4182: following code (the following code expects the address of the body on
4183: the top of stack, which is not reflected in the stack comment). This is
4184: the convention that I use and recommend (it clashes a bit with using
4185: locals declarations for stack effect specification, though).
1.1 anton 4186:
1.26 crook 4187: @subsubsection Applications of @code{CREATE..DOES>}
4188: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 4189:
1.26 crook 4190: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 4191:
1.26 crook 4192: @cindex factoring similar colon definitions
4193: When you see a sequence of code occurring several times, and you can
4194: identify a meaning, you will factor it out as a colon definition. When
4195: you see similar colon definitions, you can factor them using
4196: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
4197: that look very similar:
1.1 anton 4198: @example
1.26 crook 4199: : ori, ( reg-target reg-source n -- )
4200: 0 asm-reg-reg-imm ;
4201: : andi, ( reg-target reg-source n -- )
4202: 1 asm-reg-reg-imm ;
1.1 anton 4203: @end example
4204:
1.26 crook 4205: @noindent
4206: This could be factored with:
4207: @example
4208: : reg-reg-imm ( op-code -- )
4209: CREATE ,
4210: DOES> ( reg-target reg-source n -- )
4211: @@ asm-reg-reg-imm ;
4212:
4213: 0 reg-reg-imm ori,
4214: 1 reg-reg-imm andi,
4215: @end example
1.1 anton 4216:
1.26 crook 4217: @cindex currying
4218: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
4219: supply a part of the parameters for a word (known as @dfn{currying} in
4220: the functional language community). E.g., @code{+} needs two
4221: parameters. Creating versions of @code{+} with one parameter fixed can
4222: be done like this:
1.1 anton 4223: @example
1.26 crook 4224: : curry+ ( n1 -- )
4225: CREATE ,
4226: DOES> ( n2 -- n1+n2 )
4227: @@ + ;
4228:
4229: 3 curry+ 3+
4230: -2 curry+ 2-
1.1 anton 4231: @end example
4232:
1.26 crook 4233: @subsubsection The gory details of @code{CREATE..DOES>}
4234: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 4235:
1.26 crook 4236: doc-does>
1.1 anton 4237:
1.26 crook 4238: @cindex @code{DOES>} in a separate definition
4239: This means that you need not use @code{CREATE} and @code{DOES>} in the
4240: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 4241: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 4242: @example
4243: : does1
4244: DOES> ( ... -- ... )
4245: ... ;
1.1 anton 4246:
1.26 crook 4247: : does2
4248: DOES> ( ... -- ... )
4249: ... ;
1.1 anton 4250:
1.26 crook 4251: : def-word ( ... -- ... )
4252: create ...
4253: IF
4254: does1
4255: ELSE
4256: does2
4257: ENDIF ;
4258: @end example
1.1 anton 4259:
1.26 crook 4260: In this example, the selection of whether to use @code{does1} or
4261: @code{does2} is made at compile-time; at the time that the child word is
1.29 crook 4262: @code{CREATE}d.
1.1 anton 4263:
1.26 crook 4264: @cindex @code{DOES>} in interpretation state
4265: In a standard program you can apply a @code{DOES>}-part only if the last
4266: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
4267: will override the behaviour of the last word defined in any case. In a
4268: standard program, you can use @code{DOES>} only in a colon
4269: definition. In Gforth, you can also use it in interpretation state, in a
4270: kind of one-shot mode; for example:
1.1 anton 4271: @example
1.26 crook 4272: CREATE name ( ... -- ... )
1.29 crook 4273: @i{initialization}
1.26 crook 4274: DOES>
1.29 crook 4275: @i{code} ;
1.1 anton 4276: @end example
4277:
1.26 crook 4278: @noindent
4279: is equivalent to the standard:
1.1 anton 4280: @example
1.26 crook 4281: :noname
4282: DOES>
1.29 crook 4283: @i{code} ;
1.26 crook 4284: CREATE name EXECUTE ( ... -- ... )
1.29 crook 4285: @i{initialization}
1.1 anton 4286: @end example
4287:
1.26 crook 4288: You can get the address of the body of a word with:
4289:
4290: doc->body
1.1 anton 4291:
1.26 crook 4292: @node Supplying names, Interpretation and Compilation Semantics, User-defined Defining Words, Defining Words
1.29 crook 4293: @subsection Supplying the name of a defined word
1.26 crook 4294: @cindex names for defined words
4295: @cindex defining words, name parameter
1.1 anton 4296:
1.26 crook 4297: @cindex defining words, name given in a string
1.29 crook 4298: By default, a defining word takes the name for the defined word from the
1.26 crook 4299: input stream. Sometimes you want to supply the name from a string. You
4300: can do this with:
1.1 anton 4301:
1.26 crook 4302: doc-nextname
1.1 anton 4303:
1.26 crook 4304: For example:
1.1 anton 4305:
1.26 crook 4306: @example
4307: s" foo" nextname create
4308: @end example
4309: @noindent
4310: is equivalent to:
4311: @example
4312: create foo
4313: @end example
1.1 anton 4314:
1.26 crook 4315: @cindex defining words without name
1.29 crook 4316: Sometimes you want to define an @dfn{anonymous word}; a word without a
1.26 crook 4317: name. You can do this with:
1.1 anton 4318:
1.26 crook 4319: doc-:noname
1.1 anton 4320:
1.26 crook 4321: This leaves the execution token for the word on the stack after the
4322: closing @code{;}. Here's an example in which a deferred word is
4323: initialised with an @code{xt} from an anonymous colon definition:
4324: @example
4325: Defer deferred
4326: :noname ( ... -- ... )
4327: ... ;
4328: IS deferred
4329: @end example
1.1 anton 4330:
1.29 crook 4331: @noindent
1.26 crook 4332: Gforth provides an alternative way of doing this, using two separate
4333: words:
1.1 anton 4334:
1.26 crook 4335: doc-noname
4336: @cindex execution token of last defined word
4337: doc-lastxt
1.1 anton 4338:
1.29 crook 4339: @noindent
1.26 crook 4340: The previous example can be rewritten using @code{noname} and
4341: @code{lastxt}:
1.1 anton 4342:
1.26 crook 4343: @example
4344: Defer deferred
4345: noname : ( ... -- ... )
4346: ... ;
4347: lastxt IS deferred
4348: @end example
1.1 anton 4349:
1.29 crook 4350: @noindent
1.26 crook 4351: @code{lastxt} also works when the last word was not defined as
1.29 crook 4352: @code{noname}. It also has the useful property that is is valid as soon
4353: as the header for a definition has been build. Thus:
4354:
4355: @example
4356: lastxt . : foo [ lastxt . ] ; ' foo .
4357: @end example
4358:
4359: @noindent
4360: prints 3 numbers; the last two are the same.
1.1 anton 4361:
4362:
1.26 crook 4363: @node Interpretation and Compilation Semantics, , Supplying names, Defining Words
4364: @subsection Interpretation and Compilation Semantics
4365: @cindex semantics, interpretation and compilation
1.1 anton 4366:
1.26 crook 4367: @cindex interpretation semantics
4368: The @dfn{interpretation semantics} of a word are what the text
4369: interpreter does when it encounters the word in interpret state. It also
4370: appears in some other contexts, e.g., the execution token returned by
1.29 crook 4371: @code{' @i{word}} identifies the interpretation semantics of
4372: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
4373: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 4374:
1.26 crook 4375: @cindex compilation semantics
4376: The @dfn{compilation semantics} of a word are what the text interpreter
4377: does when it encounters the word in compile state. It also appears in
1.29 crook 4378: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
1.26 crook 4379: standard terminology, ``appends to the current definition''.} the
1.29 crook 4380: compilation semantics of @i{word}.
1.1 anton 4381:
1.26 crook 4382: @cindex execution semantics
4383: The standard also talks about @dfn{execution semantics}. They are used
4384: only for defining the interpretation and compilation semantics of many
4385: words. By default, the interpretation semantics of a word are to
4386: @code{execute} its execution semantics, and the compilation semantics of
4387: a word are to @code{compile,} its execution semantics.@footnote{In
4388: standard terminology: The default interpretation semantics are its
4389: execution semantics; the default compilation semantics are to append its
4390: execution semantics to the execution semantics of the current
4391: definition.}
4392:
4393: @comment TODO expand, make it co-operate with new sections on text interpreter.
4394:
4395: @cindex immediate words
4396: @cindex compile-only words
4397: You can change the semantics of the most-recently defined word:
4398:
4399: doc-immediate
4400: doc-compile-only
4401: doc-restrict
4402:
4403: Note that ticking (@code{'}) a compile-only word gives an error
4404: (``Interpreting a compile-only word'').
1.1 anton 4405:
1.26 crook 4406: Gforth also allows you to define words with arbitrary combinations of
4407: interpretation and compilation semantics.
1.1 anton 4408:
1.26 crook 4409: doc-interpret/compile:
1.1 anton 4410:
1.26 crook 4411: This feature was introduced for implementing @code{TO} and @code{S"}. I
4412: recommend that you do not define such words, as cute as they may be:
4413: they make it hard to get at both parts of the word in some contexts.
4414: E.g., assume you want to get an execution token for the compilation
4415: part. Instead, define two words, one that embodies the interpretation
4416: part, and one that embodies the compilation part. Once you have done
4417: that, you can define a combined word with @code{interpret/compile:} for
4418: the convenience of your users.
1.1 anton 4419:
1.26 crook 4420: You might try to use this feature to provide an optimizing
4421: implementation of the default compilation semantics of a word. For
4422: example, by defining:
1.1 anton 4423: @example
1.26 crook 4424: :noname
4425: foo bar ;
4426: :noname
4427: POSTPONE foo POSTPONE bar ;
1.29 crook 4428: interpret/compile: opti-foobar
1.1 anton 4429: @end example
1.26 crook 4430:
1.23 crook 4431: @noindent
1.26 crook 4432: as an optimizing version of:
4433:
1.1 anton 4434: @example
1.26 crook 4435: : foobar
4436: foo bar ;
1.1 anton 4437: @end example
4438:
1.26 crook 4439: Unfortunately, this does not work correctly with @code{[compile]},
4440: because @code{[compile]} assumes that the compilation semantics of all
4441: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 4442: opti-foobar} would compile compilation semantics, whereas
4443: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 4444:
1.26 crook 4445: @cindex state-smart words (are a bad idea)
1.29 crook 4446: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 4447: by @code{interpret/compile:} (words are state-smart if they check
4448: @code{STATE} during execution). E.g., they would try to code
4449: @code{foobar} like this:
1.1 anton 4450:
1.26 crook 4451: @example
4452: : foobar
4453: STATE @@
4454: IF ( compilation state )
4455: POSTPONE foo POSTPONE bar
4456: ELSE
4457: foo bar
4458: ENDIF ; immediate
4459: @end example
1.1 anton 4460:
1.26 crook 4461: Although this works if @code{foobar} is only processed by the text
4462: interpreter, it does not work in other contexts (like @code{'} or
4463: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
4464: for a state-smart word, not for the interpretation semantics of the
4465: original @code{foobar}; when you execute this execution token (directly
4466: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
4467: state, the result will not be what you expected (i.e., it will not
4468: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
4469: write them@footnote{For a more detailed discussion of this topic, see
4470: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
4471: Ertl; presented at EuroForth '98 and available from
4472: @url{http://www.complang.tuwien.ac.at/papers/}}!
1.1 anton 4473:
1.26 crook 4474: @cindex defining words with arbitrary semantics combinations
4475: It is also possible to write defining words that define words with
4476: arbitrary combinations of interpretation and compilation semantics. In
4477: general, they look like this:
1.1 anton 4478:
1.26 crook 4479: @example
4480: : def-word
4481: create-interpret/compile
1.29 crook 4482: @i{code1}
1.26 crook 4483: interpretation>
1.29 crook 4484: @i{code2}
1.26 crook 4485: <interpretation
4486: compilation>
1.29 crook 4487: @i{code3}
1.26 crook 4488: <compilation ;
4489: @end example
1.1 anton 4490:
1.29 crook 4491: For a @i{word} defined with @code{def-word}, the interpretation
4492: semantics are to push the address of the body of @i{word} and perform
4493: @i{code2}, and the compilation semantics are to push the address of
4494: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 4495: can also be defined like this (except that the defined constants don't
4496: behave correctly when @code{[compile]}d):
1.1 anton 4497:
1.26 crook 4498: @example
4499: : constant ( n "name" -- )
4500: create-interpret/compile
4501: ,
4502: interpretation> ( -- n )
4503: @@
4504: <interpretation
4505: compilation> ( compilation. -- ; run-time. -- n )
4506: @@ postpone literal
4507: <compilation ;
4508: @end example
1.1 anton 4509:
1.26 crook 4510: doc-create-interpret/compile
4511: doc-interpretation>
4512: doc-<interpretation
4513: doc-compilation>
4514: doc-<compilation
1.1 anton 4515:
1.29 crook 4516: Words defined with @code{interpret/compile:} and
1.26 crook 4517: @code{create-interpret/compile} have an extended header structure that
4518: differs from other words; however, unless you try to access them with
4519: plain address arithmetic, you should not notice this. Words for
4520: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 4521: @code{'} @i{word} @code{>body} also gives you the body of a word created
4522: with @code{create-interpret/compile}.
1.1 anton 4523:
1.27 crook 4524: doc-postpone
1.29 crook 4525: @comment TODO -- expand glossary text for POSTPONE
1.27 crook 4526:
1.26 crook 4527: @c ----------------------------------------------------------
4528: @node The Text Interpreter, Tokens for Words, Defining Words, Words
4529: @section The Text Interpreter
4530: @cindex interpreter - outer
4531: @cindex text interpreter
4532: @cindex outer interpreter
1.1 anton 4533:
1.29 crook 4534: The text interpreter@footnote{This is an expanded version of the
4535: material in @ref{Introducing the Text Interpreter}.} is an endless loop
4536: that processes input from the current input device. A popular
4537: implementation technique for Forth is to implement a @dfn{forth virtual
4538: machine} using a loop called the @dfn{inner interpreter}. Because of
4539: this naming, the text interpreter is also known as the @dfn{outer
1.27 crook 4540: interpreter}.
4541:
1.29 crook 4542: @cindex interpret state
4543: @cindex compile state
4544: The text interpreter operates in one of two states: @dfn{interpret
4545: state} and @dfn{compile state}. The current state is defined by the
4546: aptly-named variable, @code{state}.
4547:
4548: This section starts by describing how the text interpreter behaves when
4549: it is in interpret state, processing input from the user input device --
4550: the keyboard. This is the mode that a Forth system is in after it starts
4551: up.
4552:
4553: @cindex input buffer
4554: @cindex terminal input buffer
4555: The text interpreter works from an area of memory called the @dfn{input
4556: buffer}@footnote{When the text interpreter is processing input from the
4557: keyboard, this area of memory is called the @dfn{terminal input buffer}
4558: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
4559: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 ! anton 4560: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 4561: leading spaces (called @dfn{delimiters}) then parses a string (a
4562: sequence of non-space characters) until it reaches either a space
4563: character or the end of the buffer. Having parsed a string, it makes two
4564: attempts to process it:
1.27 crook 4565:
1.29 crook 4566: @cindex dictionary
1.27 crook 4567: @itemize @bullet
4568: @item
1.29 crook 4569: It looks for the string in a @dfn{dictionary} of definitions. If the
4570: string is found, the string names a @dfn{definition} (also known as a
4571: @dfn{word}) and the dictionary search returns information that allows
4572: the text interpreter to perform the word's @dfn{interpretation
4573: semantics}. In most cases, this simply means that the word will be
4574: executed.
1.27 crook 4575: @item
4576: If the string is not found in the dictionary, the text interpreter
1.29 crook 4577: attempts to treat it as a number, using the rules described in
4578: @ref{Number Conversion}. If the string represents a legal number in the
4579: current radix, the number is pushed onto a parameter stack (the data
4580: stack for integers, the floating-point stack for floating-point
4581: numbers).
4582: @end itemize
4583:
4584: If both attempts fail, or if the word is found in the dictionary but has
4585: no interpretation semantics@footnote{This happens if the word was
4586: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
4587: remainder of the input buffer, issues an error message and waits for
4588: more input. If one of the attempts succeeds, the text interpreter
4589: repeats the parsing process until the whole of the input buffer has been
4590: processed, at which point it prints the status message ``@code{ ok}''
4591: and waits for more input.
4592:
4593: @cindex parse area
4594: The text interpreter keeps track of its position in the input buffer by
4595: updating a variable called @code{>IN} (pronounced ``to-in''). The value
4596: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
4597: of the input buffer. The region from offset @code{>IN @@} to the end of
4598: the input buffer is called the @dfn{parse area}@footnote{In other words,
4599: the text interpreter processes the contents of the input buffer by
4600: parsing strings from the parse area until the parse area is empty.}.
4601: This example shows how @code{>IN} changes as the text interpreter parses
4602: the input buffer:
4603:
4604: @example
4605: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
4606: CR ." ->" TYPE ." <-" ; IMMEDIATE
4607:
4608: 1 2 3 remaining + remaining .
4609:
4610: : foo 1 2 3 remaining SWAP remaining ;
4611: @end example
4612:
4613: @noindent
4614: The result is:
4615:
4616: @example
4617: ->+ remaining .<-
4618: ->.<-5 ok
4619:
4620: ->SWAP remaining ;-<
4621: ->;<- ok
4622: @end example
4623:
4624: @cindex parsing words
4625: The value of @code{>IN} can also be modified by a word in the input
4626: buffer that is executed by the text interpreter. This means that a word
4627: can ``trick'' the text interpreter into either skipping a section of the
4628: input buffer@footnote{This is how parsing words work.} or into parsing a
4629: section twice. For example:
1.27 crook 4630:
1.29 crook 4631: @example
4632: : lat ." <<lat>>" ;
4633: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
4634: @end example
4635:
4636: @noindent
4637: When @code{flat} is executed, this output is produced@footnote{Exercise
4638: for the reader: what would happen if the @code{3} were replaced with
4639: @code{4}?}:
4640:
4641: @example
4642: <<flat>><<lat>>
4643: @end example
4644:
4645: @noindent
4646: Two important notes about the behaviour of the text interpreter:
1.27 crook 4647:
4648: @itemize @bullet
4649: @item
4650: It processes each input string to completion before parsing additional
1.29 crook 4651: characters from the input buffer.
4652: @item
4653: It treats the input buffer as a read-only region (and so must your code).
4654: @end itemize
4655:
4656: @noindent
4657: When the text interpreter is in compile state, its behaviour changes in
4658: these ways:
4659:
4660: @itemize @bullet
4661: @item
4662: If a parsed string is found in the dictionary, the text interpreter will
4663: perform the word's @dfn{compilation semantics}. In most cases, this
4664: simply means that the execution semantics of the word will be appended
4665: to the current definition.
1.27 crook 4666: @item
1.29 crook 4667: When a number is encountered, it is compiled into the current definition
4668: (as a literal) rather than being pushed onto a parameter stack.
4669: @item
4670: If an error occurs, @code{state} is modified to put the text interpreter
4671: back into interpret state.
4672: @item
4673: Each time a line is entered from the keyboard, Gforth prints
4674: ``@code{ compiled}'' rather than `` @code{ok}''.
4675: @end itemize
4676:
4677: @cindex text interpreter - input sources
4678: When the text interpreter is using an input device other than the
4679: keyboard, its behaviour changes in these ways:
4680:
4681: @itemize @bullet
4682: @item
4683: When the parse area is empty, the text interpreter attempts to refill
4684: the input buffer from the input source. When the input source is
4685: exhausted, the input source is set back to the user input device.
4686: @item
4687: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
4688: time the parse area is emptied.
4689: @item
4690: If an error occurs, the input source is set back to the user input
4691: device.
1.27 crook 4692: @end itemize
1.21 crook 4693:
1.29 crook 4694: @ref{Input Sources} describes this in more detail.
4695:
1.26 crook 4696: doc->in
1.27 crook 4697: doc-source
4698:
1.26 crook 4699: doc-tib
4700: doc-#tib
1.1 anton 4701:
1.26 crook 4702: @menu
1.29 crook 4703: * Input Sources::
1.26 crook 4704: * Number Conversion::
4705: * Interpret/Compile states::
4706: * Literals::
4707: * Interpreter Directives::
4708: @end menu
1.1 anton 4709:
1.29 crook 4710: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
4711: @subsection Input Sources
4712: @cindex input sources
4713: @cindex text interpreter - input sources
4714:
4715: By default, the text interpreter accepts input from the user input
4716: device (the keyboard) when Forth starts up. The text interpreter can
4717: process input from any of these sources:
4718:
4719: @itemize @bullet
4720: @item
4721: The user input device -- the keyboard.
4722: @item
4723: A file, using the words described in @ref{Forth source files}.
4724: @item
4725: A block, using the words described in @ref{Blocks}.
4726: @item
4727: A text string, using @code{evaluate}.
4728: @end itemize
4729:
4730: A program can identify the current input device from the values of
4731: @code{source-id} and @code{blk}.
4732:
4733: doc-source-id
4734: doc-blk
4735:
4736: doc-save-input
4737: doc-restore-input
4738:
4739: doc-evaluate
1.1 anton 4740:
1.29 crook 4741:
4742: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 4743: @subsection Number Conversion
4744: @cindex number conversion
4745: @cindex double-cell numbers, input format
4746: @cindex input format for double-cell numbers
4747: @cindex single-cell numbers, input format
4748: @cindex input format for single-cell numbers
4749: @cindex floating-point numbers, input format
4750: @cindex input format for floating-point numbers
1.1 anton 4751:
1.29 crook 4752: This section describes the rules that the text interpreter uses when it
4753: tries to convert a string into a number.
1.1 anton 4754:
1.26 crook 4755: Let <digit> represent any character that is a legal digit in the current
1.29 crook 4756: number base@footnote{For example, 0-9 when the number base is decimal or
4757: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 4758:
1.26 crook 4759: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 4760:
1.29 crook 4761: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
4762: in the braces (@i{a} or @i{b} or neither).
1.1 anton 4763:
1.26 crook 4764: Let * represent any number of instances of the previous character
4765: (including none).
1.1 anton 4766:
1.26 crook 4767: Let any other character represent itself.
1.1 anton 4768:
1.29 crook 4769: @noindent
1.26 crook 4770: Now, the conversion rules are:
1.21 crook 4771:
1.26 crook 4772: @itemize @bullet
4773: @item
4774: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 4775: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 4776: @item
4777: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 4778: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 4779: arithmetic. Examples are -45 -5681 -0
4780: @item
4781: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 4782: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
4783: (all three of these represent the same number).
1.26 crook 4784: @item
4785: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 4786: double-precision (double-cell-sized) negative integer, and is
1.26 crook 4787: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 4788: -34.65 (all three of these represent the same number).
1.26 crook 4789: @item
1.29 crook 4790: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
4791: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.26 crook 4792: number. Examples are 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 4793: number) +12.E-4
1.26 crook 4794: @end itemize
1.1 anton 4795:
1.26 crook 4796: By default, the number base used for integer number conversion is given
1.29 crook 4797: by the contents of the variable @code{BASE}. Base 10 (decimal) is
1.26 crook 4798: always used for floating-point number conversion.
1.1 anton 4799:
1.29 crook 4800: doc-dpl
1.26 crook 4801: doc-base
4802: doc-hex
4803: doc-decimal
1.1 anton 4804:
1.26 crook 4805: @cindex '-prefix for character strings
4806: @cindex &-prefix for decimal numbers
4807: @cindex %-prefix for binary numbers
4808: @cindex $-prefix for hexadecimal numbers
1.29 crook 4809: Gforth allows you to override the value of @code{BASE} by using a
4810: prefix@footnote{Some Forth implementations provide a similar scheme by
4811: implementing @code{$} etc. as parsing words that process the subsequent
4812: number in the input stream and push it onto the stack. For example, see
4813: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
4814: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
4815: is required between the prefix and the number.} before the first digit
4816: of an (integer) number. Four prefixes are supported:
1.1 anton 4817:
1.26 crook 4818: @itemize @bullet
4819: @item
4820: @code{&} -- decimal number
4821: @item
4822: @code{%} -- binary number
4823: @item
4824: @code{$} -- hexadecimal number
4825: @item
4826: @code{'} -- base 256 number
4827: @end itemize
1.1 anton 4828:
1.26 crook 4829: Here are some examples, with the equivalent decimal number shown after
4830: in braces:
1.1 anton 4831:
1.26 crook 4832: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
4833: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
4834: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
4835: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 4836:
1.26 crook 4837: @cindex number conversion - traps for the unwary
1.29 crook 4838: @noindent
1.26 crook 4839: Number conversion has a number of traps for the unwary:
1.1 anton 4840:
1.26 crook 4841: @itemize @bullet
4842: @item
4843: You cannot determine the current number base using the code sequence
4844: @code{BASE @@ .} -- the number base is always 10 in the current number
4845: base. Instead, use something like @code{BASE @@ DECIMAL DUP . BASE !}
4846: @item
4847: If the number base is set to a value greater than 14 (for example,
4848: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
4849: it to be intepreted as either a single-precision integer or a
4850: floating-point number (Gforth treats it as an integer). The ambiguity
4851: can be resolved by explicitly stating the sign of the mantissa and/or
4852: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
4853: ambiguity arises; either representation will be treated as a
4854: floating-point number.
4855: @item
1.29 crook 4856: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 4857: It is used to specify file types.
4858: @item
4859: ANS Forth requires the @code{.} of a double-precision number to
4860: be the final character in the string. Allowing the @code{.} to be
4861: anywhere after the first digit is a Gforth extension.
4862: @item
4863: The number conversion process does not check for overflow.
4864: @item
4865: In Gforth, number conversion to floating-point numbers always use base
4866: 10, irrespective of the value of @code{BASE}. In ANS Forth,
4867: conversion to floating-point numbers whilst the value of
4868: @code{BASE} is not 10 is an ambiguous condition.
4869: @end itemize
1.1 anton 4870:
1.29 crook 4871: @ref{Input} describes words that you can use to read numbers into your
4872: programs.
1.1 anton 4873:
1.26 crook 4874: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
4875: @subsection Interpret/Compile states
4876: @cindex Interpret/Compile states
1.1 anton 4877:
1.29 crook 4878: A standard program is not permitted to change @code{state}
4879: explicitly. However, it can change @code{state} implicitly, using the
4880: words @code{[} and @code{]}. When @code{[} is executed it switches
4881: @code{state} to interpret state, and therefore the text interpreter
4882: starts interpreting. When @code{]} is executed it switches @code{state}
4883: to compile state and therefore the text interpreter starts
4884: compiling. The most common usage for these words is to compile literals,
4885: as shown in @ref{Literals}. However, they give you the freedom to switch
4886: modes at will. Here is an example of building a jump-table of execution
4887: tokens:
4888:
4889: @example
4890: : AA ." this is A" ;
4891: : BB ." this is B" ;
4892: : CC ." this is C" ;
4893:
4894: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
4895: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
4896: cells table + @ execute ;
4897: @end example
4898:
4899: @noindent
4900: Now @code{0 go} will display ``@code{this is A}''. The table can be
4901: built far more neatly@footnote{The source code is neater.. what is
4902: compiled in memory in each case is identical.} like this:
4903:
4904: @example
4905: create table ] aa bb cc [
4906: @end example
4907:
4908: The problem with this code is that it is not portable; it will only work
4909: on systems where code space and data space co-incide. The reason is that
4910: both tables @i{compile} execution tokens -- into code space. The
4911: Standard only allows data space to be assigned for a @code{CREATE}d
4912: word. In addition, the Standard only allows @code{@@} to access data
4913: space, whilst this example is using it to access code space. The only
4914: portable, Standard way to build this table is to build it in data space,
4915: like this:
4916:
4917: @example
4918: create table ' aa , ' bb , ' cc ,
4919: @end example
4920:
4921: @noindent
4922: A similar technique can be used to build a table of constants:
4923:
4924: @example
4925: create primes 1 , 3 , 5 , 7 , 11 ,
4926: @end example
1.1 anton 4927:
1.26 crook 4928: doc-state
4929: doc-[
4930: doc-]
1.1 anton 4931:
1.26 crook 4932: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
4933: @subsection Literals
4934: @cindex Literals
1.21 crook 4935:
1.29 crook 4936: Often, you want to use a number within a colon definition. When you do
4937: this, the text interpreter automatically compiles the number as a
4938: @i{literal}. A literal is a number whose run-time effect is to be pushed
4939: onto the stack. If you had to do some maths to generate the number, you
4940: might write it like this:
4941:
4942: @example
4943: : HOUR-TO-SEC ( n1 -- n2 )
4944: 60 * \ to minutes
4945: 60 * ; \ to seconds
4946: @end example
4947:
4948: It is very clear what this definition is doing, but it's inefficient
4949: since it is performing 2 multiples at run-time. An alternative would be
4950: to write:
4951:
4952: @example
4953: : HOUR-TO-SEC ( n1 -- n2 )
4954: 3600 * ; \ to seconds
4955: @end example
4956:
4957: Which does the same thing, and has the advantage of using a single
4958: multiply. Ideally, we'd like the efficiency of the second with the
4959: readability of the first.
4960:
4961: @code{Literal} allows us to achieve that. It takes a number from the
4962: stack and lays it down in the current definition just as though the
4963: number had been typed directly into the definition. Our first attempt
4964: might look like this:
4965:
4966: @example
4967: 60 \ mins per hour
4968: 60 * \ seconds per minute
4969: : HOUR-TO-SEC ( n1 -- n2 )
4970: Literal * ; \ to seconds
4971: @end example
4972:
4973: But this produces the error message @code{unstructured}. What happened?
4974: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
4975: @i{colon-sys} is implementation-defined. In other words, once we start a
4976: colon definition we can't portably access anything that was on the stack
4977: before the definition began@footnote{@cite{Two Problems in ANS Forth},
4978: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
4979: some situations where you might want to access stack items above
4980: colon-sys, and provides a solution to the problem.}. The correct way of
4981: solving this problem in this instance is to use @code{[ ]} like this:
4982:
4983: @example
4984: : HOUR-TO-SEC ( n1 -- n2 )
4985: [ 60 \ minutes per hour
4986: 60 * ] \ seconds per minute
4987: LITERAL * ; \ to seconds
4988: @end example
1.23 crook 4989:
1.26 crook 4990: doc-literal
4991: doc-]L
4992: doc-2literal
4993: doc-fliteral
1.1 anton 4994:
1.29 crook 4995: @node Interpreter Directives, , Literals, The Text Interpreter
1.26 crook 4996: @subsection Interpreter Directives
4997: @cindex interpreter directives
1.1 anton 4998:
1.29 crook 4999: These words are usually used in interpret state; typically to control
5000: which parts of a source file are processed by the text
1.26 crook 5001: interpreter. There are only a few ANS Forth Standard words, but Gforth
5002: supplements these with a rich set of immediate control structure words
5003: to compensate for the fact that the non-immediate versions can only be
1.29 crook 5004: used in compile state (@pxref{Control Structures}). Typical usages:
5005:
5006: @example
5007: FALSE Constant ASSEMBLER
5008: .
5009: .
5010: ASSEMBLER [IF]
5011: : ASSEMBLER-FEATURE
5012: ...
5013: ;
5014: [ENDIF]
5015: .
5016: .
5017: : SEE
5018: ... \ general-purpose SEE code
5019: [ ASSEMBLER [IF] ]
5020: ... \ assembler-specific SEE code
5021: [ [ENDIF] ]
5022: ;
5023: @end example
1.1 anton 5024:
1.26 crook 5025: doc-[IF]
5026: doc-[ELSE]
5027: doc-[THEN]
5028: doc-[ENDIF]
1.1 anton 5029:
1.26 crook 5030: doc-[IFDEF]
5031: doc-[IFUNDEF]
1.1 anton 5032:
1.26 crook 5033: doc-[?DO]
5034: doc-[DO]
5035: doc-[FOR]
5036: doc-[LOOP]
5037: doc-[+LOOP]
5038: doc-[NEXT]
1.1 anton 5039:
1.26 crook 5040: doc-[BEGIN]
5041: doc-[UNTIL]
5042: doc-[AGAIN]
5043: doc-[WHILE]
5044: doc-[REPEAT]
1.1 anton 5045:
1.27 crook 5046:
5047:
1.26 crook 5048: @c -------------------------------------------------------------
5049: @node Tokens for Words, Word Lists, The Text Interpreter, Words
5050: @section Tokens for Words
5051: @cindex tokens for words
1.1 anton 5052:
1.28 crook 5053: This section describes the creation and use of tokens that represent
1.29 crook 5054: words.
5055:
5056: Named words have information stored in their name dictionary entries to
5057: indicate any non-default semantics (@pxref{Interpretation and
5058: Compilation Semantics}). The semantics can be modified, using
5059: @code{immediate} and/or @code{compile-only}, at the time that the words
5060: are defined. Unnamed words have (by definition) no name dictionary
5061: entry, and therefore must have default semantics.
1.21 crook 5062:
1.26 crook 5063: Named words have interpretation and compilation semantics. Unnamed words
5064: just have execution semantics.
1.21 crook 5065:
1.29 crook 5066: @cindex xt
5067: @cindex execution token
5068: The execution semantics of an unnamed word are represented by an
5069: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
5070: the execution token of the last word defined can be produced with
5071: @code{lastxt}.
5072:
5073: The interpretation semantics of a named word are also represented by an
5074: execution token. You can produce the execution token using @code{'} or
5075: @code{[']}. A simple example shows the difference between the two:
1.21 crook 5076:
1.29 crook 5077: @example
5078: : greet ( -- ) ." Hello" ;
5079: : foo ( -- xt ) ['] greet ; \ ['] parses greet at compile-time
5080: : bar ( -- ) ' EXECUTE ; \ ' parses at run-time
1.1 anton 5081:
1.29 crook 5082: \ the next four lines all do the same thing
5083: foo EXECUTE
5084: greet
5085: ' greet EXECUTE
5086: boo greet
5087: @end example
1.1 anton 5088:
1.29 crook 5089: An execution token occupies one cell.
1.26 crook 5090: @cindex code field address
5091: @cindex CFA
1.29 crook 5092: In Gforth, the abstract data type @i{execution token} is implemented
1.26 crook 5093: as a code field address (CFA).
5094: @comment TODO note that the standard does not say what it represents..
5095: @comment and you cannot necessarily compile it in all Forths (eg native
5096: @comment compilers?).
1.1 anton 5097:
1.29 crook 5098: For literals, use @code{'} in interpreted code and @code{[']} in
5099: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
5100: unusually by complaining about compile-only words. To get the execution
5101: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
5102: or @code{[COMP'] @i{name} DROP}.
1.1 anton 5103:
1.26 crook 5104: @cindex compilation token
1.29 crook 5105: The compilation semantics of a named word are represented by a
5106: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
5107: @i{xt} is an execution token. The compilation semantics represented by
5108: the compilation token can be performed with @code{execute}, which
5109: consumes the whole compilation token, with an additional stack effect
5110: determined by the represented compilation semantics.
5111:
5112: At present, the @i{w} part of a compilation token is an execution token,
5113: and the @i{xt} part represents either @code{execute} or
5114: @code{compile,}@footnote{Depending upon the compilation semantics of the
5115: word. If the word has default compilation semantics, the @i{xt} will
5116: represent @code{compile,}. If the word is @code{immediate}, the @i{xt}
5117: will represent @code{execute}.}. However, don't rely on that knowledge,
5118: unless necessary; future versions of Gforth may introduce unusual
5119: compilation tokens (e.g., a compilation token that represents the
5120: compilation semantics of a literal).
1.1 anton 5121:
1.26 crook 5122: You can compile the compilation semantics with @code{postpone,}. I.e.,
1.29 crook 5123: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
5124: @i{word}}.
1.21 crook 5125:
1.26 crook 5126: @cindex name token
5127: @cindex name field address
5128: @cindex NFA
1.29 crook 5129: Named words are also represented by the @dfn{name token}, (@i{nt}). In
5130: Gforth, the abstract data type @emph{name token} is implemented as a
5131: name field address (NFA).
5132:
5133: doc-execute
5134: doc-compile,
5135: doc-[']
5136: doc-'
5137: doc-[comp']
5138: doc-comp'
5139: doc-postpone,
1.1 anton 5140:
1.26 crook 5141: doc-find-name
5142: doc-name>int
5143: doc-name?int
5144: doc-name>comp
5145: doc-name>string
1.1 anton 5146:
1.26 crook 5147: @c -------------------------------------------------------------
5148: @node Word Lists, Environmental Queries, Tokens for Words, Words
5149: @section Word Lists
5150: @cindex word lists
5151: @cindex name dictionary
1.1 anton 5152:
1.26 crook 5153: @cindex wid
5154: All definitions other than those created by @code{:noname} have an entry
5155: in the name dictionary. The name dictionary is fragmented into a number
1.29 crook 5156: of parts, called @dfn{word lists}. A word list is identified by a
5157: cell-sized word list identifier (@i{wid}) in much the same way as a
1.26 crook 5158: file is identified by a file handle. The numerical value of the wid has
5159: no (portable) meaning, and might change from session to session.
1.1 anton 5160:
1.26 crook 5161: @cindex compilation word list
5162: At any one time, a single word list is defined as the word list to which
1.29 crook 5163: all new definitions will be added -- this is called the @dfn{compilation
1.26 crook 5164: word list}. When Gforth is started, the compilation word list is the
5165: word list called @code{FORTH-WORDLIST}.
1.1 anton 5166:
1.26 crook 5167: @cindex search order stack
1.29 crook 5168: Forth maintains a stack of word lists, representing the @dfn{search
1.26 crook 5169: order}. When the name dictionary is searched (for example, when
5170: attempting to find a word's execution token during compilation), only
5171: those word lists that are currently in the search order are
5172: searched. The most recently-defined word in the word list at the top of
5173: the word list stack is searched first, and the search proceeds until
5174: either the word is located or the oldest definition in the word list at
5175: the bottom of the stack is reached. Definitions of the word may exist in
5176: more than one word lists; the search order determines which version will
5177: be found.
1.1 anton 5178:
1.29 crook 5179: The ANS Forth ``Search order'' word set is intended to provide a set of
5180: low-level tools that allow various different schemes to be
1.26 crook 5181: implemented. Gforth provides @code{vocabulary}, a traditional Forth
5182: word. @file{compat/vocabulary.fs} provides an implementation in ANS
5183: Standard Forth.
1.1 anton 5184:
1.27 crook 5185: @comment TODO: locals section refers to here, saying that every word list (aka
5186: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.1 anton 5187:
1.27 crook 5188: @comment the thisone- prefix is used to pick out the true definition of a
5189: @comment word from the source files, rather than some alias.
1.26 crook 5190: doc-forth-wordlist
5191: doc-definitions
5192: doc-get-current
5193: doc-set-current
5194: doc-get-order
1.27 crook 5195: doc---thisone-set-order
1.26 crook 5196: doc-wordlist
1.30 ! anton 5197: doc-table
1.26 crook 5198: doc-also
1.27 crook 5199: doc---thisone-forth
1.26 crook 5200: doc-only
1.27 crook 5201: doc---thisone-order
1.26 crook 5202: doc-previous
1.15 anton 5203:
1.26 crook 5204: doc-find
5205: doc-search-wordlist
1.15 anton 5206:
1.26 crook 5207: doc-words
5208: doc-vlist
1.1 anton 5209:
1.26 crook 5210: doc-mappedwordlist
5211: doc-root
5212: doc-vocabulary
5213: doc-seal
5214: doc-vocs
5215: doc-current
5216: doc-context
1.1 anton 5217:
1.26 crook 5218: @menu
5219: * Why use word lists?::
5220: * Word list examples::
5221: @end menu
5222:
5223: @node Why use word lists?, Word list examples, Word Lists, Word Lists
5224: @subsection Why use word lists?
5225: @cindex word lists - why use them?
5226:
1.29 crook 5227: Here are some reasons for using multiple word lists:
1.26 crook 5228:
5229: @itemize @bullet
5230: @item
5231: To improve compilation speed by reducing the number of name dictionary
5232: entries that must be searched. This is achieved by creating a new
5233: word list that contains all of the definitions that are used in the
5234: definition of a Forth system but which would not usually be used by
5235: programs running on that system. That word list would be on the search
5236: list when the Forth system was compiled but would be removed from the
5237: search list for normal operation. This can be a useful technique for
5238: low-performance systems (for example, 8-bit processors in embedded
5239: systems) but is unlikely to be necessary in high-performance desktop
5240: systems.
5241: @item
5242: To prevent a set of words from being used outside the context in which
5243: they are valid. Two classic examples of this are an integrated editor
5244: (all of the edit commands are defined in a separate word list; the
5245: search order is set to the editor word list when the editor is invoked;
5246: the old search order is restored when the editor is terminated) and an
5247: integrated assembler (the op-codes for the machine are defined in a
5248: separate word list which is used when a @code{CODE} word is defined).
5249: @item
5250: To prevent a name-space clash between multiple definitions with the same
5251: name. For example, when building a cross-compiler you might have a word
5252: @code{IF} that generates conditional code for your target system. By
5253: placing this definition in a different word list you can control whether
5254: the host system's @code{IF} or the target system's @code{IF} get used in
5255: any particular context by controlling the order of the word lists on the
5256: search order stack.
5257: @end itemize
1.1 anton 5258:
1.26 crook 5259: @node Word list examples, ,Why use word lists?, Word Lists
5260: @subsection Word list examples
5261: @cindex word lists - examples
1.1 anton 5262:
1.26 crook 5263: Here is an example of creating and using a new wordlist using ANS
5264: Forth Standard words:
1.1 anton 5265:
5266: @example
1.26 crook 5267: wordlist constant my-new-words-wordlist
5268: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
1.21 crook 5269:
1.26 crook 5270: \ add it to the search order
5271: also my-new-words
1.21 crook 5272:
1.26 crook 5273: \ alternatively, add it to the search order and make it
5274: \ the compilation word list
5275: also my-new-words definitions
5276: \ type "order" to see the problem
1.21 crook 5277: @end example
5278:
1.26 crook 5279: The problem with this example is that @code{order} has no way to
5280: associate the name @code{my-new-words} with the wid of the word list (in
5281: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
5282: that has no associated name). There is no Standard way of associating a
5283: name with a wid.
5284:
5285: In Gforth, this example can be re-coded using @code{vocabulary}, which
5286: associates a name with a wid:
1.21 crook 5287:
1.26 crook 5288: @example
5289: vocabulary my-new-words
1.21 crook 5290:
1.26 crook 5291: \ add it to the search order
5292: my-new-words
1.21 crook 5293:
1.26 crook 5294: \ alternatively, add it to the search order and make it
5295: \ the compilation word list
5296: my-new-words definitions
5297: \ type "order" to see that the problem is solved
5298: @end example
1.23 crook 5299:
1.26 crook 5300: @c -------------------------------------------------------------
5301: @node Environmental Queries, Files, Word Lists, Words
5302: @section Environmental Queries
5303: @cindex environmental queries
1.21 crook 5304:
1.26 crook 5305: ANS Forth introduced the idea of ``environmental queries'' as a way
5306: for a program running on a system to determine certain characteristics of the system.
5307: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 5308:
1.26 crook 5309: The Standard requires that the name space used for environmental queries
5310: be distinct from the name space used for definitions.
1.21 crook 5311:
1.26 crook 5312: Typically, environmental queries are supported by creating a set of
1.29 crook 5313: definitions in a word list that is @i{only} used during environmental
1.26 crook 5314: queries; that is what Gforth does. There is no Standard way of adding
5315: definitions to the set of recognised environmental queries, but any
5316: implementation that supports the loading of optional word sets must have
5317: some mechanism for doing this (after loading the word set, the
5318: associated environmental query string must return @code{true}). In
5319: Gforth, the word list used to honour environmental queries can be
5320: manipulated just like any other word list.
1.21 crook 5321:
1.26 crook 5322: doc-environment?
5323: doc-environment-wordlist
1.21 crook 5324:
1.26 crook 5325: doc-gforth
5326: doc-os-class
1.21 crook 5327:
1.26 crook 5328: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
5329: returning two items on the stack, querying it using @code{environment?}
5330: will return an additional item; the @code{true} flag that shows that the
5331: string was recognised.
1.21 crook 5332:
1.26 crook 5333: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 5334:
1.26 crook 5335: Here are some examples of using environmental queries:
1.21 crook 5336:
1.26 crook 5337: @example
5338: s" address-unit-bits" environment? 0=
5339: [IF]
5340: cr .( environmental attribute address-units-bits unknown... ) cr
5341: [THEN]
1.21 crook 5342:
1.26 crook 5343: s" block" environment? [IF] DROP include block.fs [THEN]
1.21 crook 5344:
1.26 crook 5345: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
1.21 crook 5346:
1.26 crook 5347: s" gforth" environment? [IF] .( Gforth version ) TYPE
5348: [ELSE] .( Not Gforth..) [THEN]
5349: @end example
1.21 crook 5350:
5351:
1.26 crook 5352: Here is an example of adding a definition to the environment word list:
1.21 crook 5353:
1.26 crook 5354: @example
5355: get-current environment-wordlist set-current
5356: true constant block
5357: true constant block-ext
5358: set-current
5359: @end example
1.21 crook 5360:
1.26 crook 5361: You can see what definitions are in the environment word list like this:
1.21 crook 5362:
1.26 crook 5363: @example
5364: get-order 1+ environment-wordlist swap set-order words previous
5365: @end example
1.21 crook 5366:
5367:
1.26 crook 5368: @c -------------------------------------------------------------
5369: @node Files, Blocks, Environmental Queries, Words
5370: @section Files
1.28 crook 5371: @cindex files
5372: @cindex I/O - file-handling
1.21 crook 5373:
1.26 crook 5374: Gforth provides facilities for accessing files that are stored in the
5375: host operating system's file-system. Files that are processed by Gforth
5376: can be divided into two categories:
1.21 crook 5377:
1.23 crook 5378: @itemize @bullet
5379: @item
1.29 crook 5380: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 5381: @item
1.29 crook 5382: Files that are processed by some other program (@dfn{general files}).
1.26 crook 5383: @end itemize
5384:
5385: @menu
5386: * Forth source files::
5387: * General files::
5388: * Search Paths::
5389: * Forth Search Paths::
5390: * General Search Paths::
5391: @end menu
5392:
1.21 crook 5393:
1.26 crook 5394: @c -------------------------------------------------------------
5395: @node Forth source files, General files, Files, Files
5396: @subsection Forth source files
5397: @cindex including files
5398: @cindex Forth source files
1.21 crook 5399:
1.26 crook 5400: The simplest way to interpret the contents of a file is to use one of
5401: these two formats:
1.21 crook 5402:
1.26 crook 5403: @example
5404: include mysource.fs
5405: s" mysource.fs" included
5406: @end example
1.21 crook 5407:
1.26 crook 5408: Sometimes you want to include a file only if it is not included already
5409: (by, say, another source file). In that case, you can use one of these
5410: fomats:
1.21 crook 5411:
1.26 crook 5412: @example
5413: require mysource.fs
5414: needs mysource.fs
5415: s" mysource.fs" required
5416: @end example
1.21 crook 5417:
1.26 crook 5418: @cindex stack effect of included files
5419: @cindex including files, stack effect
5420: I recommend that you write your source files such that interpreting them
5421: does not change the stack. This allows using these files with
5422: @code{required} and friends without complications. For example:
1.21 crook 5423:
1.26 crook 5424: @example
5425: 1 require foo.fs drop
5426: @end example
1.21 crook 5427:
1.26 crook 5428: doc-include-file
5429: doc-included
1.28 crook 5430: doc-included?
1.26 crook 5431: doc-include
5432: doc-required
5433: doc-require
5434: doc-needs
1.28 crook 5435: doc-init-included-files
1.21 crook 5436:
1.26 crook 5437: A definition in ANS Forth for @code{required} is provided in
5438: @file{compat/required.fs}.
1.21 crook 5439:
1.26 crook 5440: @c -------------------------------------------------------------
5441: @node General files, Search Paths, Forth source files, Files
5442: @subsection General files
5443: @cindex general files
5444: @cindex file-handling
1.21 crook 5445:
1.26 crook 5446: Files are opened/created by name and type. The following types are
5447: recognised:
1.1 anton 5448:
1.26 crook 5449: doc-r/o
5450: doc-r/w
5451: doc-w/o
5452: doc-bin
1.1 anton 5453:
1.26 crook 5454: When a file is opened/created, it returns a file identifier,
1.29 crook 5455: @i{wfileid} that is used for all other file commands. All file
5456: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 5457: successful operation and an implementation-defined non-zero value in the
5458: case of an error.
1.21 crook 5459:
1.26 crook 5460: doc-open-file
5461: doc-create-file
1.21 crook 5462:
1.26 crook 5463: doc-close-file
5464: doc-delete-file
5465: doc-rename-file
5466: doc-read-file
5467: doc-read-line
5468: doc-write-file
5469: doc-write-line
5470: doc-emit-file
5471: doc-flush-file
1.21 crook 5472:
1.26 crook 5473: doc-file-status
5474: doc-file-position
5475: doc-reposition-file
5476: doc-file-size
5477: doc-resize-file
1.21 crook 5478:
1.26 crook 5479: @c ---------------------------------------------------------
5480: @node Search Paths, Forth Search Paths, General files, Files
5481: @subsection Search Paths
5482: @cindex path for @code{included}
5483: @cindex file search path
5484: @cindex @code{include} search path
5485: @cindex search path for files
1.21 crook 5486:
1.26 crook 5487: If you specify an absolute filename (i.e., a filename starting with
5488: @file{/} or @file{~}, or with @file{:} in the second position (as in
5489: @samp{C:...})) for @code{included} and friends, that file is included
5490: just as you would expect.
1.21 crook 5491:
1.26 crook 5492: For relative filenames, Gforth uses a search path similar to Forth's
5493: search order (@pxref{Word Lists}). It tries to find the given filename
5494: in the directories present in the path, and includes the first one it
5495: finds. There are separate search paths for Forth source files and
5496: general files.
1.21 crook 5497:
1.26 crook 5498: If the search path contains the directory @file{.} (as it should), this
5499: refers to the directory that the present file was @code{included}
5500: from. This allows files to include other files relative to their own
5501: position (irrespective of the current working directory or the absolute
5502: position). This feature is essential for libraries consisting of
5503: several files, where a file may include other files from the library.
5504: It corresponds to @code{#include "..."} in C. If the current input
5505: source is not a file, @file{.} refers to the directory of the innermost
5506: file being included, or, if there is no file being included, to the
5507: current working directory.
1.21 crook 5508:
1.26 crook 5509: Use @file{~+} to refer to the current working directory (as in the
5510: @code{bash}).
1.1 anton 5511:
1.26 crook 5512: If the filename starts with @file{./}, the search path is not searched
5513: (just as with absolute filenames), and the @file{.} has the same meaning
5514: as described above.
1.1 anton 5515:
1.26 crook 5516: @c ---------------------------------------------------------
5517: @node Forth Search Paths, General Search Paths, Search Paths, Files
5518: @subsubsection Forth Search Paths
1.28 crook 5519: @cindex search path control - Forth
1.5 anton 5520:
1.26 crook 5521: The search path is initialized when you start Gforth (@pxref{Invoking
5522: Gforth}). You can display it and change it using these words:
1.5 anton 5523:
1.26 crook 5524: doc-.fpath
5525: doc-fpath+
5526: doc-fpath=
5527: doc-open-fpath-file
1.5 anton 5528:
1.26 crook 5529: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 5530:
1.26 crook 5531: @example
5532: fpath= /usr/lib/forth/|./
5533: require timer.fs
5534: @end example
1.5 anton 5535:
1.26 crook 5536: @c ---------------------------------------------------------
5537: @node General Search Paths, , Forth Search Paths, Files
5538: @subsubsection General Search Paths
5539: @cindex search path control - for user applications
1.5 anton 5540:
1.26 crook 5541: Your application may need to search files in several directories, like
5542: @code{included} does. To facilitate this, Gforth allows you to define
5543: and use your own search paths, by providing generic equivalents of the
5544: Forth search path words:
1.5 anton 5545:
1.26 crook 5546: doc-.path
5547: doc-path+
5548: doc-path=
5549: doc-open-path-file
1.5 anton 5550:
1.26 crook 5551: Here's an example of creating a search path:
1.5 anton 5552:
1.26 crook 5553: @example
5554: \ Make a buffer for the path:
5555: create mypath 100 chars , \ maximum length (is checked)
5556: 0 , \ real len
5557: 100 chars allot \ space for path
5558: @end example
1.5 anton 5559:
1.26 crook 5560: @c -------------------------------------------------------------
5561: @node Blocks, Other I/O, Files, Words
5562: @section Blocks
1.28 crook 5563: @cindex I/O - blocks
5564: @cindex blocks
5565:
5566: When you run Gforth on a modern desk-top computer, it runs under the
5567: control of an operating system which provides certain services. One of
5568: these services is @var{file services}, which allows Forth source code
5569: and data to be stored in files and read into Gforth (@pxref{Files}).
5570:
5571: Traditionally, Forth has been an important programming language on
5572: systems where it has interfaced directly to the underlying hardware with
5573: no intervening operating system. Forth provides a mechanism, called
1.29 crook 5574: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 5575:
5576: A block is a 1024-byte data area, which can be used to hold data or
5577: Forth source code. No structure is imposed on the contents of the
5578: block. A block is identified by its number; blocks are numbered
5579: contiguously from 1 to an implementation-defined maximum.
5580:
5581: A typical system that used blocks but no operating system might use a
5582: single floppy-disk drive for mass storage, with the disks formatted to
5583: provide 256-byte sectors. Blocks would be implemented by assigning the
5584: first four sectors of the disk to block 1, the second four sectors to
5585: block 2 and so on, up to the limit of the capacity of the disk. The disk
5586: would not contain any file system information, just the set of blocks.
5587:
1.29 crook 5588: @cindex blocks file
1.28 crook 5589: On systems that do provide file services, blocks are typically
1.29 crook 5590: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 5591: file}. The size of the blocks file will be an exact multiple of 1024
5592: bytes, corresponding to the number of blocks it contains. This is the
5593: mechanism that Gforth uses.
5594:
1.29 crook 5595: @cindex @file{blocks.fb}
1.28 crook 5596: Only 1 blocks file can be open at a time. If you use block words without
5597: having specified a blocks file, Gforth defaults to the blocks file
5598: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
5599: locate a blocks file (@pxref{Forth Search Paths}).
5600:
1.29 crook 5601: @cindex block buffers
1.28 crook 5602: When you read and write blocks under program control, Gforth uses a
1.29 crook 5603: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 5604: not used when you use @code{load} to interpret the contents of a block.
5605:
5606: The behaviour of the block buffers is directly analagous to that of a
5607: cache. Each block buffer has three states:
5608:
5609: @itemize @bullet
5610: @item
5611: Unassigned
5612: @item
5613: Assigned-clean
5614: @item
5615: Assigned-dirty
5616: @end itemize
5617:
1.29 crook 5618: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 5619: block, the block (specified by its block number) must be assigned to a
5620: block buffer.
5621:
5622: The assignment of a block to a block buffer is performed by @code{block}
5623: or @code{buffer}. Use @code{block} when you wish to modify the existing
5624: contents of a block. Use @code{buffer} when you don't care about the
5625: existing contents of the block@footnote{The ANS Forth definition of
5626: @code{block} is intended not to cause disk I/O; if the data associated
5627: with the particular block is already stored in a block buffer due to an
5628: earlier @code{block} command, @code{buffer} will return that block
5629: buffer and the existing contents of the block will be
5630: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 5631: block buffer for the block.}.
1.28 crook 5632:
5633: Once a block has been assigned to a block buffer, the block buffer state
1.29 crook 5634: becomes @i{assigned-clean}. Data can now be manipulated within the
1.28 crook 5635: block buffer.
5636:
5637: When the contents of a block buffer is changed it is necessary,
5638: @i{before calling} @code{block} @i{or} @code{buffer} @i{again}, to
5639: either abandon the changes (by doing nothing) or commit the changes,
5640: using @code{update}. Using @code{update} does not change the blocks
1.29 crook 5641: file; it simply changes a block buffer's state to @i{assigned-dirty}.
1.28 crook 5642:
1.29 crook 5643: The word @code{flush} causes all @i{assigned-dirty} blocks to be
1.28 crook 5644: written back to the blocks file on disk. Leaving Gforth using @code{bye}
5645: also causes a @code{flush} to be performed.
5646:
1.29 crook 5647: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 5648: algorithm to assign a block buffer to a block. That means that any
5649: particular block can only be assigned to one specific block buffer,
1.29 crook 5650: called (for the particular operation) the @i{victim buffer}. If the
5651: victim buffer is @i{unassigned} or @i{assigned-clean} it can be
5652: allocated to the new block immediately. If it is @i{assigned-dirty}
1.28 crook 5653: its current contents must be written out to disk before it can be
5654: allocated to the new block.
5655:
5656: Although no structure is imposed on the contents of a block, it is
5657: traditional to display the contents as 16 lines each of 64 characters. A
5658: block provides a single, continuous stream of input (for example, it
5659: acts as a single parse area) -- there are no end-of-line characters
5660: within a block, and no end-of-file character at the end of a
5661: block. There are two consequences of this:
1.26 crook 5662:
1.28 crook 5663: @itemize @bullet
5664: @item
5665: The last character of one line wraps straight into the first character
5666: of the following line
5667: @item
5668: The word @code{\} -- comment to end of line -- requires special
5669: treatment; in the context of a block it causes all characters until the
5670: end of the current 64-character ``line'' to be ignored.
5671: @end itemize
5672:
5673: In Gforth, when you use @code{block} with a non-existent block number,
5674: the current block file will be extended to the appropriate size and the
5675: block buffer will be initialised with spaces.
5676:
1.29 crook 5677: Gforth doesn't encourage the use of blocks; the mechanism is only
5678: provided for backward compatibility -- ANS Forth requires blocks to be
5679: available when files are.
1.28 crook 5680:
5681: Common techniques that are used when working with blocks include:
5682:
5683: @itemize @bullet
5684: @item
5685: A screen editor that allows you to edit blocks without leaving the Forth
5686: environment.
5687: @item
5688: Shadow screens; where every code block has an associated block
5689: containing comments (for example: code in odd block numbers, comments in
5690: even block numbers). Typically, the block editor provides a convenient
5691: mechanism to toggle between code and comments.
5692: @item
5693: Load blocks; a single block (typically block 1) contains a number of
5694: @code{thru} commands which @code{load} the whole of the application.
5695: @item
5696: Chaining blocks; a block terminates with a @code{-->} so that a whole
5697: application can be @code{load}ed by @code{load}ing a single block.
5698: @end itemize
1.26 crook 5699:
1.29 crook 5700: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
5701: integrated into a Forth programming environment.
1.26 crook 5702:
5703: @comment TODO what about errors on open-blocks?
5704: doc-open-blocks
5705: doc-use
5706: doc-get-block-fid
5707: doc-block-position
1.28 crook 5708:
5709: doc-scr
5710: doc-list
5711:
5712: doc---block-block
5713: doc-buffer
5714:
1.26 crook 5715: doc-update
1.28 crook 5716: doc-updated?
1.26 crook 5717: doc-save-buffers
5718: doc-empty-buffers
5719: doc-empty-buffer
5720: doc-flush
1.28 crook 5721:
1.26 crook 5722: doc-load
5723: doc-thru
5724: doc-+load
5725: doc-+thru
5726: doc---block--->
5727: doc-block-included
5728:
5729: @c -------------------------------------------------------------
5730: @node Other I/O, Programming Tools, Blocks, Words
5731: @section Other I/O
1.28 crook 5732: @cindex I/O - keyboard and display
1.26 crook 5733:
5734: @menu
5735: * Simple numeric output:: Predefined formats
5736: * Formatted numeric output:: Formatted (pictured) output
5737: * String Formats:: How Forth stores strings in memory
5738: * Displaying characters and strings:: Other stuff
5739: * Input:: Input
5740: @end menu
5741:
5742: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
5743: @subsection Simple numeric output
1.28 crook 5744: @cindex numeric output - simple/free-format
1.5 anton 5745:
1.26 crook 5746: The simplest output functions are those that display numbers from the
5747: data or floating-point stacks. Floating-point output is always displayed
5748: using base 10. Numbers displayed from the data stack use the value stored
5749: in @code{base}.
1.5 anton 5750:
1.26 crook 5751: doc-.
5752: doc-dec.
5753: doc-hex.
5754: doc-u.
5755: doc-.r
5756: doc-u.r
5757: doc-d.
5758: doc-ud.
5759: doc-d.r
5760: doc-ud.r
5761: doc-f.
5762: doc-fe.
5763: doc-fs.
1.5 anton 5764:
1.26 crook 5765: Examples of printing the number 1234.5678E23 in the different floating-point output
5766: formats are shown below:
1.5 anton 5767:
5768: @example
1.26 crook 5769: f. 123456779999999000000000000.
5770: fe. 123.456779999999E24
5771: fs. 1.23456779999999E26
1.5 anton 5772: @end example
5773:
5774:
1.26 crook 5775: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
5776: @subsection Formatted numeric output
1.28 crook 5777: @cindex formatted numeric output
1.26 crook 5778: @cindex pictured numeric output
1.28 crook 5779: @cindex numeric output - formatted
1.26 crook 5780:
1.29 crook 5781: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 5782: output} for formatted printing of integers. In this technique, digits
5783: are extracted from the number (using the current output radix defined by
5784: @code{base}), converted to ASCII codes and appended to a string that is
5785: built in a scratch-pad area of memory (@pxref{core-idef,
5786: Implementation-defined options, Implementation-defined
5787: options}). Arbitrary characters can be appended to the string during the
5788: extraction process. The completed string is specified by an address
5789: and length and can be manipulated (@code{TYPE}ed, copied, modified)
5790: under program control.
1.5 anton 5791:
1.26 crook 5792: All of the words described in the previous section for simple numeric
5793: output are implemented in Gforth using pictured numeric output.
1.5 anton 5794:
1.26 crook 5795: Three important things to remember about Pictured Numeric Output:
1.5 anton 5796:
1.26 crook 5797: @itemize @bullet
5798: @item
1.28 crook 5799: It always operates on double-precision numbers; to display a
5800: single-precision number, convert it first (@pxref{Double precision} for
5801: ways of doing this).
1.26 crook 5802: @item
1.28 crook 5803: It always treats the double-precision number as though it were
5804: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 5805: @item
5806: The string is built up from right to left; least significant digit first.
5807: @end itemize
1.5 anton 5808:
1.26 crook 5809: doc-<#
5810: doc-#
5811: doc-#s
5812: doc-hold
5813: doc-sign
5814: doc-#>
1.5 anton 5815:
1.26 crook 5816: doc-represent
1.5 anton 5817:
1.26 crook 5818: Here are some examples of using pictured numeric output:
1.5 anton 5819:
5820: @example
1.26 crook 5821: : my-u. ( u -- )
5822: \ Simplest use of pns.. behaves like Standard u.
5823: 0 \ convert to unsigned double
5824: <# \ start conversion
5825: #s \ convert all digits
5826: #> \ complete conversion
5827: TYPE SPACE ; \ display, with trailing space
1.5 anton 5828:
1.26 crook 5829: : cents-only ( u -- )
5830: 0 \ convert to unsigned double
5831: <# \ start conversion
5832: # # \ convert two least-significant digits
5833: #> \ complete conversion, discard other digits
5834: TYPE SPACE ; \ display, with trailing space
1.5 anton 5835:
1.26 crook 5836: : dollars-and-cents ( u -- )
5837: 0 \ convert to unsigned double
5838: <# \ start conversion
5839: # # \ convert two least-significant digits
5840: [char] . hold \ insert decimal point
5841: #s \ convert remaining digits
5842: [char] $ hold \ append currency symbol
5843: #> \ complete conversion
5844: TYPE SPACE ; \ display, with trailing space
1.5 anton 5845:
1.26 crook 5846: : my-. ( n -- )
5847: \ handling negatives.. behaves like Standard .
5848: s>d \ convert to signed double
5849: swap over dabs \ leave sign byte followed by unsigned double
5850: <# \ start conversion
5851: #s \ convert all digits
5852: rot sign \ get at sign byte, append "-" if needed
5853: #> \ complete conversion
5854: TYPE SPACE ; \ display, with trailing space
1.5 anton 5855:
1.26 crook 5856: : account. ( n -- )
5857: \ accountants don't like minus signs, they use braces
5858: \ for negative numbers
5859: s>d \ convert to signed double
5860: swap over dabs \ leave sign byte followed by unsigned double
5861: <# \ start conversion
5862: 2 pick \ get copy of sign byte
5863: 0< IF [char] ) hold THEN \ right-most character of output
5864: #s \ convert all digits
5865: rot \ get at sign byte
5866: 0< IF [char] ( hold THEN
5867: #> \ complete conversion
5868: TYPE SPACE ; \ display, with trailing space
1.5 anton 5869: @end example
5870:
1.26 crook 5871: Here are some examples of using these words:
1.5 anton 5872:
5873: @example
1.26 crook 5874: 1 my-u. 1
5875: hex -1 my-u. decimal FFFFFFFF
5876: 1 cents-only 01
5877: 1234 cents-only 34
5878: 2 dollars-and-cents $0.02
5879: 1234 dollars-and-cents $12.34
5880: 123 my-. 123
5881: -123 my. -123
5882: 123 account. 123
5883: -456 account. (456)
1.5 anton 5884: @end example
5885:
5886:
1.26 crook 5887: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
5888: @subsection String Formats
1.27 crook 5889: @cindex strings - see character strings
5890: @cindex character strings - formats
1.28 crook 5891: @cindex I/O - see character strings
1.26 crook 5892:
1.27 crook 5893: Forth commonly uses two different methods for representing character
5894: strings:
1.26 crook 5895:
5896: @itemize @bullet
5897: @item
5898: @cindex address of counted string
1.29 crook 5899: As a @dfn{counted string}, represented by a @i{c-addr}. The char
5900: addressed by @i{c-addr} contains a character-count, @i{n}, of the
5901: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 5902: memory.
5903: @item
1.29 crook 5904: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
5905: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 5906: first byte of the string.
5907: @end itemize
5908:
5909: ANS Forth encourages the use of the second format when representing
5910: strings on the stack, whilst conceeding that the counted string format
5911: remains useful as a way of storing strings in memory.
5912:
5913: doc-count
5914:
5915: @xref{Memory Blocks} for words that move, copy and search
5916: for strings. @xref{Displaying characters and strings,} for words that
5917: display characters and strings.
5918:
5919:
5920: @node Displaying characters and strings, Input, String Formats, Other I/O
5921: @subsection Displaying characters and strings
1.27 crook 5922: @cindex characters - compiling and displaying
5923: @cindex character strings - compiling and displaying
1.26 crook 5924:
5925: This section starts with a glossary of Forth words and ends with a set
5926: of examples.
5927:
5928: doc-bl
5929: doc-space
5930: doc-spaces
5931: doc-emit
5932: doc-toupper
5933: doc-."
5934: doc-.(
5935: doc-type
5936: doc-cr
1.27 crook 5937: @cindex cursor control
1.26 crook 5938: doc-at-xy
5939: doc-page
5940: doc-s"
5941: doc-c"
5942: doc-char
5943: doc-[char]
5944: doc-sliteral
5945:
5946: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 5947:
5948: @example
1.26 crook 5949: .( text-1)
5950: : my-word
5951: ." text-2" cr
5952: .( text-3)
5953: ;
5954:
5955: ." text-4"
5956:
5957: : my-char
5958: [char] ALPHABET emit
5959: char emit
5960: ;
1.5 anton 5961: @end example
5962:
1.26 crook 5963: When you load this code into Gforth, the following output is generated:
1.5 anton 5964:
1.26 crook 5965: @example
1.30 ! anton 5966: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 5967: @end example
1.5 anton 5968:
1.26 crook 5969: @itemize @bullet
5970: @item
5971: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
5972: is an immediate word; it behaves in the same way whether it is used inside
5973: or outside a colon definition.
5974: @item
5975: Message @code{text-4} is displayed because of Gforth's added interpretation
5976: semantics for @code{."}.
5977: @item
1.29 crook 5978: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 5979: performs the compilation semantics for @code{."} within the definition of
5980: @code{my-word}.
5981: @end itemize
1.5 anton 5982:
1.26 crook 5983: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 5984:
1.26 crook 5985: @example
1.30 ! anton 5986: @kbd{my-word @key{RET}} text-2
1.26 crook 5987: ok
1.30 ! anton 5988: @kbd{my-char fred @key{RET}} Af ok
! 5989: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 5990: @end example
1.5 anton 5991:
5992: @itemize @bullet
5993: @item
1.26 crook 5994: Message @code{text-2} is displayed because of the run-time behaviour of
5995: @code{."}.
5996: @item
5997: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
5998: on the stack at run-time. @code{emit} always displays the character
5999: when @code{my-char} is executed.
6000: @item
6001: @code{char} parses a string at run-time and the second @code{emit} displays
6002: the first character of the string.
1.5 anton 6003: @item
1.26 crook 6004: If you type @code{see my-char} you can see that @code{[char]} discarded
6005: the text ``LPHABET'' and only compiled the display code for ``A'' into the
6006: definition of @code{my-char}.
1.5 anton 6007: @end itemize
6008:
6009:
6010:
1.26 crook 6011: @node Input, , Displaying characters and strings, Other I/O
6012: @subsection Input
6013: @cindex input
1.28 crook 6014: @cindex I/O - see input
6015: @cindex parsing a string
1.5 anton 6016:
1.27 crook 6017: @xref{String Formats} for ways of storing character strings in memory.
1.5 anton 6018:
1.27 crook 6019: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 6020: @comment then index them
1.27 crook 6021:
6022: doc-key
6023: doc-key?
1.26 crook 6024: doc->number
6025: doc->float
6026: doc-accept
1.27 crook 6027: doc-pad
6028: doc-parse
6029: doc-word
6030: doc-sword
6031: doc-refill
6032: @comment obsolescent words..
6033: doc-convert
1.26 crook 6034: doc-query
6035: doc-expect
1.27 crook 6036: doc-span
1.5 anton 6037:
6038:
6039: @c -------------------------------------------------------------
1.26 crook 6040: @node Programming Tools, Assembler and Code Words, Other I/O, Words
6041: @section Programming Tools
6042: @cindex programming tools
1.12 anton 6043:
6044: @menu
1.26 crook 6045: * Debugging:: Simple and quick.
6046: * Assertions:: Making your programs self-checking.
6047: * Singlestep Debugger:: Executing your program word by word.
1.5 anton 6048: @end menu
6049:
1.26 crook 6050: @node Debugging, Assertions, Programming Tools, Programming Tools
6051: @subsection Debugging
6052: @cindex debugging
1.5 anton 6053:
1.26 crook 6054: Languages with a slow edit/compile/link/test development loop tend to
6055: require sophisticated tracing/stepping debuggers to facilate
6056: productive debugging.
1.5 anton 6057:
1.26 crook 6058: A much better (faster) way in fast-compiling languages is to add
6059: printing code at well-selected places, let the program run, look at
6060: the output, see where things went wrong, add more printing code, etc.,
6061: until the bug is found.
1.5 anton 6062:
1.26 crook 6063: The simple debugging aids provided in @file{debugs.fs}
6064: are meant to support this style of debugging. In addition, there are
6065: words for non-destructively inspecting the stack and memory:
1.5 anton 6066:
1.26 crook 6067: doc-.s
6068: doc-f.s
1.5 anton 6069:
1.29 crook 6070: There is a word @code{.r} but it does @i{not} display the return
1.26 crook 6071: stack! It is used for formatted numeric output.
1.5 anton 6072:
1.26 crook 6073: doc-depth
6074: doc-fdepth
6075: doc-clearstack
6076: doc-?
6077: doc-dump
1.5 anton 6078:
1.26 crook 6079: The word @code{~~} prints debugging information (by default the source
6080: location and the stack contents). It is easy to insert. If you use Emacs
6081: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
6082: query-replace them with nothing). The deferred words
6083: @code{printdebugdata} and @code{printdebugline} control the output of
6084: @code{~~}. The default source location output format works well with
6085: Emacs' compilation mode, so you can step through the program at the
6086: source level using @kbd{C-x `} (the advantage over a stepping debugger
6087: is that you can step in any direction and you know where the crash has
6088: happened or where the strange data has occurred).
1.5 anton 6089:
1.26 crook 6090: The default actions of @code{~~} clobber the contents of the pictured
6091: numeric output string, so you should not use @code{~~}, e.g., between
6092: @code{<#} and @code{#>}.
1.5 anton 6093:
1.26 crook 6094: doc-~~
6095: doc-printdebugdata
6096: doc-printdebugline
1.5 anton 6097:
1.26 crook 6098: doc-see
6099: doc-marker
1.5 anton 6100:
1.26 crook 6101: Here's an example of using @code{marker} at the start of a source file
6102: that you are debugging; it ensures that you only ever have one copy of
6103: the file's definitions compiled at any time:
1.5 anton 6104:
1.26 crook 6105: @example
6106: [IFDEF] my-code
6107: my-code
6108: [ENDIF]
1.5 anton 6109:
1.26 crook 6110: marker my-code
1.28 crook 6111: init-included-files
1.5 anton 6112:
1.26 crook 6113: \ .. definitions start here
6114: \ .
6115: \ .
6116: \ end
6117: @end example
1.5 anton 6118:
6119:
6120:
1.26 crook 6121: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
6122: @subsection Assertions
6123: @cindex assertions
1.5 anton 6124:
1.26 crook 6125: It is a good idea to make your programs self-checking, especially if you
6126: make an assumption that may become invalid during maintenance (for
6127: example, that a certain field of a data structure is never zero). Gforth
1.29 crook 6128: supports @dfn{assertions} for this purpose. They are used like this:
1.23 crook 6129:
1.26 crook 6130: @example
1.29 crook 6131: assert( @i{flag} )
1.26 crook 6132: @end example
1.23 crook 6133:
1.26 crook 6134: The code between @code{assert(} and @code{)} should compute a flag, that
6135: should be true if everything is alright and false otherwise. It should
6136: not change anything else on the stack. The overall stack effect of the
6137: assertion is @code{( -- )}. E.g.
1.23 crook 6138:
1.26 crook 6139: @example
6140: assert( 1 1 + 2 = ) \ what we learn in school
6141: assert( dup 0<> ) \ assert that the top of stack is not zero
6142: assert( false ) \ this code should not be reached
6143: @end example
1.23 crook 6144:
1.26 crook 6145: The need for assertions is different at different times. During
6146: debugging, we want more checking, in production we sometimes care more
6147: for speed. Therefore, assertions can be turned off, i.e., the assertion
6148: becomes a comment. Depending on the importance of an assertion and the
6149: time it takes to check it, you may want to turn off some assertions and
6150: keep others turned on. Gforth provides several levels of assertions for
6151: this purpose:
1.23 crook 6152:
1.26 crook 6153: doc-assert0(
6154: doc-assert1(
6155: doc-assert2(
6156: doc-assert3(
6157: doc-assert(
6158: doc-)
1.23 crook 6159:
1.26 crook 6160: The variable @code{assert-level} specifies the highest assertions that
6161: are turned on. I.e., at the default @code{assert-level} of one,
6162: @code{assert0(} and @code{assert1(} assertions perform checking, while
6163: @code{assert2(} and @code{assert3(} assertions are treated as comments.
6164:
6165: The value of @code{assert-level} is evaluated at compile-time, not at
6166: run-time. Therefore you cannot turn assertions on or off at run-time;
6167: you have to set the @code{assert-level} appropriately before compiling a
6168: piece of code. You can compile different pieces of code at different
6169: @code{assert-level}s (e.g., a trusted library at level 1 and
6170: newly-written code at level 3).
1.23 crook 6171:
1.26 crook 6172: doc-assert-level
1.23 crook 6173:
1.26 crook 6174: If an assertion fails, a message compatible with Emacs' compilation mode
6175: is produced and the execution is aborted (currently with @code{ABORT"}.
6176: If there is interest, we will introduce a special throw code. But if you
6177: intend to @code{catch} a specific condition, using @code{throw} is
6178: probably more appropriate than an assertion).
1.23 crook 6179:
1.26 crook 6180: Definitions in ANS Forth for these assertion words are provided
6181: in @file{compat/assert.fs}.
1.23 crook 6182:
6183:
1.26 crook 6184: @node Singlestep Debugger, , Assertions, Programming Tools
6185: @subsection Singlestep Debugger
6186: @cindex singlestep Debugger
6187: @cindex debugging Singlestep
6188: @cindex @code{dbg}
6189: @cindex @code{BREAK:}
6190: @cindex @code{BREAK"}
1.23 crook 6191:
1.26 crook 6192: When you create a new word there's often the need to check whether it
6193: behaves correctly or not. You can do this by typing @code{dbg
6194: badword}. A debug session might look like this:
1.23 crook 6195:
1.26 crook 6196: @example
6197: : badword 0 DO i . LOOP ; ok
6198: 2 dbg badword
6199: : badword
6200: Scanning code...
1.23 crook 6201:
1.26 crook 6202: Nesting debugger ready!
1.23 crook 6203:
1.26 crook 6204: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
6205: 400D4740 8049F68 DO -> [ 0 ]
6206: 400D4744 804A0C8 i -> [ 1 ] 00000
6207: 400D4748 400C5E60 . -> 0 [ 0 ]
6208: 400D474C 8049D0C LOOP -> [ 0 ]
6209: 400D4744 804A0C8 i -> [ 1 ] 00001
6210: 400D4748 400C5E60 . -> 1 [ 0 ]
6211: 400D474C 8049D0C LOOP -> [ 0 ]
6212: 400D4758 804B384 ; -> ok
6213: @end example
1.23 crook 6214:
1.26 crook 6215: Each line displayed is one step. You always have to hit return to
6216: execute the next word that is displayed. If you don't want to execute
6217: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
6218: an overview what keys are available:
1.23 crook 6219:
1.26 crook 6220: @table @i
1.23 crook 6221:
1.30 ! anton 6222: @item @key{RET}
1.26 crook 6223: Next; Execute the next word.
1.23 crook 6224:
1.26 crook 6225: @item n
6226: Nest; Single step through next word.
1.5 anton 6227:
1.26 crook 6228: @item u
6229: Unnest; Stop debugging and execute rest of word. If we got to this word
6230: with nest, continue debugging with the calling word.
1.5 anton 6231:
1.26 crook 6232: @item d
6233: Done; Stop debugging and execute rest.
1.5 anton 6234:
1.26 crook 6235: @item s
6236: Stop; Abort immediately.
1.5 anton 6237:
1.26 crook 6238: @end table
1.5 anton 6239:
1.26 crook 6240: Debugging large application with this mechanism is very difficult, because
6241: you have to nest very deeply into the program before the interesting part
6242: begins. This takes a lot of time.
1.5 anton 6243:
1.26 crook 6244: To do it more directly put a @code{BREAK:} command into your source code.
6245: When program execution reaches @code{BREAK:} the single step debugger is
6246: invoked and you have all the features described above.
1.23 crook 6247:
1.26 crook 6248: If you have more than one part to debug it is useful to know where the
6249: program has stopped at the moment. You can do this by the
6250: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
6251: string is typed out when the ``breakpoint'' is reached.
6252:
6253: doc-dbg
6254: doc-BREAK:
6255: doc-BREAK"
6256:
6257:
6258: @c -------------------------------------------------------------
6259: @node Assembler and Code Words, Threading Words, Programming Tools, Words
6260: @section Assembler and Code Words
6261: @cindex assembler
6262: @cindex code words
1.5 anton 6263:
1.26 crook 6264: Gforth provides some words for defining primitives (words written in
1.29 crook 6265: machine code), and for defining the machine-code equivalent of
1.26 crook 6266: @code{DOES>}-based defining words. However, the machine-independent
6267: nature of Gforth poses a few problems: First of all, Gforth runs on
6268: several architectures, so it can provide no standard assembler. What's
6269: worse is that the register allocation not only depends on the processor,
6270: but also on the @code{gcc} version and options used.
1.5 anton 6271:
1.29 crook 6272: The words that Gforth offers encapsulate some system dependences (e.g.,
6273: the header structure), so a system-independent assembler may be used in
1.26 crook 6274: Gforth. If you do not have an assembler, you can compile machine code
1.29 crook 6275: directly with @code{,} and @code{c,}@footnote{This isn't portable,
6276: because these words emit stuff in @i{data} space; it works because
6277: Gforth has unified code/data spaces. Assembler isn't likely to be
6278: portable anyway.}.
1.5 anton 6279:
1.26 crook 6280: doc-assembler
6281: doc-code
6282: doc-end-code
6283: doc-;code
6284: doc-flush-icache
1.5 anton 6285:
1.26 crook 6286: If @code{flush-icache} does not work correctly, @code{code} words
6287: etc. will not work (reliably), either.
1.5 anton 6288:
1.29 crook 6289: The typical usage of these @code{code} words can be shown most easily by
6290: analogy to the equivalent high-level defining words:
6291:
6292: @example
6293: : foo code foo
6294: <high-level Forth words> <assembler>
6295: ; end-code
6296:
6297: : bar : bar
6298: <high-level Forth words> <high-level Forth words>
6299: CREATE CREATE
6300: <high-level Forth words> <high-level Forth words>
6301: DOES> ;code
6302: <high-level Forth words> <assembler>
6303: ; end-code
6304: @end example
6305:
1.26 crook 6306: @code{flush-icache} is always present. The other words are rarely used
6307: and reside in @code{code.fs}, which is usually not loaded. You can load
6308: it with @code{require code.fs}.
1.5 anton 6309:
1.26 crook 6310: @cindex registers of the inner interpreter
6311: In the assembly code you will want to refer to the inner interpreter's
6312: registers (e.g., the data stack pointer) and you may want to use other
6313: registers for temporary storage. Unfortunately, the register allocation
6314: is installation-dependent.
1.5 anton 6315:
1.26 crook 6316: The easiest solution is to use explicit register declarations
6317: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
6318: GNU C Manual}) for all of the inner interpreter's registers: You have to
6319: compile Gforth with @code{-DFORCE_REG} (configure option
6320: @code{--enable-force-reg}) and the appropriate declarations must be
6321: present in the @code{machine.h} file (see @code{mips.h} for an example;
6322: you can find a full list of all declarable register symbols with
6323: @code{grep register engine.c}). If you give explicit registers to all
6324: variables that are declared at the beginning of @code{engine()}, you
6325: should be able to use the other caller-saved registers for temporary
6326: storage. Alternatively, you can use the @code{gcc} option
6327: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
6328: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
6329: (however, this restriction on register allocation may slow Gforth
6330: significantly).
1.5 anton 6331:
1.26 crook 6332: If this solution is not viable (e.g., because @code{gcc} does not allow
6333: you to explicitly declare all the registers you need), you have to find
6334: out by looking at the code where the inner interpreter's registers
6335: reside and which registers can be used for temporary storage. You can
6336: get an assembly listing of the engine's code with @code{make engine.s}.
1.5 anton 6337:
1.26 crook 6338: In any case, it is good practice to abstract your assembly code from the
6339: actual register allocation. E.g., if the data stack pointer resides in
6340: register @code{$17}, create an alias for this register called @code{sp},
6341: and use that in your assembly code.
1.5 anton 6342:
1.26 crook 6343: @cindex code words, portable
6344: Another option for implementing normal and defining words efficiently
6345: is to add the desired functionality to the source of Gforth. For normal
6346: words you just have to edit @file{primitives} (@pxref{Automatic
6347: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
6348: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
6349: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5 anton 6350:
6351:
1.26 crook 6352: @c -------------------------------------------------------------
6353: @node Threading Words, Locals, Assembler and Code Words, Words
6354: @section Threading Words
6355: @cindex threading words
1.5 anton 6356:
1.26 crook 6357: @cindex code address
6358: These words provide access to code addresses and other threading stuff
6359: in Gforth (and, possibly, other interpretive Forths). It more or less
6360: abstracts away the differences between direct and indirect threading
6361: (and, for direct threading, the machine dependences). However, at
6362: present this wordset is still incomplete. It is also pretty low-level;
6363: some day it will hopefully be made unnecessary by an internals wordset
6364: that abstracts implementation details away completely.
1.5 anton 6365:
1.26 crook 6366: doc-threading-method
6367: doc->code-address
6368: doc->does-code
6369: doc-code-address!
6370: doc-does-code!
6371: doc-does-handler!
6372: doc-/does-handler
1.5 anton 6373:
1.26 crook 6374: The code addresses produced by various defining words are produced by
6375: the following words:
1.5 anton 6376:
1.26 crook 6377: doc-docol:
6378: doc-docon:
6379: doc-dovar:
6380: doc-douser:
6381: doc-dodefer:
6382: doc-dofield:
1.5 anton 6383:
1.26 crook 6384: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
6385: with @code{>does-code}. If the word was defined in that way, the value
6386: returned is non-zero and identifies the @code{DOES>} used by the
6387: defining word.
6388: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5 anton 6389:
1.26 crook 6390: @c -------------------------------------------------------------
6391: @node Locals, Structures, Threading Words, Words
6392: @section Locals
6393: @cindex locals
1.5 anton 6394:
1.26 crook 6395: Local variables can make Forth programming more enjoyable and Forth
6396: programs easier to read. Unfortunately, the locals of ANS Forth are
6397: laden with restrictions. Therefore, we provide not only the ANS Forth
6398: locals wordset, but also our own, more powerful locals wordset (we
6399: implemented the ANS Forth locals wordset through our locals wordset).
1.5 anton 6400:
1.26 crook 6401: The ideas in this section have also been published in the paper
6402: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
6403: at EuroForth '94; it is available at
6404: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
1.5 anton 6405:
1.26 crook 6406: @menu
6407: * Gforth locals::
6408: * ANS Forth locals::
6409: @end menu
1.5 anton 6410:
1.26 crook 6411: @node Gforth locals, ANS Forth locals, Locals, Locals
6412: @subsection Gforth locals
6413: @cindex Gforth locals
6414: @cindex locals, Gforth style
1.5 anton 6415:
1.26 crook 6416: Locals can be defined with
1.5 anton 6417:
6418: @example
1.26 crook 6419: @{ local1 local2 ... -- comment @}
6420: @end example
6421: or
6422: @example
6423: @{ local1 local2 ... @}
1.5 anton 6424: @end example
6425:
1.26 crook 6426: E.g.,
1.5 anton 6427: @example
1.26 crook 6428: : max @{ n1 n2 -- n3 @}
6429: n1 n2 > if
6430: n1
6431: else
6432: n2
6433: endif ;
1.5 anton 6434: @end example
6435:
1.26 crook 6436: The similarity of locals definitions with stack comments is intended. A
6437: locals definition often replaces the stack comment of a word. The order
6438: of the locals corresponds to the order in a stack comment and everything
6439: after the @code{--} is really a comment.
1.5 anton 6440:
1.26 crook 6441: This similarity has one disadvantage: It is too easy to confuse locals
6442: declarations with stack comments, causing bugs and making them hard to
6443: find. However, this problem can be avoided by appropriate coding
6444: conventions: Do not use both notations in the same program. If you do,
6445: they should be distinguished using additional means, e.g. by position.
6446:
6447: @cindex types of locals
6448: @cindex locals types
6449: The name of the local may be preceded by a type specifier, e.g.,
6450: @code{F:} for a floating point value:
6451:
6452: @example
6453: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
6454: \ complex multiplication
6455: Ar Br f* Ai Bi f* f-
6456: Ar Bi f* Ai Br f* f+ ;
6457: @end example
6458:
6459: @cindex flavours of locals
6460: @cindex locals flavours
6461: @cindex value-flavoured locals
6462: @cindex variable-flavoured locals
6463: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
6464: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
6465: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
6466: with @code{W:}, @code{D:} etc.) produces its value and can be changed
6467: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
6468: produces its address (which becomes invalid when the variable's scope is
6469: left). E.g., the standard word @code{emit} can be defined in terms of
6470: @code{type} like this:
1.5 anton 6471:
6472: @example
1.26 crook 6473: : emit @{ C^ char* -- @}
6474: char* 1 type ;
1.5 anton 6475: @end example
6476:
1.26 crook 6477: @cindex default type of locals
6478: @cindex locals, default type
6479: A local without type specifier is a @code{W:} local. Both flavours of
6480: locals are initialized with values from the data or FP stack.
1.5 anton 6481:
1.26 crook 6482: Currently there is no way to define locals with user-defined data
6483: structures, but we are working on it.
1.5 anton 6484:
1.26 crook 6485: Gforth allows defining locals everywhere in a colon definition. This
6486: poses the following questions:
1.5 anton 6487:
1.26 crook 6488: @menu
6489: * Where are locals visible by name?::
6490: * How long do locals live?::
6491: * Programming Style::
6492: * Implementation::
6493: @end menu
1.5 anton 6494:
1.26 crook 6495: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
6496: @subsubsection Where are locals visible by name?
6497: @cindex locals visibility
6498: @cindex visibility of locals
6499: @cindex scope of locals
1.5 anton 6500:
1.26 crook 6501: Basically, the answer is that locals are visible where you would expect
6502: it in block-structured languages, and sometimes a little longer. If you
6503: want to restrict the scope of a local, enclose its definition in
6504: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 6505:
1.26 crook 6506: doc-scope
6507: doc-endscope
1.5 anton 6508:
1.26 crook 6509: These words behave like control structure words, so you can use them
6510: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
6511: arbitrary ways.
1.5 anton 6512:
1.26 crook 6513: If you want a more exact answer to the visibility question, here's the
6514: basic principle: A local is visible in all places that can only be
6515: reached through the definition of the local@footnote{In compiler
6516: construction terminology, all places dominated by the definition of the
6517: local.}. In other words, it is not visible in places that can be reached
6518: without going through the definition of the local. E.g., locals defined
6519: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
6520: defined in @code{BEGIN}...@code{UNTIL} are visible after the
6521: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5 anton 6522:
1.26 crook 6523: The reasoning behind this solution is: We want to have the locals
6524: visible as long as it is meaningful. The user can always make the
6525: visibility shorter by using explicit scoping. In a place that can
6526: only be reached through the definition of a local, the meaning of a
6527: local name is clear. In other places it is not: How is the local
6528: initialized at the control flow path that does not contain the
6529: definition? Which local is meant, if the same name is defined twice in
6530: two independent control flow paths?
1.5 anton 6531:
1.26 crook 6532: This should be enough detail for nearly all users, so you can skip the
6533: rest of this section. If you really must know all the gory details and
6534: options, read on.
1.5 anton 6535:
1.26 crook 6536: In order to implement this rule, the compiler has to know which places
6537: are unreachable. It knows this automatically after @code{AHEAD},
6538: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
6539: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
6540: compiler that the control flow never reaches that place. If
6541: @code{UNREACHABLE} is not used where it could, the only consequence is
6542: that the visibility of some locals is more limited than the rule above
6543: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
6544: lie to the compiler), buggy code will be produced.
1.5 anton 6545:
1.26 crook 6546: doc-unreachable
1.5 anton 6547:
1.26 crook 6548: Another problem with this rule is that at @code{BEGIN}, the compiler
6549: does not know which locals will be visible on the incoming
6550: back-edge. All problems discussed in the following are due to this
6551: ignorance of the compiler (we discuss the problems using @code{BEGIN}
6552: loops as examples; the discussion also applies to @code{?DO} and other
6553: loops). Perhaps the most insidious example is:
1.5 anton 6554: @example
1.26 crook 6555: AHEAD
6556: BEGIN
6557: x
6558: [ 1 CS-ROLL ] THEN
6559: @{ x @}
6560: ...
6561: UNTIL
6562: @end example
1.5 anton 6563:
1.26 crook 6564: This should be legal according to the visibility rule. The use of
6565: @code{x} can only be reached through the definition; but that appears
6566: textually below the use.
1.5 anton 6567:
1.26 crook 6568: From this example it is clear that the visibility rules cannot be fully
6569: implemented without major headaches. Our implementation treats common
6570: cases as advertised and the exceptions are treated in a safe way: The
6571: compiler makes a reasonable guess about the locals visible after a
6572: @code{BEGIN}; if it is too pessimistic, the
6573: user will get a spurious error about the local not being defined; if the
6574: compiler is too optimistic, it will notice this later and issue a
6575: warning. In the case above the compiler would complain about @code{x}
6576: being undefined at its use. You can see from the obscure examples in
6577: this section that it takes quite unusual control structures to get the
6578: compiler into trouble, and even then it will often do fine.
1.5 anton 6579:
1.26 crook 6580: If the @code{BEGIN} is reachable from above, the most optimistic guess
6581: is that all locals visible before the @code{BEGIN} will also be
6582: visible after the @code{BEGIN}. This guess is valid for all loops that
6583: are entered only through the @code{BEGIN}, in particular, for normal
6584: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
6585: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
6586: compiler. When the branch to the @code{BEGIN} is finally generated by
6587: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
6588: warns the user if it was too optimistic:
6589: @example
6590: IF
6591: @{ x @}
6592: BEGIN
6593: \ x ?
6594: [ 1 cs-roll ] THEN
6595: ...
6596: UNTIL
1.5 anton 6597: @end example
6598:
1.26 crook 6599: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
6600: optimistically assumes that it lives until the @code{THEN}. It notices
6601: this difference when it compiles the @code{UNTIL} and issues a
6602: warning. The user can avoid the warning, and make sure that @code{x}
6603: is not used in the wrong area by using explicit scoping:
6604: @example
6605: IF
6606: SCOPE
6607: @{ x @}
6608: ENDSCOPE
6609: BEGIN
6610: [ 1 cs-roll ] THEN
6611: ...
6612: UNTIL
6613: @end example
1.5 anton 6614:
1.26 crook 6615: Since the guess is optimistic, there will be no spurious error messages
6616: about undefined locals.
1.5 anton 6617:
1.26 crook 6618: If the @code{BEGIN} is not reachable from above (e.g., after
6619: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
6620: optimistic guess, as the locals visible after the @code{BEGIN} may be
6621: defined later. Therefore, the compiler assumes that no locals are
6622: visible after the @code{BEGIN}. However, the user can use
6623: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
6624: visible at the BEGIN as at the point where the top control-flow stack
6625: item was created.
1.5 anton 6626:
1.26 crook 6627: doc-assume-live
1.5 anton 6628:
1.26 crook 6629: E.g.,
1.5 anton 6630: @example
1.26 crook 6631: @{ x @}
6632: AHEAD
6633: ASSUME-LIVE
6634: BEGIN
6635: x
6636: [ 1 CS-ROLL ] THEN
6637: ...
6638: UNTIL
1.5 anton 6639: @end example
6640:
1.26 crook 6641: Other cases where the locals are defined before the @code{BEGIN} can be
6642: handled by inserting an appropriate @code{CS-ROLL} before the
6643: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
6644: behind the @code{ASSUME-LIVE}).
1.5 anton 6645:
1.26 crook 6646: Cases where locals are defined after the @code{BEGIN} (but should be
6647: visible immediately after the @code{BEGIN}) can only be handled by
6648: rearranging the loop. E.g., the ``most insidious'' example above can be
6649: arranged into:
1.5 anton 6650: @example
1.26 crook 6651: BEGIN
6652: @{ x @}
6653: ... 0=
6654: WHILE
6655: x
6656: REPEAT
1.5 anton 6657: @end example
6658:
1.26 crook 6659: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
6660: @subsubsection How long do locals live?
6661: @cindex locals lifetime
6662: @cindex lifetime of locals
1.5 anton 6663:
1.26 crook 6664: The right answer for the lifetime question would be: A local lives at
6665: least as long as it can be accessed. For a value-flavoured local this
6666: means: until the end of its visibility. However, a variable-flavoured
6667: local could be accessed through its address far beyond its visibility
6668: scope. Ultimately, this would mean that such locals would have to be
6669: garbage collected. Since this entails un-Forth-like implementation
6670: complexities, I adopted the same cowardly solution as some other
6671: languages (e.g., C): The local lives only as long as it is visible;
6672: afterwards its address is invalid (and programs that access it
6673: afterwards are erroneous).
1.5 anton 6674:
1.26 crook 6675: @node Programming Style, Implementation, How long do locals live?, Gforth locals
6676: @subsubsection Programming Style
6677: @cindex locals programming style
6678: @cindex programming style, locals
1.5 anton 6679:
1.26 crook 6680: The freedom to define locals anywhere has the potential to change
6681: programming styles dramatically. In particular, the need to use the
6682: return stack for intermediate storage vanishes. Moreover, all stack
6683: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
6684: determined arguments) can be eliminated: If the stack items are in the
6685: wrong order, just write a locals definition for all of them; then
6686: write the items in the order you want.
1.5 anton 6687:
1.26 crook 6688: This seems a little far-fetched and eliminating stack manipulations is
6689: unlikely to become a conscious programming objective. Still, the number
6690: of stack manipulations will be reduced dramatically if local variables
6691: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
6692: a traditional implementation of @code{max}).
1.5 anton 6693:
1.26 crook 6694: This shows one potential benefit of locals: making Forth programs more
6695: readable. Of course, this benefit will only be realized if the
6696: programmers continue to honour the principle of factoring instead of
6697: using the added latitude to make the words longer.
1.5 anton 6698:
1.26 crook 6699: @cindex single-assignment style for locals
6700: Using @code{TO} can and should be avoided. Without @code{TO},
6701: every value-flavoured local has only a single assignment and many
6702: advantages of functional languages apply to Forth. I.e., programs are
6703: easier to analyse, to optimize and to read: It is clear from the
6704: definition what the local stands for, it does not turn into something
6705: different later.
1.5 anton 6706:
1.26 crook 6707: E.g., a definition using @code{TO} might look like this:
1.5 anton 6708: @example
1.26 crook 6709: : strcmp @{ addr1 u1 addr2 u2 -- n @}
6710: u1 u2 min 0
6711: ?do
6712: addr1 c@@ addr2 c@@ -
6713: ?dup-if
6714: unloop exit
6715: then
6716: addr1 char+ TO addr1
6717: addr2 char+ TO addr2
6718: loop
6719: u1 u2 - ;
1.5 anton 6720: @end example
1.26 crook 6721: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
6722: every loop iteration. @code{strcmp} is a typical example of the
6723: readability problems of using @code{TO}. When you start reading
6724: @code{strcmp}, you think that @code{addr1} refers to the start of the
6725: string. Only near the end of the loop you realize that it is something
6726: else.
1.5 anton 6727:
1.26 crook 6728: This can be avoided by defining two locals at the start of the loop that
6729: are initialized with the right value for the current iteration.
1.5 anton 6730: @example
1.26 crook 6731: : strcmp @{ addr1 u1 addr2 u2 -- n @}
6732: addr1 addr2
6733: u1 u2 min 0
6734: ?do @{ s1 s2 @}
6735: s1 c@@ s2 c@@ -
6736: ?dup-if
6737: unloop exit
6738: then
6739: s1 char+ s2 char+
6740: loop
6741: 2drop
6742: u1 u2 - ;
1.5 anton 6743: @end example
1.26 crook 6744: Here it is clear from the start that @code{s1} has a different value
6745: in every loop iteration.
1.5 anton 6746:
1.26 crook 6747: @node Implementation, , Programming Style, Gforth locals
6748: @subsubsection Implementation
6749: @cindex locals implementation
6750: @cindex implementation of locals
1.5 anton 6751:
1.26 crook 6752: @cindex locals stack
6753: Gforth uses an extra locals stack. The most compelling reason for
6754: this is that the return stack is not float-aligned; using an extra stack
6755: also eliminates the problems and restrictions of using the return stack
6756: as locals stack. Like the other stacks, the locals stack grows toward
6757: lower addresses. A few primitives allow an efficient implementation:
1.5 anton 6758:
1.26 crook 6759: doc-@local#
6760: doc-f@local#
6761: doc-laddr#
6762: doc-lp+!#
6763: doc-lp!
6764: doc->l
6765: doc-f>l
1.5 anton 6766:
1.26 crook 6767: In addition to these primitives, some specializations of these
6768: primitives for commonly occurring inline arguments are provided for
6769: efficiency reasons, e.g., @code{@@local0} as specialization of
6770: @code{@@local#} for the inline argument 0. The following compiling words
6771: compile the right specialized version, or the general version, as
6772: appropriate:
1.6 pazsan 6773:
1.26 crook 6774: doc-compile-@local
6775: doc-compile-f@local
6776: doc-compile-lp+!
1.12 anton 6777:
1.26 crook 6778: Combinations of conditional branches and @code{lp+!#} like
6779: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
6780: is taken) are provided for efficiency and correctness in loops.
1.6 pazsan 6781:
1.26 crook 6782: A special area in the dictionary space is reserved for keeping the
6783: local variable names. @code{@{} switches the dictionary pointer to this
6784: area and @code{@}} switches it back and generates the locals
6785: initializing code. @code{W:} etc.@ are normal defining words. This
6786: special area is cleared at the start of every colon definition.
1.6 pazsan 6787:
1.26 crook 6788: @cindex word list for defining locals
6789: A special feature of Gforth's dictionary is used to implement the
6790: definition of locals without type specifiers: every word list (aka
6791: vocabulary) has its own methods for searching
6792: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
6793: with a special search method: When it is searched for a word, it
6794: actually creates that word using @code{W:}. @code{@{} changes the search
6795: order to first search the word list containing @code{@}}, @code{W:} etc.,
6796: and then the word list for defining locals without type specifiers.
1.12 anton 6797:
1.26 crook 6798: The lifetime rules support a stack discipline within a colon
6799: definition: The lifetime of a local is either nested with other locals
6800: lifetimes or it does not overlap them.
1.6 pazsan 6801:
1.26 crook 6802: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
6803: pointer manipulation is generated. Between control structure words
6804: locals definitions can push locals onto the locals stack. @code{AGAIN}
6805: is the simplest of the other three control flow words. It has to
6806: restore the locals stack depth of the corresponding @code{BEGIN}
6807: before branching. The code looks like this:
6808: @format
6809: @code{lp+!#} current-locals-size @minus{} dest-locals-size
6810: @code{branch} <begin>
6811: @end format
1.6 pazsan 6812:
1.26 crook 6813: @code{UNTIL} is a little more complicated: If it branches back, it
6814: must adjust the stack just like @code{AGAIN}. But if it falls through,
6815: the locals stack must not be changed. The compiler generates the
6816: following code:
6817: @format
6818: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
6819: @end format
6820: The locals stack pointer is only adjusted if the branch is taken.
1.6 pazsan 6821:
1.26 crook 6822: @code{THEN} can produce somewhat inefficient code:
6823: @format
6824: @code{lp+!#} current-locals-size @minus{} orig-locals-size
6825: <orig target>:
6826: @code{lp+!#} orig-locals-size @minus{} new-locals-size
6827: @end format
6828: The second @code{lp+!#} adjusts the locals stack pointer from the
1.29 crook 6829: level at the @i{orig} point to the level after the @code{THEN}. The
1.26 crook 6830: first @code{lp+!#} adjusts the locals stack pointer from the current
6831: level to the level at the orig point, so the complete effect is an
6832: adjustment from the current level to the right level after the
6833: @code{THEN}.
1.6 pazsan 6834:
1.26 crook 6835: @cindex locals information on the control-flow stack
6836: @cindex control-flow stack items, locals information
6837: In a conventional Forth implementation a dest control-flow stack entry
6838: is just the target address and an orig entry is just the address to be
6839: patched. Our locals implementation adds a word list to every orig or dest
6840: item. It is the list of locals visible (or assumed visible) at the point
6841: described by the entry. Our implementation also adds a tag to identify
6842: the kind of entry, in particular to differentiate between live and dead
6843: (reachable and unreachable) orig entries.
1.6 pazsan 6844:
1.26 crook 6845: A few unusual operations have to be performed on locals word lists:
1.6 pazsan 6846:
1.26 crook 6847: doc-common-list
6848: doc-sub-list?
6849: doc-list-size
1.6 pazsan 6850:
1.26 crook 6851: Several features of our locals word list implementation make these
6852: operations easy to implement: The locals word lists are organised as
6853: linked lists; the tails of these lists are shared, if the lists
6854: contain some of the same locals; and the address of a name is greater
6855: than the address of the names behind it in the list.
1.6 pazsan 6856:
1.26 crook 6857: Another important implementation detail is the variable
6858: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
6859: determine if they can be reached directly or only through the branch
6860: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
6861: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
6862: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6 pazsan 6863:
1.26 crook 6864: Counted loops are similar to other loops in most respects, but
6865: @code{LEAVE} requires special attention: It performs basically the same
6866: service as @code{AHEAD}, but it does not create a control-flow stack
6867: entry. Therefore the information has to be stored elsewhere;
6868: traditionally, the information was stored in the target fields of the
6869: branches created by the @code{LEAVE}s, by organizing these fields into a
6870: linked list. Unfortunately, this clever trick does not provide enough
6871: space for storing our extended control flow information. Therefore, we
6872: introduce another stack, the leave stack. It contains the control-flow
6873: stack entries for all unresolved @code{LEAVE}s.
1.6 pazsan 6874:
1.26 crook 6875: Local names are kept until the end of the colon definition, even if
6876: they are no longer visible in any control-flow path. In a few cases
6877: this may lead to increased space needs for the locals name area, but
6878: usually less than reclaiming this space would cost in code size.
1.6 pazsan 6879:
6880:
1.26 crook 6881: @node ANS Forth locals, , Gforth locals, Locals
6882: @subsection ANS Forth locals
6883: @cindex locals, ANS Forth style
1.6 pazsan 6884:
1.26 crook 6885: The ANS Forth locals wordset does not define a syntax for locals, but
6886: words that make it possible to define various syntaxes. One of the
6887: possible syntaxes is a subset of the syntax we used in the Gforth locals
6888: wordset, i.e.:
1.6 pazsan 6889:
6890: @example
1.26 crook 6891: @{ local1 local2 ... -- comment @}
1.6 pazsan 6892: @end example
1.23 crook 6893: @noindent
1.26 crook 6894: or
1.6 pazsan 6895: @example
1.26 crook 6896: @{ local1 local2 ... @}
1.6 pazsan 6897: @end example
6898:
1.26 crook 6899: The order of the locals corresponds to the order in a stack comment. The
6900: restrictions are:
1.6 pazsan 6901:
6902: @itemize @bullet
6903: @item
1.26 crook 6904: Locals can only be cell-sized values (no type specifiers are allowed).
1.6 pazsan 6905: @item
1.26 crook 6906: Locals can be defined only outside control structures.
1.6 pazsan 6907: @item
1.26 crook 6908: Locals can interfere with explicit usage of the return stack. For the
6909: exact (and long) rules, see the standard. If you don't use return stack
6910: accessing words in a definition using locals, you will be all right. The
6911: purpose of this rule is to make locals implementation on the return
6912: stack easier.
1.6 pazsan 6913: @item
1.26 crook 6914: The whole definition must be in one line.
6915: @end itemize
1.6 pazsan 6916:
1.26 crook 6917: Locals defined in this way behave like @code{VALUE}s (@xref{Simple
6918: Defining Words}). I.e., they are initialized from the stack. Using their
6919: name produces their value. Their value can be changed using @code{TO}.
1.6 pazsan 6920:
1.26 crook 6921: Since this syntax is supported by Gforth directly, you need not do
6922: anything to use it. If you want to port a program using this syntax to
6923: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
6924: syntax on the other system.
1.6 pazsan 6925:
1.26 crook 6926: Note that a syntax shown in the standard, section A.13 looks
6927: similar, but is quite different in having the order of locals
6928: reversed. Beware!
1.6 pazsan 6929:
1.26 crook 6930: The ANS Forth locals wordset itself consists of a word:
1.6 pazsan 6931:
1.26 crook 6932: doc-(local)
1.6 pazsan 6933:
1.26 crook 6934: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
6935: awful that we strongly recommend not to use it. We have implemented this
6936: syntax to make porting to Gforth easy, but do not document it here. The
6937: problem with this syntax is that the locals are defined in an order
6938: reversed with respect to the standard stack comment notation, making
6939: programs harder to read, and easier to misread and miswrite. The only
6940: merit of this syntax is that it is easy to implement using the ANS Forth
6941: locals wordset.
1.7 pazsan 6942:
6943:
1.26 crook 6944: @c ----------------------------------------------------------
6945: @node Structures, Object-oriented Forth, Locals, Words
6946: @section Structures
6947: @cindex structures
6948: @cindex records
1.7 pazsan 6949:
1.26 crook 6950: This section presents the structure package that comes with Gforth. A
6951: version of the package implemented in ANS Forth is available in
6952: @file{compat/struct.fs}. This package was inspired by a posting on
6953: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
6954: possibly John Hayes). A version of this section has been published in
6955: ???. Marcel Hendrix provided helpful comments.
1.7 pazsan 6956:
1.26 crook 6957: @menu
6958: * Why explicit structure support?::
6959: * Structure Usage::
6960: * Structure Naming Convention::
6961: * Structure Implementation::
6962: * Structure Glossary::
6963: @end menu
1.7 pazsan 6964:
1.26 crook 6965: @node Why explicit structure support?, Structure Usage, Structures, Structures
6966: @subsection Why explicit structure support?
1.7 pazsan 6967:
1.26 crook 6968: @cindex address arithmetic for structures
6969: @cindex structures using address arithmetic
6970: If we want to use a structure containing several fields, we could simply
6971: reserve memory for it, and access the fields using address arithmetic
1.27 crook 6972: (@pxref{Address Arithmetic}). As an example, consider a structure with
1.26 crook 6973: the following fields
1.7 pazsan 6974:
1.26 crook 6975: @table @code
6976: @item a
6977: is a float
6978: @item b
6979: is a cell
6980: @item c
6981: is a float
6982: @end table
1.7 pazsan 6983:
1.26 crook 6984: Given the (float-aligned) base address of the structure we get the
6985: address of the field
1.13 pazsan 6986:
1.26 crook 6987: @table @code
6988: @item a
6989: without doing anything further.
6990: @item b
6991: with @code{float+}
6992: @item c
6993: with @code{float+ cell+ faligned}
6994: @end table
1.13 pazsan 6995:
1.26 crook 6996: It is easy to see that this can become quite tiring.
1.13 pazsan 6997:
1.26 crook 6998: Moreover, it is not very readable, because seeing a
6999: @code{cell+} tells us neither which kind of structure is
7000: accessed nor what field is accessed; we have to somehow infer the kind
7001: of structure, and then look up in the documentation, which field of
7002: that structure corresponds to that offset.
1.13 pazsan 7003:
1.26 crook 7004: Finally, this kind of address arithmetic also causes maintenance
7005: troubles: If you add or delete a field somewhere in the middle of the
7006: structure, you have to find and change all computations for the fields
7007: afterwards.
1.13 pazsan 7008:
1.26 crook 7009: So, instead of using @code{cell+} and friends directly, how
7010: about storing the offsets in constants:
1.13 pazsan 7011:
7012: @example
1.26 crook 7013: 0 constant a-offset
7014: 0 float+ constant b-offset
7015: 0 float+ cell+ faligned c-offset
1.13 pazsan 7016: @end example
7017:
1.26 crook 7018: Now we can get the address of field @code{x} with @code{x-offset
7019: +}. This is much better in all respects. Of course, you still
7020: have to change all later offset definitions if you add a field. You can
7021: fix this by declaring the offsets in the following way:
1.13 pazsan 7022:
7023: @example
1.26 crook 7024: 0 constant a-offset
7025: a-offset float+ constant b-offset
7026: b-offset cell+ faligned constant c-offset
1.13 pazsan 7027: @end example
7028:
1.26 crook 7029: Since we always use the offsets with @code{+}, we could use a defining
7030: word @code{cfield} that includes the @code{+} in the action of the
7031: defined word:
1.8 pazsan 7032:
7033: @example
1.26 crook 7034: : cfield ( n "name" -- )
7035: create ,
7036: does> ( name execution: addr1 -- addr2 )
7037: @@ + ;
1.13 pazsan 7038:
1.26 crook 7039: 0 cfield a
7040: 0 a float+ cfield b
7041: 0 b cell+ faligned cfield c
1.13 pazsan 7042: @end example
7043:
1.26 crook 7044: Instead of @code{x-offset +}, we now simply write @code{x}.
7045:
7046: The structure field words now can be used quite nicely. However,
7047: their definition is still a bit cumbersome: We have to repeat the
7048: name, the information about size and alignment is distributed before
7049: and after the field definitions etc. The structure package presented
7050: here addresses these problems.
7051:
7052: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
7053: @subsection Structure Usage
7054: @cindex structure usage
1.13 pazsan 7055:
1.26 crook 7056: @cindex @code{field} usage
7057: @cindex @code{struct} usage
7058: @cindex @code{end-struct} usage
7059: You can define a structure for a (data-less) linked list with:
1.13 pazsan 7060: @example
1.26 crook 7061: struct
7062: cell% field list-next
7063: end-struct list%
1.13 pazsan 7064: @end example
7065:
1.26 crook 7066: With the address of the list node on the stack, you can compute the
7067: address of the field that contains the address of the next node with
7068: @code{list-next}. E.g., you can determine the length of a list
7069: with:
1.13 pazsan 7070:
7071: @example
1.26 crook 7072: : list-length ( list -- n )
7073: \ "list" is a pointer to the first element of a linked list
7074: \ "n" is the length of the list
7075: 0 BEGIN ( list1 n1 )
7076: over
7077: WHILE ( list1 n1 )
7078: 1+ swap list-next @@ swap
7079: REPEAT
7080: nip ;
1.13 pazsan 7081: @end example
7082:
1.26 crook 7083: You can reserve memory for a list node in the dictionary with
7084: @code{list% %allot}, which leaves the address of the list node on the
7085: stack. For the equivalent allocation on the heap you can use @code{list%
7086: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
7087: use @code{list% %allocate}). You can get the the size of a list
7088: node with @code{list% %size} and its alignment with @code{list%
7089: %alignment}.
1.13 pazsan 7090:
1.26 crook 7091: Note that in ANS Forth the body of a @code{create}d word is
7092: @code{aligned} but not necessarily @code{faligned};
7093: therefore, if you do a:
1.13 pazsan 7094: @example
1.26 crook 7095: create @emph{name} foo% %allot
1.8 pazsan 7096: @end example
7097:
1.26 crook 7098: @noindent
7099: then the memory alloted for @code{foo%} is
7100: guaranteed to start at the body of @code{@emph{name}} only if
7101: @code{foo%} contains only character, cell and double fields.
1.20 pazsan 7102:
1.26 crook 7103: @cindex strcutures containing structures
7104: You can include a structure @code{foo%} as a field of
7105: another structure, like this:
1.20 pazsan 7106: @example
1.26 crook 7107: struct
7108: ...
7109: foo% field ...
7110: ...
7111: end-struct ...
1.20 pazsan 7112: @end example
7113:
1.26 crook 7114: @cindex structure extension
7115: @cindex extended records
7116: Instead of starting with an empty structure, you can extend an
7117: existing structure. E.g., a plain linked list without data, as defined
7118: above, is hardly useful; You can extend it to a linked list of integers,
7119: like this:@footnote{This feature is also known as @emph{extended
7120: records}. It is the main innovation in the Oberon language; in other
7121: words, adding this feature to Modula-2 led Wirth to create a new
7122: language, write a new compiler etc. Adding this feature to Forth just
7123: required a few lines of code.}
1.20 pazsan 7124:
7125: @example
1.26 crook 7126: list%
7127: cell% field intlist-int
7128: end-struct intlist%
1.20 pazsan 7129: @end example
7130:
1.26 crook 7131: @code{intlist%} is a structure with two fields:
7132: @code{list-next} and @code{intlist-int}.
1.20 pazsan 7133:
1.26 crook 7134: @cindex structures containing arrays
7135: You can specify an array type containing @emph{n} elements of
7136: type @code{foo%} like this:
1.20 pazsan 7137:
7138: @example
1.26 crook 7139: foo% @emph{n} *
1.20 pazsan 7140: @end example
7141:
1.26 crook 7142: You can use this array type in any place where you can use a normal
7143: type, e.g., when defining a @code{field}, or with
7144: @code{%allot}.
1.20 pazsan 7145:
1.26 crook 7146: @cindex first field optimization
7147: The first field is at the base address of a structure and the word
7148: for this field (e.g., @code{list-next}) actually does not change
7149: the address on the stack. You may be tempted to leave it away in the
7150: interest of run-time and space efficiency. This is not necessary,
7151: because the structure package optimizes this case and compiling such
7152: words does not generate any code. So, in the interest of readability
7153: and maintainability you should include the word for the field when
7154: accessing the field.
1.20 pazsan 7155:
1.26 crook 7156: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
7157: @subsection Structure Naming Convention
7158: @cindex structure naming convention
1.20 pazsan 7159:
1.26 crook 7160: The field names that come to (my) mind are often quite generic, and,
7161: if used, would cause frequent name clashes. E.g., many structures
7162: probably contain a @code{counter} field. The structure names
7163: that come to (my) mind are often also the logical choice for the names
7164: of words that create such a structure.
1.20 pazsan 7165:
1.26 crook 7166: Therefore, I have adopted the following naming conventions:
1.20 pazsan 7167:
1.26 crook 7168: @itemize @bullet
7169: @cindex field naming convention
7170: @item
7171: The names of fields are of the form
7172: @code{@emph{struct}-@emph{field}}, where
7173: @code{@emph{struct}} is the basic name of the structure, and
7174: @code{@emph{field}} is the basic name of the field. You can
7175: think of field words as converting the (address of the)
7176: structure into the (address of the) field.
1.20 pazsan 7177:
1.26 crook 7178: @cindex structure naming convention
7179: @item
7180: The names of structures are of the form
7181: @code{@emph{struct}%}, where
7182: @code{@emph{struct}} is the basic name of the structure.
7183: @end itemize
1.20 pazsan 7184:
1.26 crook 7185: This naming convention does not work that well for fields of extended
7186: structures; e.g., the integer list structure has a field
7187: @code{intlist-int}, but has @code{list-next}, not
7188: @code{intlist-next}.
1.20 pazsan 7189:
1.26 crook 7190: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
7191: @subsection Structure Implementation
7192: @cindex structure implementation
7193: @cindex implementation of structures
1.20 pazsan 7194:
1.26 crook 7195: The central idea in the implementation is to pass the data about the
7196: structure being built on the stack, not in some global
7197: variable. Everything else falls into place naturally once this design
7198: decision is made.
1.20 pazsan 7199:
1.26 crook 7200: The type description on the stack is of the form @emph{align
7201: size}. Keeping the size on the top-of-stack makes dealing with arrays
7202: very simple.
1.20 pazsan 7203:
1.26 crook 7204: @code{field} is a defining word that uses @code{Create}
7205: and @code{DOES>}. The body of the field contains the offset
7206: of the field, and the normal @code{DOES>} action is simply:
1.20 pazsan 7207:
7208: @example
1.26 crook 7209: @ +
1.20 pazsan 7210: @end example
7211:
1.23 crook 7212: @noindent
1.26 crook 7213: i.e., add the offset to the address, giving the stack effect
1.29 crook 7214: @i{addr1 -- addr2} for a field.
1.20 pazsan 7215:
1.26 crook 7216: @cindex first field optimization, implementation
7217: This simple structure is slightly complicated by the optimization
7218: for fields with offset 0, which requires a different
7219: @code{DOES>}-part (because we cannot rely on there being
7220: something on the stack if such a field is invoked during
7221: compilation). Therefore, we put the different @code{DOES>}-parts
7222: in separate words, and decide which one to invoke based on the
7223: offset. For a zero offset, the field is basically a noop; it is
7224: immediate, and therefore no code is generated when it is compiled.
1.20 pazsan 7225:
1.26 crook 7226: @node Structure Glossary, , Structure Implementation, Structures
7227: @subsection Structure Glossary
7228: @cindex structure glossary
1.20 pazsan 7229:
1.26 crook 7230: doc-%align
7231: doc-%alignment
7232: doc-%alloc
7233: doc-%allocate
7234: doc-%allot
7235: doc-cell%
7236: doc-char%
7237: doc-dfloat%
7238: doc-double%
7239: doc-end-struct
7240: doc-field
7241: doc-float%
7242: doc-naligned
7243: doc-sfloat%
7244: doc-%size
7245: doc-struct
1.23 crook 7246:
1.26 crook 7247: @c -------------------------------------------------------------
7248: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
7249: @section Object-oriented Forth
1.20 pazsan 7250:
1.26 crook 7251: Gforth comes with three packages for object-oriented programming:
7252: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
7253: is preloaded, so you have to @code{include} them before use. The most
7254: important differences between these packages (and others) are discussed
7255: in @ref{Comparison with other object models}. All packages are written
7256: in ANS Forth and can be used with any other ANS Forth.
1.20 pazsan 7257:
1.26 crook 7258: @menu
7259: * Why object-oriented programming?::
7260: * Object-Oriented Terminology::
7261: * Objects::
7262: * OOF::
7263: * Mini-OOF::
7264: * Comparison with other object models::
7265: @end menu
1.20 pazsan 7266:
1.23 crook 7267:
1.26 crook 7268: @node Why object-oriented programming?, Object-Oriented Terminology, , Object-oriented Forth
7269: @subsubsection Why object-oriented programming?
7270: @cindex object-oriented programming motivation
7271: @cindex motivation for object-oriented programming
1.23 crook 7272:
1.26 crook 7273: Often we have to deal with several data structures (@emph{objects}),
7274: that have to be treated similarly in some respects, but differently in
7275: others. Graphical objects are the textbook example: circles, triangles,
7276: dinosaurs, icons, and others, and we may want to add more during program
7277: development. We want to apply some operations to any graphical object,
7278: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
7279: has to do something different for every kind of object.
7280: @comment TODO add some other operations eg perimeter, area
7281: @comment and tie in to concrete examples later..
1.23 crook 7282:
1.26 crook 7283: We could implement @code{draw} as a big @code{CASE}
7284: control structure that executes the appropriate code depending on the
7285: kind of object to be drawn. This would be not be very elegant, and,
7286: moreover, we would have to change @code{draw} every time we add
7287: a new kind of graphical object (say, a spaceship).
1.23 crook 7288:
1.26 crook 7289: What we would rather do is: When defining spaceships, we would tell
7290: the system: ``Here's how you @code{draw} a spaceship; you figure
7291: out the rest''.
1.23 crook 7292:
1.26 crook 7293: This is the problem that all systems solve that (rightfully) call
7294: themselves object-oriented; the object-oriented packages presented here
7295: solve this problem (and not much else).
7296: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23 crook 7297:
1.26 crook 7298: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
7299: @subsubsection Object-Oriented Terminology
7300: @cindex object-oriented terminology
7301: @cindex terminology for object-oriented programming
1.23 crook 7302:
1.26 crook 7303: This section is mainly for reference, so you don't have to understand
7304: all of it right away. The terminology is mainly Smalltalk-inspired. In
7305: short:
1.23 crook 7306:
1.26 crook 7307: @table @emph
7308: @cindex class
7309: @item class
7310: a data structure definition with some extras.
1.23 crook 7311:
1.26 crook 7312: @cindex object
7313: @item object
7314: an instance of the data structure described by the class definition.
1.23 crook 7315:
1.26 crook 7316: @cindex instance variables
7317: @item instance variables
7318: fields of the data structure.
1.23 crook 7319:
1.26 crook 7320: @cindex selector
7321: @cindex method selector
7322: @cindex virtual function
7323: @item selector
7324: (or @emph{method selector}) a word (e.g.,
7325: @code{draw}) that performs an operation on a variety of data
7326: structures (classes). A selector describes @emph{what} operation to
7327: perform. In C++ terminology: a (pure) virtual function.
1.23 crook 7328:
1.26 crook 7329: @cindex method
7330: @item method
7331: the concrete definition that performs the operation
7332: described by the selector for a specific class. A method specifies
7333: @emph{how} the operation is performed for a specific class.
1.23 crook 7334:
1.26 crook 7335: @cindex selector invocation
7336: @cindex message send
7337: @cindex invoking a selector
7338: @item selector invocation
7339: a call of a selector. One argument of the call (the TOS (top-of-stack))
7340: is used for determining which method is used. In Smalltalk terminology:
7341: a message (consisting of the selector and the other arguments) is sent
7342: to the object.
1.1 anton 7343:
1.26 crook 7344: @cindex receiving object
7345: @item receiving object
7346: the object used for determining the method executed by a selector
7347: invocation. In the @file{objects.fs} model, it is the object that is on
7348: the TOS when the selector is invoked. (@emph{Receiving} comes from
7349: the Smalltalk @emph{message} terminology.)
1.1 anton 7350:
1.26 crook 7351: @cindex child class
7352: @cindex parent class
7353: @cindex inheritance
7354: @item child class
7355: a class that has (@emph{inherits}) all properties (instance variables,
7356: selectors, methods) from a @emph{parent class}. In Smalltalk
7357: terminology: The subclass inherits from the superclass. In C++
7358: terminology: The derived class inherits from the base class.
1.1 anton 7359:
1.26 crook 7360: @end table
1.21 crook 7361:
1.26 crook 7362: @c If you wonder about the message sending terminology, it comes from
7363: @c a time when each object had it's own task and objects communicated via
7364: @c message passing; eventually the Smalltalk developers realized that
7365: @c they can do most things through simple (indirect) calls. They kept the
7366: @c terminology.
1.1 anton 7367:
7368:
1.26 crook 7369: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
7370: @subsection The @file{objects.fs} model
7371: @cindex objects
7372: @cindex object-oriented programming
1.1 anton 7373:
1.26 crook 7374: @cindex @file{objects.fs}
7375: @cindex @file{oof.fs}
1.1 anton 7376:
1.26 crook 7377: 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}).
7378: @c McKewan's and Zsoter's packages
1.1 anton 7379:
1.26 crook 7380: This section assumes that you have read @ref{Structures}.
1.1 anton 7381:
1.26 crook 7382: The techniques on which this model is based have been used to implement
7383: the parser generator, Gray, and have also been used in Gforth for
7384: implementing the various flavours of word lists (hashed or not,
7385: case-sensitive or not, special-purpose word lists for locals etc.).
1.1 anton 7386:
7387:
1.26 crook 7388: @menu
7389: * Properties of the Objects model::
7390: * Basic Objects Usage::
7391: * The Objects base class::
7392: * Creating objects::
7393: * Object-Oriented Programming Style::
7394: * Class Binding::
7395: * Method conveniences::
7396: * Classes and Scoping::
7397: * Object Interfaces::
7398: * Objects Implementation::
7399: * Objects Glossary::
7400: @end menu
1.1 anton 7401:
1.26 crook 7402: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
7403: and Bernd Paysan helped me with the related works section.
1.1 anton 7404:
1.26 crook 7405: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
7406: @subsubsection Properties of the @file{objects.fs} model
7407: @cindex @file{objects.fs} properties
1.1 anton 7408:
1.26 crook 7409: @itemize @bullet
7410: @item
7411: It is straightforward to pass objects on the stack. Passing
7412: selectors on the stack is a little less convenient, but possible.
1.1 anton 7413:
1.26 crook 7414: @item
7415: Objects are just data structures in memory, and are referenced by their
7416: address. You can create words for objects with normal defining words
7417: like @code{constant}. Likewise, there is no difference between instance
7418: variables that contain objects and those that contain other data.
1.1 anton 7419:
1.26 crook 7420: @item
7421: Late binding is efficient and easy to use.
1.21 crook 7422:
1.26 crook 7423: @item
7424: It avoids parsing, and thus avoids problems with state-smartness
7425: and reduced extensibility; for convenience there are a few parsing
7426: words, but they have non-parsing counterparts. There are also a few
7427: defining words that parse. This is hard to avoid, because all standard
7428: defining words parse (except @code{:noname}); however, such
7429: words are not as bad as many other parsing words, because they are not
7430: state-smart.
1.21 crook 7431:
1.26 crook 7432: @item
7433: It does not try to incorporate everything. It does a few things and does
7434: them well (IMO). In particular, this model was not designed to support
7435: information hiding (although it has features that may help); you can use
7436: a separate package for achieving this.
1.21 crook 7437:
1.26 crook 7438: @item
7439: It is layered; you don't have to learn and use all features to use this
7440: model. Only a few features are necessary (@xref{Basic Objects Usage},
7441: @xref{The Objects base class}, @xref{Creating objects}.), the others
7442: are optional and independent of each other.
1.21 crook 7443:
1.26 crook 7444: @item
7445: An implementation in ANS Forth is available.
1.21 crook 7446:
1.26 crook 7447: @end itemize
1.21 crook 7448:
7449:
1.26 crook 7450: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
7451: @subsubsection Basic @file{objects.fs} Usage
7452: @cindex basic objects usage
7453: @cindex objects, basic usage
1.21 crook 7454:
1.26 crook 7455: You can define a class for graphical objects like this:
1.21 crook 7456:
1.26 crook 7457: @cindex @code{class} usage
7458: @cindex @code{end-class} usage
7459: @cindex @code{selector} usage
7460: @example
7461: object class \ "object" is the parent class
7462: selector draw ( x y graphical -- )
7463: end-class graphical
7464: @end example
1.21 crook 7465:
1.26 crook 7466: This code defines a class @code{graphical} with an
7467: operation @code{draw}. We can perform the operation
7468: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 7469:
1.26 crook 7470: @example
7471: 100 100 t-rex draw
7472: @end example
1.21 crook 7473:
1.26 crook 7474: @noindent
7475: where @code{t-rex} is a word (say, a constant) that produces a
7476: graphical object.
1.21 crook 7477:
1.29 crook 7478: @comment TODO add a 2nd operation eg perimeter.. and use for
1.26 crook 7479: @comment a concrete example
1.21 crook 7480:
1.26 crook 7481: @cindex abstract class
7482: How do we create a graphical object? With the present definitions,
7483: we cannot create a useful graphical object. The class
7484: @code{graphical} describes graphical objects in general, but not
7485: any concrete graphical object type (C++ users would call it an
7486: @emph{abstract class}); e.g., there is no method for the selector
7487: @code{draw} in the class @code{graphical}.
1.21 crook 7488:
1.26 crook 7489: For concrete graphical objects, we define child classes of the
7490: class @code{graphical}, e.g.:
1.21 crook 7491:
1.26 crook 7492: @cindex @code{overrides} usage
7493: @cindex @code{field} usage in class definition
7494: @example
7495: graphical class \ "graphical" is the parent class
7496: cell% field circle-radius
1.21 crook 7497:
1.26 crook 7498: :noname ( x y circle -- )
7499: circle-radius @@ draw-circle ;
7500: overrides draw
1.21 crook 7501:
1.26 crook 7502: :noname ( n-radius circle -- )
7503: circle-radius ! ;
7504: overrides construct
1.21 crook 7505:
1.26 crook 7506: end-class circle
1.21 crook 7507: @end example
7508:
1.26 crook 7509: Here we define a class @code{circle} as a child of @code{graphical},
7510: with field @code{circle-radius} (which behaves just like a field
7511: (@pxref{Structures}); it defines (using @code{overrides}) new methods
7512: for the selectors @code{draw} and @code{construct} (@code{construct} is
7513: defined in @code{object}, the parent class of @code{graphical}).
1.21 crook 7514:
1.26 crook 7515: Now we can create a circle on the heap (i.e.,
7516: @code{allocate}d memory) with:
1.21 crook 7517:
1.26 crook 7518: @cindex @code{heap-new} usage
1.21 crook 7519: @example
1.26 crook 7520: 50 circle heap-new constant my-circle
7521: @end example
1.21 crook 7522:
1.26 crook 7523: @noindent
7524: @code{heap-new} invokes @code{construct}, thus
7525: initializing the field @code{circle-radius} with 50. We can draw
7526: this new circle at (100,100) with:
1.21 crook 7527:
1.26 crook 7528: @example
7529: 100 100 my-circle draw
1.21 crook 7530: @end example
7531:
1.26 crook 7532: @cindex selector invocation, restrictions
7533: @cindex class definition, restrictions
7534: Note: You can only invoke a selector if the object on the TOS
7535: (the receiving object) belongs to the class where the selector was
7536: defined or one of its descendents; e.g., you can invoke
7537: @code{draw} only for objects belonging to @code{graphical}
7538: or its descendents (e.g., @code{circle}). Immediately before
7539: @code{end-class}, the search order has to be the same as
7540: immediately after @code{class}.
1.21 crook 7541:
1.26 crook 7542: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
7543: @subsubsection The @file{object.fs} base class
7544: @cindex @code{object} class
1.21 crook 7545:
1.26 crook 7546: When you define a class, you have to specify a parent class. So how do
7547: you start defining classes? There is one class available from the start:
7548: @code{object}. It is ancestor for all classes and so is the
7549: only class that has no parent. It has two selectors: @code{construct}
7550: and @code{print}.
1.21 crook 7551:
1.26 crook 7552: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
7553: @subsubsection Creating objects
7554: @cindex creating objects
7555: @cindex object creation
7556: @cindex object allocation options
1.21 crook 7557:
1.26 crook 7558: @cindex @code{heap-new} discussion
7559: @cindex @code{dict-new} discussion
7560: @cindex @code{construct} discussion
7561: You can create and initialize an object of a class on the heap with
7562: @code{heap-new} ( ... class -- object ) and in the dictionary
7563: (allocation with @code{allot}) with @code{dict-new} (
7564: ... class -- object ). Both words invoke @code{construct}, which
7565: consumes the stack items indicated by "..." above.
1.21 crook 7566:
1.26 crook 7567: @cindex @code{init-object} discussion
7568: @cindex @code{class-inst-size} discussion
7569: If you want to allocate memory for an object yourself, you can get its
7570: alignment and size with @code{class-inst-size 2@@} ( class --
7571: align size ). Once you have memory for an object, you can initialize
7572: it with @code{init-object} ( ... class object -- );
7573: @code{construct} does only a part of the necessary work.
1.21 crook 7574:
1.26 crook 7575: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
7576: @subsubsection Object-Oriented Programming Style
7577: @cindex object-oriented programming style
1.21 crook 7578:
1.26 crook 7579: This section is not exhaustive.
1.1 anton 7580:
1.26 crook 7581: @cindex stack effects of selectors
7582: @cindex selectors and stack effects
7583: In general, it is a good idea to ensure that all methods for the
7584: same selector have the same stack effect: when you invoke a selector,
7585: you often have no idea which method will be invoked, so, unless all
7586: methods have the same stack effect, you will not know the stack effect
7587: of the selector invocation.
1.21 crook 7588:
1.26 crook 7589: One exception to this rule is methods for the selector
7590: @code{construct}. We know which method is invoked, because we
7591: specify the class to be constructed at the same place. Actually, I
7592: defined @code{construct} as a selector only to give the users a
7593: convenient way to specify initialization. The way it is used, a
7594: mechanism different from selector invocation would be more natural
7595: (but probably would take more code and more space to explain).
1.21 crook 7596:
1.26 crook 7597: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
7598: @subsubsection Class Binding
7599: @cindex class binding
7600: @cindex early binding
1.21 crook 7601:
1.26 crook 7602: @cindex late binding
7603: Normal selector invocations determine the method at run-time depending
7604: on the class of the receiving object. This run-time selection is called
1.29 crook 7605: @i{late binding}.
1.21 crook 7606:
1.26 crook 7607: Sometimes it's preferable to invoke a different method. For example,
7608: you might want to use the simple method for @code{print}ing
7609: @code{object}s instead of the possibly long-winded @code{print} method
7610: of the receiver class. You can achieve this by replacing the invocation
7611: of @code{print} with:
1.21 crook 7612:
1.26 crook 7613: @cindex @code{[bind]} usage
7614: @example
7615: [bind] object print
1.21 crook 7616: @end example
7617:
1.26 crook 7618: @noindent
7619: in compiled code or:
1.21 crook 7620:
1.26 crook 7621: @cindex @code{bind} usage
1.21 crook 7622: @example
1.26 crook 7623: bind object print
1.21 crook 7624: @end example
7625:
1.26 crook 7626: @cindex class binding, alternative to
7627: @noindent
7628: in interpreted code. Alternatively, you can define the method with a
7629: name (e.g., @code{print-object}), and then invoke it through the
7630: name. Class binding is just a (often more convenient) way to achieve
7631: the same effect; it avoids name clutter and allows you to invoke
7632: methods directly without naming them first.
7633:
7634: @cindex superclass binding
7635: @cindex parent class binding
7636: A frequent use of class binding is this: When we define a method
7637: for a selector, we often want the method to do what the selector does
7638: in the parent class, and a little more. There is a special word for
7639: this purpose: @code{[parent]}; @code{[parent]
7640: @emph{selector}} is equivalent to @code{[bind] @emph{parent
7641: selector}}, where @code{@emph{parent}} is the parent
7642: class of the current class. E.g., a method definition might look like:
1.21 crook 7643:
1.26 crook 7644: @cindex @code{[parent]} usage
1.21 crook 7645: @example
1.26 crook 7646: :noname
7647: dup [parent] foo \ do parent's foo on the receiving object
7648: ... \ do some more
7649: ; overrides foo
1.21 crook 7650: @end example
7651:
1.26 crook 7652: @cindex class binding as optimization
7653: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
7654: March 1997), Andrew McKewan presents class binding as an optimization
7655: technique. I recommend not using it for this purpose unless you are in
7656: an emergency. Late binding is pretty fast with this model anyway, so the
7657: benefit of using class binding is small; the cost of using class binding
7658: where it is not appropriate is reduced maintainability.
1.21 crook 7659:
1.26 crook 7660: While we are at programming style questions: You should bind
7661: selectors only to ancestor classes of the receiving object. E.g., say,
7662: you know that the receiving object is of class @code{foo} or its
7663: descendents; then you should bind only to @code{foo} and its
7664: ancestors.
1.21 crook 7665:
1.26 crook 7666: @node Method conveniences, Classes and Scoping, Class Binding, Objects
7667: @subsubsection Method conveniences
7668: @cindex method conveniences
1.1 anton 7669:
1.26 crook 7670: In a method you usually access the receiving object pretty often. If
7671: you define the method as a plain colon definition (e.g., with
7672: @code{:noname}), you may have to do a lot of stack
7673: gymnastics. To avoid this, you can define the method with @code{m:
7674: ... ;m}. E.g., you could define the method for
7675: @code{draw}ing a @code{circle} with
1.20 pazsan 7676:
1.26 crook 7677: @cindex @code{this} usage
7678: @cindex @code{m:} usage
7679: @cindex @code{;m} usage
7680: @example
7681: m: ( x y circle -- )
7682: ( x y ) this circle-radius @@ draw-circle ;m
7683: @end example
1.20 pazsan 7684:
1.26 crook 7685: @cindex @code{exit} in @code{m: ... ;m}
7686: @cindex @code{exitm} discussion
7687: @cindex @code{catch} in @code{m: ... ;m}
7688: When this method is executed, the receiver object is removed from the
7689: stack; you can access it with @code{this} (admittedly, in this
7690: example the use of @code{m: ... ;m} offers no advantage). Note
7691: that I specify the stack effect for the whole method (i.e. including
7692: the receiver object), not just for the code between @code{m:}
7693: and @code{;m}. You cannot use @code{exit} in
7694: @code{m:...;m}; instead, use
7695: @code{exitm}.@footnote{Moreover, for any word that calls
7696: @code{catch} and was defined before loading
7697: @code{objects.fs}, you have to redefine it like I redefined
7698: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20 pazsan 7699:
1.26 crook 7700: @cindex @code{inst-var} usage
7701: You will frequently use sequences of the form @code{this
7702: @emph{field}} (in the example above: @code{this
7703: circle-radius}). If you use the field only in this way, you can
7704: define it with @code{inst-var} and eliminate the
7705: @code{this} before the field name. E.g., the @code{circle}
7706: class above could also be defined with:
1.20 pazsan 7707:
1.26 crook 7708: @example
7709: graphical class
7710: cell% inst-var radius
1.20 pazsan 7711:
1.26 crook 7712: m: ( x y circle -- )
7713: radius @@ draw-circle ;m
7714: overrides draw
1.20 pazsan 7715:
1.26 crook 7716: m: ( n-radius circle -- )
7717: radius ! ;m
7718: overrides construct
1.12 anton 7719:
1.26 crook 7720: end-class circle
7721: @end example
1.12 anton 7722:
1.26 crook 7723: @code{radius} can only be used in @code{circle} and its
7724: descendent classes and inside @code{m:...;m}.
1.12 anton 7725:
1.26 crook 7726: @cindex @code{inst-value} usage
7727: You can also define fields with @code{inst-value}, which is
7728: to @code{inst-var} what @code{value} is to
7729: @code{variable}. You can change the value of such a field with
7730: @code{[to-inst]}. E.g., we could also define the class
7731: @code{circle} like this:
1.12 anton 7732:
1.26 crook 7733: @example
7734: graphical class
7735: inst-value radius
1.12 anton 7736:
1.26 crook 7737: m: ( x y circle -- )
7738: radius draw-circle ;m
7739: overrides draw
1.12 anton 7740:
1.26 crook 7741: m: ( n-radius circle -- )
7742: [to-inst] radius ;m
7743: overrides construct
1.21 crook 7744:
1.26 crook 7745: end-class circle
1.12 anton 7746: @end example
7747:
7748:
1.26 crook 7749: @node Classes and Scoping, Object Interfaces, Method conveniences, Objects
7750: @subsubsection Classes and Scoping
7751: @cindex classes and scoping
7752: @cindex scoping and classes
1.12 anton 7753:
1.26 crook 7754: Inheritance is frequent, unlike structure extension. This exacerbates
7755: the problem with the field name convention (@pxref{Structure Naming
7756: Convention}): One always has to remember in which class the field was
7757: originally defined; changing a part of the class structure would require
7758: changes for renaming in otherwise unaffected code.
1.12 anton 7759:
1.26 crook 7760: @cindex @code{inst-var} visibility
7761: @cindex @code{inst-value} visibility
7762: To solve this problem, I added a scoping mechanism (which was not in my
7763: original charter): A field defined with @code{inst-var} (or
7764: @code{inst-value}) is visible only in the class where it is defined and in
7765: the descendent classes of this class. Using such fields only makes
7766: sense in @code{m:}-defined methods in these classes anyway.
1.12 anton 7767:
1.26 crook 7768: This scoping mechanism allows us to use the unadorned field name,
7769: because name clashes with unrelated words become much less likely.
1.12 anton 7770:
1.26 crook 7771: @cindex @code{protected} discussion
7772: @cindex @code{private} discussion
7773: Once we have this mechanism, we can also use it for controlling the
7774: visibility of other words: All words defined after
7775: @code{protected} are visible only in the current class and its
7776: descendents. @code{public} restores the compilation
7777: (i.e. @code{current}) word list that was in effect before. If you
7778: have several @code{protected}s without an intervening
7779: @code{public} or @code{set-current}, @code{public}
7780: will restore the compilation word list in effect before the first of
7781: these @code{protected}s.
1.12 anton 7782:
1.26 crook 7783: @node Object Interfaces, Objects Implementation, Classes and Scoping, Objects
7784: @subsubsection Object Interfaces
7785: @cindex object interfaces
7786: @cindex interfaces for objects
1.12 anton 7787:
1.26 crook 7788: In this model you can only call selectors defined in the class of the
7789: receiving objects or in one of its ancestors. If you call a selector
7790: with a receiving object that is not in one of these classes, the
7791: result is undefined; if you are lucky, the program crashes
7792: immediately.
1.12 anton 7793:
1.26 crook 7794: @cindex selectors common to hardly-related classes
7795: Now consider the case when you want to have a selector (or several)
7796: available in two classes: You would have to add the selector to a
7797: common ancestor class, in the worst case to @code{object}. You
7798: may not want to do this, e.g., because someone else is responsible for
7799: this ancestor class.
1.12 anton 7800:
1.26 crook 7801: The solution for this problem is interfaces. An interface is a
7802: collection of selectors. If a class implements an interface, the
7803: selectors become available to the class and its descendents. A class
7804: can implement an unlimited number of interfaces. For the problem
7805: discussed above, we would define an interface for the selector(s), and
7806: both classes would implement the interface.
1.12 anton 7807:
1.26 crook 7808: As an example, consider an interface @code{storage} for
7809: writing objects to disk and getting them back, and a class
7810: @code{foo} that implements it. The code would look like this:
1.12 anton 7811:
1.26 crook 7812: @cindex @code{interface} usage
7813: @cindex @code{end-interface} usage
7814: @cindex @code{implementation} usage
7815: @example
7816: interface
7817: selector write ( file object -- )
7818: selector read1 ( file object -- )
7819: end-interface storage
1.12 anton 7820:
1.26 crook 7821: bar class
7822: storage implementation
1.12 anton 7823:
1.26 crook 7824: ... overrides write
7825: ... overrides read
7826: ...
7827: end-class foo
1.12 anton 7828: @end example
7829:
1.26 crook 7830: @noindent
1.29 crook 7831: (I would add a word @code{read} @i{( file -- object )} that uses
1.26 crook 7832: @code{read1} internally, but that's beyond the point illustrated
7833: here.)
1.12 anton 7834:
1.26 crook 7835: Note that you cannot use @code{protected} in an interface; and
7836: of course you cannot define fields.
1.12 anton 7837:
1.26 crook 7838: In the Neon model, all selectors are available for all classes;
7839: therefore it does not need interfaces. The price you pay in this model
7840: is slower late binding, and therefore, added complexity to avoid late
7841: binding.
1.12 anton 7842:
1.26 crook 7843: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
7844: @subsubsection @file{objects.fs} Implementation
7845: @cindex @file{objects.fs} implementation
1.12 anton 7846:
1.26 crook 7847: @cindex @code{object-map} discussion
7848: An object is a piece of memory, like one of the data structures
7849: described with @code{struct...end-struct}. It has a field
7850: @code{object-map} that points to the method map for the object's
7851: class.
1.12 anton 7852:
1.26 crook 7853: @cindex method map
7854: @cindex virtual function table
7855: The @emph{method map}@footnote{This is Self terminology; in C++
7856: terminology: virtual function table.} is an array that contains the
1.29 crook 7857: execution tokens (@i{xt}s) of the methods for the object's class. Each
1.26 crook 7858: selector contains an offset into a method map.
1.12 anton 7859:
1.26 crook 7860: @cindex @code{selector} implementation, class
7861: @code{selector} is a defining word that uses
7862: @code{CREATE} and @code{DOES>}. The body of the
7863: selector contains the offset; the @code{does>} action for a
7864: class selector is, basically:
1.21 crook 7865:
1.26 crook 7866: @example
7867: ( object addr ) @@ over object-map @@ + @@ execute
7868: @end example
1.12 anton 7869:
1.26 crook 7870: Since @code{object-map} is the first field of the object, it
7871: does not generate any code. As you can see, calling a selector has a
7872: small, constant cost.
1.12 anton 7873:
1.26 crook 7874: @cindex @code{current-interface} discussion
7875: @cindex class implementation and representation
7876: A class is basically a @code{struct} combined with a method
7877: map. During the class definition the alignment and size of the class
7878: are passed on the stack, just as with @code{struct}s, so
7879: @code{field} can also be used for defining class
7880: fields. However, passing more items on the stack would be
7881: inconvenient, so @code{class} builds a data structure in memory,
7882: which is accessed through the variable
7883: @code{current-interface}. After its definition is complete, the
7884: class is represented on the stack by a pointer (e.g., as parameter for
7885: a child class definition).
1.1 anton 7886:
1.26 crook 7887: A new class starts off with the alignment and size of its parent,
7888: and a copy of the parent's method map. Defining new fields extends the
7889: size and alignment; likewise, defining new selectors extends the
1.29 crook 7890: method map. @code{overrides} just stores a new @i{xt} in the method
1.26 crook 7891: map at the offset given by the selector.
1.20 pazsan 7892:
1.26 crook 7893: @cindex class binding, implementation
1.29 crook 7894: Class binding just gets the @i{xt} at the offset given by the selector
1.26 crook 7895: from the class's method map and @code{compile,}s (in the case of
7896: @code{[bind]}) it.
1.21 crook 7897:
1.26 crook 7898: @cindex @code{this} implementation
7899: @cindex @code{catch} and @code{this}
7900: @cindex @code{this} and @code{catch}
7901: I implemented @code{this} as a @code{value}. At the
7902: start of an @code{m:...;m} method the old @code{this} is
7903: stored to the return stack and restored at the end; and the object on
7904: the TOS is stored @code{TO this}. This technique has one
7905: disadvantage: If the user does not leave the method via
7906: @code{;m}, but via @code{throw} or @code{exit},
7907: @code{this} is not restored (and @code{exit} may
7908: crash). To deal with the @code{throw} problem, I have redefined
7909: @code{catch} to save and restore @code{this}; the same
7910: should be done with any word that can catch an exception. As for
7911: @code{exit}, I simply forbid it (as a replacement, there is
7912: @code{exitm}).
1.21 crook 7913:
1.26 crook 7914: @cindex @code{inst-var} implementation
7915: @code{inst-var} is just the same as @code{field}, with
7916: a different @code{DOES>} action:
7917: @example
7918: @@ this +
7919: @end example
7920: Similar for @code{inst-value}.
1.21 crook 7921:
1.26 crook 7922: @cindex class scoping implementation
7923: Each class also has a word list that contains the words defined with
7924: @code{inst-var} and @code{inst-value}, and its protected
7925: words. It also has a pointer to its parent. @code{class} pushes
7926: the word lists of the class and all its ancestors onto the search order stack,
7927: and @code{end-class} drops them.
1.21 crook 7928:
1.26 crook 7929: @cindex interface implementation
7930: An interface is like a class without fields, parent and protected
7931: words; i.e., it just has a method map. If a class implements an
7932: interface, its method map contains a pointer to the method map of the
7933: interface. The positive offsets in the map are reserved for class
7934: methods, therefore interface map pointers have negative
7935: offsets. Interfaces have offsets that are unique throughout the
7936: system, unlike class selectors, whose offsets are only unique for the
7937: classes where the selector is available (invokable).
1.21 crook 7938:
1.26 crook 7939: This structure means that interface selectors have to perform one
7940: indirection more than class selectors to find their method. Their body
7941: contains the interface map pointer offset in the class method map, and
7942: the method offset in the interface method map. The
7943: @code{does>} action for an interface selector is, basically:
1.21 crook 7944:
7945: @example
1.26 crook 7946: ( object selector-body )
7947: 2dup selector-interface @@ ( object selector-body object interface-offset )
7948: swap object-map @@ + @@ ( object selector-body map )
7949: swap selector-offset @@ + @@ execute
1.21 crook 7950: @end example
7951:
1.26 crook 7952: where @code{object-map} and @code{selector-offset} are
7953: first fields and generate no code.
7954:
7955: As a concrete example, consider the following code:
1.21 crook 7956:
1.26 crook 7957: @example
7958: interface
7959: selector if1sel1
7960: selector if1sel2
7961: end-interface if1
1.21 crook 7962:
1.26 crook 7963: object class
7964: if1 implementation
7965: selector cl1sel1
7966: cell% inst-var cl1iv1
1.21 crook 7967:
1.26 crook 7968: ' m1 overrides construct
7969: ' m2 overrides if1sel1
7970: ' m3 overrides if1sel2
7971: ' m4 overrides cl1sel2
7972: end-class cl1
1.21 crook 7973:
1.26 crook 7974: create obj1 object dict-new drop
7975: create obj2 cl1 dict-new drop
7976: @end example
1.21 crook 7977:
1.26 crook 7978: The data structure created by this code (including the data structure
7979: for @code{object}) is shown in the <a
7980: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.29 crook 7981: @comment TODO add this diagram..
1.21 crook 7982:
1.26 crook 7983: @node Objects Glossary, , Objects Implementation, Objects
7984: @subsubsection @file{objects.fs} Glossary
7985: @cindex @file{objects.fs} Glossary
1.21 crook 7986:
1.26 crook 7987: doc---objects-bind
7988: doc---objects-<bind>
7989: doc---objects-bind'
7990: doc---objects-[bind]
7991: doc---objects-class
7992: doc---objects-class->map
7993: doc---objects-class-inst-size
7994: doc---objects-class-override!
7995: doc---objects-construct
7996: doc---objects-current'
7997: doc---objects-[current]
7998: doc---objects-current-interface
7999: doc---objects-dict-new
8000: doc---objects-drop-order
8001: doc---objects-end-class
8002: doc---objects-end-class-noname
8003: doc---objects-end-interface
8004: doc---objects-end-interface-noname
8005: doc---objects-exitm
8006: doc---objects-heap-new
8007: doc---objects-implementation
8008: doc---objects-init-object
8009: doc---objects-inst-value
8010: doc---objects-inst-var
8011: doc---objects-interface
8012: doc---objects-;m
8013: doc---objects-m:
8014: doc---objects-method
8015: doc---objects-object
8016: doc---objects-overrides
8017: doc---objects-[parent]
8018: doc---objects-print
8019: doc---objects-protected
8020: doc---objects-public
8021: doc---objects-push-order
8022: doc---objects-selector
8023: doc---objects-this
8024: doc---objects-<to-inst>
8025: doc---objects-[to-inst]
8026: doc---objects-to-this
8027: doc---objects-xt-new
1.21 crook 8028:
1.26 crook 8029: @c -------------------------------------------------------------
8030: @node OOF, Mini-OOF, Objects, Object-oriented Forth
8031: @subsection The @file{oof.fs} model
8032: @cindex oof
8033: @cindex object-oriented programming
1.21 crook 8034:
1.26 crook 8035: @cindex @file{objects.fs}
8036: @cindex @file{oof.fs}
1.21 crook 8037:
1.26 crook 8038: This section describes the @file{oof.fs} package.
1.21 crook 8039:
1.26 crook 8040: The package described in this section has been used in bigFORTH since 1991, and
8041: used for two large applications: a chromatographic system used to
8042: create new medicaments, and a graphic user interface library (MINOS).
1.21 crook 8043:
1.26 crook 8044: You can find a description (in German) of @file{oof.fs} in @cite{Object
8045: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
8046: 10(2), 1994.
1.21 crook 8047:
1.26 crook 8048: @menu
8049: * Properties of the OOF model::
8050: * Basic OOF Usage::
8051: * The OOF base class::
8052: * Class Declaration::
8053: * Class Implementation::
8054: @end menu
1.21 crook 8055:
1.26 crook 8056: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
8057: @subsubsection Properties of the @file{oof.fs} model
8058: @cindex @file{oof.fs} properties
1.21 crook 8059:
1.26 crook 8060: @itemize @bullet
8061: @item
8062: This model combines object oriented programming with information
8063: hiding. It helps you writing large application, where scoping is
8064: necessary, because it provides class-oriented scoping.
1.21 crook 8065:
1.26 crook 8066: @item
8067: Named objects, object pointers, and object arrays can be created,
8068: selector invocation uses the ``object selector'' syntax. Selector invocation
8069: to objects and/or selectors on the stack is a bit less convenient, but
8070: possible.
1.21 crook 8071:
1.26 crook 8072: @item
8073: Selector invocation and instance variable usage of the active object is
8074: straightforward, since both make use of the active object.
1.21 crook 8075:
1.26 crook 8076: @item
8077: Late binding is efficient and easy to use.
1.21 crook 8078:
1.26 crook 8079: @item
8080: State-smart objects parse selectors. However, extensibility is provided
8081: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21 crook 8082:
8083: @item
1.26 crook 8084: An implementation in ANS Forth is available.
8085:
1.21 crook 8086: @end itemize
8087:
8088:
1.26 crook 8089: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
8090: @subsubsection Basic @file{oof.fs} Usage
8091: @cindex @file{oof.fs} usage
8092:
8093: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21 crook 8094:
1.26 crook 8095: You can define a class for graphical objects like this:
1.21 crook 8096:
1.26 crook 8097: @cindex @code{class} usage
8098: @cindex @code{class;} usage
8099: @cindex @code{method} usage
8100: @example
8101: object class graphical \ "object" is the parent class
8102: method draw ( x y graphical -- )
8103: class;
8104: @end example
1.21 crook 8105:
1.26 crook 8106: This code defines a class @code{graphical} with an
8107: operation @code{draw}. We can perform the operation
8108: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 8109:
1.26 crook 8110: @example
8111: 100 100 t-rex draw
8112: @end example
1.21 crook 8113:
1.26 crook 8114: @noindent
8115: where @code{t-rex} is an object or object pointer, created with e.g.
8116: @code{graphical : t-rex}.
1.21 crook 8117:
1.26 crook 8118: @cindex abstract class
8119: How do we create a graphical object? With the present definitions,
8120: we cannot create a useful graphical object. The class
8121: @code{graphical} describes graphical objects in general, but not
8122: any concrete graphical object type (C++ users would call it an
8123: @emph{abstract class}); e.g., there is no method for the selector
8124: @code{draw} in the class @code{graphical}.
1.21 crook 8125:
1.26 crook 8126: For concrete graphical objects, we define child classes of the
8127: class @code{graphical}, e.g.:
1.21 crook 8128:
8129: @example
1.26 crook 8130: graphical class circle \ "graphical" is the parent class
8131: cell var circle-radius
8132: how:
8133: : draw ( x y -- )
8134: circle-radius @@ draw-circle ;
8135:
8136: : init ( n-radius -- (
8137: circle-radius ! ;
8138: class;
8139: @end example
8140:
8141: Here we define a class @code{circle} as a child of @code{graphical},
8142: with a field @code{circle-radius}; it defines new methods for the
8143: selectors @code{draw} and @code{init} (@code{init} is defined in
8144: @code{object}, the parent class of @code{graphical}).
1.21 crook 8145:
1.26 crook 8146: Now we can create a circle in the dictionary with:
1.21 crook 8147:
1.26 crook 8148: @example
8149: 50 circle : my-circle
1.21 crook 8150: @end example
8151:
1.26 crook 8152: @noindent
8153: @code{:} invokes @code{init}, thus initializing the field
8154: @code{circle-radius} with 50. We can draw this new circle at (100,100)
8155: with:
1.21 crook 8156:
8157: @example
1.26 crook 8158: 100 100 my-circle draw
1.21 crook 8159: @end example
8160:
1.26 crook 8161: @cindex selector invocation, restrictions
8162: @cindex class definition, restrictions
8163: Note: You can only invoke a selector if the receiving object belongs to
8164: the class where the selector was defined or one of its descendents;
8165: e.g., you can invoke @code{draw} only for objects belonging to
8166: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
8167: mechanism will check if you try to invoke a selector that is not
8168: defined in this class hierarchy, so you'll get an error at compilation
8169: time.
8170:
8171:
8172: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
8173: @subsubsection The @file{oof.fs} base class
8174: @cindex @file{oof.fs} base class
8175:
8176: When you define a class, you have to specify a parent class. So how do
8177: you start defining classes? There is one class available from the start:
8178: @code{object}. You have to use it as ancestor for all classes. It is the
8179: only class that has no parent. Classes are also objects, except that
8180: they don't have instance variables; class manipulation such as
8181: inheritance or changing definitions of a class is handled through
8182: selectors of the class @code{object}.
8183:
8184: @code{object} provides a number of selectors:
8185:
1.21 crook 8186: @itemize @bullet
8187: @item
1.26 crook 8188: @code{class} for subclassing, @code{definitions} to add definitions
8189: later on, and @code{class?} to get type informations (is the class a
8190: subclass of the class passed on the stack?).
8191: doc---object-class
8192: doc---object-definitions
8193: doc---object-class?
8194:
1.21 crook 8195: @item
1.26 crook 8196: @code{init} and @code{dispose} as constructor and destructor of the
8197: object. @code{init} is invocated after the object's memory is allocated,
8198: while @code{dispose} also handles deallocation. Thus if you redefine
8199: @code{dispose}, you have to call the parent's dispose with @code{super
8200: dispose}, too.
8201: doc---object-init
8202: doc---object-dispose
8203:
1.21 crook 8204: @item
1.26 crook 8205: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
8206: @code{[]} to create named and unnamed objects and object arrays or
8207: object pointers.
8208: doc---object-new
8209: doc---object-new[]
8210: doc---object-:
8211: doc---object-ptr
8212: doc---object-asptr
8213: doc---object-[]
1.21 crook 8214:
1.26 crook 8215: @item
8216: @code{::} and @code{super} for explicit scoping. You should use explicit
8217: scoping only for super classes or classes with the same set of instance
8218: variables. Explicitly-scoped selectors use early binding.
8219: doc---object-::
8220: doc---object-super
1.21 crook 8221:
1.26 crook 8222: @item
8223: @code{self} to get the address of the object
8224: doc---object-self
1.21 crook 8225:
8226: @item
1.26 crook 8227: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
8228: pointers and instance defers.
8229: doc---object-bind
8230: doc---object-bound
8231: doc---object-link
8232: doc---object-is
8233:
1.21 crook 8234: @item
1.26 crook 8235: @code{'} to obtain selector tokens, @code{send} to invocate selectors
8236: form the stack, and @code{postpone} to generate selector invocation code.
8237: doc---object-'
8238: doc---object-postpone
8239:
1.21 crook 8240: @item
1.26 crook 8241: @code{with} and @code{endwith} to select the active object from the
8242: stack, and enable its scope. Using @code{with} and @code{endwith}
8243: also allows you to create code using selector @code{postpone} without being
8244: trapped by the state-smart objects.
8245: doc---object-with
8246: doc---object-endwith
8247:
1.21 crook 8248: @end itemize
8249:
1.26 crook 8250: @node Class Declaration, Class Implementation, The OOF base class, OOF
8251: @subsubsection Class Declaration
8252: @cindex class declaration
8253:
8254: @itemize @bullet
8255: @item
8256: Instance variables
8257: doc---oof-var
1.21 crook 8258:
1.26 crook 8259: @item
8260: Object pointers
8261: doc---oof-ptr
8262: doc---oof-asptr
1.21 crook 8263:
1.26 crook 8264: @item
8265: Instance defers
8266: doc---oof-defer
1.21 crook 8267:
1.26 crook 8268: @item
8269: Method selectors
8270: doc---oof-early
8271: doc---oof-method
1.21 crook 8272:
1.26 crook 8273: @item
8274: Class-wide variables
8275: doc---oof-static
1.21 crook 8276:
1.26 crook 8277: @item
8278: End declaration
8279: doc---oof-how:
8280: doc---oof-class;
1.21 crook 8281:
1.26 crook 8282: @end itemize
1.21 crook 8283:
1.26 crook 8284: @c -------------------------------------------------------------
8285: @node Class Implementation, , Class Declaration, OOF
8286: @subsubsection Class Implementation
8287: @cindex class implementation
1.21 crook 8288:
1.26 crook 8289: @c -------------------------------------------------------------
8290: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
8291: @subsection The @file{mini-oof.fs} model
8292: @cindex mini-oof
1.1 anton 8293:
1.26 crook 8294: Gforth's third object oriented Forth package is a 12-liner. It uses a
8295: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
8296: and reduces to the bare minimum of features. This is based on a posting
8297: of Bernd Paysan in comp.arch.
1.1 anton 8298:
8299: @menu
1.26 crook 8300: * Basic Mini-OOF Usage::
8301: * Mini-OOF Example::
8302: * Mini-OOF Implementation::
1.1 anton 8303: @end menu
8304:
1.26 crook 8305: @c -------------------------------------------------------------
8306: @node Basic Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
8307: @subsubsection Basic @file{mini-oof.fs} Usage
8308: @cindex mini-oof usage
1.1 anton 8309:
1.28 crook 8310: There is a base class (@code{class}, which allocates one cell for the
8311: object pointer) plus seven other words: to define a method, a variable,
8312: a class; to end a class, to resolve binding, to allocate an object and
8313: to compile a class method.
1.26 crook 8314: @comment TODO better description of the last one
1.1 anton 8315:
1.26 crook 8316: doc-object
8317: doc-method
8318: doc-var
8319: doc-class
8320: doc-end-class
8321: doc-defines
8322: doc-new
8323: doc-::
1.1 anton 8324:
1.21 crook 8325:
1.26 crook 8326: @c -------------------------------------------------------------
8327: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
8328: @subsubsection Mini-OOF Example
8329: @cindex mini-oof example
1.21 crook 8330:
1.26 crook 8331: A short example shows how to use this package. This example, in slightly
8332: extended form, is supplied as @file{moof-exm.fs}
1.29 crook 8333: @comment TODO could flesh this out with some comments from the Forthwrite article
1.21 crook 8334:
1.26 crook 8335: @example
8336: object class
8337: method init
8338: method draw
8339: end-class graphical
8340: @end example
1.21 crook 8341:
1.26 crook 8342: This code defines a class @code{graphical} with an
8343: operation @code{draw}. We can perform the operation
8344: @code{draw} on any @code{graphical} object, e.g.:
1.1 anton 8345:
1.26 crook 8346: @example
8347: 100 100 t-rex draw
8348: @end example
1.1 anton 8349:
1.26 crook 8350: where @code{t-rex} is an object or object pointer, created with e.g.
8351: @code{graphical new Constant t-rex}.
1.1 anton 8352:
1.26 crook 8353: For concrete graphical objects, we define child classes of the
8354: class @code{graphical}, e.g.:
1.21 crook 8355:
8356: @example
1.26 crook 8357: graphical class
8358: cell var circle-radius
8359: end-class circle \ "graphical" is the parent class
1.21 crook 8360:
1.26 crook 8361: :noname ( x y -- )
8362: circle-radius @@ draw-circle ; circle defines draw
8363: :noname ( r -- )
8364: circle-radius ! ; circle defines init
1.21 crook 8365: @end example
8366:
1.26 crook 8367: There is no implicit init method, so we have to define one. The creation
8368: code of the object now has to call init explicitely.
1.21 crook 8369:
1.26 crook 8370: @example
8371: circle new Constant my-circle
8372: 50 my-circle init
8373: @end example
1.21 crook 8374:
1.26 crook 8375: It is also possible to add a function to create named objects with
8376: automatic call of @code{init}, given that all objects have @code{init}
8377: on the same place:
1.1 anton 8378:
8379: @example
1.26 crook 8380: : new: ( .. o "name" -- )
8381: new dup Constant init ;
8382: 80 circle new: large-circle
1.1 anton 8383: @end example
8384:
1.26 crook 8385: We can draw this new circle at (100,100) with:
1.1 anton 8386:
8387: @example
1.26 crook 8388: 100 100 my-circle draw
1.1 anton 8389: @end example
8390:
1.26 crook 8391: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
8392: @subsubsection @file{mini-oof.fs} Implementation
1.1 anton 8393:
1.26 crook 8394: Object-oriented systems with late binding typically use a
8395: ``vtable''-approach: the first variable in each object is a pointer to a
8396: table, which contains the methods as function pointers. The vtable
8397: may also contain other information.
1.1 anton 8398:
1.26 crook 8399: So first, let's declare methods:
1.1 anton 8400:
1.26 crook 8401: @example
8402: : method ( m v -- m' v ) Create over , swap cell+ swap
8403: DOES> ( ... o -- ... ) @ over @ + @ execute ;
8404: @end example
1.1 anton 8405:
1.26 crook 8406: During method declaration, the number of methods and instance
8407: variables is on the stack (in address units). @code{method} creates
8408: one method and increments the method number. To execute a method, it
8409: takes the object, fetches the vtable pointer, adds the offset, and
1.29 crook 8410: executes the @i{xt} stored there. Each method takes the object it is
1.26 crook 8411: invoked from as top of stack parameter. The method itself should
8412: consume that object.
1.1 anton 8413:
1.26 crook 8414: Now, we also have to declare instance variables
1.21 crook 8415:
1.26 crook 8416: @example
8417: : var ( m v size -- m v' ) Create over , +
8418: DOES> ( o -- addr ) @ + ;
8419: @end example
1.21 crook 8420:
1.26 crook 8421: As before, a word is created with the current offset. Instance
8422: variables can have different sizes (cells, floats, doubles, chars), so
8423: all we do is take the size and add it to the offset. If your machine
8424: has alignment restrictions, put the proper @code{aligned} or
8425: @code{faligned} before the variable, to adjust the variable
8426: offset. That's why it is on the top of stack.
1.2 jwilke 8427:
1.26 crook 8428: We need a starting point (the base object) and some syntactic sugar:
1.21 crook 8429:
1.26 crook 8430: @example
8431: Create object 1 cells , 2 cells ,
8432: : class ( class -- class methods vars ) dup 2@ ;
8433: @end example
1.21 crook 8434:
1.26 crook 8435: For inheritance, the vtable of the parent object has to be
8436: copied when a new, derived class is declared. This gives all the
8437: methods of the parent class, which can be overridden, though.
1.21 crook 8438:
1.2 jwilke 8439: @example
1.26 crook 8440: : end-class ( class methods vars -- )
8441: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
8442: cell+ dup cell+ r> rot @ 2 cells /string move ;
8443: @end example
8444:
8445: The first line creates the vtable, initialized with
8446: @code{noop}s. The second line is the inheritance mechanism, it
8447: copies the xts from the parent vtable.
1.2 jwilke 8448:
1.26 crook 8449: We still have no way to define new methods, let's do that now:
1.2 jwilke 8450:
1.26 crook 8451: @example
8452: : defines ( xt class -- ) ' >body @ + ! ;
1.2 jwilke 8453: @end example
8454:
1.26 crook 8455: To allocate a new object, we need a word, too:
1.2 jwilke 8456:
1.26 crook 8457: @example
8458: : new ( class -- o ) here over @ allot swap over ! ;
8459: @end example
1.2 jwilke 8460:
1.26 crook 8461: Sometimes derived classes want to access the method of the
8462: parent object. There are two ways to achieve this with Mini-OOF:
8463: first, you could use named words, and second, you could look up the
8464: vtable of the parent object.
1.2 jwilke 8465:
1.26 crook 8466: @example
8467: : :: ( class "name" -- ) ' >body @ + @ compile, ;
8468: @end example
1.2 jwilke 8469:
8470:
1.26 crook 8471: Nothing can be more confusing than a good example, so here is
8472: one. First let's declare a text object (called
8473: @code{button}), that stores text and position:
1.2 jwilke 8474:
1.26 crook 8475: @example
8476: object class
8477: cell var text
8478: cell var len
8479: cell var x
8480: cell var y
8481: method init
8482: method draw
8483: end-class button
8484: @end example
1.2 jwilke 8485:
1.26 crook 8486: @noindent
8487: Now, implement the two methods, @code{draw} and @code{init}:
1.2 jwilke 8488:
1.26 crook 8489: @example
8490: :noname ( o -- )
8491: >r r@ x @ r@ y @ at-xy r@ text @ r> len @ type ;
8492: button defines draw
8493: :noname ( addr u o -- )
8494: >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
8495: button defines init
8496: @end example
1.2 jwilke 8497:
1.26 crook 8498: @noindent
8499: To demonstrate inheritance, we define a class @code{bold-button}, with no
8500: new data and no new methods:
1.2 jwilke 8501:
1.26 crook 8502: @example
8503: button class
8504: end-class bold-button
1.1 anton 8505:
1.26 crook 8506: : bold 27 emit ." [1m" ;
8507: : normal 27 emit ." [0m" ;
8508: @end example
1.1 anton 8509:
1.26 crook 8510: @noindent
8511: The class @code{bold-button} has a different draw method to
8512: @code{button}, but the new method is defined in terms of the draw method
8513: for @code{button}:
1.1 anton 8514:
1.26 crook 8515: @example
8516: :noname bold [ button :: draw ] normal ; bold-button defines draw
8517: @end example
1.1 anton 8518:
1.26 crook 8519: @noindent
8520: Finally, create two objects and apply methods:
1.1 anton 8521:
1.26 crook 8522: @example
8523: button new Constant foo
8524: s" thin foo" foo init
8525: page
8526: foo draw
8527: bold-button new Constant bar
8528: s" fat bar" bar init
8529: 1 bar y !
8530: bar draw
8531: @end example
1.1 anton 8532:
8533:
1.26 crook 8534: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
8535: @subsubsection Comparison with other object models
8536: @cindex comparison of object models
8537: @cindex object models, comparison
1.1 anton 8538:
1.26 crook 8539: Many object-oriented Forth extensions have been proposed (@cite{A survey
8540: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
8541: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
8542: relation of the object models described here to two well-known and two
8543: closely-related (by the use of method maps) models.
1.1 anton 8544:
1.26 crook 8545: @cindex Neon model
8546: The most popular model currently seems to be the Neon model (see
8547: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
8548: 1997) by Andrew McKewan) but this model has a number of limitations
8549: @footnote{A longer version of this critique can be
8550: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
8551: Dimensions, May 1997) by Anton Ertl.}:
1.1 anton 8552:
1.26 crook 8553: @itemize @bullet
8554: @item
8555: It uses a @code{@emph{selector
8556: object}} syntax, which makes it unnatural to pass objects on the
8557: stack.
1.1 anton 8558:
1.26 crook 8559: @item
8560: It requires that the selector parses the input stream (at
8561: compile time); this leads to reduced extensibility and to bugs that are+
8562: hard to find.
1.1 anton 8563:
1.26 crook 8564: @item
8565: It allows using every selector to every object;
8566: this eliminates the need for classes, but makes it harder to create
8567: efficient implementations.
8568: @end itemize
1.1 anton 8569:
1.26 crook 8570: @cindex Pountain's object-oriented model
8571: Another well-known publication is @cite{Object-Oriented Forth} (Academic
8572: Press, London, 1987) by Dick Pountain. However, it is not really about
8573: object-oriented programming, because it hardly deals with late
8574: binding. Instead, it focuses on features like information hiding and
8575: overloading that are characteristic of modular languages like Ada (83).
1.1 anton 8576:
1.26 crook 8577: @cindex Zsoter's object-oriented model
8578: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1) 1996, pages 31-35)
8579: Andras Zsoter describes a model that makes heavy use of an active object
8580: (like @code{this} in @file{objects.fs}): The active object is not only
8581: used for accessing all fields, but also specifies the receiving object
8582: of every selector invocation; you have to change the active object
8583: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
8584: changes more or less implicitly at @code{m: ... ;m}. Such a change at
8585: the method entry point is unnecessary with the Zsoter's model, because
8586: the receiving object is the active object already. On the other hand, the explicit
8587: change is absolutely necessary in that model, because otherwise no one
8588: could ever change the active object. An ANS Forth implementation of this
8589: model is available at @url{http://www.forth.org/fig/oopf.html}.
1.1 anton 8590:
1.26 crook 8591: @cindex @file{oof.fs}, differences to other models
8592: The @file{oof.fs} model combines information hiding and overloading
8593: resolution (by keeping names in various word lists) with object-oriented
8594: programming. It sets the active object implicitly on method entry, but
8595: also allows explicit changing (with @code{>o...o>} or with
8596: @code{with...endwith}). It uses parsing and state-smart objects and
8597: classes for resolving overloading and for early binding: the object or
8598: class parses the selector and determines the method from this. If the
8599: selector is not parsed by an object or class, it performs a call to the
8600: selector for the active object (late binding), like Zsoter's model.
8601: Fields are always accessed through the active object. The big
8602: disadvantage of this model is the parsing and the state-smartness, which
8603: reduces extensibility and increases the opportunities for subtle bugs;
8604: essentially, you are only safe if you never tick or @code{postpone} an
8605: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1 anton 8606:
1.26 crook 8607: @cindex @file{mini-oof.fs}, differences to other models
8608: The @file{mini-oof.fs} model is quite similar to a very stripped-down version of
8609: the @file{objects.fs} model, but syntactically it is a mixture of the @file{objects.fs} and
8610: @file{oof.fs} models.
1.1 anton 8611:
1.26 crook 8612: @c -------------------------------------------------------------
8613: @node Passing Commands to the OS, Miscellaneous Words, Object-oriented Forth, Words
1.21 crook 8614: @section Passing Commands to the Operating System
8615: @cindex operating system - passing commands
8616: @cindex shell commands
8617:
8618: Gforth allows you to pass an arbitrary string to the host operating
8619: system shell (if such a thing exists) for execution.
8620:
8621: doc-sh
8622: doc-system
8623: doc-$?
1.23 crook 8624: doc-getenv
1.21 crook 8625:
1.26 crook 8626: @c -------------------------------------------------------------
1.21 crook 8627: @node Miscellaneous Words, , Passing Commands to the OS, Words
8628: @section Miscellaneous Words
8629: @cindex miscellaneous words
8630:
1.29 crook 8631: @comment TODO find homes for these
8632:
1.26 crook 8633: These section lists the ANS Forth words that are not documented
1.21 crook 8634: elsewhere in this manual. Ultimately, they all need proper homes.
8635:
8636: doc-ms
8637: doc-time&date
1.27 crook 8638:
1.21 crook 8639: doc-[compile]
8640:
1.26 crook 8641: The following ANS Forth words are not currently supported by Gforth
1.27 crook 8642: (@pxref{ANS conformance}):
1.21 crook 8643:
8644: @code{EDITOR}
8645: @code{EKEY}
8646: @code{EKEY>CHAR}
8647: @code{EKEY?}
8648: @code{EMIT?}
8649: @code{FORGET}
8650:
1.24 anton 8651: @c ******************************************************************
8652: @node Error messages, Tools, Words, Top
8653: @chapter Error messages
8654: @cindex error messages
8655: @cindex backtrace
8656:
8657: A typical Gforth error message looks like this:
8658:
8659: @example
8660: in file included from :-1
8661: in file included from ./yyy.fs:1
8662: ./xxx.fs:4: Invalid memory address
8663: bar
8664: ^^^
1.25 anton 8665: $400E664C @@
8666: $400E6664 foo
1.24 anton 8667: @end example
8668:
8669: The message identifying the error is @code{Invalid memory address}. The
8670: error happened when text-interpreting line 4 of the file
8671: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
8672: word on the line where the error happened, is pointed out (with
8673: @code{^^^}).
8674:
8675: The file containing the error was included in line 1 of @file{./yyy.fs},
8676: and @file{yyy.fs} was included from a non-file (in this case, by giving
8677: @file{yyy.fs} as command-line parameter to Gforth).
8678:
8679: At the end of the error message you find a return stack dump that can be
8680: interpreted as a backtrace (possibly empty). On top you find the top of
8681: the return stack when the @code{throw} happened, and at the bottom you
8682: find the return stack entry just above the return stack of the topmost
8683: text interpreter.
8684:
8685: To the right of most return stack entries you see a guess for the word
8686: that pushed that return stack entry as its return address. This gives a
8687: backtrace. In our case we see that @code{bar} called @code{foo}, and
8688: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
8689: address} exception).
8690:
8691: Note that the backtrace is not perfect: We don't know which return stack
8692: entries are return addresses (so we may get false positives); and in
8693: some cases (e.g., for @code{abort"}) we cannot determine from the return
8694: address the word that pushed the return address, so for some return
8695: addresses you see no names in the return stack dump.
1.25 anton 8696:
8697: @cindex @code{catch} and backtraces
8698: The return stack dump represents the return stack at the time when a
8699: specific @code{throw} was executed. In programs that make use of
8700: @code{catch}, it is not necessarily clear which @code{throw} should be
8701: used for the return stack dump (e.g., consider one @code{throw} that
8702: indicates an error, which is caught, and during recovery another error
8703: happens; which @code{throw} should be used for the stack dump). Gforth
8704: presents the return stack dump for the first @code{throw} after the last
8705: executed (not returned-to) @code{catch}; this works well in the usual
8706: case.
8707:
8708: @cindex @code{gforth-fast} and backtraces
8709: @cindex @code{gforth-fast}, difference from @code{gforth}
8710: @cindex backtraces with @code{gforth-fast}
8711: @cindex return stack dump with @code{gforth-fast}
8712: @code{gforth} is able to do a return stack dump for throws generated
8713: from primitives (e.g., invalid memory address, stack empty etc.);
8714: @code{gforth-fast} is only able to do a return stack dump from a
8715: directly called @code{throw} (including @code{abort} etc.). This is the
1.30 ! anton 8716: only difference (apart from a speed factor of between 1.15 (K6-2) and
! 8717: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}. Given an
! 8718: exception caused by a primitive in @code{gforth-fast}, you will
! 8719: typically see no return stack dump at all; however, if the exception is
! 8720: caught by @code{catch} (e.g., for restoring some state), and then
! 8721: @code{throw}n again, the return stack dump will be for the first such
! 8722: @code{throw}.
1.2 jwilke 8723:
1.5 anton 8724: @c ******************************************************************
1.24 anton 8725: @node Tools, ANS conformance, Error messages, Top
1.1 anton 8726: @chapter Tools
8727:
8728: @menu
8729: * ANS Report:: Report the words used, sorted by wordset.
8730: @end menu
8731:
8732: See also @ref{Emacs and Gforth}.
8733:
8734: @node ANS Report, , Tools, Tools
8735: @section @file{ans-report.fs}: Report the words used, sorted by wordset
8736: @cindex @file{ans-report.fs}
8737: @cindex report the words used in your program
8738: @cindex words used in your program
8739:
8740: If you want to label a Forth program as ANS Forth Program, you must
8741: document which wordsets the program uses; for extension wordsets, it is
8742: helpful to list the words the program requires from these wordsets
8743: (because Forth systems are allowed to provide only some words of them).
8744:
8745: The @file{ans-report.fs} tool makes it easy for you to determine which
8746: words from which wordset and which non-ANS words your application
8747: uses. You simply have to include @file{ans-report.fs} before loading the
8748: program you want to check. After loading your program, you can get the
8749: report with @code{print-ans-report}. A typical use is to run this as
8750: batch job like this:
8751: @example
8752: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
8753: @end example
8754:
8755: The output looks like this (for @file{compat/control.fs}):
8756: @example
8757: The program uses the following words
8758: from CORE :
8759: : POSTPONE THEN ; immediate ?dup IF 0=
8760: from BLOCK-EXT :
8761: \
8762: from FILE :
8763: (
8764: @end example
8765:
8766: @subsection Caveats
8767:
8768: Note that @file{ans-report.fs} just checks which words are used, not whether
8769: they are used in an ANS Forth conforming way!
8770:
8771: Some words are defined in several wordsets in the
8772: standard. @file{ans-report.fs} reports them for only one of the
8773: wordsets, and not necessarily the one you expect. It depends on usage
8774: which wordset is the right one to specify. E.g., if you only use the
8775: compilation semantics of @code{S"}, it is a Core word; if you also use
8776: its interpretation semantics, it is a File word.
8777:
8778: @c ******************************************************************
8779: @node ANS conformance, Model, Tools, Top
8780: @chapter ANS conformance
8781: @cindex ANS conformance of Gforth
8782:
8783: To the best of our knowledge, Gforth is an
8784:
8785: ANS Forth System
8786: @itemize @bullet
8787: @item providing the Core Extensions word set
8788: @item providing the Block word set
8789: @item providing the Block Extensions word set
8790: @item providing the Double-Number word set
8791: @item providing the Double-Number Extensions word set
8792: @item providing the Exception word set
8793: @item providing the Exception Extensions word set
8794: @item providing the Facility word set
8795: @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
8796: @item providing the File Access word set
8797: @item providing the File Access Extensions word set
8798: @item providing the Floating-Point word set
8799: @item providing the Floating-Point Extensions word set
8800: @item providing the Locals word set
8801: @item providing the Locals Extensions word set
8802: @item providing the Memory-Allocation word set
8803: @item providing the Memory-Allocation Extensions word set (that one's easy)
8804: @item providing the Programming-Tools word set
8805: @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
8806: @item providing the Search-Order word set
8807: @item providing the Search-Order Extensions word set
8808: @item providing the String word set
8809: @item providing the String Extensions word set (another easy one)
8810: @end itemize
8811:
8812: @cindex system documentation
8813: In addition, ANS Forth systems are required to document certain
8814: implementation choices. This chapter tries to meet these
8815: requirements. In many cases it gives a way to ask the system for the
8816: information instead of providing the information directly, in
8817: particular, if the information depends on the processor, the operating
8818: system or the installation options chosen, or if they are likely to
8819: change during the maintenance of Gforth.
8820:
8821: @comment The framework for the rest has been taken from pfe.
8822:
8823: @menu
8824: * The Core Words::
8825: * The optional Block word set::
8826: * The optional Double Number word set::
8827: * The optional Exception word set::
8828: * The optional Facility word set::
8829: * The optional File-Access word set::
8830: * The optional Floating-Point word set::
8831: * The optional Locals word set::
8832: * The optional Memory-Allocation word set::
8833: * The optional Programming-Tools word set::
8834: * The optional Search-Order word set::
8835: @end menu
8836:
8837:
8838: @c =====================================================================
8839: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
8840: @comment node-name, next, previous, up
8841: @section The Core Words
8842: @c =====================================================================
8843: @cindex core words, system documentation
8844: @cindex system documentation, core words
8845:
8846: @menu
8847: * core-idef:: Implementation Defined Options
8848: * core-ambcond:: Ambiguous Conditions
8849: * core-other:: Other System Documentation
8850: @end menu
8851:
8852: @c ---------------------------------------------------------------------
8853: @node core-idef, core-ambcond, The Core Words, The Core Words
8854: @subsection Implementation Defined Options
8855: @c ---------------------------------------------------------------------
8856: @cindex core words, implementation-defined options
8857: @cindex implementation-defined options, core words
8858:
8859:
8860: @table @i
8861: @item (Cell) aligned addresses:
8862: @cindex cell-aligned addresses
8863: @cindex aligned addresses
8864: processor-dependent. Gforth's alignment words perform natural alignment
8865: (e.g., an address aligned for a datum of size 8 is divisible by
8866: 8). Unaligned accesses usually result in a @code{-23 THROW}.
8867:
8868: @item @code{EMIT} and non-graphic characters:
8869: @cindex @code{EMIT} and non-graphic characters
8870: @cindex non-graphic characters and @code{EMIT}
8871: The character is output using the C library function (actually, macro)
8872: @code{putc}.
8873:
8874: @item character editing of @code{ACCEPT} and @code{EXPECT}:
8875: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
8876: @cindex editing in @code{ACCEPT} and @code{EXPECT}
8877: @cindex @code{ACCEPT}, editing
8878: @cindex @code{EXPECT}, editing
8879: This is modeled on the GNU readline library (@pxref{Readline
8880: Interaction, , Command Line Editing, readline, The GNU Readline
8881: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
8882: producing a full word completion every time you type it (instead of
1.28 crook 8883: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 8884:
8885: @item character set:
8886: @cindex character set
8887: The character set of your computer and display device. Gforth is
8888: 8-bit-clean (but some other component in your system may make trouble).
8889:
8890: @item Character-aligned address requirements:
8891: @cindex character-aligned address requirements
8892: installation-dependent. Currently a character is represented by a C
8893: @code{unsigned char}; in the future we might switch to @code{wchar_t}
8894: (Comments on that requested).
8895:
8896: @item character-set extensions and matching of names:
8897: @cindex character-set extensions and matching of names
1.26 crook 8898: @cindex case-sensitivity for name lookup
8899: @cindex name lookup, case-sensitivity
8900: @cindex locale and case-sensitivity
1.21 crook 8901: Any character except the ASCII NUL character can be used in a
1.1 anton 8902: name. Matching is case-insensitive (except in @code{TABLE}s). The
8903: matching is performed using the C function @code{strncasecmp}, whose
8904: function is probably influenced by the locale. E.g., the @code{C} locale
8905: does not know about accents and umlauts, so they are matched
8906: case-sensitively in that locale. For portability reasons it is best to
8907: write programs such that they work in the @code{C} locale. Then one can
8908: use libraries written by a Polish programmer (who might use words
8909: containing ISO Latin-2 encoded characters) and by a French programmer
8910: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
8911: funny results for some of the words (which ones, depends on the font you
8912: are using)). Also, the locale you prefer may not be available in other
8913: operating systems. Hopefully, Unicode will solve these problems one day.
8914:
8915: @item conditions under which control characters match a space delimiter:
8916: @cindex space delimiters
8917: @cindex control characters as delimiters
8918: If @code{WORD} is called with the space character as a delimiter, all
8919: white-space characters (as identified by the C macro @code{isspace()})
8920: are delimiters. @code{PARSE}, on the other hand, treats space like other
8921: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
8922: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
8923: interpreter (aka text interpreter) by default, treats all white-space
8924: characters as delimiters.
8925:
1.26 crook 8926: @item format of the control-flow stack:
8927: @cindex control-flow stack, format
8928: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 8929: stack item in cells is given by the constant @code{cs-item-size}. At the
8930: time of this writing, an item consists of a (pointer to a) locals list
8931: (third), an address in the code (second), and a tag for identifying the
8932: item (TOS). The following tags are used: @code{defstart},
8933: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
8934: @code{scopestart}.
8935:
8936: @item conversion of digits > 35
8937: @cindex digits > 35
8938: The characters @code{[\]^_'} are the digits with the decimal value
8939: 36@minus{}41. There is no way to input many of the larger digits.
8940:
8941: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
8942: @cindex @code{EXPECT}, display after end of input
8943: @cindex @code{ACCEPT}, display after end of input
8944: The cursor is moved to the end of the entered string. If the input is
8945: terminated using the @kbd{Return} key, a space is typed.
8946:
8947: @item exception abort sequence of @code{ABORT"}:
8948: @cindex exception abort sequence of @code{ABORT"}
8949: @cindex @code{ABORT"}, exception abort sequence
8950: The error string is stored into the variable @code{"error} and a
8951: @code{-2 throw} is performed.
8952:
8953: @item input line terminator:
8954: @cindex input line terminator
8955: @cindex line terminator on input
1.26 crook 8956: @cindex newline character on input
1.1 anton 8957: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
8958: lines. One of these characters is typically produced when you type the
8959: @kbd{Enter} or @kbd{Return} key.
8960:
8961: @item maximum size of a counted string:
8962: @cindex maximum size of a counted string
8963: @cindex counted string, maximum size
8964: @code{s" /counted-string" environment? drop .}. Currently 255 characters
8965: on all ports, but this may change.
8966:
8967: @item maximum size of a parsed string:
8968: @cindex maximum size of a parsed string
8969: @cindex parsed string, maximum size
8970: Given by the constant @code{/line}. Currently 255 characters.
8971:
8972: @item maximum size of a definition name, in characters:
8973: @cindex maximum size of a definition name, in characters
8974: @cindex name, maximum length
8975: 31
8976:
8977: @item maximum string length for @code{ENVIRONMENT?}, in characters:
8978: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
8979: @cindex @code{ENVIRONMENT?} string length, maximum
8980: 31
8981:
8982: @item method of selecting the user input device:
8983: @cindex user input device, method of selecting
8984: The user input device is the standard input. There is currently no way to
8985: change it from within Gforth. However, the input can typically be
8986: redirected in the command line that starts Gforth.
8987:
8988: @item method of selecting the user output device:
8989: @cindex user output device, method of selecting
8990: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 8991: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
8992: output when the user output device is a terminal, otherwise the output
8993: is buffered.
1.1 anton 8994:
8995: @item methods of dictionary compilation:
8996: What are we expected to document here?
8997:
8998: @item number of bits in one address unit:
8999: @cindex number of bits in one address unit
9000: @cindex address unit, size in bits
9001: @code{s" address-units-bits" environment? drop .}. 8 in all current
9002: ports.
9003:
9004: @item number representation and arithmetic:
9005: @cindex number representation and arithmetic
9006: Processor-dependent. Binary two's complement on all current ports.
9007:
9008: @item ranges for integer types:
9009: @cindex ranges for integer types
9010: @cindex integer types, ranges
9011: Installation-dependent. Make environmental queries for @code{MAX-N},
9012: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
9013: unsigned (and positive) types is 0. The lower bound for signed types on
9014: two's complement and one's complement machines machines can be computed
9015: by adding 1 to the upper bound.
9016:
9017: @item read-only data space regions:
9018: @cindex read-only data space regions
9019: @cindex data-space, read-only regions
9020: The whole Forth data space is writable.
9021:
9022: @item size of buffer at @code{WORD}:
9023: @cindex size of buffer at @code{WORD}
9024: @cindex @code{WORD} buffer size
9025: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
9026: shared with the pictured numeric output string. If overwriting
9027: @code{PAD} is acceptable, it is as large as the remaining dictionary
9028: space, although only as much can be sensibly used as fits in a counted
9029: string.
9030:
9031: @item size of one cell in address units:
9032: @cindex cell size
9033: @code{1 cells .}.
9034:
9035: @item size of one character in address units:
9036: @cindex char size
9037: @code{1 chars .}. 1 on all current ports.
9038:
9039: @item size of the keyboard terminal buffer:
9040: @cindex size of the keyboard terminal buffer
9041: @cindex terminal buffer, size
9042: Varies. You can determine the size at a specific time using @code{lp@@
9043: tib - .}. It is shared with the locals stack and TIBs of files that
9044: include the current file. You can change the amount of space for TIBs
9045: and locals stack at Gforth startup with the command line option
9046: @code{-l}.
9047:
9048: @item size of the pictured numeric output buffer:
9049: @cindex size of the pictured numeric output buffer
9050: @cindex pictured numeric output buffer, size
9051: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
9052: shared with @code{WORD}.
9053:
9054: @item size of the scratch area returned by @code{PAD}:
9055: @cindex size of the scratch area returned by @code{PAD}
9056: @cindex @code{PAD} size
9057: The remainder of dictionary space. @code{unused pad here - - .}.
9058:
9059: @item system case-sensitivity characteristics:
9060: @cindex case-sensitivity characteristics
1.26 crook 9061: Dictionary searches are case-insensitive (except in
1.1 anton 9062: @code{TABLE}s). However, as explained above under @i{character-set
9063: extensions}, the matching for non-ASCII characters is determined by the
9064: locale you are using. In the default @code{C} locale all non-ASCII
9065: characters are matched case-sensitively.
9066:
9067: @item system prompt:
9068: @cindex system prompt
9069: @cindex prompt
9070: @code{ ok} in interpret state, @code{ compiled} in compile state.
9071:
9072: @item division rounding:
9073: @cindex division rounding
9074: installation dependent. @code{s" floored" environment? drop .}. We leave
9075: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
9076: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
9077:
9078: @item values of @code{STATE} when true:
9079: @cindex @code{STATE} values
9080: -1.
9081:
9082: @item values returned after arithmetic overflow:
9083: On two's complement machines, arithmetic is performed modulo
9084: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
9085: arithmetic (with appropriate mapping for signed types). Division by zero
9086: typically results in a @code{-55 throw} (Floating-point unidentified
9087: fault), although a @code{-10 throw} (divide by zero) would be more
9088: appropriate.
9089:
9090: @item whether the current definition can be found after @t{DOES>}:
9091: @cindex @t{DOES>}, visibility of current definition
9092: No.
9093:
9094: @end table
9095:
9096: @c ---------------------------------------------------------------------
9097: @node core-ambcond, core-other, core-idef, The Core Words
9098: @subsection Ambiguous conditions
9099: @c ---------------------------------------------------------------------
9100: @cindex core words, ambiguous conditions
9101: @cindex ambiguous conditions, core words
9102:
9103: @table @i
9104:
9105: @item a name is neither a word nor a number:
9106: @cindex name not found
1.26 crook 9107: @cindex undefined word
1.1 anton 9108: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
9109: preserves the data and FP stack, so you don't lose more work than
9110: necessary.
9111:
9112: @item a definition name exceeds the maximum length allowed:
1.26 crook 9113: @cindex word name too long
1.1 anton 9114: @code{-19 throw} (Word name too long)
9115:
9116: @item addressing a region not inside the various data spaces of the forth system:
9117: @cindex Invalid memory address
9118: The stacks, code space and name space are accessible. Machine code space is
9119: typically readable. Accessing other addresses gives results dependent on
9120: the operating system. On decent systems: @code{-9 throw} (Invalid memory
9121: address).
9122:
9123: @item argument type incompatible with parameter:
1.26 crook 9124: @cindex argument type mismatch
1.1 anton 9125: This is usually not caught. Some words perform checks, e.g., the control
9126: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
9127: mismatch).
9128:
9129: @item attempting to obtain the execution token of a word with undefined execution semantics:
9130: @cindex Interpreting a compile-only word, for @code{'} etc.
9131: @cindex execution token of words with undefined execution semantics
9132: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
9133: get an execution token for @code{compile-only-error} (which performs a
9134: @code{-14 throw} when executed).
9135:
9136: @item dividing by zero:
9137: @cindex dividing by zero
9138: @cindex floating point unidentified fault, integer division
1.24 anton 9139: On better platforms, this produces a @code{-10 throw} (Division by
9140: zero); on other systems, this typically results in a @code{-55 throw}
9141: (Floating-point unidentified fault).
1.1 anton 9142:
9143: @item insufficient data stack or return stack space:
9144: @cindex insufficient data stack or return stack space
9145: @cindex stack overflow
1.26 crook 9146: @cindex address alignment exception, stack overflow
1.1 anton 9147: @cindex Invalid memory address, stack overflow
9148: Depending on the operating system, the installation, and the invocation
9149: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 9150: it is not checked. If it is checked, you typically get a @code{-3 throw}
9151: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
9152: throw} (Invalid memory address) (depending on the platform and how you
9153: achieved the overflow) as soon as the overflow happens. If it is not
9154: checked, overflows typically result in mysterious illegal memory
9155: accesses, producing @code{-9 throw} (Invalid memory address) or
9156: @code{-23 throw} (Address alignment exception); they might also destroy
9157: the internal data structure of @code{ALLOCATE} and friends, resulting in
9158: various errors in these words.
1.1 anton 9159:
9160: @item insufficient space for loop control parameters:
9161: @cindex insufficient space for loop control parameters
9162: like other return stack overflows.
9163:
9164: @item insufficient space in the dictionary:
9165: @cindex insufficient space in the dictionary
9166: @cindex dictionary overflow
1.12 anton 9167: If you try to allot (either directly with @code{allot}, or indirectly
9168: with @code{,}, @code{create} etc.) more memory than available in the
9169: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
9170: to access memory beyond the end of the dictionary, the results are
9171: similar to stack overflows.
1.1 anton 9172:
9173: @item interpreting a word with undefined interpretation semantics:
9174: @cindex interpreting a word with undefined interpretation semantics
9175: @cindex Interpreting a compile-only word
9176: For some words, we have defined interpretation semantics. For the
9177: others: @code{-14 throw} (Interpreting a compile-only word).
9178:
9179: @item modifying the contents of the input buffer or a string literal:
9180: @cindex modifying the contents of the input buffer or a string literal
9181: These are located in writable memory and can be modified.
9182:
9183: @item overflow of the pictured numeric output string:
9184: @cindex overflow of the pictured numeric output string
9185: @cindex pictured numeric output string, overflow
1.24 anton 9186: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 9187:
9188: @item parsed string overflow:
9189: @cindex parsed string overflow
9190: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
9191:
9192: @item producing a result out of range:
9193: @cindex result out of range
9194: On two's complement machines, arithmetic is performed modulo
9195: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
9196: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 9197: typically results in a @code{-10 throw} (divide by zero) or @code{-55
9198: throw} (floating point unidentified fault). @code{convert} and
9199: @code{>number} currently overflow silently.
1.1 anton 9200:
9201: @item reading from an empty data or return stack:
9202: @cindex stack empty
9203: @cindex stack underflow
1.24 anton 9204: @cindex return stack underflow
1.1 anton 9205: The data stack is checked by the outer (aka text) interpreter after
9206: every word executed. If it has underflowed, a @code{-4 throw} (Stack
9207: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 9208: depending on operating system, installation, and invocation. If they are
9209: caught by a check, they typically result in @code{-4 throw} (Stack
9210: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
9211: (Invalid memory address), depending on the platform and which stack
9212: underflows and by how much. Note that even if the system uses checking
9213: (through the MMU), your program may have to underflow by a significant
9214: number of stack items to trigger the reaction (the reason for this is
9215: that the MMU, and therefore the checking, works with a page-size
9216: granularity). If there is no checking, the symptoms resulting from an
9217: underflow are similar to those from an overflow. Unbalanced return
9218: stack errors result in a variaty of symptoms, including @code{-9 throw}
9219: (Invalid memory address) and Illegal Instruction (typically @code{-260
9220: throw}).
1.1 anton 9221:
9222: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
9223: @cindex unexpected end of the input buffer
9224: @cindex zero-length string as a name
9225: @cindex Attempt to use zero-length string as a name
9226: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
9227: use zero-length string as a name). Words like @code{'} probably will not
9228: find what they search. Note that it is possible to create zero-length
9229: names with @code{nextname} (should it not?).
9230:
9231: @item @code{>IN} greater than input buffer:
9232: @cindex @code{>IN} greater than input buffer
9233: The next invocation of a parsing word returns a string with length 0.
9234:
9235: @item @code{RECURSE} appears after @code{DOES>}:
9236: @cindex @code{RECURSE} appears after @code{DOES>}
9237: Compiles a recursive call to the defining word, not to the defined word.
9238:
9239: @item argument input source different than current input source for @code{RESTORE-INPUT}:
9240: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 9241: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 9242: @cindex @code{RESTORE-INPUT}, Argument type mismatch
9243: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
9244: the end of the file was reached), its source-id may be
9245: reused. Therefore, restoring an input source specification referencing a
9246: closed file may lead to unpredictable results instead of a @code{-12
9247: THROW}.
9248:
9249: In the future, Gforth may be able to restore input source specifications
9250: from other than the current input source.
9251:
9252: @item data space containing definitions gets de-allocated:
9253: @cindex data space containing definitions gets de-allocated
9254: Deallocation with @code{allot} is not checked. This typically results in
9255: memory access faults or execution of illegal instructions.
9256:
9257: @item data space read/write with incorrect alignment:
9258: @cindex data space read/write with incorrect alignment
9259: @cindex alignment faults
1.26 crook 9260: @cindex address alignment exception
1.1 anton 9261: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 9262: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 9263: alignment turned on, incorrect alignment results in a @code{-9 throw}
9264: (Invalid memory address). There are reportedly some processors with
1.12 anton 9265: alignment restrictions that do not report violations.
1.1 anton 9266:
9267: @item data space pointer not properly aligned, @code{,}, @code{C,}:
9268: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
9269: Like other alignment errors.
9270:
9271: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
9272: Like other stack underflows.
9273:
9274: @item loop control parameters not available:
9275: @cindex loop control parameters not available
9276: Not checked. The counted loop words simply assume that the top of return
9277: stack items are loop control parameters and behave accordingly.
9278:
9279: @item most recent definition does not have a name (@code{IMMEDIATE}):
9280: @cindex most recent definition does not have a name (@code{IMMEDIATE})
9281: @cindex last word was headerless
9282: @code{abort" last word was headerless"}.
9283:
9284: @item name not defined by @code{VALUE} used by @code{TO}:
9285: @cindex name not defined by @code{VALUE} used by @code{TO}
9286: @cindex @code{TO} on non-@code{VALUE}s
9287: @cindex Invalid name argument, @code{TO}
9288: @code{-32 throw} (Invalid name argument) (unless name is a local or was
9289: defined by @code{CONSTANT}; in the latter case it just changes the constant).
9290:
9291: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
9292: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 9293: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 9294: @code{-13 throw} (Undefined word)
9295:
9296: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
9297: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
9298: Gforth behaves as if they were of the same type. I.e., you can predict
9299: the behaviour by interpreting all parameters as, e.g., signed.
9300:
9301: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
9302: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
9303: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
9304: compilation semantics of @code{TO}.
9305:
9306: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 9307: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 9308: @cindex @code{WORD}, string overflow
9309: Not checked. The string will be ok, but the count will, of course,
9310: contain only the least significant bits of the length.
9311:
9312: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
9313: @cindex @code{LSHIFT}, large shift counts
9314: @cindex @code{RSHIFT}, large shift counts
9315: Processor-dependent. Typical behaviours are returning 0 and using only
9316: the low bits of the shift count.
9317:
9318: @item word not defined via @code{CREATE}:
9319: @cindex @code{>BODY} of non-@code{CREATE}d words
9320: @code{>BODY} produces the PFA of the word no matter how it was defined.
9321:
9322: @cindex @code{DOES>} of non-@code{CREATE}d words
9323: @code{DOES>} changes the execution semantics of the last defined word no
9324: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
9325: @code{CREATE , DOES>}.
9326:
9327: @item words improperly used outside @code{<#} and @code{#>}:
9328: Not checked. As usual, you can expect memory faults.
9329:
9330: @end table
9331:
9332:
9333: @c ---------------------------------------------------------------------
9334: @node core-other, , core-ambcond, The Core Words
9335: @subsection Other system documentation
9336: @c ---------------------------------------------------------------------
9337: @cindex other system documentation, core words
9338: @cindex core words, other system documentation
9339:
9340: @table @i
9341: @item nonstandard words using @code{PAD}:
9342: @cindex @code{PAD} use by nonstandard words
9343: None.
9344:
9345: @item operator's terminal facilities available:
9346: @cindex operator's terminal facilities available
9347: After processing the command line, Gforth goes into interactive mode,
9348: and you can give commands to Gforth interactively. The actual facilities
9349: available depend on how you invoke Gforth.
9350:
9351: @item program data space available:
9352: @cindex program data space available
9353: @cindex data space available
9354: @code{UNUSED .} gives the remaining dictionary space. The total
9355: dictionary space can be specified with the @code{-m} switch
9356: (@pxref{Invoking Gforth}) when Gforth starts up.
9357:
9358: @item return stack space available:
9359: @cindex return stack space available
9360: You can compute the total return stack space in cells with
9361: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
9362: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
9363:
9364: @item stack space available:
9365: @cindex stack space available
9366: You can compute the total data stack space in cells with
9367: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
9368: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
9369:
9370: @item system dictionary space required, in address units:
9371: @cindex system dictionary space required, in address units
9372: Type @code{here forthstart - .} after startup. At the time of this
9373: writing, this gives 80080 (bytes) on a 32-bit system.
9374: @end table
9375:
9376:
9377: @c =====================================================================
9378: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
9379: @section The optional Block word set
9380: @c =====================================================================
9381: @cindex system documentation, block words
9382: @cindex block words, system documentation
9383:
9384: @menu
9385: * block-idef:: Implementation Defined Options
9386: * block-ambcond:: Ambiguous Conditions
9387: * block-other:: Other System Documentation
9388: @end menu
9389:
9390:
9391: @c ---------------------------------------------------------------------
9392: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
9393: @subsection Implementation Defined Options
9394: @c ---------------------------------------------------------------------
9395: @cindex implementation-defined options, block words
9396: @cindex block words, implementation-defined options
9397:
9398: @table @i
9399: @item the format for display by @code{LIST}:
9400: @cindex @code{LIST} display format
9401: First the screen number is displayed, then 16 lines of 64 characters,
9402: each line preceded by the line number.
9403:
9404: @item the length of a line affected by @code{\}:
9405: @cindex length of a line affected by @code{\}
9406: @cindex @code{\}, line length in blocks
9407: 64 characters.
9408: @end table
9409:
9410:
9411: @c ---------------------------------------------------------------------
9412: @node block-ambcond, block-other, block-idef, The optional Block word set
9413: @subsection Ambiguous conditions
9414: @c ---------------------------------------------------------------------
9415: @cindex block words, ambiguous conditions
9416: @cindex ambiguous conditions, block words
9417:
9418: @table @i
9419: @item correct block read was not possible:
9420: @cindex block read not possible
9421: Typically results in a @code{throw} of some OS-derived value (between
9422: -512 and -2048). If the blocks file was just not long enough, blanks are
9423: supplied for the missing portion.
9424:
9425: @item I/O exception in block transfer:
9426: @cindex I/O exception in block transfer
9427: @cindex block transfer, I/O exception
9428: Typically results in a @code{throw} of some OS-derived value (between
9429: -512 and -2048).
9430:
9431: @item invalid block number:
9432: @cindex invalid block number
9433: @cindex block number invalid
9434: @code{-35 throw} (Invalid block number)
9435:
9436: @item a program directly alters the contents of @code{BLK}:
9437: @cindex @code{BLK}, altering @code{BLK}
9438: The input stream is switched to that other block, at the same
9439: position. If the storing to @code{BLK} happens when interpreting
9440: non-block input, the system will get quite confused when the block ends.
9441:
9442: @item no current block buffer for @code{UPDATE}:
9443: @cindex @code{UPDATE}, no current block buffer
9444: @code{UPDATE} has no effect.
9445:
9446: @end table
9447:
9448: @c ---------------------------------------------------------------------
9449: @node block-other, , block-ambcond, The optional Block word set
9450: @subsection Other system documentation
9451: @c ---------------------------------------------------------------------
9452: @cindex other system documentation, block words
9453: @cindex block words, other system documentation
9454:
9455: @table @i
9456: @item any restrictions a multiprogramming system places on the use of buffer addresses:
9457: No restrictions (yet).
9458:
9459: @item the number of blocks available for source and data:
9460: depends on your disk space.
9461:
9462: @end table
9463:
9464:
9465: @c =====================================================================
9466: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
9467: @section The optional Double Number word set
9468: @c =====================================================================
9469: @cindex system documentation, double words
9470: @cindex double words, system documentation
9471:
9472: @menu
9473: * double-ambcond:: Ambiguous Conditions
9474: @end menu
9475:
9476:
9477: @c ---------------------------------------------------------------------
9478: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
9479: @subsection Ambiguous conditions
9480: @c ---------------------------------------------------------------------
9481: @cindex double words, ambiguous conditions
9482: @cindex ambiguous conditions, double words
9483:
9484: @table @i
1.29 crook 9485: @item @i{d} outside of range of @i{n} in @code{D>S}:
9486: @cindex @code{D>S}, @i{d} out of range of @i{n}
9487: The least significant cell of @i{d} is produced.
1.1 anton 9488:
9489: @end table
9490:
9491:
9492: @c =====================================================================
9493: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
9494: @section The optional Exception word set
9495: @c =====================================================================
9496: @cindex system documentation, exception words
9497: @cindex exception words, system documentation
9498:
9499: @menu
9500: * exception-idef:: Implementation Defined Options
9501: @end menu
9502:
9503:
9504: @c ---------------------------------------------------------------------
9505: @node exception-idef, , The optional Exception word set, The optional Exception word set
9506: @subsection Implementation Defined Options
9507: @c ---------------------------------------------------------------------
9508: @cindex implementation-defined options, exception words
9509: @cindex exception words, implementation-defined options
9510:
9511: @table @i
9512: @item @code{THROW}-codes used in the system:
9513: @cindex @code{THROW}-codes used in the system
9514: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 9515: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 9516: codes -512@minus{}-2047 are used for OS errors (for file and memory
9517: allocation operations). The mapping from OS error numbers to throw codes
9518: is -512@minus{}@code{errno}. One side effect of this mapping is that
9519: undefined OS errors produce a message with a strange number; e.g.,
9520: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
9521: @end table
9522:
9523: @c =====================================================================
9524: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
9525: @section The optional Facility word set
9526: @c =====================================================================
9527: @cindex system documentation, facility words
9528: @cindex facility words, system documentation
9529:
9530: @menu
9531: * facility-idef:: Implementation Defined Options
9532: * facility-ambcond:: Ambiguous Conditions
9533: @end menu
9534:
9535:
9536: @c ---------------------------------------------------------------------
9537: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
9538: @subsection Implementation Defined Options
9539: @c ---------------------------------------------------------------------
9540: @cindex implementation-defined options, facility words
9541: @cindex facility words, implementation-defined options
9542:
9543: @table @i
9544: @item encoding of keyboard events (@code{EKEY}):
9545: @cindex keyboard events, encoding in @code{EKEY}
9546: @cindex @code{EKEY}, encoding of keyboard events
9547: Not yet implemented.
9548:
9549: @item duration of a system clock tick:
9550: @cindex duration of a system clock tick
9551: @cindex clock tick duration
9552: System dependent. With respect to @code{MS}, the time is specified in
9553: microseconds. How well the OS and the hardware implement this, is
9554: another question.
9555:
9556: @item repeatability to be expected from the execution of @code{MS}:
9557: @cindex repeatability to be expected from the execution of @code{MS}
9558: @cindex @code{MS}, repeatability to be expected
9559: System dependent. On Unix, a lot depends on load. If the system is
9560: lightly loaded, and the delay is short enough that Gforth does not get
9561: swapped out, the performance should be acceptable. Under MS-DOS and
9562: other single-tasking systems, it should be good.
9563:
9564: @end table
9565:
9566:
9567: @c ---------------------------------------------------------------------
9568: @node facility-ambcond, , facility-idef, The optional Facility word set
9569: @subsection Ambiguous conditions
9570: @c ---------------------------------------------------------------------
9571: @cindex facility words, ambiguous conditions
9572: @cindex ambiguous conditions, facility words
9573:
9574: @table @i
9575: @item @code{AT-XY} can't be performed on user output device:
9576: @cindex @code{AT-XY} can't be performed on user output device
9577: Largely terminal dependent. No range checks are done on the arguments.
9578: No errors are reported. You may see some garbage appearing, you may see
9579: simply nothing happen.
9580:
9581: @end table
9582:
9583:
9584: @c =====================================================================
9585: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
9586: @section The optional File-Access word set
9587: @c =====================================================================
9588: @cindex system documentation, file words
9589: @cindex file words, system documentation
9590:
9591: @menu
9592: * file-idef:: Implementation Defined Options
9593: * file-ambcond:: Ambiguous Conditions
9594: @end menu
9595:
9596: @c ---------------------------------------------------------------------
9597: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
9598: @subsection Implementation Defined Options
9599: @c ---------------------------------------------------------------------
9600: @cindex implementation-defined options, file words
9601: @cindex file words, implementation-defined options
9602:
9603: @table @i
9604: @item file access methods used:
9605: @cindex file access methods used
9606: @code{R/O}, @code{R/W} and @code{BIN} work as you would
9607: expect. @code{W/O} translates into the C file opening mode @code{w} (or
9608: @code{wb}): The file is cleared, if it exists, and created, if it does
9609: not (with both @code{open-file} and @code{create-file}). Under Unix
9610: @code{create-file} creates a file with 666 permissions modified by your
9611: umask.
9612:
9613: @item file exceptions:
9614: @cindex file exceptions
9615: The file words do not raise exceptions (except, perhaps, memory access
9616: faults when you pass illegal addresses or file-ids).
9617:
9618: @item file line terminator:
9619: @cindex file line terminator
9620: System-dependent. Gforth uses C's newline character as line
9621: terminator. What the actual character code(s) of this are is
9622: system-dependent.
9623:
9624: @item file name format:
9625: @cindex file name format
9626: System dependent. Gforth just uses the file name format of your OS.
9627:
9628: @item information returned by @code{FILE-STATUS}:
9629: @cindex @code{FILE-STATUS}, returned information
9630: @code{FILE-STATUS} returns the most powerful file access mode allowed
9631: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
9632: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
9633: along with the returned mode.
9634:
9635: @item input file state after an exception when including source:
9636: @cindex exception when including source
9637: All files that are left via the exception are closed.
9638:
1.29 crook 9639: @item @i{ior} values and meaning:
9640: @cindex @i{ior} values and meaning
9641: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 9642: intended as throw codes. They typically are in the range
9643: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 9644: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 9645:
9646: @item maximum depth of file input nesting:
9647: @cindex maximum depth of file input nesting
9648: @cindex file input nesting, maximum depth
9649: limited by the amount of return stack, locals/TIB stack, and the number
9650: of open files available. This should not give you troubles.
9651:
9652: @item maximum size of input line:
9653: @cindex maximum size of input line
9654: @cindex input line size, maximum
9655: @code{/line}. Currently 255.
9656:
9657: @item methods of mapping block ranges to files:
9658: @cindex mapping block ranges to files
9659: @cindex files containing blocks
9660: @cindex blocks in files
9661: By default, blocks are accessed in the file @file{blocks.fb} in the
9662: current working directory. The file can be switched with @code{USE}.
9663:
9664: @item number of string buffers provided by @code{S"}:
9665: @cindex @code{S"}, number of string buffers
9666: 1
9667:
9668: @item size of string buffer used by @code{S"}:
9669: @cindex @code{S"}, size of string buffer
9670: @code{/line}. currently 255.
9671:
9672: @end table
9673:
9674: @c ---------------------------------------------------------------------
9675: @node file-ambcond, , file-idef, The optional File-Access word set
9676: @subsection Ambiguous conditions
9677: @c ---------------------------------------------------------------------
9678: @cindex file words, ambiguous conditions
9679: @cindex ambiguous conditions, file words
9680:
9681: @table @i
9682: @item attempting to position a file outside its boundaries:
9683: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
9684: @code{REPOSITION-FILE} is performed as usual: Afterwards,
9685: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
9686:
9687: @item attempting to read from file positions not yet written:
9688: @cindex reading from file positions not yet written
9689: End-of-file, i.e., zero characters are read and no error is reported.
9690:
1.29 crook 9691: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
9692: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 9693: An appropriate exception may be thrown, but a memory fault or other
9694: problem is more probable.
9695:
1.29 crook 9696: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
9697: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
9698: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
9699: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 9700: thrown.
9701:
9702: @item named file cannot be opened (@code{INCLUDED}):
9703: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 9704: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 9705:
9706: @item requesting an unmapped block number:
9707: @cindex unmapped block numbers
9708: There are no unmapped legal block numbers. On some operating systems,
9709: writing a block with a large number may overflow the file system and
9710: have an error message as consequence.
9711:
9712: @item using @code{source-id} when @code{blk} is non-zero:
9713: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
9714: @code{source-id} performs its function. Typically it will give the id of
9715: the source which loaded the block. (Better ideas?)
9716:
9717: @end table
9718:
9719:
9720: @c =====================================================================
9721: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
9722: @section The optional Floating-Point word set
9723: @c =====================================================================
9724: @cindex system documentation, floating-point words
9725: @cindex floating-point words, system documentation
9726:
9727: @menu
9728: * floating-idef:: Implementation Defined Options
9729: * floating-ambcond:: Ambiguous Conditions
9730: @end menu
9731:
9732:
9733: @c ---------------------------------------------------------------------
9734: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
9735: @subsection Implementation Defined Options
9736: @c ---------------------------------------------------------------------
9737: @cindex implementation-defined options, floating-point words
9738: @cindex floating-point words, implementation-defined options
9739:
9740: @table @i
9741: @item format and range of floating point numbers:
9742: @cindex format and range of floating point numbers
9743: @cindex floating point numbers, format and range
9744: System-dependent; the @code{double} type of C.
9745:
1.29 crook 9746: @item results of @code{REPRESENT} when @i{float} is out of range:
9747: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 9748: System dependent; @code{REPRESENT} is implemented using the C library
9749: function @code{ecvt()} and inherits its behaviour in this respect.
9750:
9751: @item rounding or truncation of floating-point numbers:
9752: @cindex rounding of floating-point numbers
9753: @cindex truncation of floating-point numbers
9754: @cindex floating-point numbers, rounding or truncation
9755: System dependent; the rounding behaviour is inherited from the hosting C
9756: compiler. IEEE-FP-based (i.e., most) systems by default round to
9757: nearest, and break ties by rounding to even (i.e., such that the last
9758: bit of the mantissa is 0).
9759:
9760: @item size of floating-point stack:
9761: @cindex floating-point stack size
9762: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
9763: the floating-point stack (in floats). You can specify this on startup
9764: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
9765:
9766: @item width of floating-point stack:
9767: @cindex floating-point stack width
9768: @code{1 floats}.
9769:
9770: @end table
9771:
9772:
9773: @c ---------------------------------------------------------------------
9774: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
9775: @subsection Ambiguous conditions
9776: @c ---------------------------------------------------------------------
9777: @cindex floating-point words, ambiguous conditions
9778: @cindex ambiguous conditions, floating-point words
9779:
9780: @table @i
9781: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
9782: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
9783: System-dependent. Typically results in a @code{-23 THROW} like other
9784: alignment violations.
9785:
9786: @item @code{f@@} or @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: @cindex @code{f!} used with an address that is not float aligned
9789: System-dependent. Typically results in a @code{-23 THROW} like other
9790: alignment violations.
9791:
9792: @item floating-point result out of range:
9793: @cindex floating-point result out of range
9794: System-dependent. Can result in a @code{-55 THROW} (Floating-point
9795: unidentified fault), or can produce a special value representing, e.g.,
9796: Infinity.
9797:
9798: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
9799: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
9800: System-dependent. Typically results in an alignment fault like other
9801: alignment violations.
9802:
9803: @item @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
9804: @cindex @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
9805: The floating-point number is converted into decimal nonetheless.
9806:
9807: @item Both arguments are equal to zero (@code{FATAN2}):
9808: @cindex @code{FATAN2}, both arguments are equal to zero
9809: System-dependent. @code{FATAN2} is implemented using the C library
9810: function @code{atan2()}.
9811:
1.29 crook 9812: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
9813: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
9814: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 9815: because of small errors and the tan will be a very large (or very small)
9816: but finite number.
9817:
1.29 crook 9818: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
9819: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 9820: The result is rounded to the nearest float.
9821:
9822: @item dividing by zero:
9823: @cindex dividing by zero, floating-point
9824: @cindex floating-point dividing by zero
9825: @cindex floating-point unidentified fault, FP divide-by-zero
9826: @code{-55 throw} (Floating-point unidentified fault)
9827:
9828: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
9829: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
9830: System dependent. On IEEE-FP based systems the number is converted into
9831: an infinity.
9832:
1.29 crook 9833: @item @i{float}<1 (@code{FACOSH}):
9834: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 9835: @cindex floating-point unidentified fault, @code{FACOSH}
9836: @code{-55 throw} (Floating-point unidentified fault)
9837:
1.29 crook 9838: @item @i{float}=<-1 (@code{FLNP1}):
9839: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 9840: @cindex floating-point unidentified fault, @code{FLNP1}
9841: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29 crook 9842: negative infinity is typically produced for @i{float}=-1.
1.1 anton 9843:
1.29 crook 9844: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
9845: @cindex @code{FLN}, @i{float}=<0
9846: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 9847: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
9848: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29 crook 9849: negative infinity is typically produced for @i{float}=0.
1.1 anton 9850:
1.29 crook 9851: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
9852: @cindex @code{FASINH}, @i{float}<0
9853: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 9854: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
9855: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
9856: produces values for these inputs on my Linux box (Bug in the C library?)
9857:
1.29 crook 9858: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
9859: @cindex @code{FACOS}, |@i{float}|>1
9860: @cindex @code{FASIN}, |@i{float}|>1
9861: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 9862: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
9863: @code{-55 throw} (Floating-point unidentified fault).
9864:
1.29 crook 9865: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
9866: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 9867: @cindex floating-point unidentified fault, @code{F>D}
9868: @code{-55 throw} (Floating-point unidentified fault).
9869:
9870: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
9871: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
9872: This does not happen.
9873: @end table
9874:
9875: @c =====================================================================
9876: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
9877: @section The optional Locals word set
9878: @c =====================================================================
9879: @cindex system documentation, locals words
9880: @cindex locals words, system documentation
9881:
9882: @menu
9883: * locals-idef:: Implementation Defined Options
9884: * locals-ambcond:: Ambiguous Conditions
9885: @end menu
9886:
9887:
9888: @c ---------------------------------------------------------------------
9889: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
9890: @subsection Implementation Defined Options
9891: @c ---------------------------------------------------------------------
9892: @cindex implementation-defined options, locals words
9893: @cindex locals words, implementation-defined options
9894:
9895: @table @i
9896: @item maximum number of locals in a definition:
9897: @cindex maximum number of locals in a definition
9898: @cindex locals, maximum number in a definition
9899: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
9900: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
9901: characters. The number of locals in a definition is bounded by the size
9902: of locals-buffer, which contains the names of the locals.
9903:
9904: @end table
9905:
9906:
9907: @c ---------------------------------------------------------------------
9908: @node locals-ambcond, , locals-idef, The optional Locals word set
9909: @subsection Ambiguous conditions
9910: @c ---------------------------------------------------------------------
9911: @cindex locals words, ambiguous conditions
9912: @cindex ambiguous conditions, locals words
9913:
9914: @table @i
9915: @item executing a named local in interpretation state:
9916: @cindex local in interpretation state
9917: @cindex Interpreting a compile-only word, for a local
9918: Locals have no interpretation semantics. If you try to perform the
9919: interpretation semantics, you will get a @code{-14 throw} somewhere
9920: (Interpreting a compile-only word). If you perform the compilation
9921: semantics, the locals access will be compiled (irrespective of state).
9922:
1.29 crook 9923: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 9924: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
9925: @cindex @code{TO} on non-@code{VALUE}s and non-locals
9926: @cindex Invalid name argument, @code{TO}
9927: @code{-32 throw} (Invalid name argument)
9928:
9929: @end table
9930:
9931:
9932: @c =====================================================================
9933: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
9934: @section The optional Memory-Allocation word set
9935: @c =====================================================================
9936: @cindex system documentation, memory-allocation words
9937: @cindex memory-allocation words, system documentation
9938:
9939: @menu
9940: * memory-idef:: Implementation Defined Options
9941: @end menu
9942:
9943:
9944: @c ---------------------------------------------------------------------
9945: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
9946: @subsection Implementation Defined Options
9947: @c ---------------------------------------------------------------------
9948: @cindex implementation-defined options, memory-allocation words
9949: @cindex memory-allocation words, implementation-defined options
9950:
9951: @table @i
1.29 crook 9952: @item values and meaning of @i{ior}:
9953: @cindex @i{ior} values and meaning
9954: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 9955: intended as throw codes. They typically are in the range
9956: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 9957: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 9958:
9959: @end table
9960:
9961: @c =====================================================================
9962: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
9963: @section The optional Programming-Tools word set
9964: @c =====================================================================
9965: @cindex system documentation, programming-tools words
9966: @cindex programming-tools words, system documentation
9967:
9968: @menu
9969: * programming-idef:: Implementation Defined Options
9970: * programming-ambcond:: Ambiguous Conditions
9971: @end menu
9972:
9973:
9974: @c ---------------------------------------------------------------------
9975: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
9976: @subsection Implementation Defined Options
9977: @c ---------------------------------------------------------------------
9978: @cindex implementation-defined options, programming-tools words
9979: @cindex programming-tools words, implementation-defined options
9980:
9981: @table @i
9982: @item ending sequence for input following @code{;CODE} and @code{CODE}:
9983: @cindex @code{;CODE} ending sequence
9984: @cindex @code{CODE} ending sequence
9985: @code{END-CODE}
9986:
9987: @item manner of processing input following @code{;CODE} and @code{CODE}:
9988: @cindex @code{;CODE}, processing input
9989: @cindex @code{CODE}, processing input
9990: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
9991: the input is processed by the text interpreter, (starting) in interpret
9992: state.
9993:
9994: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
9995: @cindex @code{ASSEMBLER}, search order capability
9996: The ANS Forth search order word set.
9997:
9998: @item source and format of display by @code{SEE}:
9999: @cindex @code{SEE}, source and format of output
10000: The source for @code{see} is the intermediate code used by the inner
10001: interpreter. The current @code{see} tries to output Forth source code
10002: as well as possible.
10003:
10004: @end table
10005:
10006: @c ---------------------------------------------------------------------
10007: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
10008: @subsection Ambiguous conditions
10009: @c ---------------------------------------------------------------------
10010: @cindex programming-tools words, ambiguous conditions
10011: @cindex ambiguous conditions, programming-tools words
10012:
10013: @table @i
10014:
1.21 crook 10015: @item deleting the compilation word list (@code{FORGET}):
10016: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 10017: Not implemented (yet).
10018:
1.29 crook 10019: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
10020: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
10021: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 10022: @cindex control-flow stack underflow
10023: This typically results in an @code{abort"} with a descriptive error
10024: message (may change into a @code{-22 throw} (Control structure mismatch)
10025: in the future). You may also get a memory access error. If you are
10026: unlucky, this ambiguous condition is not caught.
10027:
1.29 crook 10028: @item @i{name} can't be found (@code{FORGET}):
10029: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 10030: Not implemented (yet).
10031:
1.29 crook 10032: @item @i{name} not defined via @code{CREATE}:
10033: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 10034: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
10035: the execution semantics of the last defined word no matter how it was
10036: defined.
10037:
10038: @item @code{POSTPONE} applied to @code{[IF]}:
10039: @cindex @code{POSTPONE} applied to @code{[IF]}
10040: @cindex @code{[IF]} and @code{POSTPONE}
10041: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
10042: equivalent to @code{[IF]}.
10043:
10044: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
10045: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
10046: Continue in the same state of conditional compilation in the next outer
10047: input source. Currently there is no warning to the user about this.
10048:
10049: @item removing a needed definition (@code{FORGET}):
10050: @cindex @code{FORGET}, removing a needed definition
10051: Not implemented (yet).
10052:
10053: @end table
10054:
10055:
10056: @c =====================================================================
10057: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
10058: @section The optional Search-Order word set
10059: @c =====================================================================
10060: @cindex system documentation, search-order words
10061: @cindex search-order words, system documentation
10062:
10063: @menu
10064: * search-idef:: Implementation Defined Options
10065: * search-ambcond:: Ambiguous Conditions
10066: @end menu
10067:
10068:
10069: @c ---------------------------------------------------------------------
10070: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
10071: @subsection Implementation Defined Options
10072: @c ---------------------------------------------------------------------
10073: @cindex implementation-defined options, search-order words
10074: @cindex search-order words, implementation-defined options
10075:
10076: @table @i
10077: @item maximum number of word lists in search order:
10078: @cindex maximum number of word lists in search order
10079: @cindex search order, maximum depth
10080: @code{s" wordlists" environment? drop .}. Currently 16.
10081:
10082: @item minimum search order:
10083: @cindex minimum search order
10084: @cindex search order, minimum
10085: @code{root root}.
10086:
10087: @end table
10088:
10089: @c ---------------------------------------------------------------------
10090: @node search-ambcond, , search-idef, The optional Search-Order word set
10091: @subsection Ambiguous conditions
10092: @c ---------------------------------------------------------------------
10093: @cindex search-order words, ambiguous conditions
10094: @cindex ambiguous conditions, search-order words
10095:
10096: @table @i
1.21 crook 10097: @item changing the compilation word list (during compilation):
10098: @cindex changing the compilation word list (during compilation)
10099: @cindex compilation word list, change before definition ends
10100: The word is entered into the word list that was the compilation word list
1.1 anton 10101: at the start of the definition. Any changes to the name field (e.g.,
10102: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
10103: are applied to the latest defined word (as reported by @code{last} or
1.21 crook 10104: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1 anton 10105:
10106: @item search order empty (@code{previous}):
10107: @cindex @code{previous}, search order empty
1.26 crook 10108: @cindex vocstack empty, @code{previous}
1.1 anton 10109: @code{abort" Vocstack empty"}.
10110:
10111: @item too many word lists in search order (@code{also}):
10112: @cindex @code{also}, too many word lists in search order
1.26 crook 10113: @cindex vocstack full, @code{also}
1.1 anton 10114: @code{abort" Vocstack full"}.
10115:
10116: @end table
10117:
10118: @c ***************************************************************
10119: @node Model, Integrating Gforth, ANS conformance, Top
10120: @chapter Model
10121:
10122: This chapter has yet to be written. It will contain information, on
10123: which internal structures you can rely.
10124:
10125: @c ***************************************************************
10126: @node Integrating Gforth, Emacs and Gforth, Model, Top
10127: @chapter Integrating Gforth into C programs
10128:
10129: This is not yet implemented.
10130:
10131: Several people like to use Forth as scripting language for applications
10132: that are otherwise written in C, C++, or some other language.
10133:
10134: The Forth system ATLAST provides facilities for embedding it into
10135: applications; unfortunately it has several disadvantages: most
10136: importantly, it is not based on ANS Forth, and it is apparently dead
10137: (i.e., not developed further and not supported). The facilities
1.21 crook 10138: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 10139: making the switch should not be hard.
10140:
10141: We also tried to design the interface such that it can easily be
10142: implemented by other Forth systems, so that we may one day arrive at a
10143: standardized interface. Such a standard interface would allow you to
10144: replace the Forth system without having to rewrite C code.
10145:
10146: You embed the Gforth interpreter by linking with the library
10147: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
10148: global symbols in this library that belong to the interface, have the
10149: prefix @code{forth_}. (Global symbols that are used internally have the
10150: prefix @code{gforth_}).
10151:
10152: You can include the declarations of Forth types and the functions and
10153: variables of the interface with @code{#include <forth.h>}.
10154:
10155: Types.
10156:
10157: Variables.
10158:
10159: Data and FP Stack pointer. Area sizes.
10160:
10161: functions.
10162:
10163: forth_init(imagefile)
10164: forth_evaluate(string) exceptions?
10165: forth_goto(address) (or forth_execute(xt)?)
10166: forth_continue() (a corountining mechanism)
10167:
10168: Adding primitives.
10169:
10170: No checking.
10171:
10172: Signals?
10173:
10174: Accessing the Stacks
10175:
1.26 crook 10176: @c ******************************************************************
1.1 anton 10177: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
10178: @chapter Emacs and Gforth
10179: @cindex Emacs and Gforth
10180:
10181: @cindex @file{gforth.el}
10182: @cindex @file{forth.el}
10183: @cindex Rydqvist, Goran
10184: @cindex comment editing commands
10185: @cindex @code{\}, editing with Emacs
10186: @cindex debug tracer editing commands
10187: @cindex @code{~~}, removal with Emacs
10188: @cindex Forth mode in Emacs
10189: Gforth comes with @file{gforth.el}, an improved version of
10190: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 10191: improvements are:
10192:
10193: @itemize @bullet
10194: @item
10195: A better (but still not perfect) handling of indentation.
10196: @item
10197: Comment paragraph filling (@kbd{M-q})
10198: @item
10199: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
10200: @item
10201: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
10202: @end itemize
10203:
10204: I left the stuff I do not use alone, even though some of it only makes
10205: sense for TILE. To get a description of these features, enter Forth mode
10206: and type @kbd{C-h m}.
1.1 anton 10207:
10208: @cindex source location of error or debugging output in Emacs
10209: @cindex error output, finding the source location in Emacs
10210: @cindex debugging output, finding the source location in Emacs
10211: In addition, Gforth supports Emacs quite well: The source code locations
10212: given in error messages, debugging output (from @code{~~}) and failed
10213: assertion messages are in the right format for Emacs' compilation mode
10214: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
10215: Manual}) so the source location corresponding to an error or other
10216: message is only a few keystrokes away (@kbd{C-x `} for the next error,
10217: @kbd{C-c C-c} for the error under the cursor).
10218:
10219: @cindex @file{TAGS} file
10220: @cindex @file{etags.fs}
10221: @cindex viewing the source of a word in Emacs
1.26 crook 10222: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file will
10223: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 10224: contains the definitions of all words defined afterwards. You can then
10225: find the source for a word using @kbd{M-.}. Note that emacs can use
10226: several tags files at the same time (e.g., one for the Gforth sources
10227: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
10228: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
10229: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
10230: @file{/usr/local/share/gforth/0.2.0/TAGS}).
10231:
10232: @cindex @file{.emacs}
10233: To get all these benefits, add the following lines to your @file{.emacs}
10234: file:
10235:
10236: @example
10237: (autoload 'forth-mode "gforth.el")
10238: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
10239: @end example
10240:
1.26 crook 10241: @c ******************************************************************
1.1 anton 10242: @node Image Files, Engine, Emacs and Gforth, Top
10243: @chapter Image Files
1.26 crook 10244: @cindex image file
10245: @cindex @file{.fi} files
1.1 anton 10246: @cindex precompiled Forth code
10247: @cindex dictionary in persistent form
10248: @cindex persistent form of dictionary
10249:
10250: An image file is a file containing an image of the Forth dictionary,
10251: i.e., compiled Forth code and data residing in the dictionary. By
10252: convention, we use the extension @code{.fi} for image files.
10253:
10254: @menu
1.18 anton 10255: * Image Licensing Issues:: Distribution terms for images.
10256: * Image File Background:: Why have image files?
1.29 crook 10257: * Non-Relocatable Image Files:: don't always work.
1.18 anton 10258: * Data-Relocatable Image Files:: are better.
1.29 crook 10259: * Fully Relocatable Image Files:: better yet.
1.18 anton 10260: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 10261: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 10262: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 10263: @end menu
10264:
1.18 anton 10265: @node Image Licensing Issues, Image File Background, Image Files, Image Files
10266: @section Image Licensing Issues
10267: @cindex license for images
10268: @cindex image license
10269:
10270: An image created with @code{gforthmi} (@pxref{gforthmi}) or
10271: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
10272: original image; i.e., according to copyright law it is a derived work of
10273: the original image.
10274:
10275: Since Gforth is distributed under the GNU GPL, the newly created image
10276: falls under the GNU GPL, too. In particular, this means that if you
10277: distribute the image, you have to make all of the sources for the image
10278: available, including those you wrote. For details see @ref{License, ,
10279: GNU General Public License (Section 3)}.
10280:
10281: If you create an image with @code{cross} (@pxref{cross.fs}), the image
10282: contains only code compiled from the sources you gave it; if none of
10283: these sources is under the GPL, the terms discussed above do not apply
10284: to the image. However, if your image needs an engine (a gforth binary)
10285: that is under the GPL, you should make sure that you distribute both in
10286: a way that is at most a @emph{mere aggregation}, if you don't want the
10287: terms of the GPL to apply to the image.
10288:
10289: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 10290: @section Image File Background
10291: @cindex image file background
10292:
10293: Our Forth system consists not only of primitives, but also of
10294: definitions written in Forth. Since the Forth compiler itself belongs to
10295: those definitions, it is not possible to start the system with the
10296: primitives and the Forth source alone. Therefore we provide the Forth
1.26 crook 10297: code as an image file in nearly executable form. When Gforth starts up,
10298: a C routine loads the image file into memory, optionally relocates the
10299: addresses, then sets up the memory (stacks etc.) according to
10300: information in the image file, and (finally) starts executing Forth
10301: code.
1.1 anton 10302:
10303: The image file variants represent different compromises between the
10304: goals of making it easy to generate image files and making them
10305: portable.
10306:
10307: @cindex relocation at run-time
1.26 crook 10308: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 10309: run-time. This avoids many of the complications discussed below (image
10310: files are data relocatable without further ado), but costs performance
10311: (one addition per memory access).
10312:
10313: @cindex relocation at load-time
1.26 crook 10314: By contrast, the Gforth loader performs relocation at image load time. The
10315: loader also has to replace tokens that represent primitive calls with the
1.1 anton 10316: appropriate code-field addresses (or code addresses in the case of
10317: direct threading).
10318:
10319: There are three kinds of image files, with different degrees of
10320: relocatability: non-relocatable, data-relocatable, and fully relocatable
10321: image files.
10322:
10323: @cindex image file loader
10324: @cindex relocating loader
10325: @cindex loader for image files
10326: These image file variants have several restrictions in common; they are
10327: caused by the design of the image file loader:
10328:
10329: @itemize @bullet
10330: @item
10331: There is only one segment; in particular, this means, that an image file
10332: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 10333: them). The contents of the stacks are not represented, either.
1.1 anton 10334:
10335: @item
10336: The only kinds of relocation supported are: adding the same offset to
10337: all cells that represent data addresses; and replacing special tokens
10338: with code addresses or with pieces of machine code.
10339:
10340: If any complex computations involving addresses are performed, the
10341: results cannot be represented in the image file. Several applications that
10342: use such computations come to mind:
10343: @itemize @minus
10344: @item
10345: Hashing addresses (or data structures which contain addresses) for table
10346: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
10347: purpose, you will have no problem, because the hash tables are
10348: recomputed automatically when the system is started. If you use your own
10349: hash tables, you will have to do something similar.
10350:
10351: @item
10352: There's a cute implementation of doubly-linked lists that uses
10353: @code{XOR}ed addresses. You could represent such lists as singly-linked
10354: in the image file, and restore the doubly-linked representation on
10355: startup.@footnote{In my opinion, though, you should think thrice before
10356: using a doubly-linked list (whatever implementation).}
10357:
10358: @item
10359: The code addresses of run-time routines like @code{docol:} cannot be
10360: represented in the image file (because their tokens would be replaced by
10361: machine code in direct threaded implementations). As a workaround,
10362: compute these addresses at run-time with @code{>code-address} from the
10363: executions tokens of appropriate words (see the definitions of
10364: @code{docol:} and friends in @file{kernel.fs}).
10365:
10366: @item
10367: On many architectures addresses are represented in machine code in some
10368: shifted or mangled form. You cannot put @code{CODE} words that contain
10369: absolute addresses in this form in a relocatable image file. Workarounds
10370: are representing the address in some relative form (e.g., relative to
10371: the CFA, which is present in some register), or loading the address from
10372: a place where it is stored in a non-mangled form.
10373: @end itemize
10374: @end itemize
10375:
10376: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
10377: @section Non-Relocatable Image Files
10378: @cindex non-relocatable image files
1.26 crook 10379: @cindex image file, non-relocatable
1.1 anton 10380:
10381: These files are simple memory dumps of the dictionary. They are specific
10382: to the executable (i.e., @file{gforth} file) they were created
10383: with. What's worse, they are specific to the place on which the
10384: dictionary resided when the image was created. Now, there is no
10385: guarantee that the dictionary will reside at the same place the next
10386: time you start Gforth, so there's no guarantee that a non-relocatable
10387: image will work the next time (Gforth will complain instead of crashing,
10388: though).
10389:
10390: You can create a non-relocatable image file with
10391:
10392: doc-savesystem
10393:
10394: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
10395: @section Data-Relocatable Image Files
10396: @cindex data-relocatable image files
1.26 crook 10397: @cindex image file, data-relocatable
1.1 anton 10398:
10399: These files contain relocatable data addresses, but fixed code addresses
10400: (instead of tokens). They are specific to the executable (i.e.,
10401: @file{gforth} file) they were created with. For direct threading on some
10402: architectures (e.g., the i386), data-relocatable images do not work. You
10403: get a data-relocatable image, if you use @file{gforthmi} with a
10404: Gforth binary that is not doubly indirect threaded (@pxref{Fully
10405: Relocatable Image Files}).
10406:
10407: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
10408: @section Fully Relocatable Image Files
10409: @cindex fully relocatable image files
1.26 crook 10410: @cindex image file, fully relocatable
1.1 anton 10411:
10412: @cindex @file{kern*.fi}, relocatability
10413: @cindex @file{gforth.fi}, relocatability
10414: These image files have relocatable data addresses, and tokens for code
10415: addresses. They can be used with different binaries (e.g., with and
10416: without debugging) on the same machine, and even across machines with
10417: the same data formats (byte order, cell size, floating point
10418: format). However, they are usually specific to the version of Gforth
10419: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
10420: are fully relocatable.
10421:
10422: There are two ways to create a fully relocatable image file:
10423:
10424: @menu
1.29 crook 10425: * gforthmi:: The normal way
1.1 anton 10426: * cross.fs:: The hard way
10427: @end menu
10428:
10429: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
10430: @subsection @file{gforthmi}
10431: @cindex @file{comp-i.fs}
10432: @cindex @file{gforthmi}
10433:
10434: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 10435: image @i{file} that contains everything you would load by invoking
10436: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 10437: @example
1.29 crook 10438: gforthmi @i{file} @i{options}
1.1 anton 10439: @end example
10440:
10441: E.g., if you want to create an image @file{asm.fi} that has the file
10442: @file{asm.fs} loaded in addition to the usual stuff, you could do it
10443: like this:
10444:
10445: @example
10446: gforthmi asm.fi asm.fs
10447: @end example
10448:
1.27 crook 10449: @file{gforthmi} is implemented as a sh script and works like this: It
10450: produces two non-relocatable images for different addresses and then
10451: compares them. Its output reflects this: first you see the output (if
10452: any) of the two Gforth invocations that produce the nonrelocatable image
10453: files, then you see the output of the comparing program: It displays the
10454: offset used for data addresses and the offset used for code addresses;
1.1 anton 10455: moreover, for each cell that cannot be represented correctly in the
10456: image files, it displays a line like the following one:
10457:
10458: @example
10459: 78DC BFFFFA50 BFFFFA40
10460: @end example
10461:
10462: This means that at offset $78dc from @code{forthstart}, one input image
10463: contains $bffffa50, and the other contains $bffffa40. Since these cells
10464: cannot be represented correctly in the output image, you should examine
10465: these places in the dictionary and verify that these cells are dead
10466: (i.e., not read before they are written).
10467:
1.27 crook 10468: If you type @file{gforthmi} with no arguments, it prints some usage
10469: instructions.
10470:
1.1 anton 10471: @cindex @code{savesystem} during @file{gforthmi}
10472: @cindex @code{bye} during @file{gforthmi}
10473: @cindex doubly indirect threaded code
10474: @cindex environment variable @code{GFORTHD}
10475: @cindex @code{GFORTHD} environment variable
10476: @cindex @code{gforth-ditc}
1.29 crook 10477: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 10478: words @code{savesystem} and @code{bye} must be visible. A special doubly
10479: indirect threaded version of the @file{gforth} executable is used for
10480: creating the nonrelocatable images; you can pass the exact filename of
10481: this executable through the environment variable @code{GFORTHD}
10482: (default: @file{gforth-ditc}); if you pass a version that is not doubly
10483: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 10484: data-relocatable image (because there is no code address offset). The
10485: normal @file{gforth} executable is used for creating the relocatable
10486: image; you can pass the exact filename of this executable through the
10487: environment variable @code{GFORTH}.
1.1 anton 10488:
10489: @node cross.fs, , gforthmi, Fully Relocatable Image Files
10490: @subsection @file{cross.fs}
10491: @cindex @file{cross.fs}
10492: @cindex cross-compiler
10493: @cindex metacompiler
10494:
10495: You can also use @code{cross}, a batch compiler that accepts a Forth-like
10496: programming language. This @code{cross} language has to be documented
10497: yet.
10498:
10499: @cindex target compiler
10500: @code{cross} also allows you to create image files for machines with
10501: different data sizes and data formats than the one used for generating
10502: the image file. You can also use it to create an application image that
10503: does not contain a Forth compiler. These features are bought with
10504: restrictions and inconveniences in programming. E.g., addresses have to
10505: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
10506: order to make the code relocatable.
10507:
10508:
10509: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
10510: @section Stack and Dictionary Sizes
10511: @cindex image file, stack and dictionary sizes
10512: @cindex dictionary size default
10513: @cindex stack size default
10514:
10515: If you invoke Gforth with a command line flag for the size
10516: (@pxref{Invoking Gforth}), the size you specify is stored in the
10517: dictionary. If you save the dictionary with @code{savesystem} or create
10518: an image with @file{gforthmi}, this size will become the default
10519: for the resulting image file. E.g., the following will create a
1.21 crook 10520: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 10521:
10522: @example
10523: gforthmi gforth.fi -m 1M
10524: @end example
10525:
10526: In other words, if you want to set the default size for the dictionary
10527: and the stacks of an image, just invoke @file{gforthmi} with the
10528: appropriate options when creating the image.
10529:
10530: @cindex stack size, cache-friendly
10531: Note: For cache-friendly behaviour (i.e., good performance), you should
10532: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
10533: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
10534: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
10535:
10536: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
10537: @section Running Image Files
10538: @cindex running image files
10539: @cindex invoking image files
10540: @cindex image file invocation
10541:
10542: @cindex -i, invoke image file
10543: @cindex --image file, invoke image file
1.29 crook 10544: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 10545: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
10546: @example
1.29 crook 10547: gforth -i @i{image}
1.1 anton 10548: @end example
10549:
10550: @cindex executable image file
1.26 crook 10551: @cindex image file, executable
1.1 anton 10552: If your operating system supports starting scripts with a line of the
10553: form @code{#! ...}, you just have to type the image file name to start
10554: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 10555: just a convention). I.e., to run Gforth with the image file @i{image},
10556: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 10557: This works because every @code{.fi} file starts with a line of this
10558: format:
10559:
10560: @example
10561: #! /usr/local/bin/gforth-0.4.0 -i
10562: @end example
10563:
10564: The file and pathname for the Gforth engine specified on this line is
10565: the specific Gforth executable that it was built against; i.e. the value
10566: of the environment variable @code{GFORTH} at the time that
10567: @file{gforthmi} was executed.
1.1 anton 10568:
1.27 crook 10569: You can make use of the same shell capability to make a Forth source
10570: file into an executable. For example, if you place this text in a file:
1.26 crook 10571:
10572: @example
10573: #! /usr/local/bin/gforth
10574:
10575: ." Hello, world" CR
10576: bye
10577: @end example
10578:
10579: @noindent
1.27 crook 10580: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 10581: directly from the command line. The sequence @code{#!} is used in two
10582: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 10583: system@footnote{The Unix kernel actually recognises two types of files:
10584: executable files and files of data, where the data is processed by an
10585: interpreter that is specified on the ``interpreter line'' -- the first
10586: line of the file, starting with the sequence #!. There may be a small
10587: limit (e.g., 32) on the number of characters that may be specified on
10588: the interpreter line.} secondly it is treated as a comment character by
10589: Gforth. Because of the second usage, a space is required between
10590: @code{#!} and the path to the executable.
1.27 crook 10591:
10592: The disadvantage of this latter technique, compared with using
10593: @file{gforthmi}, is that it is slower; the Forth source code is compiled
10594: on-the-fly, each time the program is invoked.
10595:
1.26 crook 10596: @comment TODO describe the #! magic with reference to the Power Tools book.
10597:
1.1 anton 10598: doc-#!
10599:
10600: @node Modifying the Startup Sequence, , Running Image Files, Image Files
10601: @section Modifying the Startup Sequence
10602: @cindex startup sequence for image file
10603: @cindex image file initialization sequence
10604: @cindex initialization sequence of image file
10605:
10606: You can add your own initialization to the startup sequence through the
1.26 crook 10607: deferred word @code{'cold}. @code{'cold} is invoked just before the
10608: image-specific command line processing (by default, loading files and
10609: evaluating (@code{-e}) strings) starts.
1.1 anton 10610:
10611: A sequence for adding your initialization usually looks like this:
10612:
10613: @example
10614: :noname
10615: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
10616: ... \ your stuff
10617: ; IS 'cold
10618: @end example
10619:
10620: @cindex turnkey image files
1.26 crook 10621: @cindex image file, turnkey applications
1.1 anton 10622: You can make a turnkey image by letting @code{'cold} execute a word
10623: (your turnkey application) that never returns; instead, it exits Gforth
10624: via @code{bye} or @code{throw}.
10625:
10626: @cindex command-line arguments, access
10627: @cindex arguments on the command line, access
10628: You can access the (image-specific) command-line arguments through the
1.26 crook 10629: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1 anton 10630: access to @code{argv}.
10631:
1.26 crook 10632: If @code{'cold} exits normally, Gforth processes the command-line
10633: arguments as files to be loaded and strings to be evaluated. Therefore,
10634: @code{'cold} should remove the arguments it has used in this case.
10635:
10636: doc-'cold
1.1 anton 10637: doc-argc
10638: doc-argv
10639: doc-arg
10640:
10641:
10642: @c ******************************************************************
1.13 pazsan 10643: @node Engine, Binding to System Library, Image Files, Top
1.1 anton 10644: @chapter Engine
10645: @cindex engine
10646: @cindex virtual machine
10647:
1.26 crook 10648: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 10649: may be helpful for finding your way in the Gforth sources.
10650:
10651: The ideas in this section have also been published in the papers
10652: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
10653: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
10654: Ertl, presented at EuroForth '93; the latter is available at
10655: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
10656:
10657: @menu
10658: * Portability::
10659: * Threading::
10660: * Primitives::
10661: * Performance::
10662: @end menu
10663:
10664: @node Portability, Threading, Engine, Engine
10665: @section Portability
10666: @cindex engine portability
10667:
1.26 crook 10668: An important goal of the Gforth Project is availability across a wide
10669: range of personal machines. fig-Forth, and, to a lesser extent, F83,
10670: achieved this goal by manually coding the engine in assembly language
10671: for several then-popular processors. This approach is very
10672: labor-intensive and the results are short-lived due to progress in
10673: computer architecture.
1.1 anton 10674:
10675: @cindex C, using C for the engine
10676: Others have avoided this problem by coding in C, e.g., Mitch Bradley
10677: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
10678: particularly popular for UNIX-based Forths due to the large variety of
10679: architectures of UNIX machines. Unfortunately an implementation in C
10680: does not mix well with the goals of efficiency and with using
10681: traditional techniques: Indirect or direct threading cannot be expressed
10682: in C, and switch threading, the fastest technique available in C, is
10683: significantly slower. Another problem with C is that it is very
10684: cumbersome to express double integer arithmetic.
10685:
10686: @cindex GNU C for the engine
10687: @cindex long long
10688: Fortunately, there is a portable language that does not have these
10689: limitations: GNU C, the version of C processed by the GNU C compiler
10690: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
10691: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
10692: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
10693: threading possible, its @code{long long} type (@pxref{Long Long, ,
10694: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
10695: double numbers@footnote{Unfortunately, long longs are not implemented
10696: properly on all machines (e.g., on alpha-osf1, long longs are only 64
10697: bits, the same size as longs (and pointers), but they should be twice as
1.4 anton 10698: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1 anton 10699: C Manual}). So, we had to implement doubles in C after all. Still, on
10700: most machines we can use long longs and achieve better performance than
10701: with the emulation package.}. GNU C is available for free on all
10702: important (and many unimportant) UNIX machines, VMS, 80386s running
10703: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
10704: on all these machines.
10705:
10706: Writing in a portable language has the reputation of producing code that
10707: is slower than assembly. For our Forth engine we repeatedly looked at
10708: the code produced by the compiler and eliminated most compiler-induced
10709: inefficiencies by appropriate changes in the source code.
10710:
10711: @cindex explicit register declarations
10712: @cindex --enable-force-reg, configuration flag
10713: @cindex -DFORCE_REG
10714: However, register allocation cannot be portably influenced by the
10715: programmer, leading to some inefficiencies on register-starved
10716: machines. We use explicit register declarations (@pxref{Explicit Reg
10717: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
10718: improve the speed on some machines. They are turned on by using the
10719: configuration flag @code{--enable-force-reg} (@code{gcc} switch
10720: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
10721: machine, but also on the compiler version: On some machines some
10722: compiler versions produce incorrect code when certain explicit register
10723: declarations are used. So by default @code{-DFORCE_REG} is not used.
10724:
10725: @node Threading, Primitives, Portability, Engine
10726: @section Threading
10727: @cindex inner interpreter implementation
10728: @cindex threaded code implementation
10729:
10730: @cindex labels as values
10731: GNU C's labels as values extension (available since @code{gcc-2.0},
10732: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 10733: makes it possible to take the address of @i{label} by writing
10734: @code{&&@i{label}}. This address can then be used in a statement like
10735: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 10736: @code{goto x}.
10737:
1.26 crook 10738: @cindex @code{NEXT}, indirect threaded
1.1 anton 10739: @cindex indirect threaded inner interpreter
10740: @cindex inner interpreter, indirect threaded
1.26 crook 10741: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 10742: @example
10743: cfa = *ip++;
10744: ca = *cfa;
10745: goto *ca;
10746: @end example
10747: @cindex instruction pointer
10748: For those unfamiliar with the names: @code{ip} is the Forth instruction
10749: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
10750: execution token and points to the code field of the next word to be
10751: executed; The @code{ca} (code address) fetched from there points to some
10752: executable code, e.g., a primitive or the colon definition handler
10753: @code{docol}.
10754:
1.26 crook 10755: @cindex @code{NEXT}, direct threaded
1.1 anton 10756: @cindex direct threaded inner interpreter
10757: @cindex inner interpreter, direct threaded
10758: Direct threading is even simpler:
10759: @example
10760: ca = *ip++;
10761: goto *ca;
10762: @end example
10763:
10764: Of course we have packaged the whole thing neatly in macros called
1.26 crook 10765: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 10766:
10767: @menu
10768: * Scheduling::
10769: * Direct or Indirect Threaded?::
10770: * DOES>::
10771: @end menu
10772:
10773: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
10774: @subsection Scheduling
10775: @cindex inner interpreter optimization
10776:
10777: There is a little complication: Pipelined and superscalar processors,
10778: i.e., RISC and some modern CISC machines can process independent
10779: instructions while waiting for the results of an instruction. The
10780: compiler usually reorders (schedules) the instructions in a way that
10781: achieves good usage of these delay slots. However, on our first tries
10782: the compiler did not do well on scheduling primitives. E.g., for
10783: @code{+} implemented as
10784: @example
10785: n=sp[0]+sp[1];
10786: sp++;
10787: sp[0]=n;
10788: NEXT;
10789: @end example
1.26 crook 10790: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1 anton 10791: scheduling. After a little thought the problem becomes clear: The
1.21 crook 10792: compiler cannot know that @code{sp} and @code{ip} point to different
10793: addresses (and the version of @code{gcc} we used would not know it even
10794: if it was possible), so it could not move the load of the cfa above the
10795: store to the TOS. Indeed the pointers could be the same, if code on or
10796: very near the top of stack were executed. In the interest of speed we
10797: chose to forbid this probably unused ``feature'' and helped the compiler
1.26 crook 10798: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21 crook 10799: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1 anton 10800: @example
10801: n=sp[0]+sp[1];
10802: sp++;
10803: NEXT_P1;
10804: sp[0]=n;
10805: NEXT_P2;
10806: @end example
10807: This can be scheduled optimally by the compiler.
10808:
10809: This division can be turned off with the switch @code{-DCISC_NEXT}. This
10810: switch is on by default on machines that do not profit from scheduling
10811: (e.g., the 80386), in order to preserve registers.
10812:
10813: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
10814: @subsection Direct or Indirect Threaded?
10815: @cindex threading, direct or indirect?
10816:
10817: @cindex -DDIRECT_THREADED
10818: Both! After packaging the nasty details in macro definitions we
10819: realized that we could switch between direct and indirect threading by
10820: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
10821: defining a few machine-specific macros for the direct-threading case.
10822: On the Forth level we also offer access words that hide the
10823: differences between the threading methods (@pxref{Threading Words}).
10824:
10825: Indirect threading is implemented completely machine-independently.
10826: Direct threading needs routines for creating jumps to the executable
1.21 crook 10827: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
10828: machine-dependent, but they do not amount to many source lines. Therefore,
10829: even porting direct threading to a new machine requires little effort.
1.1 anton 10830:
10831: @cindex --enable-indirect-threaded, configuration flag
10832: @cindex --enable-direct-threaded, configuration flag
10833: The default threading method is machine-dependent. You can enforce a
10834: specific threading method when building Gforth with the configuration
10835: flag @code{--enable-direct-threaded} or
10836: @code{--enable-indirect-threaded}. Note that direct threading is not
10837: supported on all machines.
10838:
10839: @node DOES>, , Direct or Indirect Threaded?, Threading
10840: @subsection DOES>
10841: @cindex @code{DOES>} implementation
10842:
1.26 crook 10843: @cindex @code{dodoes} routine
10844: @cindex @code{DOES>}-code
1.1 anton 10845: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
10846: the chunk of code executed by every word defined by a
10847: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
10848: the Forth code to be executed, i.e. the code after the
1.26 crook 10849: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1 anton 10850:
1.21 crook 10851: In fig-Forth the code field points directly to the @code{dodoes} and the
1.26 crook 10852: @code{DOES>}code address is stored in the cell after the code address (i.e. at
1.29 crook 10853: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1 anton 10854: the Forth-79 and all later standards, because in fig-Forth this address
10855: lies in the body (which is illegal in these standards). However, by
10856: making the code field larger for all words this solution becomes legal
10857: again. We use this approach for the indirect threaded version and for
10858: direct threading on some machines. Leaving a cell unused in most words
10859: is a bit wasteful, but on the machines we are targeting this is hardly a
10860: problem. The other reason for having a code field size of two cells is
10861: to avoid having different image files for direct and indirect threaded
10862: systems (direct threaded systems require two-cell code fields on many
10863: machines).
10864:
1.26 crook 10865: @cindex @code{DOES>}-handler
1.1 anton 10866: The other approach is that the code field points or jumps to the cell
1.26 crook 10867: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
10868: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
10869: @code{DOES>}-code address by computing the code address, i.e., the address of
1.1 anton 10870: the jump to dodoes, and add the length of that jump field. A variant of
10871: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
10872: return address (which can be found in the return register on RISCs) is
1.26 crook 10873: the @code{DOES>}-code address. Since the two cells available in the code field
1.1 anton 10874: are used up by the jump to the code address in direct threading on many
10875: architectures, we use this approach for direct threading on these
10876: architectures. We did not want to add another cell to the code field.
10877:
10878: @node Primitives, Performance, Threading, Engine
10879: @section Primitives
10880: @cindex primitives, implementation
10881: @cindex virtual machine instructions, implementation
10882:
10883: @menu
10884: * Automatic Generation::
10885: * TOS Optimization::
10886: * Produced code::
10887: @end menu
10888:
10889: @node Automatic Generation, TOS Optimization, Primitives, Primitives
10890: @subsection Automatic Generation
10891: @cindex primitives, automatic generation
10892:
10893: @cindex @file{prims2x.fs}
10894: Since the primitives are implemented in a portable language, there is no
10895: longer any need to minimize the number of primitives. On the contrary,
10896: having many primitives has an advantage: speed. In order to reduce the
10897: number of errors in primitives and to make programming them easier, we
10898: provide a tool, the primitive generator (@file{prims2x.fs}), that
10899: automatically generates most (and sometimes all) of the C code for a
10900: primitive from the stack effect notation. The source for a primitive
10901: has the following form:
10902:
10903: @cindex primitive source format
10904: @format
1.29 crook 10905: @i{Forth-name} @i{stack-effect} @i{category} [@i{pronounc.}]
10906: [@code{""}@i{glossary entry}@code{""}]
10907: @i{C code}
1.1 anton 10908: [@code{:}
1.29 crook 10909: @i{Forth code}]
1.1 anton 10910: @end format
10911:
10912: The items in brackets are optional. The category and glossary fields
10913: are there for generating the documentation, the Forth code is there
10914: for manual implementations on machines without GNU C. E.g., the source
10915: for the primitive @code{+} is:
10916: @example
10917: + n1 n2 -- n core plus
10918: n = n1+n2;
10919: @end example
10920:
10921: This looks like a specification, but in fact @code{n = n1+n2} is C
10922: code. Our primitive generation tool extracts a lot of information from
10923: the stack effect notations@footnote{We use a one-stack notation, even
10924: though we have separate data and floating-point stacks; The separate
10925: notation can be generated easily from the unified notation.}: The number
10926: of items popped from and pushed on the stack, their type, and by what
10927: name they are referred to in the C code. It then generates a C code
10928: prelude and postlude for each primitive. The final C code for @code{+}
10929: looks like this:
10930:
10931: @example
10932: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
10933: /* */ /* documentation */
10934: @{
10935: DEF_CA /* definition of variable ca (indirect threading) */
10936: Cell n1; /* definitions of variables */
10937: Cell n2;
10938: Cell n;
10939: n1 = (Cell) sp[1]; /* input */
10940: n2 = (Cell) TOS;
10941: sp += 1; /* stack adjustment */
10942: NAME("+") /* debugging output (with -DDEBUG) */
10943: @{
10944: n = n1+n2; /* C code taken from the source */
10945: @}
10946: NEXT_P1; /* NEXT part 1 */
10947: TOS = (Cell)n; /* output */
10948: NEXT_P2; /* NEXT part 2 */
10949: @}
10950: @end example
10951:
10952: This looks long and inefficient, but the GNU C compiler optimizes quite
10953: well and produces optimal code for @code{+} on, e.g., the R3000 and the
10954: HP RISC machines: Defining the @code{n}s does not produce any code, and
10955: using them as intermediate storage also adds no cost.
10956:
1.26 crook 10957: There are also other optimizations that are not illustrated by this
10958: example: assignments between simple variables are usually for free (copy
1.1 anton 10959: propagation). If one of the stack items is not used by the primitive
10960: (e.g. in @code{drop}), the compiler eliminates the load from the stack
10961: (dead code elimination). On the other hand, there are some things that
10962: the compiler does not do, therefore they are performed by
10963: @file{prims2x.fs}: The compiler does not optimize code away that stores
10964: a stack item to the place where it just came from (e.g., @code{over}).
10965:
10966: While programming a primitive is usually easy, there are a few cases
10967: where the programmer has to take the actions of the generator into
10968: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 10969: fall through to @code{NEXT}.
1.1 anton 10970:
10971: @node TOS Optimization, Produced code, Automatic Generation, Primitives
10972: @subsection TOS Optimization
10973: @cindex TOS optimization for primitives
10974: @cindex primitives, keeping the TOS in a register
10975:
10976: An important optimization for stack machine emulators, e.g., Forth
10977: engines, is keeping one or more of the top stack items in
1.29 crook 10978: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
10979: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 10980: @itemize @bullet
10981: @item
1.29 crook 10982: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 10983: due to fewer loads from and stores to the stack.
1.29 crook 10984: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
10985: @i{y<n}, due to additional moves between registers.
1.1 anton 10986: @end itemize
10987:
10988: @cindex -DUSE_TOS
10989: @cindex -DUSE_NO_TOS
10990: In particular, keeping one item in a register is never a disadvantage,
10991: if there are enough registers. Keeping two items in registers is a
10992: disadvantage for frequent words like @code{?branch}, constants,
10993: variables, literals and @code{i}. Therefore our generator only produces
10994: code that keeps zero or one items in registers. The generated C code
10995: covers both cases; the selection between these alternatives is made at
10996: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
10997: code for @code{+} is just a simple variable name in the one-item case,
10998: otherwise it is a macro that expands into @code{sp[0]}. Note that the
10999: GNU C compiler tries to keep simple variables like @code{TOS} in
11000: registers, and it usually succeeds, if there are enough registers.
11001:
11002: @cindex -DUSE_FTOS
11003: @cindex -DUSE_NO_FTOS
11004: The primitive generator performs the TOS optimization for the
11005: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
11006: operations the benefit of this optimization is even larger:
11007: floating-point operations take quite long on most processors, but can be
11008: performed in parallel with other operations as long as their results are
11009: not used. If the FP-TOS is kept in a register, this works. If
11010: it is kept on the stack, i.e., in memory, the store into memory has to
11011: wait for the result of the floating-point operation, lengthening the
11012: execution time of the primitive considerably.
11013:
11014: The TOS optimization makes the automatic generation of primitives a
11015: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
11016: @code{TOS} is not sufficient. There are some special cases to
11017: consider:
11018: @itemize @bullet
11019: @item In the case of @code{dup ( w -- w w )} the generator must not
11020: eliminate the store to the original location of the item on the stack,
11021: if the TOS optimization is turned on.
11022: @item Primitives with stack effects of the form @code{--}
1.29 crook 11023: @i{out1}...@i{outy} must store the TOS to the stack at the start.
11024: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 11025: must load the TOS from the stack at the end. But for the null stack
11026: effect @code{--} no stores or loads should be generated.
11027: @end itemize
11028:
11029: @node Produced code, , TOS Optimization, Primitives
11030: @subsection Produced code
11031: @cindex primitives, assembly code listing
11032:
11033: @cindex @file{engine.s}
11034: To see what assembly code is produced for the primitives on your machine
11035: with your compiler and your flag settings, type @code{make engine.s} and
11036: look at the resulting file @file{engine.s}.
11037:
11038: @node Performance, , Primitives, Engine
11039: @section Performance
11040: @cindex performance of some Forth interpreters
11041: @cindex engine performance
11042: @cindex benchmarking Forth systems
11043: @cindex Gforth performance
11044:
11045: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
11046: impossible to write a significantly faster engine.
11047:
11048: On register-starved machines like the 386 architecture processors
11049: improvements are possible, because @code{gcc} does not utilize the
11050: registers as well as a human, even with explicit register declarations;
11051: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
11052: and hand-tuned it for the 486; this system is 1.19 times faster on the
11053: Sieve benchmark on a 486DX2/66 than Gforth compiled with
11054: @code{gcc-2.6.3} with @code{-DFORCE_REG}.
11055:
11056: @cindex Win32Forth performance
11057: @cindex NT Forth performance
11058: @cindex eforth performance
11059: @cindex ThisForth performance
11060: @cindex PFE performance
11061: @cindex TILE performance
11062: However, this potential advantage of assembly language implementations
11063: is not necessarily realized in complete Forth systems: We compared
11064: Gforth (direct threaded, compiled with @code{gcc-2.6.3} and
11065: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
11066: 1994) and Eforth (with and without peephole (aka pinhole) optimization
11067: of the threaded code); all these systems were written in assembly
11068: language. We also compared Gforth with three systems written in C:
11069: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
11070: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21 crook 11071: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
11072: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1 anton 11073: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
11074: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
11075: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
11076: 486DX2/66 with similar memory performance under Windows NT. Marcel
11077: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
11078: added the peephole optimizer, ran the benchmarks and reported the
11079: results.
11080:
11081: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
11082: matrix multiplication come from the Stanford integer benchmarks and have
11083: been translated into Forth by Martin Fraeman; we used the versions
11084: included in the TILE Forth package, but with bigger data set sizes; and
11085: a recursive Fibonacci number computation for benchmarking calling
11086: performance. The following table shows the time taken for the benchmarks
11087: scaled by the time taken by Gforth (in other words, it shows the speedup
11088: factor that Gforth achieved over the other systems).
11089:
11090: @example
11091: relative Win32- NT eforth This-
11092: time Gforth Forth Forth eforth +opt PFE Forth TILE
11093: sieve 1.00 1.39 1.14 1.39 0.85 1.58 3.18 8.58
11094: bubble 1.00 1.31 1.41 1.48 0.88 1.50 3.88
11095: matmul 1.00 1.47 1.35 1.46 0.74 1.58 4.09
11096: fib 1.00 1.52 1.34 1.22 0.86 1.74 2.99 4.30
11097: @end example
11098:
1.26 crook 11099: You may be quite surprised by the good performance of Gforth when
11100: compared with systems written in assembly language. One important reason
11101: for the disappointing performance of these other systems is probably
11102: that they are not written optimally for the 486 (e.g., they use the
11103: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
11104: but costly method for relocating the Forth image: like @code{cforth}, it
11105: computes the actual addresses at run time, resulting in two address
11106: computations per @code{NEXT} (@pxref{Image File Background}).
11107:
11108: Only Eforth with the peephole optimizer has a performance that is
11109: comparable to Gforth. The speedups achieved with peephole optimization
11110: of threaded code are quite remarkable. Adding a peephole optimizer to
11111: Gforth should cause similar speedups.
1.1 anton 11112:
11113: The speedup of Gforth over PFE, ThisForth and TILE can be easily
11114: explained with the self-imposed restriction of the latter systems to
11115: standard C, which makes efficient threading impossible (however, the
1.4 anton 11116: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 11117: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
11118: Moreover, current C compilers have a hard time optimizing other aspects
11119: of the ThisForth and the TILE source.
11120:
1.26 crook 11121: The performance of Gforth on 386 architecture processors varies widely
11122: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
11123: allocate any of the virtual machine registers into real machine
11124: registers by itself and would not work correctly with explicit register
11125: declarations, giving a 1.3 times slower engine (on a 486DX2/66 running
11126: the Sieve) than the one measured above.
1.1 anton 11127:
1.26 crook 11128: Note that there have been several releases of Win32Forth since the
11129: release presented here, so the results presented above may have little
1.1 anton 11130: predictive value for the performance of Win32Forth today.
11131:
11132: @cindex @file{Benchres}
11133: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
11134: Maierhofer (presented at EuroForth '95), an indirect threaded version of
11135: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
11136: version of Gforth is 2%@minus{}8% slower on a 486 than the direct
11137: threaded version used here. The paper available at
11138: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
11139: it also contains numbers for some native code systems. You can find a
11140: newer version of these measurements at
11141: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
11142: find numbers for Gforth on various machines in @file{Benchres}.
11143:
1.26 crook 11144: @c ******************************************************************
1.13 pazsan 11145: @node Binding to System Library, Cross Compiler, Engine, Top
1.14 pazsan 11146: @chapter Binding to System Library
1.13 pazsan 11147:
11148: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14 pazsan 11149: @chapter Cross Compiler
1.13 pazsan 11150:
11151: Cross Compiler
11152:
11153: @menu
11154: * Using the Cross Compiler::
11155: * How the Cross Compiler Works::
11156: @end menu
11157:
1.21 crook 11158: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 11159: @section Using the Cross Compiler
1.13 pazsan 11160:
1.21 crook 11161: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 11162: @section How the Cross Compiler Works
1.13 pazsan 11163:
11164: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 11165: @appendix Bugs
1.1 anton 11166: @cindex bug reporting
11167:
1.21 crook 11168: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 11169:
11170: If you find a bug, please send a bug report to
1.21 crook 11171: @email{bug-gforth@@gnu.ai.mit.edu}. A bug report should include this
11172: information:
11173:
11174: @itemize @bullet
11175: @item
11176: The Gforth version used (it is announced at the start of an
11177: interactive Gforth session).
11178: @item
11179: The machine and operating system (on Unix
11180: systems @code{uname -a} will report this information).
11181: @item
11182: The installation options (send the file @file{config.status}).
11183: @item
11184: A complete list of changes (if any) you (or your installer) have made to the
11185: Gforth sources.
11186: @item
11187: A program (or a sequence of keyboard commands) that reproduces the bug.
11188: @item
11189: A description of what you think constitutes the buggy behaviour.
11190: @end itemize
1.1 anton 11191:
11192: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
11193: to Report Bugs, gcc.info, GNU C Manual}.
11194:
11195:
1.21 crook 11196: @node Origin, Forth-related information, Bugs, Top
11197: @appendix Authors and Ancestors of Gforth
1.1 anton 11198:
11199: @section Authors and Contributors
11200: @cindex authors of Gforth
11201: @cindex contributors to Gforth
11202:
11203: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
11204: Ertl. The third major author was Jens Wilke. Lennart Benschop (who was
11205: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
11206: with their continuous feedback. Lennart Benshop contributed
11207: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
11208: support for calling C libraries. Helpful comments also came from Paul
11209: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.12 anton 11210: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
11211: release of Gforth-0.2.1 there were also helpful comments from many
11212: others; thank you all, sorry for not listing you here (but digging
1.23 crook 11213: through my mailbox to extract your names is on my to-do list). Since the
11214: release of Gforth-0.4.0 Neal Crook worked on the manual.
1.1 anton 11215:
11216: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
11217: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 11218: was developed across the Internet, and its authors did not meet
1.20 pazsan 11219: physically for the first 4 years of development.
1.1 anton 11220:
11221: @section Pedigree
1.26 crook 11222: @cindex pedigree of Gforth
1.1 anton 11223:
1.20 pazsan 11224: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1 anton 11225: Dirk Zoller) will cross-fertilize each other. Of course, a significant
11226: part of the design of Gforth was prescribed by ANS Forth.
11227:
1.20 pazsan 11228: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 11229: 32 bit native code version of VolksForth for the Atari ST, written
11230: mostly by Dietrich Weineck.
11231:
11232: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
11233: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
11234: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
11235:
11236: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
11237: Forth-83 standard. !! Pedigree? When?
11238:
11239: A team led by Bill Ragsdale implemented fig-Forth on many processors in
11240: 1979. Robert Selzer and Bill Ragsdale developed the original
11241: implementation of fig-Forth for the 6502 based on microForth.
11242:
11243: The principal architect of microForth was Dean Sanderson. microForth was
11244: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
11245: the 1802, and subsequently implemented on the 8080, the 6800 and the
11246: Z80.
11247:
11248: All earlier Forth systems were custom-made, usually by Charles Moore,
11249: who discovered (as he puts it) Forth during the late 60s. The first full
11250: Forth existed in 1971.
11251:
11252: A part of the information in this section comes from @cite{The Evolution
11253: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
11254: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
11255: Notices 28(3), 1993. You can find more historical and genealogical
11256: information about Forth there.
11257:
1.21 crook 11258: @node Forth-related information, Word Index, Origin, Top
11259: @appendix Other Forth-related information
11260: @cindex Forth-related information
11261:
11262: @menu
11263: * Internet resources::
11264: * Books::
11265: * The Forth Interest Group::
11266: * Conferences::
11267: @end menu
11268:
11269:
11270: @node Internet resources, Books, Forth-related information, Forth-related information
11271: @section Internet resources
1.26 crook 11272: @cindex internet resources
1.21 crook 11273:
11274: @cindex comp.lang.forth
11275: @cindex frequently asked questions
11276: There is an active newsgroup (comp.lang.forth) discussing Forth and
11277: Forth-related issues. A frequently-asked-questions (FAQ) list
11278: is posted to the newsgroup regulary, and archived at these sites:
11279:
11280: @itemize @bullet
11281: @item
11282: @url{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
11283: @item
11284: @url{ftp://ftp.forth.org/pub/Forth/FAQ/}
11285: @end itemize
11286:
11287: The FAQ list should be considered mandatory reading before posting to
11288: the newsgroup.
11289:
11290: Here are some other web sites holding Forth-related material:
11291:
11292: @itemize @bullet
11293: @item
11294: @url{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
11295: @item
11296: @url{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
11297: @item
11298: @url{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
11299: @item
11300: @url{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
11301: Research page, including links to the Journal of Forth Application and
11302: Research (JFAR) and a searchable Forth bibliography.
11303: @end itemize
11304:
11305:
11306: @node Books, The Forth Interest Group, Internet resources, Forth-related information
11307: @section Books
1.26 crook 11308: @cindex books on Forth
1.21 crook 11309:
11310: As the Standard is relatively new, there are not many books out yet. It
11311: is not recommended to learn Forth by using Gforth and a book that is not
11312: written for ANS Forth, as you will not know your mistakes from the
11313: deviations of the book. However, books based on the Forth-83 standard
11314: should be ok, because ANS Forth is primarily an extension of Forth-83.
11315:
11316: @cindex standard document for ANS Forth
11317: @cindex ANS Forth document
11318: The definite reference if you want to write ANS Forth programs is, of
1.26 crook 11319: course, the ANS Forth document. It is available in printed form from the
1.21 crook 11320: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
11321: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
11322: $200. You can also get it from Global Engineering Documents (Tel.: USA
11323: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
11324:
11325: @cite{dpANS6}, the last draft of the standard, which was then submitted
11326: to ANSI for publication is available electronically and for free in some
11327: MS Word format, and it has been converted to HTML
11328: (@url{http://www.taygeta.com/forth/dpans.html}; this is my favourite
11329: format); this HTML version also includes the answers to Requests for
11330: Interpretation (RFIs). Some pointers to these versions can be found
11331: through @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
11332:
1.26 crook 11333: @cindex introductory book on Forth
11334: @cindex book on Forth, introductory
1.21 crook 11335: @cindex Woehr, Jack: @cite{Forth: The New Model}
11336: @cindex @cite{Forth: The new model} (book)
11337: @cite{Forth: The New Model} by Jack Woehr (Prentice-Hall, 1993) is an
11338: introductory book based on a draft version of the standard. It does not
11339: cover the whole standard. It also contains interesting background
11340: information (Jack Woehr was in the ANS Forth Technical Committee). It is
11341: not appropriate for complete newbies, but programmers experienced in
11342: other languages should find it ok.
11343:
11344: @cindex Conklin, Edward K., and Elizabeth Rather: @cite{Forth Programmer's Handbook}
11345: @cindex Rather, Elizabeth and Edward K. Conklin: @cite{Forth Programmer's Handbook}
11346: @cindex @cite{Forth Programmer's Handbook} (book)
11347: @cite{Forth Programmer's Handbook} by Edward K. Conklin, Elizabeth
11348: D. Rather and the technical staff of Forth, Inc. (Forth, Inc., 1997;
11349: ISBN 0-9662156-0-5) contains little introductory material. The majority
11350: of the book is similar to @ref{Words}, but the book covers most of the
11351: standard words and some non-standard words (whereas this manual is
11352: quite incomplete). In addition, the book contains a chapter on
11353: programming style. The major drawback of this book is that it usually
11354: does not identify what is standard and what is specific to the Forth
11355: system described in the book (probably one of Forth, Inc.'s systems).
11356: Fortunately, many of the non-standard programming practices described in
11357: the book work in Gforth, too. Still, this drawback makes the book
11358: hardly more useful than a pre-ANS book.
11359:
11360: @node The Forth Interest Group, Conferences, Books, Forth-related information
11361: @section The Forth Interest Group
11362: @cindex Forth interest group (FIG)
11363:
11364: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26 crook 11365: member-supported organisation. It publishes a regular magazine,
11366: @var{FORTH Dimensions}, and offers other benefits of membership. You can
11367: contact the FIG through their office email address:
11368: @email{office@@forth.org} or by visiting their web site at
11369: @url{http://www.forth.org/}. This web site also includes links to FIG
11370: chapters in other countries and American cities
1.21 crook 11371: (@url{http://www.forth.org/chapters.html}).
11372:
11373: @node Conferences, , The Forth Interest Group, Forth-related information
11374: @section Conferences
11375: @cindex Conferences
11376:
11377: There are several regular conferences related to Forth. They are all
1.26 crook 11378: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
11379: news group:
1.21 crook 11380:
11381: @itemize @bullet
11382: @item
11383: FORML -- the Forth modification laboratory convenes every year near
11384: Monterey, California.
11385: @item
11386: The Rochester Forth Conference -- an annual conference traditionally
11387: held in Rochester, New York.
11388: @item
11389: EuroForth -- this European conference takes place annually.
11390: @end itemize
11391:
11392:
11393: @node Word Index, Concept Index, Forth-related information, Top
1.1 anton 11394: @unnumbered Word Index
11395:
1.26 crook 11396: This index is a list of Forth words that have ``glossary'' entries
11397: within this manual. Each word is listed with its stack effect and
11398: wordset.
1.1 anton 11399:
11400: @printindex fn
11401:
11402: @node Concept Index, , Word Index, Top
11403: @unnumbered Concept and Word Index
11404:
1.26 crook 11405: Not all entries listed in this index are present verbatim in the
11406: text. This index also duplicates, in abbreviated form, all of the words
11407: listed in the Word Index (only the names are listed for the words here).
1.1 anton 11408:
11409: @printindex cp
11410:
11411: @contents
11412: @bye
11413:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>