1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
3:
4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
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.
11: @c Not an improvement IMO - anton
12: @c and anyway, this should be taken up
13: @c with Karl Berry (the texinfo guy) - anton
14: @comment .. would be useful to have a word that identified all deferred words
15: @comment should semantics stuff in intro be moved to another section
16:
17: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
18:
19: @comment %**start of header (This is for running Texinfo on a region.)
20: @setfilename gforth.info
21: @settitle Gforth Manual
22: @dircategory GNU programming tools
23: @direntry
24: * Gforth: (gforth). A fast interpreter for the Forth language.
25: @end direntry
26: @c The Texinfo manual also recommends doing this, but for Gforth it may
27: @c not make much sense
28: @c @dircategory Individual utilities
29: @c @direntry
30: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
31: @c @end direntry
32:
33: @comment @setchapternewpage odd
34: @comment TODO this gets left in by HTML converter
35: @macro progstyle {}
36: Programming style note:
37: @end macro
38:
39: @macro assignment {}
40: @table @i
41: @item Assignment:
42: @end macro
43: @macro endassignment {}
44: @end table
45: @end macro
46:
47: @comment %**end of header (This is for running Texinfo on a region.)
48:
49:
50: @comment ----------------------------------------------------------
51: @comment macros for beautifying glossary entries
52: @comment if these are used, need to strip them out for HTML converter
53: @comment else they get repeated verbatim in HTML output.
54: @comment .. not working yet.
55:
56: @macro GLOSS-START {}
57: @iftex
58: @ninerm
59: @end iftex
60: @end macro
61:
62: @macro GLOSS-END {}
63: @iftex
64: @rm
65: @end iftex
66: @end macro
67:
68: @comment ----------------------------------------------------------
69:
70:
71: @include version.texi
72:
73: @ifnottex
74: This file documents Gforth @value{VERSION}
75:
76: Copyright @copyright{} 1995--2000 Free Software Foundation, Inc.
77:
78: Permission is granted to make and distribute verbatim copies of
79: this manual provided the copyright notice and this permission notice
80: are preserved on all copies.
81:
82: @ignore
83: Permission is granted to process this file through TeX and print the
84: results, provided the printed document carries a copying permission
85: notice identical to this one except for the removal of this paragraph
86: (this paragraph not being relevant to the printed manual).
87:
88: @end ignore
89: Permission is granted to copy and distribute modified versions of this
90: manual under the conditions for verbatim copying, provided also that the
91: sections entitled "Distribution" and "General Public License" are
92: included exactly as in the original, and provided that the entire
93: resulting derived work is distributed under the terms of a permission
94: notice identical to this one.
95:
96: Permission is granted to copy and distribute translations of this manual
97: into another language, under the above conditions for modified versions,
98: except that the sections entitled "Distribution" and "General Public
99: License" may be included in a translation approved by the author instead
100: of in the original English.
101: @end ifnottex
102:
103: @finalout
104: @titlepage
105: @sp 10
106: @center @titlefont{Gforth Manual}
107: @sp 2
108: @center for version @value{VERSION}
109: @sp 2
110: @center Neal Crook
111: @center Anton Ertl
112: @center Bernd Paysan
113: @center Jens Wilke
114: @sp 3
115: @center This manual is permanently under construction and was last updated on 15-Mar-2000
116:
117: @comment The following two commands start the copyright page.
118: @page
119: @vskip 0pt plus 1filll
120: Copyright @copyright{} 1995--2000 Free Software Foundation, Inc.
121:
122: @comment !! Published by ... or You can get a copy of this manual ...
123:
124: Permission is granted to make and distribute verbatim copies of
125: this manual provided the copyright notice and this permission notice
126: are preserved on all copies.
127:
128: Permission is granted to copy and distribute modified versions of this
129: manual under the conditions for verbatim copying, provided also that the
130: sections entitled "Distribution" and "General Public License" are
131: included exactly as in the original, and provided that the entire
132: resulting derived work is distributed under the terms of a permission
133: notice identical to this one.
134:
135: Permission is granted to copy and distribute translations of this manual
136: into another language, under the above conditions for modified versions,
137: except that the sections entitled "Distribution" and "General Public
138: License" may be included in a translation approved by the author instead
139: of in the original English.
140: @end titlepage
141:
142: @node Top, License, (dir), (dir)
143: @ifnottex
144: Gforth is a free implementation of ANS Forth available on many
145: personal machines. This manual corresponds to version @value{VERSION}.
146: @end ifnottex
147:
148: @menu
149: * License:: The GPL
150: * Goals:: About the Gforth Project
151: * Gforth Environment:: Starting (and exiting) Gforth
152: * Tutorial:: Hands-on Forth Tutorial
153: * Introduction:: An introduction to ANS Forth
154: * Words:: Forth words available in Gforth
155: * Error messages:: How to interpret them
156: * Tools:: Programming tools
157: * ANS conformance:: Implementation-defined options etc.
158: * Standard vs Extensions:: Should I use extensions?
159: * Model:: The abstract machine of Gforth
160: * Integrating Gforth:: Forth as scripting language for applications
161: * Emacs and Gforth:: The Gforth Mode
162: * Image Files:: @code{.fi} files contain compiled code
163: * Engine:: The inner interpreter and the primitives
164: * Binding to System Library::
165: * Cross Compiler:: The Cross Compiler
166: * Bugs:: How to report them
167: * Origin:: Authors and ancestors of Gforth
168: * Forth-related information:: Books and places to look on the WWW
169: * Word Index:: An item for each Forth word
170: * Concept Index:: A menu covering many topics
171:
172: @detailmenu --- The Detailed Node Listing ---
173:
174: Gforth Environment
175:
176: * Invoking Gforth:: Getting in
177: * Leaving Gforth:: Getting out
178: * Command-line editing::
179: * Environment variables:: that affect how Gforth starts up
180: * Gforth Files:: What gets installed and where
181: * Startup speed:: When 35ms is not fast enough ...
182:
183: Forth Tutorial
184:
185: * Starting Gforth Tutorial::
186: * Syntax Tutorial::
187: * Crash Course Tutorial::
188: * Stack Tutorial::
189: * Arithmetics Tutorial::
190: * Stack Manipulation Tutorial::
191: * Using files for Forth code Tutorial::
192: * Comments Tutorial::
193: * Colon Definitions Tutorial::
194: * Decompilation Tutorial::
195: * Stack-Effect Comments Tutorial::
196: * Types Tutorial::
197: * Factoring Tutorial::
198: * Designing the stack effect Tutorial::
199: * Local Variables Tutorial::
200: * Conditional execution Tutorial::
201: * Flags and Comparisons Tutorial::
202: * General Loops Tutorial::
203: * Counted loops Tutorial::
204: * Recursion Tutorial::
205: * Leaving definitions or loops Tutorial::
206: * Return Stack Tutorial::
207: * Memory Tutorial::
208: * Characters and Strings Tutorial::
209: * Alignment Tutorial::
210: * Files Tutorial::
211: * Interpretation and Compilation Semantics and Immediacy Tutorial::
212: * Execution Tokens Tutorial::
213: * Exceptions Tutorial::
214: * Defining Words Tutorial::
215: * Arrays and Records Tutorial::
216: * POSTPONE Tutorial::
217: * Literal Tutorial::
218: * Advanced macros Tutorial::
219: * Compilation Tokens Tutorial::
220: * Wordlists and Search Order Tutorial::
221:
222: An Introduction to ANS Forth
223:
224: * Introducing the Text Interpreter::
225: * Stacks and Postfix notation::
226: * Your first definition::
227: * How does that work?::
228: * Forth is written in Forth::
229: * Review - elements of a Forth system::
230: * Where to go next::
231: * Exercises::
232:
233: Forth Words
234:
235: * Notation::
236: * Case insensitivity::
237: * Comments::
238: * Boolean Flags::
239: * Arithmetic::
240: * Stack Manipulation::
241: * Memory::
242: * Control Structures::
243: * Defining Words::
244: * Interpretation and Compilation Semantics::
245: * Tokens for Words::
246: * Compiling words::
247: * The Text Interpreter::
248: * Word Lists::
249: * Environmental Queries::
250: * Files::
251: * Blocks::
252: * Other I/O::
253: * Locals::
254: * Structures::
255: * Object-oriented Forth::
256: * Programming Tools::
257: * Assembler and Code Words::
258: * Threading Words::
259: * Passing Commands to the OS::
260: * Keeping track of Time::
261: * Miscellaneous Words::
262:
263: Arithmetic
264:
265: * Single precision::
266: * Double precision:: Double-cell integer arithmetic
267: * Bitwise operations::
268: * Numeric comparison::
269: * Mixed precision:: Operations with single and double-cell integers
270: * Floating Point::
271:
272: Stack Manipulation
273:
274: * Data stack::
275: * Floating point stack::
276: * Return stack::
277: * Locals stack::
278: * Stack pointer manipulation::
279:
280: Memory
281:
282: * Memory model::
283: * Dictionary allocation::
284: * Heap Allocation::
285: * Memory Access::
286: * Address arithmetic::
287: * Memory Blocks::
288:
289: Control Structures
290:
291: * Selection:: IF ... ELSE ... ENDIF
292: * Simple Loops:: BEGIN ...
293: * Counted Loops:: DO
294: * Arbitrary control structures::
295: * Calls and returns::
296: * Exception Handling::
297:
298: Defining Words
299:
300: * CREATE::
301: * Variables:: Variables and user variables
302: * Constants::
303: * Values:: Initialised variables
304: * Colon Definitions::
305: * Anonymous Definitions:: Definitions without names
306: * Supplying names:: Passing definition names as strings
307: * User-defined Defining Words::
308: * Deferred words:: Allow forward references
309: * Aliases::
310:
311: User-defined Defining Words
312:
313: * CREATE..DOES> applications::
314: * CREATE..DOES> details::
315: * Advanced does> usage example::
316:
317: Interpretation and Compilation Semantics
318:
319: * Combined words::
320:
321: Tokens for Words
322:
323: * Execution token:: represents execution/interpretation semantics
324: * Compilation token:: represents compilation semantics
325: * Name token:: represents named words
326:
327: Compiling words
328:
329: * Literals:: Compiling data values
330: * Macros:: Compiling words
331:
332: The Text Interpreter
333:
334: * Input Sources::
335: * Number Conversion::
336: * Interpret/Compile states::
337: * Interpreter Directives::
338:
339: Word Lists
340:
341: * Vocabularies::
342: * Why use word lists?::
343: * Word list example::
344:
345: Files
346:
347: * Forth source files::
348: * General files::
349: * Search Paths::
350:
351: Search Paths
352:
353: * Source Search Paths::
354: * General Search Paths::
355:
356: Other I/O
357:
358: * Simple numeric output:: Predefined formats
359: * Formatted numeric output:: Formatted (pictured) output
360: * String Formats:: How Forth stores strings in memory
361: * Displaying characters and strings:: Other stuff
362: * Input:: Input
363:
364: Locals
365:
366: * Gforth locals::
367: * ANS Forth locals::
368:
369: Gforth locals
370:
371: * Where are locals visible by name?::
372: * How long do locals live?::
373: * Locals programming style::
374: * Locals implementation::
375:
376: Structures
377:
378: * Why explicit structure support?::
379: * Structure Usage::
380: * Structure Naming Convention::
381: * Structure Implementation::
382: * Structure Glossary::
383:
384: Object-oriented Forth
385:
386: * Why object-oriented programming?::
387: * Object-Oriented Terminology::
388: * Objects::
389: * OOF::
390: * Mini-OOF::
391: * Comparison with other object models::
392:
393: The @file{objects.fs} model
394:
395: * Properties of the Objects model::
396: * Basic Objects Usage::
397: * The Objects base class::
398: * Creating objects::
399: * Object-Oriented Programming Style::
400: * Class Binding::
401: * Method conveniences::
402: * Classes and Scoping::
403: * Dividing classes::
404: * Object Interfaces::
405: * Objects Implementation::
406: * Objects Glossary::
407:
408: The @file{oof.fs} model
409:
410: * Properties of the OOF model::
411: * Basic OOF Usage::
412: * The OOF base class::
413: * Class Declaration::
414: * Class Implementation::
415:
416: The @file{mini-oof.fs} model
417:
418: * Basic Mini-OOF Usage::
419: * Mini-OOF Example::
420: * Mini-OOF Implementation::
421:
422: Programming Tools
423:
424: * Examining::
425: * Forgetting words::
426: * Debugging:: Simple and quick.
427: * Assertions:: Making your programs self-checking.
428: * Singlestep Debugger:: Executing your program word by word.
429:
430: Assembler and Code Words
431:
432: * Code and ;code::
433: * Common Assembler:: Assembler Syntax
434: * Common Disassembler::
435: * 386 Assembler:: Deviations and special cases
436: * Alpha Assembler:: Deviations and special cases
437: * MIPS assembler:: Deviations and special cases
438: * Other assemblers:: How to write them
439:
440: Tools
441:
442: * ANS Report:: Report the words used, sorted by wordset.
443:
444: ANS conformance
445:
446: * The Core Words::
447: * The optional Block word set::
448: * The optional Double Number word set::
449: * The optional Exception word set::
450: * The optional Facility word set::
451: * The optional File-Access word set::
452: * The optional Floating-Point word set::
453: * The optional Locals word set::
454: * The optional Memory-Allocation word set::
455: * The optional Programming-Tools word set::
456: * The optional Search-Order word set::
457:
458: The Core Words
459:
460: * core-idef:: Implementation Defined Options
461: * core-ambcond:: Ambiguous Conditions
462: * core-other:: Other System Documentation
463:
464: The optional Block word set
465:
466: * block-idef:: Implementation Defined Options
467: * block-ambcond:: Ambiguous Conditions
468: * block-other:: Other System Documentation
469:
470: The optional Double Number word set
471:
472: * double-ambcond:: Ambiguous Conditions
473:
474: The optional Exception word set
475:
476: * exception-idef:: Implementation Defined Options
477:
478: The optional Facility word set
479:
480: * facility-idef:: Implementation Defined Options
481: * facility-ambcond:: Ambiguous Conditions
482:
483: The optional File-Access word set
484:
485: * file-idef:: Implementation Defined Options
486: * file-ambcond:: Ambiguous Conditions
487:
488: The optional Floating-Point word set
489:
490: * floating-idef:: Implementation Defined Options
491: * floating-ambcond:: Ambiguous Conditions
492:
493: The optional Locals word set
494:
495: * locals-idef:: Implementation Defined Options
496: * locals-ambcond:: Ambiguous Conditions
497:
498: The optional Memory-Allocation word set
499:
500: * memory-idef:: Implementation Defined Options
501:
502: The optional Programming-Tools word set
503:
504: * programming-idef:: Implementation Defined Options
505: * programming-ambcond:: Ambiguous Conditions
506:
507: The optional Search-Order word set
508:
509: * search-idef:: Implementation Defined Options
510: * search-ambcond:: Ambiguous Conditions
511:
512: Image Files
513:
514: * Image Licensing Issues:: Distribution terms for images.
515: * Image File Background:: Why have image files?
516: * Non-Relocatable Image Files:: don't always work.
517: * Data-Relocatable Image Files:: are better.
518: * Fully Relocatable Image Files:: better yet.
519: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
520: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
521: * Modifying the Startup Sequence:: and turnkey applications.
522:
523: Fully Relocatable Image Files
524:
525: * gforthmi:: The normal way
526: * cross.fs:: The hard way
527:
528: Engine
529:
530: * Portability::
531: * Threading::
532: * Primitives::
533: * Performance::
534:
535: Threading
536:
537: * Scheduling::
538: * Direct or Indirect Threaded?::
539: * DOES>::
540:
541: Primitives
542:
543: * Automatic Generation::
544: * TOS Optimization::
545: * Produced code::
546:
547: Cross Compiler
548:
549: * Using the Cross Compiler::
550: * How the Cross Compiler Works::
551:
552: @end detailmenu
553: @end menu
554:
555: @node License, Goals, Top, Top
556: @unnumbered GNU GENERAL PUBLIC LICENSE
557: @center Version 2, June 1991
558:
559: @display
560: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
561: 675 Mass Ave, Cambridge, MA 02139, USA
562:
563: Everyone is permitted to copy and distribute verbatim copies
564: of this license document, but changing it is not allowed.
565: @end display
566:
567: @unnumberedsec Preamble
568:
569: The licenses for most software are designed to take away your
570: freedom to share and change it. By contrast, the GNU General Public
571: License is intended to guarantee your freedom to share and change free
572: software---to make sure the software is free for all its users. This
573: General Public License applies to most of the Free Software
574: Foundation's software and to any other program whose authors commit to
575: using it. (Some other Free Software Foundation software is covered by
576: the GNU Library General Public License instead.) You can apply it to
577: your programs, too.
578:
579: When we speak of free software, we are referring to freedom, not
580: price. Our General Public Licenses are designed to make sure that you
581: have the freedom to distribute copies of free software (and charge for
582: this service if you wish), that you receive source code or can get it
583: if you want it, that you can change the software or use pieces of it
584: in new free programs; and that you know you can do these things.
585:
586: To protect your rights, we need to make restrictions that forbid
587: anyone to deny you these rights or to ask you to surrender the rights.
588: These restrictions translate to certain responsibilities for you if you
589: distribute copies of the software, or if you modify it.
590:
591: For example, if you distribute copies of such a program, whether
592: gratis or for a fee, you must give the recipients all the rights that
593: you have. You must make sure that they, too, receive or can get the
594: source code. And you must show them these terms so they know their
595: rights.
596:
597: We protect your rights with two steps: (1) copyright the software, and
598: (2) offer you this license which gives you legal permission to copy,
599: distribute and/or modify the software.
600:
601: Also, for each author's protection and ours, we want to make certain
602: that everyone understands that there is no warranty for this free
603: software. If the software is modified by someone else and passed on, we
604: want its recipients to know that what they have is not the original, so
605: that any problems introduced by others will not reflect on the original
606: authors' reputations.
607:
608: Finally, any free program is threatened constantly by software
609: patents. We wish to avoid the danger that redistributors of a free
610: program will individually obtain patent licenses, in effect making the
611: program proprietary. To prevent this, we have made it clear that any
612: patent must be licensed for everyone's free use or not licensed at all.
613:
614: The precise terms and conditions for copying, distribution and
615: modification follow.
616:
617: @iftex
618: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
619: @end iftex
620: @ifnottex
621: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
622: @end ifnottex
623:
624: @enumerate 0
625: @item
626: This License applies to any program or other work which contains
627: a notice placed by the copyright holder saying it may be distributed
628: under the terms of this General Public License. The ``Program'', below,
629: refers to any such program or work, and a ``work based on the Program''
630: means either the Program or any derivative work under copyright law:
631: that is to say, a work containing the Program or a portion of it,
632: either verbatim or with modifications and/or translated into another
633: language. (Hereinafter, translation is included without limitation in
634: the term ``modification''.) Each licensee is addressed as ``you''.
635:
636: Activities other than copying, distribution and modification are not
637: covered by this License; they are outside its scope. The act of
638: running the Program is not restricted, and the output from the Program
639: is covered only if its contents constitute a work based on the
640: Program (independent of having been made by running the Program).
641: Whether that is true depends on what the Program does.
642:
643: @item
644: You may copy and distribute verbatim copies of the Program's
645: source code as you receive it, in any medium, provided that you
646: conspicuously and appropriately publish on each copy an appropriate
647: copyright notice and disclaimer of warranty; keep intact all the
648: notices that refer to this License and to the absence of any warranty;
649: and give any other recipients of the Program a copy of this License
650: along with the Program.
651:
652: You may charge a fee for the physical act of transferring a copy, and
653: you may at your option offer warranty protection in exchange for a fee.
654:
655: @item
656: You may modify your copy or copies of the Program or any portion
657: of it, thus forming a work based on the Program, and copy and
658: distribute such modifications or work under the terms of Section 1
659: above, provided that you also meet all of these conditions:
660:
661: @enumerate a
662: @item
663: You must cause the modified files to carry prominent notices
664: stating that you changed the files and the date of any change.
665:
666: @item
667: You must cause any work that you distribute or publish, that in
668: whole or in part contains or is derived from the Program or any
669: part thereof, to be licensed as a whole at no charge to all third
670: parties under the terms of this License.
671:
672: @item
673: If the modified program normally reads commands interactively
674: when run, you must cause it, when started running for such
675: interactive use in the most ordinary way, to print or display an
676: announcement including an appropriate copyright notice and a
677: notice that there is no warranty (or else, saying that you provide
678: a warranty) and that users may redistribute the program under
679: these conditions, and telling the user how to view a copy of this
680: License. (Exception: if the Program itself is interactive but
681: does not normally print such an announcement, your work based on
682: the Program is not required to print an announcement.)
683: @end enumerate
684:
685: These requirements apply to the modified work as a whole. If
686: identifiable sections of that work are not derived from the Program,
687: and can be reasonably considered independent and separate works in
688: themselves, then this License, and its terms, do not apply to those
689: sections when you distribute them as separate works. But when you
690: distribute the same sections as part of a whole which is a work based
691: on the Program, the distribution of the whole must be on the terms of
692: this License, whose permissions for other licensees extend to the
693: entire whole, and thus to each and every part regardless of who wrote it.
694:
695: Thus, it is not the intent of this section to claim rights or contest
696: your rights to work written entirely by you; rather, the intent is to
697: exercise the right to control the distribution of derivative or
698: collective works based on the Program.
699:
700: In addition, mere aggregation of another work not based on the Program
701: with the Program (or with a work based on the Program) on a volume of
702: a storage or distribution medium does not bring the other work under
703: the scope of this License.
704:
705: @item
706: You may copy and distribute the Program (or a work based on it,
707: under Section 2) in object code or executable form under the terms of
708: Sections 1 and 2 above provided that you also do one of the following:
709:
710: @enumerate a
711: @item
712: Accompany it with the complete corresponding machine-readable
713: source code, which must be distributed under the terms of Sections
714: 1 and 2 above on a medium customarily used for software interchange; or,
715:
716: @item
717: Accompany it with a written offer, valid for at least three
718: years, to give any third party, for a charge no more than your
719: cost of physically performing source distribution, a complete
720: machine-readable copy of the corresponding source code, to be
721: distributed under the terms of Sections 1 and 2 above on a medium
722: customarily used for software interchange; or,
723:
724: @item
725: Accompany it with the information you received as to the offer
726: to distribute corresponding source code. (This alternative is
727: allowed only for noncommercial distribution and only if you
728: received the program in object code or executable form with such
729: an offer, in accord with Subsection b above.)
730: @end enumerate
731:
732: The source code for a work means the preferred form of the work for
733: making modifications to it. For an executable work, complete source
734: code means all the source code for all modules it contains, plus any
735: associated interface definition files, plus the scripts used to
736: control compilation and installation of the executable. However, as a
737: special exception, the source code distributed need not include
738: anything that is normally distributed (in either source or binary
739: form) with the major components (compiler, kernel, and so on) of the
740: operating system on which the executable runs, unless that component
741: itself accompanies the executable.
742:
743: If distribution of executable or object code is made by offering
744: access to copy from a designated place, then offering equivalent
745: access to copy the source code from the same place counts as
746: distribution of the source code, even though third parties are not
747: compelled to copy the source along with the object code.
748:
749: @item
750: You may not copy, modify, sublicense, or distribute the Program
751: except as expressly provided under this License. Any attempt
752: otherwise to copy, modify, sublicense or distribute the Program is
753: void, and will automatically terminate your rights under this License.
754: However, parties who have received copies, or rights, from you under
755: this License will not have their licenses terminated so long as such
756: parties remain in full compliance.
757:
758: @item
759: You are not required to accept this License, since you have not
760: signed it. However, nothing else grants you permission to modify or
761: distribute the Program or its derivative works. These actions are
762: prohibited by law if you do not accept this License. Therefore, by
763: modifying or distributing the Program (or any work based on the
764: Program), you indicate your acceptance of this License to do so, and
765: all its terms and conditions for copying, distributing or modifying
766: the Program or works based on it.
767:
768: @item
769: Each time you redistribute the Program (or any work based on the
770: Program), the recipient automatically receives a license from the
771: original licensor to copy, distribute or modify the Program subject to
772: these terms and conditions. You may not impose any further
773: restrictions on the recipients' exercise of the rights granted herein.
774: You are not responsible for enforcing compliance by third parties to
775: this License.
776:
777: @item
778: If, as a consequence of a court judgment or allegation of patent
779: infringement or for any other reason (not limited to patent issues),
780: conditions are imposed on you (whether by court order, agreement or
781: otherwise) that contradict the conditions of this License, they do not
782: excuse you from the conditions of this License. If you cannot
783: distribute so as to satisfy simultaneously your obligations under this
784: License and any other pertinent obligations, then as a consequence you
785: may not distribute the Program at all. For example, if a patent
786: license would not permit royalty-free redistribution of the Program by
787: all those who receive copies directly or indirectly through you, then
788: the only way you could satisfy both it and this License would be to
789: refrain entirely from distribution of the Program.
790:
791: If any portion of this section is held invalid or unenforceable under
792: any particular circumstance, the balance of the section is intended to
793: apply and the section as a whole is intended to apply in other
794: circumstances.
795:
796: It is not the purpose of this section to induce you to infringe any
797: patents or other property right claims or to contest validity of any
798: such claims; this section has the sole purpose of protecting the
799: integrity of the free software distribution system, which is
800: implemented by public license practices. Many people have made
801: generous contributions to the wide range of software distributed
802: through that system in reliance on consistent application of that
803: system; it is up to the author/donor to decide if he or she is willing
804: to distribute software through any other system and a licensee cannot
805: impose that choice.
806:
807: This section is intended to make thoroughly clear what is believed to
808: be a consequence of the rest of this License.
809:
810: @item
811: If the distribution and/or use of the Program is restricted in
812: certain countries either by patents or by copyrighted interfaces, the
813: original copyright holder who places the Program under this License
814: may add an explicit geographical distribution limitation excluding
815: those countries, so that distribution is permitted only in or among
816: countries not thus excluded. In such case, this License incorporates
817: the limitation as if written in the body of this License.
818:
819: @item
820: The Free Software Foundation may publish revised and/or new versions
821: of the General Public License from time to time. Such new versions will
822: be similar in spirit to the present version, but may differ in detail to
823: address new problems or concerns.
824:
825: Each version is given a distinguishing version number. If the Program
826: specifies a version number of this License which applies to it and ``any
827: later version'', you have the option of following the terms and conditions
828: either of that version or of any later version published by the Free
829: Software Foundation. If the Program does not specify a version number of
830: this License, you may choose any version ever published by the Free Software
831: Foundation.
832:
833: @item
834: If you wish to incorporate parts of the Program into other free
835: programs whose distribution conditions are different, write to the author
836: to ask for permission. For software which is copyrighted by the Free
837: Software Foundation, write to the Free Software Foundation; we sometimes
838: make exceptions for this. Our decision will be guided by the two goals
839: of preserving the free status of all derivatives of our free software and
840: of promoting the sharing and reuse of software generally.
841:
842: @iftex
843: @heading NO WARRANTY
844: @end iftex
845: @ifnottex
846: @center NO WARRANTY
847: @end ifnottex
848:
849: @item
850: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
851: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
852: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
853: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
854: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
855: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
856: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
857: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
858: REPAIR OR CORRECTION.
859:
860: @item
861: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
862: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
863: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
864: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
865: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
866: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
867: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
868: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
869: POSSIBILITY OF SUCH DAMAGES.
870: @end enumerate
871:
872: @iftex
873: @heading END OF TERMS AND CONDITIONS
874: @end iftex
875: @ifnottex
876: @center END OF TERMS AND CONDITIONS
877: @end ifnottex
878:
879: @page
880: @unnumberedsec How to Apply These Terms to Your New Programs
881:
882: If you develop a new program, and you want it to be of the greatest
883: possible use to the public, the best way to achieve this is to make it
884: free software which everyone can redistribute and change under these terms.
885:
886: To do so, attach the following notices to the program. It is safest
887: to attach them to the start of each source file to most effectively
888: convey the exclusion of warranty; and each file should have at least
889: the ``copyright'' line and a pointer to where the full notice is found.
890:
891: @smallexample
892: @var{one line to give the program's name and a brief idea of what it does.}
893: Copyright (C) 19@var{yy} @var{name of author}
894:
895: This program is free software; you can redistribute it and/or modify
896: it under the terms of the GNU General Public License as published by
897: the Free Software Foundation; either version 2 of the License, or
898: (at your option) any later version.
899:
900: This program is distributed in the hope that it will be useful,
901: but WITHOUT ANY WARRANTY; without even the implied warranty of
902: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
903: GNU General Public License for more details.
904:
905: You should have received a copy of the GNU General Public License
906: along with this program; if not, write to the Free Software
907: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
908: @end smallexample
909:
910: Also add information on how to contact you by electronic and paper mail.
911:
912: If the program is interactive, make it output a short notice like this
913: when it starts in an interactive mode:
914:
915: @smallexample
916: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
917: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
918: type `show w'.
919: This is free software, and you are welcome to redistribute it
920: under certain conditions; type `show c' for details.
921: @end smallexample
922:
923: The hypothetical commands @samp{show w} and @samp{show c} should show
924: the appropriate parts of the General Public License. Of course, the
925: commands you use may be called something other than @samp{show w} and
926: @samp{show c}; they could even be mouse-clicks or menu items---whatever
927: suits your program.
928:
929: You should also get your employer (if you work as a programmer) or your
930: school, if any, to sign a ``copyright disclaimer'' for the program, if
931: necessary. Here is a sample; alter the names:
932:
933: @smallexample
934: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
935: `Gnomovision' (which makes passes at compilers) written by James Hacker.
936:
937: @var{signature of Ty Coon}, 1 April 1989
938: Ty Coon, President of Vice
939: @end smallexample
940:
941: This General Public License does not permit incorporating your program into
942: proprietary programs. If your program is a subroutine library, you may
943: consider it more useful to permit linking proprietary applications with the
944: library. If this is what you want to do, use the GNU Library General
945: Public License instead of this License.
946:
947: @iftex
948: @unnumbered Preface
949: @cindex Preface
950: This manual documents Gforth. Some introductory material is provided for
951: readers who are unfamiliar with Forth or who are migrating to Gforth
952: from other Forth compilers. However, this manual is primarily a
953: reference manual.
954: @end iftex
955:
956: @comment TODO much more blurb here.
957:
958: @c ******************************************************************
959: @node Goals, Gforth Environment, License, Top
960: @comment node-name, next, previous, up
961: @chapter Goals of Gforth
962: @cindex goals of the Gforth project
963: The goal of the Gforth Project is to develop a standard model for
964: ANS Forth. This can be split into several subgoals:
965:
966: @itemize @bullet
967: @item
968: Gforth should conform to the ANS Forth Standard.
969: @item
970: It should be a model, i.e. it should define all the
971: implementation-dependent things.
972: @item
973: It should become standard, i.e. widely accepted and used. This goal
974: is the most difficult one.
975: @end itemize
976:
977: To achieve these goals Gforth should be
978: @itemize @bullet
979: @item
980: Similar to previous models (fig-Forth, F83)
981: @item
982: Powerful. It should provide for all the things that are considered
983: necessary today and even some that are not yet considered necessary.
984: @item
985: Efficient. It should not get the reputation of being exceptionally
986: slow.
987: @item
988: Free.
989: @item
990: Available on many machines/easy to port.
991: @end itemize
992:
993: Have we achieved these goals? Gforth conforms to the ANS Forth
994: standard. It may be considered a model, but we have not yet documented
995: which parts of the model are stable and which parts we are likely to
996: change. It certainly has not yet become a de facto standard, but it
997: appears to be quite popular. It has some similarities to and some
998: differences from previous models. It has some powerful features, but not
999: yet everything that we envisioned. We certainly have achieved our
1000: execution speed goals (@pxref{Performance})@footnote{However, in 1998
1001: the bar was raised when the major commercial Forth vendors switched to
1002: native code compilers.}. It is free and available on many machines.
1003:
1004: @c ******************************************************************
1005: @node Gforth Environment, Tutorial, Goals, Top
1006: @chapter Gforth Environment
1007: @cindex Gforth environment
1008:
1009: Note: ultimately, the Gforth man page will be auto-generated from the
1010: material in this chapter.
1011:
1012: @menu
1013: * Invoking Gforth:: Getting in
1014: * Leaving Gforth:: Getting out
1015: * Command-line editing::
1016: * Environment variables:: that affect how Gforth starts up
1017: * Gforth Files:: What gets installed and where
1018: * Startup speed:: When 35ms is not fast enough ...
1019: @end menu
1020:
1021: For related information about the creation of images see @ref{Image Files}.
1022:
1023: @comment ----------------------------------------------
1024: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1025: @section Invoking Gforth
1026: @cindex invoking Gforth
1027: @cindex running Gforth
1028: @cindex command-line options
1029: @cindex options on the command line
1030: @cindex flags on the command line
1031:
1032: Gforth is made up of two parts; an executable ``engine'' (named
1033: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
1034: will usually just say @code{gforth} -- this automatically loads the
1035: default image file @file{gforth.fi}. In many other cases the default
1036: Gforth image will be invoked like this:
1037: @example
1038: gforth [file | -e forth-code] ...
1039: @end example
1040: @noindent
1041: This interprets the contents of the files and the Forth code in the order they
1042: are given.
1043:
1044: In addition to the @file{gforth} engine, there is also an engine called
1045: @file{gforth-fast}, which is faster, but gives less informative error
1046: messages (@pxref{Error messages}).
1047:
1048: In general, the command line looks like this:
1049:
1050: @example
1051: gforth[-fast] [engine options] [image options]
1052: @end example
1053:
1054: The engine options must come before the rest of the command
1055: line. They are:
1056:
1057: @table @code
1058: @cindex -i, command-line option
1059: @cindex --image-file, command-line option
1060: @item --image-file @i{file}
1061: @itemx -i @i{file}
1062: Loads the Forth image @i{file} instead of the default
1063: @file{gforth.fi} (@pxref{Image Files}).
1064:
1065: @cindex --appl-image, command-line option
1066: @item --appl-image @i{file}
1067: Loads the image @i{file} and leaves all further command-line arguments
1068: to the image (instead of processing them as engine options). This is
1069: useful for building executable application images on Unix, built with
1070: @code{gforthmi --application ...}.
1071:
1072: @cindex --path, command-line option
1073: @cindex -p, command-line option
1074: @item --path @i{path}
1075: @itemx -p @i{path}
1076: Uses @i{path} for searching the image file and Forth source code files
1077: instead of the default in the environment variable @code{GFORTHPATH} or
1078: the path specified at installation time (e.g.,
1079: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
1080: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1081:
1082: @cindex --dictionary-size, command-line option
1083: @cindex -m, command-line option
1084: @cindex @i{size} parameters for command-line options
1085: @cindex size of the dictionary and the stacks
1086: @item --dictionary-size @i{size}
1087: @itemx -m @i{size}
1088: Allocate @i{size} space for the Forth dictionary space instead of
1089: using the default specified in the image (typically 256K). The
1090: @i{size} specification for this and subsequent options consists of
1091: an integer and a unit (e.g.,
1092: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
1093: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
1094: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
1095: @code{e} is used.
1096:
1097: @cindex --data-stack-size, command-line option
1098: @cindex -d, command-line option
1099: @item --data-stack-size @i{size}
1100: @itemx -d @i{size}
1101: Allocate @i{size} space for the data stack instead of using the
1102: default specified in the image (typically 16K).
1103:
1104: @cindex --return-stack-size, command-line option
1105: @cindex -r, command-line option
1106: @item --return-stack-size @i{size}
1107: @itemx -r @i{size}
1108: Allocate @i{size} space for the return stack instead of using the
1109: default specified in the image (typically 15K).
1110:
1111: @cindex --fp-stack-size, command-line option
1112: @cindex -f, command-line option
1113: @item --fp-stack-size @i{size}
1114: @itemx -f @i{size}
1115: Allocate @i{size} space for the floating point stack instead of
1116: using the default specified in the image (typically 15.5K). In this case
1117: the unit specifier @code{e} refers to floating point numbers.
1118:
1119: @cindex --locals-stack-size, command-line option
1120: @cindex -l, command-line option
1121: @item --locals-stack-size @i{size}
1122: @itemx -l @i{size}
1123: Allocate @i{size} space for the locals stack instead of using the
1124: default specified in the image (typically 14.5K).
1125:
1126: @cindex -h, command-line option
1127: @cindex --help, command-line option
1128: @item --help
1129: @itemx -h
1130: Print a message about the command-line options
1131:
1132: @cindex -v, command-line option
1133: @cindex --version, command-line option
1134: @item --version
1135: @itemx -v
1136: Print version and exit
1137:
1138: @cindex --debug, command-line option
1139: @item --debug
1140: Print some information useful for debugging on startup.
1141:
1142: @cindex --offset-image, command-line option
1143: @item --offset-image
1144: Start the dictionary at a slightly different position than would be used
1145: otherwise (useful for creating data-relocatable images,
1146: @pxref{Data-Relocatable Image Files}).
1147:
1148: @cindex --no-offset-im, command-line option
1149: @item --no-offset-im
1150: Start the dictionary at the normal position.
1151:
1152: @cindex --clear-dictionary, command-line option
1153: @item --clear-dictionary
1154: Initialize all bytes in the dictionary to 0 before loading the image
1155: (@pxref{Data-Relocatable Image Files}).
1156:
1157: @cindex --die-on-signal, command-line-option
1158: @item --die-on-signal
1159: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
1160: or the segmentation violation SIGSEGV) by translating it into a Forth
1161: @code{THROW}. With this option, Gforth exits if it receives such a
1162: signal. This option is useful when the engine and/or the image might be
1163: severely broken (such that it causes another signal before recovering
1164: from the first); this option avoids endless loops in such cases.
1165: @end table
1166:
1167: @cindex loading files at startup
1168: @cindex executing code on startup
1169: @cindex batch processing with Gforth
1170: As explained above, the image-specific command-line arguments for the
1171: default image @file{gforth.fi} consist of a sequence of filenames and
1172: @code{-e @var{forth-code}} options that are interpreted in the sequence
1173: in which they are given. The @code{-e @var{forth-code}} or
1174: @code{--evaluate @var{forth-code}} option evaluates the Forth
1175: code. This option takes only one argument; if you want to evaluate more
1176: Forth words, you have to quote them or use @code{-e} several times. To exit
1177: after processing the command line (instead of entering interactive mode)
1178: append @code{-e bye} to the command line.
1179:
1180: @cindex versions, invoking other versions of Gforth
1181: If you have several versions of Gforth installed, @code{gforth} will
1182: invoke the version that was installed last. @code{gforth-@i{version}}
1183: invokes a specific version. If your environment contains the variable
1184: @code{GFORTHPATH}, you may want to override it by using the
1185: @code{--path} option.
1186:
1187: Not yet implemented:
1188: On startup the system first executes the system initialization file
1189: (unless the option @code{--no-init-file} is given; note that the system
1190: resulting from using this option may not be ANS Forth conformant). Then
1191: the user initialization file @file{.gforth.fs} is executed, unless the
1192: option @code{--no-rc} is given; this file is searched for in @file{.},
1193: then in @file{~}, then in the normal path (see above).
1194:
1195:
1196:
1197: @comment ----------------------------------------------
1198: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
1199: @section Leaving Gforth
1200: @cindex Gforth - leaving
1201: @cindex leaving Gforth
1202:
1203: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
1204: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
1205: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1206: data are discarded. For ways of saving the state of the system before
1207: leaving Gforth see @ref{Image Files}.
1208:
1209: doc-bye
1210:
1211:
1212: @comment ----------------------------------------------
1213: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1214: @section Command-line editing
1215: @cindex command-line editing
1216:
1217: Gforth maintains a history file that records every line that you type to
1218: the text interpreter. This file is preserved between sessions, and is
1219: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
1220: repeatedly you can recall successively older commands from this (or
1221: previous) session(s). The full list of command-line editing facilities is:
1222:
1223: @itemize @bullet
1224: @item
1225: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
1226: commands from the history buffer.
1227: @item
1228: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
1229: from the history buffer.
1230: @item
1231: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
1232: @item
1233: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
1234: @item
1235: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
1236: closing up the line.
1237: @item
1238: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
1239: @item
1240: @kbd{Ctrl-a} to move the cursor to the start of the line.
1241: @item
1242: @kbd{Ctrl-e} to move the cursor to the end of the line.
1243: @item
1244: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
1245: line.
1246: @item
1247: @key{TAB} to step through all possible full-word completions of the word
1248: currently being typed.
1249: @item
1250: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
1251: using @code{bye}).
1252: @item
1253: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
1254: character under the cursor.
1255: @end itemize
1256:
1257: When editing, displayable characters are inserted to the left of the
1258: cursor position; the line is always in ``insert'' (as opposed to
1259: ``overstrike'') mode.
1260:
1261: @cindex history file
1262: @cindex @file{.gforth-history}
1263: On Unix systems, the history file is @file{~/.gforth-history} by
1264: default@footnote{i.e. it is stored in the user's home directory.}. You
1265: can find out the name and location of your history file using:
1266:
1267: @example
1268: history-file type \ Unix-class systems
1269:
1270: history-file type \ Other systems
1271: history-dir type
1272: @end example
1273:
1274: If you enter long definitions by hand, you can use a text editor to
1275: paste them out of the history file into a Forth source file for reuse at
1276: a later time.
1277:
1278: Gforth never trims the size of the history file, so you should do this
1279: periodically, if necessary.
1280:
1281: @comment this is all defined in history.fs
1282: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
1283: @comment chosen?
1284:
1285:
1286: @comment ----------------------------------------------
1287: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1288: @section Environment variables
1289: @cindex environment variables
1290:
1291: Gforth uses these environment variables:
1292:
1293: @itemize @bullet
1294: @item
1295: @cindex @code{GFORTHHIST} -- environment variable
1296: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
1297: open/create the history file, @file{.gforth-history}. Default:
1298: @code{$HOME}.
1299:
1300: @item
1301: @cindex @code{GFORTHPATH} -- environment variable
1302: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
1303: for Forth source-code files.
1304:
1305: @item
1306: @cindex @code{GFORTH} -- environment variable
1307: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1308:
1309: @item
1310: @cindex @code{GFORTHD} -- environment variable
1311: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1312:
1313: @item
1314: @cindex @code{TMP}, @code{TEMP} - environment variable
1315: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1316: location for the history file.
1317: @end itemize
1318:
1319: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1320: @comment mentioning these.
1321:
1322: All the Gforth environment variables default to sensible values if they
1323: are not set.
1324:
1325:
1326: @comment ----------------------------------------------
1327: @node Gforth Files, Startup speed, Environment variables, Gforth Environment
1328: @section Gforth files
1329: @cindex Gforth files
1330:
1331: When you install Gforth on a Unix system, it installs files in these
1332: locations by default:
1333:
1334: @itemize @bullet
1335: @item
1336: @file{/usr/local/bin/gforth}
1337: @item
1338: @file{/usr/local/bin/gforthmi}
1339: @item
1340: @file{/usr/local/man/man1/gforth.1} - man page.
1341: @item
1342: @file{/usr/local/info} - the Info version of this manual.
1343: @item
1344: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1345: @item
1346: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1347: @item
1348: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1349: @item
1350: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1351: @end itemize
1352:
1353: You can select different places for installation by using
1354: @code{configure} options (listed with @code{configure --help}).
1355:
1356: @comment ----------------------------------------------
1357: @node Startup speed, , Gforth Files, Gforth Environment
1358: @section Startup speed
1359: @cindex Startup speed
1360: @cindex speed, startup
1361:
1362: If Gforth is used for CGI scripts or in shell scripts, its startup
1363: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1364: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1365: system time.
1366:
1367: If startup speed is a problem, you may consider the following ways to
1368: improve it; or you may consider ways to reduce the number of startups
1369: (for example, by using Fast-CGI).
1370:
1371: The first step to improve startup speed is to statically link Gforth, by
1372: building it with @code{XLDFLAGS=-static}. This requires more memory for
1373: the code and will therefore slow down the first invocation, but
1374: subsequent invocations avoid the dynamic linking overhead. Another
1375: disadvantage is that Gforth won't profit from library upgrades. As a
1376: result, @code{gforth-static -e bye} takes about 17.1ms user and
1377: 8.2ms system time.
1378:
1379: The next step to improve startup speed is to use a non-relocatable image
1380: (@pxref{Non-Relocatable Image Files}). You can create this image with
1381: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1382: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1383: and a part of the copy-on-write overhead. The disadvantage is that the
1384: non-relocatable image does not work if the OS gives Gforth a different
1385: address for the dictionary, for whatever reason; so you better provide a
1386: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1387: bye} takes about 15.3ms user and 7.5ms system time.
1388:
1389: The final step is to disable dictionary hashing in Gforth. Gforth
1390: builds the hash table on startup, which takes much of the startup
1391: overhead. You can do this by commenting out the @code{include hash.fs}
1392: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1393: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1394: The disadvantages are that functionality like @code{table} and
1395: @code{ekey} is missing and that text interpretation (e.g., compiling)
1396: now takes much longer. So, you should only use this method if there is
1397: no significant text interpretation to perform (the script should be
1398: compiled into the image, amongst other things). @code{gforth-static -i
1399: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1400:
1401: @c ******************************************************************
1402: @node Tutorial, Introduction, Gforth Environment, Top
1403: @chapter Forth Tutorial
1404: @cindex Tutorial
1405: @cindex Forth Tutorial
1406:
1407: @c Topics from nac's Introduction that could be mentioned:
1408: @c press <ret> after each line
1409: @c Prompt
1410: @c numbers vs. words in dictionary on text interpretation
1411: @c what happens on redefinition
1412: @c parsing words (in particular, defining words)
1413:
1414: The difference of this chapter from the Introduction
1415: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1416: be used while sitting in front of a computer, and covers much more
1417: material, but does not explain how the Forth system works.
1418:
1419: This tutorial can be used with any ANS-compliant Forth; any
1420: Gforth-specific features are marked as such and you can skip them if you
1421: work with another Forth. This tutorial does not explain all features of
1422: Forth, just enough to get you started and give you some ideas about the
1423: facilities available in Forth. Read the rest of the manual and the
1424: standard when you are through this.
1425:
1426: The intended way to use this tutorial is that you work through it while
1427: sitting in front of the console, take a look at the examples and predict
1428: what they will do, then try them out; if the outcome is not as expected,
1429: find out why (e.g., by trying out variations of the example), so you
1430: understand what's going on. There are also some assignments that you
1431: should solve.
1432:
1433: This tutorial assumes that you have programmed before and know what,
1434: e.g., a loop is.
1435:
1436: @c !! explain compat library
1437:
1438: @menu
1439: * Starting Gforth Tutorial::
1440: * Syntax Tutorial::
1441: * Crash Course Tutorial::
1442: * Stack Tutorial::
1443: * Arithmetics Tutorial::
1444: * Stack Manipulation Tutorial::
1445: * Using files for Forth code Tutorial::
1446: * Comments Tutorial::
1447: * Colon Definitions Tutorial::
1448: * Decompilation Tutorial::
1449: * Stack-Effect Comments Tutorial::
1450: * Types Tutorial::
1451: * Factoring Tutorial::
1452: * Designing the stack effect Tutorial::
1453: * Local Variables Tutorial::
1454: * Conditional execution Tutorial::
1455: * Flags and Comparisons Tutorial::
1456: * General Loops Tutorial::
1457: * Counted loops Tutorial::
1458: * Recursion Tutorial::
1459: * Leaving definitions or loops Tutorial::
1460: * Return Stack Tutorial::
1461: * Memory Tutorial::
1462: * Characters and Strings Tutorial::
1463: * Alignment Tutorial::
1464: * Files Tutorial::
1465: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1466: * Execution Tokens Tutorial::
1467: * Exceptions Tutorial::
1468: * Defining Words Tutorial::
1469: * Arrays and Records Tutorial::
1470: * POSTPONE Tutorial::
1471: * Literal Tutorial::
1472: * Advanced macros Tutorial::
1473: * Compilation Tokens Tutorial::
1474: * Wordlists and Search Order Tutorial::
1475: @end menu
1476:
1477: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1478: @section Starting Gforth
1479: @cindex starting Gforth tutorial
1480: You can start Gforth by typing its name:
1481:
1482: @example
1483: gforth
1484: @end example
1485:
1486: That puts you into interactive mode; you can leave Gforth by typing
1487: @code{bye}. While in Gforth, you can edit the command line and access
1488: the command line history with cursor keys, similar to bash.
1489:
1490:
1491: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1492: @section Syntax
1493: @cindex syntax tutorial
1494:
1495: A @dfn{word} is a sequence of arbitrary characters (expcept white
1496: space). Words are separated by white space. E.g., each of the
1497: following lines contains exactly one word:
1498:
1499: @example
1500: word
1501: !@@#$%^&*()
1502: 1234567890
1503: 5!a
1504: @end example
1505:
1506: A frequent beginner's error is to leave away necessary white space,
1507: resulting in an error like @samp{Undefined word}; so if you see such an
1508: error, check if you have put spaces wherever necessary.
1509:
1510: @example
1511: ." hello, world" \ correct
1512: ."hello, world" \ gives an "Undefined word" error
1513: @end example
1514:
1515: Gforth and most other Forth systems ignore differences in case (they are
1516: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1517: your system is case-sensitive, you may have to type all the examples
1518: given here in upper case.
1519:
1520:
1521: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1522: @section Crash Course
1523:
1524: Type
1525:
1526: @example
1527: 0 0 !
1528: here execute
1529: ' catch >body 20 erase abort
1530: ' (quit) >body 20 erase
1531: @end example
1532:
1533: The last two examples are guaranteed to destroy parts of Gforth (and
1534: most other systems), so you better leave Gforth afterwards (if it has
1535: not finished by itself). On some systems you may have to kill gforth
1536: from outside (e.g., in Unix with @code{kill}).
1537:
1538: Now that you know how to produce crashes (and that there's not much to
1539: them), let's learn how to produce meaningful programs.
1540:
1541:
1542: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1543: @section Stack
1544: @cindex stack tutorial
1545:
1546: The most obvious feature of Forth is the stack. When you type in a
1547: number, it is pushed on the stack. You can display the content of the
1548: stack with @code{.s}.
1549:
1550: @example
1551: 1 2 .s
1552: 3 .s
1553: @end example
1554:
1555: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1556: appear in @code{.s} output as they appeared in the input.
1557:
1558: You can print the top of stack element with @code{.}.
1559:
1560: @example
1561: 1 2 3 . . .
1562: @end example
1563:
1564: In general, words consume their stack arguments (@code{.s} is an
1565: exception).
1566:
1567: @assignment
1568: What does the stack contain after @code{5 6 7 .}?
1569: @endassignment
1570:
1571:
1572: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1573: @section Arithmetics
1574: @cindex arithmetics tutorial
1575:
1576: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1577: operate on the top two stack items:
1578:
1579: @example
1580: 2 2 .s
1581: + .s
1582: .
1583: 2 1 - .
1584: 7 3 mod .
1585: @end example
1586:
1587: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1588: as in the corresponding infix expression (this is generally the case in
1589: Forth).
1590:
1591: Parentheses are superfluous (and not available), because the order of
1592: the words unambiguously determines the order of evaluation and the
1593: operands:
1594:
1595: @example
1596: 3 4 + 5 * .
1597: 3 4 5 * + .
1598: @end example
1599:
1600: @assignment
1601: What are the infix expressions corresponding to the Forth code above?
1602: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1603: known as Postfix or RPN (Reverse Polish Notation).}.
1604: @endassignment
1605:
1606: To change the sign, use @code{negate}:
1607:
1608: @example
1609: 2 negate .
1610: @end example
1611:
1612: @assignment
1613: Convert -(-3)*4-5 to Forth.
1614: @endassignment
1615:
1616: @code{/mod} performs both @code{/} and @code{mod}.
1617:
1618: @example
1619: 7 3 /mod . .
1620: @end example
1621:
1622: Reference: @ref{Arithmetic}.
1623:
1624:
1625: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1626: @section Stack Manipulation
1627: @cindex stack manipulation tutorial
1628:
1629: Stack manipulation words rearrange the data on the stack.
1630:
1631: @example
1632: 1 .s drop .s
1633: 1 .s dup .s drop drop .s
1634: 1 2 .s over .s drop drop drop
1635: 1 2 .s swap .s drop drop
1636: 1 2 3 .s rot .s drop drop drop
1637: @end example
1638:
1639: These are the most important stack manipulation words. There are also
1640: variants that manipulate twice as many stack items:
1641:
1642: @example
1643: 1 2 3 4 .s 2swap .s 2drop 2drop
1644: @end example
1645:
1646: Two more stack manipulation words are:
1647:
1648: @example
1649: 1 2 .s nip .s drop
1650: 1 2 .s tuck .s 2drop drop
1651: @end example
1652:
1653: @assignment
1654: Replace @code{nip} and @code{tuck} with combinations of other stack
1655: manipulation words.
1656:
1657: @example
1658: Given: How do you get:
1659: 1 2 3 3 2 1
1660: 1 2 3 1 2 3 2
1661: 1 2 3 1 2 3 3
1662: 1 2 3 1 3 3
1663: 1 2 3 2 1 3
1664: 1 2 3 4 4 3 2 1
1665: 1 2 3 1 2 3 1 2 3
1666: 1 2 3 4 1 2 3 4 1 2
1667: 1 2 3
1668: 1 2 3 1 2 3 4
1669: 1 2 3 1 3
1670: @end example
1671: @endassignment
1672:
1673: @example
1674: 5 dup * .
1675: @end example
1676:
1677: @assignment
1678: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1679: Write a piece of Forth code that expects two numbers on the stack
1680: (@var{a} and @var{b}, with @var{b} on top) and computes
1681: @code{(a-b)(a+1)}.
1682: @endassignment
1683:
1684: Reference: @ref{Stack Manipulation}.
1685:
1686:
1687: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1688: @section Using files for Forth code
1689: @cindex loading Forth code, tutorial
1690: @cindex files containing Forth code, tutorial
1691:
1692: While working at the Forth command line is convenient for one-line
1693: examples and short one-off code, you probably want to store your source
1694: code in files for convenient editing and persistence. You can use your
1695: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1696: Gforth}) to create @var{file} and use
1697:
1698: @example
1699: s" @var{file}" included
1700: @end example
1701:
1702: to load it into your Forth system. The file name extension I use for
1703: Forth files is @samp{.fs}.
1704:
1705: You can easily start Gforth with some files loaded like this:
1706:
1707: @example
1708: gforth @var{file1} @var{file2}
1709: @end example
1710:
1711: If an error occurs during loading these files, Gforth terminates,
1712: whereas an error during @code{INCLUDED} within Gforth usually gives you
1713: a Gforth command line. Starting the Forth system every time gives you a
1714: clean start every time, without interference from the results of earlier
1715: tries.
1716:
1717: I often put all the tests in a file, then load the code and run the
1718: tests with
1719:
1720: @example
1721: gforth @var{code} @var{tests} -e bye
1722: @end example
1723:
1724: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1725: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1726: restart this command without ado.
1727:
1728: The advantage of this approach is that the tests can be repeated easily
1729: every time the program ist changed, making it easy to catch bugs
1730: introduced by the change.
1731:
1732: Reference: @ref{Forth source files}.
1733:
1734:
1735: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1736: @section Comments
1737: @cindex comments tutorial
1738:
1739: @example
1740: \ That's a comment; it ends at the end of the line
1741: ( Another comment; it ends here: ) .s
1742: @end example
1743:
1744: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1745: separated with white space from the following text.
1746:
1747: @example
1748: \This gives an "Undefined word" error
1749: @end example
1750:
1751: The first @code{)} ends a comment started with @code{(}, so you cannot
1752: nest @code{(}-comments; and you cannot comment out text containing a
1753: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1754: avoid @code{)} in word names.}.
1755:
1756: I use @code{\}-comments for descriptive text and for commenting out code
1757: of one or more line; I use @code{(}-comments for describing the stack
1758: effect, the stack contents, or for commenting out sub-line pieces of
1759: code.
1760:
1761: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1762: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1763: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1764: with @kbd{M-q}.
1765:
1766: Reference: @ref{Comments}.
1767:
1768:
1769: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1770: @section Colon Definitions
1771: @cindex colon definitions, tutorial
1772: @cindex definitions, tutorial
1773: @cindex procedures, tutorial
1774: @cindex functions, tutorial
1775:
1776: are similar to procedures and functions in other programming languages.
1777:
1778: @example
1779: : squared ( n -- n^2 )
1780: dup * ;
1781: 5 squared .
1782: 7 squared .
1783: @end example
1784:
1785: @code{:} starts the colon definition; its name is @code{squared}. The
1786: following comment describes its stack effect. The words @code{dup *}
1787: are not executed, but compiled into the definition. @code{;} ends the
1788: colon definition.
1789:
1790: The newly-defined word can be used like any other word, including using
1791: it in other definitions:
1792:
1793: @example
1794: : cubed ( n -- n^3 )
1795: dup squared * ;
1796: -5 cubed .
1797: : fourth-power ( n -- n^4 )
1798: squared squared ;
1799: 3 fourth-power .
1800: @end example
1801:
1802: @assignment
1803: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1804: @code{/mod} in terms of other Forth words, and check if they work (hint:
1805: test your tests on the originals first). Don't let the
1806: @samp{redefined}-Messages spook you, they are just warnings.
1807: @endassignment
1808:
1809: Reference: @ref{Colon Definitions}.
1810:
1811:
1812: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1813: @section Decompilation
1814: @cindex decompilation tutorial
1815: @cindex see tutorial
1816:
1817: You can decompile colon definitions with @code{see}:
1818:
1819: @example
1820: see squared
1821: see cubed
1822: @end example
1823:
1824: In Gforth @code{see} shows you a reconstruction of the source code from
1825: the executable code. Informations that were present in the source, but
1826: not in the executable code, are lost (e.g., comments).
1827:
1828: You can also decompile the predefined words:
1829:
1830: @example
1831: see .
1832: see +
1833: @end example
1834:
1835:
1836: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1837: @section Stack-Effect Comments
1838: @cindex stack-effect comments, tutorial
1839: @cindex --, tutorial
1840: By convention the comment after the name of a definition describes the
1841: stack effect: The part in from of the @samp{--} describes the state of
1842: the stack before the execution of the definition, i.e., the parameters
1843: that are passed into the colon definition; the part behind the @samp{--}
1844: is the state of the stack after the execution of the definition, i.e.,
1845: the results of the definition. The stack comment only shows the top
1846: stack items that the definition accesses and/or changes.
1847:
1848: You should put a correct stack effect on every definition, even if it is
1849: just @code{( -- )}. You should also add some descriptive comment to
1850: more complicated words (I usually do this in the lines following
1851: @code{:}). If you don't do this, your code becomes unreadable (because
1852: you have to work through every definition before you can undertsand
1853: any).
1854:
1855: @assignment
1856: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1857: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1858: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1859: are done, you can compare your stack effects to those in this manual
1860: (@pxref{Word Index}).
1861: @endassignment
1862:
1863: Sometimes programmers put comments at various places in colon
1864: definitions that describe the contents of the stack at that place (stack
1865: comments); i.e., they are like the first part of a stack-effect
1866: comment. E.g.,
1867:
1868: @example
1869: : cubed ( n -- n^3 )
1870: dup squared ( n n^2 ) * ;
1871: @end example
1872:
1873: In this case the stack comment is pretty superfluous, because the word
1874: is simple enough. If you think it would be a good idea to add such a
1875: comment to increase readability, you should also consider factoring the
1876: word into several simpler words (@pxref{Factoring Tutorial,,
1877: Factoring}), which typically eliminates the need for the stack comment;
1878: however, if you decide not to refactor it, then having such a comment is
1879: better than not having it.
1880:
1881: The names of the stack items in stack-effect and stack comments in the
1882: standard, in this manual, and in many programs specify the type through
1883: a type prefix, similar to Fortran and Hungarian notation. The most
1884: frequent prefixes are:
1885:
1886: @table @code
1887: @item n
1888: signed integer
1889: @item u
1890: unsigned integer
1891: @item c
1892: character
1893: @item f
1894: Boolean flags, i.e. @code{false} or @code{true}.
1895: @item a-addr,a-
1896: Cell-aligned address
1897: @item c-addr,c-
1898: Char-aligned address (note that a Char may have two bytes in Windows NT)
1899: @item xt
1900: Execution token, same size as Cell
1901: @item w,x
1902: Cell, can contain an integer or an address. It usually takes 32, 64 or
1903: 16 bits (depending on your platform and Forth system). A cell is more
1904: commonly known as machine word, but the term @emph{word} already means
1905: something different in Forth.
1906: @item d
1907: signed double-cell integer
1908: @item ud
1909: unsigned double-cell integer
1910: @item r
1911: Float (on the FP stack)
1912: @end table
1913:
1914: You can find a more complete list in @ref{Notation}.
1915:
1916: @assignment
1917: Write stack-effect comments for all definitions you have written up to
1918: now.
1919: @endassignment
1920:
1921:
1922: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1923: @section Types
1924: @cindex types tutorial
1925:
1926: In Forth the names of the operations are not overloaded; so similar
1927: operations on different types need different names; e.g., @code{+} adds
1928: integers, and you have to use @code{f+} to add floating-point numbers.
1929: The following prefixes are often used for related operations on
1930: different types:
1931:
1932: @table @code
1933: @item (none)
1934: signed integer
1935: @item u
1936: unsigned integer
1937: @item c
1938: character
1939: @item d
1940: signed double-cell integer
1941: @item ud, du
1942: unsigned double-cell integer
1943: @item 2
1944: two cells (not-necessarily double-cell numbers)
1945: @item m, um
1946: mixed single-cell and double-cell operations
1947: @item f
1948: floating-point (note that in stack comments @samp{f} represents flags,
1949: and @samp{r} represents FP numbers).
1950: @end table
1951:
1952: If there are no differences between the signed and the unsigned variant
1953: (e.g., for @code{+}), there is only the prefix-less variant.
1954:
1955: Forth does not perform type checking, neither at compile time, nor at
1956: run time. If you use the wrong oeration, the data are interpreted
1957: incorrectly:
1958:
1959: @example
1960: -1 u.
1961: @end example
1962:
1963: If you have only experience with type-checked languages until now, and
1964: have heard how important type-checking is, don't panic! In my
1965: experience (and that of other Forthers), type errors in Forth code are
1966: usually easy to find (once you get used to it), the increased vigilance
1967: of the programmer tends to catch some harder errors in addition to most
1968: type errors, and you never have to work around the type system, so in
1969: most situations the lack of type-checking seems to be a win (projects to
1970: add type checking to Forth have not caught on).
1971:
1972:
1973: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1974: @section Factoring
1975: @cindex factoring tutorial
1976:
1977: If you try to write longer definitions, you will soon find it hard to
1978: keep track of the stack contents. Therefore, good Forth programmers
1979: tend to write only short definitions (e.g., three lines). The art of
1980: finding meaningful short definitions is known as factoring (as in
1981: factoring polynomials).
1982:
1983: Well-factored programs offer additional advantages: smaller, more
1984: general words, are easier to test and debug and can be reused more and
1985: better than larger, specialized words.
1986:
1987: So, if you run into difficulties with stack management, when writing
1988: code, try to define meaningful factors for the word, and define the word
1989: in terms of those. Even if a factor contains only two words, it is
1990: often helpful.
1991:
1992: Good factoring is not easy, and it takes some practice to get the knack
1993: for it; but even experienced Forth programmers often don't find the
1994: right solution right away, but only when rewriting the program. So, if
1995: you don't come up with a good solution immediately, keep trying, don't
1996: despair.
1997:
1998: @c example !!
1999:
2000:
2001: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
2002: @section Designing the stack effect
2003: @cindex Stack effect design, tutorial
2004: @cindex design of stack effects, tutorial
2005:
2006: In other languages you can use an arbitrary order of parameters for a
2007: function; and since there is only one result, you don't have to deal with
2008: the order of results, either.
2009:
2010: In Forth (and other stack-based languages, e.g., Postscript) the
2011: parameter and result order of a definition is important and should be
2012: designed well. The general guideline is to design the stack effect such
2013: that the word is simple to use in most cases, even if that complicates
2014: the implementation of the word. Some concrete rules are:
2015:
2016: @itemize @bullet
2017:
2018: @item
2019: Words consume all of their parameters (e.g., @code{.}).
2020:
2021: @item
2022: If there is a convention on the order of parameters (e.g., from
2023: mathematics or another programming language), stick with it (e.g.,
2024: @code{-}).
2025:
2026: @item
2027: If one parameter usually requires only a short computation (e.g., it is
2028: a constant), pass it on the top of the stack. Conversely, parameters
2029: that usually require a long sequence of code to compute should be passed
2030: as the bottom (i.e., first) parameter. This makes the code easier to
2031: read, because reader does not need to keep track of the bottom item
2032: through a long sequence of code (or, alternatively, through stack
2033: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
2034: address on top of the stack because it is usually simpler to compute
2035: than the stored value (often the address is just a variable).
2036:
2037: @item
2038: Similarly, results that are usually consumed quickly should be returned
2039: on the top of stack, whereas a result that is often used in long
2040: computations should be passed as bottom result. E.g., the file words
2041: like @code{open-file} return the error code on the top of stack, because
2042: it is usually consumed quickly by @code{throw}; moreover, the error code
2043: has to be checked before doing anything with the other results.
2044:
2045: @end itemize
2046:
2047: These rules are just general guidelines, don't lose sight of the overall
2048: goal to make the words easy to use. E.g., if the convention rule
2049: conflicts with the computation-length rule, you might decide in favour
2050: of the convention if the word will be used rarely, and in favour of the
2051: computation-length rule if the word will be used frequently (because
2052: with frequent use the cost of breaking the computation-length rule would
2053: be quite high, and frequent use makes it easier to remember an
2054: unconventional order).
2055:
2056: @c example !! structure package
2057:
2058:
2059: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
2060: @section Local Variables
2061: @cindex local variables, tutorial
2062:
2063: You can define local variables (@emph{locals}) in a colon definition:
2064:
2065: @example
2066: : swap @{ a b -- b a @}
2067: b a ;
2068: 1 2 swap .s 2drop
2069: @end example
2070:
2071: (If your Forth system does not support this syntax, include
2072: @file{compat/anslocals.fs} first).
2073:
2074: In this example @code{@{ a b -- b a @}} is the locals definition; it
2075: takes two cells from the stack, puts the top of stack in @code{b} and
2076: the next stack element in @code{a}. @code{--} starts a comment ending
2077: with @code{@}}. After the locals definition, using the name of the
2078: local will push its value on the stack. You can leave the comment
2079: part (@code{-- b a}) away:
2080:
2081: @example
2082: : swap ( x1 x2 -- x2 x1 )
2083: @{ a b @} b a ;
2084: @end example
2085:
2086: In Gforth you can have several locals definitions, anywhere in a colon
2087: definition; in contrast, in a standard program you can have only one
2088: locals definition per colon definition, and that locals definition must
2089: be outside any controll structure.
2090:
2091: With locals you can write slightly longer definitions without running
2092: into stack trouble. However, I recommend trying to write colon
2093: definitions without locals for exercise purposes to help you gain the
2094: essential factoring skills.
2095:
2096: @assignment
2097: Rewrite your definitions until now with locals
2098: @endassignment
2099:
2100: Reference: @ref{Locals}.
2101:
2102:
2103: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
2104: @section Conditional execution
2105: @cindex conditionals, tutorial
2106: @cindex if, tutorial
2107:
2108: In Forth you can use control structures only inside colon definitions.
2109: An @code{if}-structure looks like this:
2110:
2111: @example
2112: : abs ( n1 -- +n2 )
2113: dup 0 < if
2114: negate
2115: endif ;
2116: 5 abs .
2117: -5 abs .
2118: @end example
2119:
2120: @code{if} takes a flag from the stack. If the flag is non-zero (true),
2121: the following code is performed, otherwise execution continues after the
2122: @code{endif} (or @code{else}). @code{<} compares the top two stack
2123: elements and prioduces a flag:
2124:
2125: @example
2126: 1 2 < .
2127: 2 1 < .
2128: 1 1 < .
2129: @end example
2130:
2131: Actually the standard name for @code{endif} is @code{then}. This
2132: tutorial presents the examples using @code{endif}, because this is often
2133: less confusing for people familiar with other programming languages
2134: where @code{then} has a different meaning. If your system does not have
2135: @code{endif}, define it with
2136:
2137: @example
2138: : endif postpone then ; immediate
2139: @end example
2140:
2141: You can optionally use an @code{else}-part:
2142:
2143: @example
2144: : min ( n1 n2 -- n )
2145: 2dup < if
2146: drop
2147: else
2148: nip
2149: endif ;
2150: 2 3 min .
2151: 3 2 min .
2152: @end example
2153:
2154: @assignment
2155: Write @code{min} without @code{else}-part (hint: what's the definition
2156: of @code{nip}?).
2157: @endassignment
2158:
2159: Reference: @ref{Selection}.
2160:
2161:
2162: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
2163: @section Flags and Comparisons
2164: @cindex flags tutorial
2165: @cindex comparison tutorial
2166:
2167: In a false-flag all bits are clear (0 when interpreted as integer). In
2168: a canonical true-flag all bits are set (-1 as a twos-complement signed
2169: integer); in many contexts (e.g., @code{if}) any non-zero value is
2170: treated as true flag.
2171:
2172: @example
2173: false .
2174: true .
2175: true hex u. decimal
2176: @end example
2177:
2178: Comparison words produce canonical flags:
2179:
2180: @example
2181: 1 1 = .
2182: 1 0= .
2183: 0 1 < .
2184: 0 0 < .
2185: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
2186: -1 1 < .
2187: @end example
2188:
2189: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
2190: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
2191: these combinations are standard (for details see the standard,
2192: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
2193:
2194: You can use @code{and or xor invert} can be used as operations on
2195: canonical flags. Actually they are bitwise operations:
2196:
2197: @example
2198: 1 2 and .
2199: 1 2 or .
2200: 1 3 xor .
2201: 1 invert .
2202: @end example
2203:
2204: You can convert a zero/non-zero flag into a canonical flag with
2205: @code{0<>} (and complement it on the way with @code{0=}).
2206:
2207: @example
2208: 1 0= .
2209: 1 0<> .
2210: @end example
2211:
2212: You can use the all-bits-set feature of canonical flags and the bitwise
2213: operation of the Boolean operations to avoid @code{if}s:
2214:
2215: @example
2216: : foo ( n1 -- n2 )
2217: 0= if
2218: 14
2219: else
2220: 0
2221: endif ;
2222: 0 foo .
2223: 1 foo .
2224:
2225: : foo ( n1 -- n2 )
2226: 0= 14 and ;
2227: 0 foo .
2228: 1 foo .
2229: @end example
2230:
2231: @assignment
2232: Write @code{min} without @code{if}.
2233: @endassignment
2234:
2235: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2236: @ref{Bitwise operations}.
2237:
2238:
2239: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2240: @section General Loops
2241: @cindex loops, indefinite, tutorial
2242:
2243: The endless loop is the most simple one:
2244:
2245: @example
2246: : endless ( -- )
2247: 0 begin
2248: dup . 1+
2249: again ;
2250: endless
2251: @end example
2252:
2253: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2254: does nothing at run-time, @code{again} jumps back to @code{begin}.
2255:
2256: A loop with one exit at any place looks like this:
2257:
2258: @example
2259: : log2 ( +n1 -- n2 )
2260: \ logarithmus dualis of n1>0, rounded down to the next integer
2261: assert( dup 0> )
2262: 2/ 0 begin
2263: over 0> while
2264: 1+ swap 2/ swap
2265: repeat
2266: nip ;
2267: 7 log2 .
2268: 8 log2 .
2269: @end example
2270:
2271: At run-time @code{while} consumes a flag; if it is 0, execution
2272: continues behind the @code{repeat}; if the flag is non-zero, execution
2273: continues behind the @code{while}. @code{Repeat} jumps back to
2274: @code{begin}, just like @code{again}.
2275:
2276: In Forth there are many combinations/abbreviations, like @code{1+}.
2277: However, @code{2/} is not one of them; it shifts it's argument right by
2278: one bit (arithmetic shift right):
2279:
2280: @example
2281: -5 2 / .
2282: -5 2/ .
2283: @end example
2284:
2285: @code{assert(} is no standard word, but you can get it on systems other
2286: then Gforth by including @file{compat/assert.fs}. You can see what it
2287: does by trying
2288:
2289: @example
2290: 0 log2 .
2291: @end example
2292:
2293: Here's a loop with an exit at the end:
2294:
2295: @example
2296: : log2 ( +n1 -- n2 )
2297: \ logarithmus dualis of n1>0, rounded down to the next integer
2298: assert( dup 0 > )
2299: -1 begin
2300: 1+ swap 2/ swap
2301: over 0 <=
2302: until
2303: nip ;
2304: @end example
2305:
2306: @code{Until} consumes a flag; if it is non-zero, execution continues at
2307: the @code{begin}, otherwise after the @code{until}.
2308:
2309: @assignment
2310: Write a definition for computing the greatest common divisor.
2311: @endassignment
2312:
2313: Reference: @ref{Simple Loops}.
2314:
2315:
2316: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2317: @section Counted loops
2318: @cindex loops, counted, tutorial
2319:
2320: @example
2321: : ^ ( n1 u -- n )
2322: \ n = the uth power of u1
2323: 1 swap 0 u+do
2324: over *
2325: loop
2326: nip ;
2327: 3 2 ^ .
2328: 4 3 ^ .
2329: @end example
2330:
2331: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2332: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2333: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2334: times (or not at all, if @code{u3-u4<0}).
2335:
2336: You can see the stack effect design rules at work in the stack effect of
2337: the loop start words: Since the start value of the loop is more
2338: frequently constant than the end value, the start value is passed on
2339: the top-of-stack.
2340:
2341: You can access the counter of a counted loop with @code{i}:
2342:
2343: @example
2344: : fac ( u -- u! )
2345: 1 swap 1+ 1 u+do
2346: i *
2347: loop ;
2348: 5 fac .
2349: 7 fac .
2350: @end example
2351:
2352: There is also @code{+do}, which expects signed numbers (important for
2353: deciding whether to enter the loop).
2354:
2355: @assignment
2356: Write a definition for computing the nth Fibonacci number.
2357: @endassignment
2358:
2359: You can also use increments other than 1:
2360:
2361: @example
2362: : up2 ( n1 n2 -- )
2363: +do
2364: i .
2365: 2 +loop ;
2366: 10 0 up2
2367:
2368: : down2 ( n1 n2 -- )
2369: -do
2370: i .
2371: 2 -loop ;
2372: 0 10 down2
2373: @end example
2374:
2375: Reference: @ref{Counted Loops}.
2376:
2377:
2378: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2379: @section Recursion
2380: @cindex recursion tutorial
2381:
2382: Usually the name of a definition is not visible in the definition; but
2383: earlier definitions are usually visible:
2384:
2385: @example
2386: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2387: : / ( n1 n2 -- n )
2388: dup 0= if
2389: -10 throw \ report division by zero
2390: endif
2391: / \ old version
2392: ;
2393: 1 0 /
2394: @end example
2395:
2396: For recursive definitions you can use @code{recursive} (non-standard) or
2397: @code{recurse}:
2398:
2399: @example
2400: : fac1 ( n -- n! ) recursive
2401: dup 0> if
2402: dup 1- fac1 *
2403: else
2404: drop 1
2405: endif ;
2406: 7 fac1 .
2407:
2408: : fac2 ( n -- n! )
2409: dup 0> if
2410: dup 1- recurse *
2411: else
2412: drop 1
2413: endif ;
2414: 8 fac2 .
2415: @end example
2416:
2417: @assignment
2418: Write a recursive definition for computing the nth Fibonacci number.
2419: @endassignment
2420:
2421: Reference (including indirect recursion): @xref{Calls and returns}.
2422:
2423:
2424: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2425: @section Leaving definitions or loops
2426: @cindex leaving definitions, tutorial
2427: @cindex leaving loops, tutorial
2428:
2429: @code{EXIT} exits the current definition right away. For every counted
2430: loop that is left in this way, an @code{UNLOOP} has to be performed
2431: before the @code{EXIT}:
2432:
2433: @c !! real examples
2434: @example
2435: : ...
2436: ... u+do
2437: ... if
2438: ... unloop exit
2439: endif
2440: ...
2441: loop
2442: ... ;
2443: @end example
2444:
2445: @code{LEAVE} leaves the innermost counted loop right away:
2446:
2447: @example
2448: : ...
2449: ... u+do
2450: ... if
2451: ... leave
2452: endif
2453: ...
2454: loop
2455: ... ;
2456: @end example
2457:
2458: @c !! example
2459:
2460: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2461:
2462:
2463: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2464: @section Return Stack
2465: @cindex return stack tutorial
2466:
2467: In addition to the data stack Forth also has a second stack, the return
2468: stack; most Forth systems store the return addresses of procedure calls
2469: there (thus its name). Programmers can also use this stack:
2470:
2471: @example
2472: : foo ( n1 n2 -- )
2473: .s
2474: >r .s
2475: r@@ .
2476: >r .s
2477: r@@ .
2478: r> .
2479: r@@ .
2480: r> . ;
2481: 1 2 foo
2482: @end example
2483:
2484: @code{>r} takes an element from the data stack and pushes it onto the
2485: return stack; conversely, @code{r>} moves an elementm from the return to
2486: the data stack; @code{r@@} pushes a copy of the top of the return stack
2487: on the return stack.
2488:
2489: Forth programmers usually use the return stack for storing data
2490: temporarily, if using the data stack alone would be too complex, and
2491: factoring and locals are not an option:
2492:
2493: @example
2494: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2495: rot >r rot r> ;
2496: @end example
2497:
2498: The return address of the definition and the loop control parameters of
2499: counted loops usually reside on the return stack, so you have to take
2500: all items, that you have pushed on the return stack in a colon
2501: definition or counted loop, from the return stack before the definition
2502: or loop ends. You cannot access items that you pushed on the return
2503: stack outside some definition or loop within the definition of loop.
2504:
2505: If you miscount the return stack items, this usually ends in a crash:
2506:
2507: @example
2508: : crash ( n -- )
2509: >r ;
2510: 5 crash
2511: @end example
2512:
2513: You cannot mix using locals and using the return stack (according to the
2514: standard; Gforth has no problem). However, they solve the same
2515: problems, so this shouldn't be an issue.
2516:
2517: @assignment
2518: Can you rewrite any of the definitions you wrote until now in a better
2519: way using the return stack?
2520: @endassignment
2521:
2522: Reference: @ref{Return stack}.
2523:
2524:
2525: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2526: @section Memory
2527: @cindex memory access/allocation tutorial
2528:
2529: You can create a global variable @code{v} with
2530:
2531: @example
2532: variable v ( -- addr )
2533: @end example
2534:
2535: @code{v} pushes the address of a cell in memory on the stack. This cell
2536: was reserved by @code{variable}. You can use @code{!} (store) to store
2537: values into this cell and @code{@@} (fetch) to load the value from the
2538: stack into memory:
2539:
2540: @example
2541: v .
2542: 5 v ! .s
2543: v @@ .
2544: @end example
2545:
2546: You can see a raw dump of memory with @code{dump}:
2547:
2548: @example
2549: v 1 cells .s dump
2550: @end example
2551:
2552: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2553: generally, address units (aus)) that @code{n1 cells} occupy. You can
2554: also reserve more memory:
2555:
2556: @example
2557: create v2 20 cells allot
2558: v2 20 cells dump
2559: @end example
2560:
2561: creates a word @code{v2} and reserves 20 uninitialized cells; the
2562: address pushed by @code{v2} points to the start of these 20 cells. You
2563: can use address arithmetic to access these cells:
2564:
2565: @example
2566: 3 v2 5 cells + !
2567: v2 20 cells dump
2568: @end example
2569:
2570: You can reserve and initialize memory with @code{,}:
2571:
2572: @example
2573: create v3
2574: 5 , 4 , 3 , 2 , 1 ,
2575: v3 @@ .
2576: v3 cell+ @@ .
2577: v3 2 cells + @@ .
2578: v3 5 cells dump
2579: @end example
2580:
2581: @assignment
2582: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2583: @code{u} cells, with the first of these cells at @code{addr}, the next
2584: one at @code{addr cell+} etc.
2585: @endassignment
2586:
2587: You can also reserve memory without creating a new word:
2588:
2589: @example
2590: here 10 cells allot .
2591: here .
2592: @end example
2593:
2594: @code{Here} pushes the start address of the memory area. You should
2595: store it somewhere, or you will have a hard time finding the memory area
2596: again.
2597:
2598: @code{Allot} manages dictionary memory. The dictionary memory contains
2599: the system's data structures for words etc. on Gforth and most other
2600: Forth systems. It is managed like a stack: You can free the memory that
2601: you have just @code{allot}ed with
2602:
2603: @example
2604: -10 cells allot
2605: here .
2606: @end example
2607:
2608: Note that you cannot do this if you have created a new word in the
2609: meantime (because then your @code{allot}ed memory is no longer on the
2610: top of the dictionary ``stack'').
2611:
2612: Alternatively, you can use @code{allocate} and @code{free} which allow
2613: freeing memory in any order:
2614:
2615: @example
2616: 10 cells allocate throw .s
2617: 20 cells allocate throw .s
2618: swap
2619: free throw
2620: free throw
2621: @end example
2622:
2623: The @code{throw}s deal with errors (e.g., out of memory).
2624:
2625: And there is also a
2626: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2627: garbage collector}, which eliminates the need to @code{free} memory
2628: explicitly.
2629:
2630: Reference: @ref{Memory}.
2631:
2632:
2633: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2634: @section Characters and Strings
2635: @cindex strings tutorial
2636: @cindex characters tutorial
2637:
2638: On the stack characters take up a cell, like numbers. In memory they
2639: have their own size (one 8-bit byte on most systems), and therefore
2640: require their own words for memory access:
2641:
2642: @example
2643: create v4
2644: 104 c, 97 c, 108 c, 108 c, 111 c,
2645: v4 4 chars + c@@ .
2646: v4 5 chars dump
2647: @end example
2648:
2649: The preferred representation of strings on the stack is @code{addr
2650: u-count}, where @code{addr} is the address of the first character and
2651: @code{u-count} is the number of characters in the string.
2652:
2653: @example
2654: v4 5 type
2655: @end example
2656:
2657: You get a string constant with
2658:
2659: @example
2660: s" hello, world" .s
2661: type
2662: @end example
2663:
2664: Make sure you have a space between @code{s"} and the string; @code{s"}
2665: is a normal Forth word and must be delimited with white space (try what
2666: happens when you remove the space).
2667:
2668: However, this interpretive use of @code{s"} is quite restricted: the
2669: string exists only until the next call of @code{s"} (some Forth systems
2670: keep more than one of these strings, but usually they still have a
2671: limited lifetime).
2672:
2673: @example
2674: s" hello," s" world" .s
2675: type
2676: type
2677: @end example
2678:
2679: You can also use @code{s"} in a definition, and the resulting
2680: strings then live forever (well, for as long as the definition):
2681:
2682: @example
2683: : foo s" hello," s" world" ;
2684: foo .s
2685: type
2686: type
2687: @end example
2688:
2689: @assignment
2690: @code{Emit ( c -- )} types @code{c} as character (not a number).
2691: Implement @code{type ( addr u -- )}.
2692: @endassignment
2693:
2694: Reference: @ref{Memory Blocks}.
2695:
2696:
2697: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
2698: @section Alignment
2699: @cindex alignment tutorial
2700: @cindex memory alignment tutorial
2701:
2702: On many processors cells have to be aligned in memory, if you want to
2703: access them with @code{@@} and @code{!} (and even if the processor does
2704: not require alignment, access to aligned cells is faster).
2705:
2706: @code{Create} aligns @code{here} (i.e., the place where the next
2707: allocation will occur, and that the @code{create}d word points to).
2708: Likewise, the memory produced by @code{allocate} starts at an aligned
2709: address. Adding a number of @code{cells} to an aligned address produces
2710: another aligned address.
2711:
2712: However, address arithmetic involving @code{char+} and @code{chars} can
2713: create an address that is not cell-aligned. @code{Aligned ( addr --
2714: a-addr )} produces the next aligned address:
2715:
2716: @example
2717: v3 char+ aligned .s @@ .
2718: v3 char+ .s @@ .
2719: @end example
2720:
2721: Similarly, @code{align} advances @code{here} to the next aligned
2722: address:
2723:
2724: @example
2725: create v5 97 c,
2726: here .
2727: align here .
2728: 1000 ,
2729: @end example
2730:
2731: Note that you should use aligned addresses even if your processor does
2732: not require them, if you want your program to be portable.
2733:
2734: Reference: @ref{Address arithmetic}.
2735:
2736:
2737: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2738: @section Files
2739: @cindex files tutorial
2740:
2741: This section gives a short introduction into how to use files inside
2742: Forth. It's broken up into five easy steps:
2743:
2744: @enumerate 1
2745: @item Opened an ASCII text file for input
2746: @item Opened a file for output
2747: @item Read input file until string matched (or some other condition matched)
2748: @item Wrote some lines from input ( modified or not) to output
2749: @item Closed the files.
2750: @end enumerate
2751:
2752: @subsection Open file for input
2753:
2754: @example
2755: s" foo.in" r/o open-file throw Value fd-in
2756: @end example
2757:
2758: @subsection Create file for output
2759:
2760: @example
2761: s" foo.out" w/o create-file throw Value fd-out
2762: @end example
2763:
2764: The available file modes are r/o for read-only access, r/w for
2765: read-write access, and w/o for write-only access. You could open both
2766: files with r/w, too, if you like. All file words return error codes; for
2767: most applications, it's best to pass there error codes with @code{throw}
2768: to the outer error handler.
2769:
2770: If you want words for opening and assigning, define them as follows:
2771:
2772: @example
2773: 0 Value fd-in
2774: 0 Value fd-out
2775: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2776: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2777: @end example
2778:
2779: Usage example:
2780:
2781: @example
2782: s" foo.in" open-input
2783: s" foo.out" open-output
2784: @end example
2785:
2786: @subsection Scan file for a particular line
2787:
2788: @example
2789: 256 Constant max-line
2790: Create line-buffer max-line 2 + allot
2791:
2792: : scan-file ( addr u -- )
2793: begin
2794: line-buffer max-line fd-in read-line throw
2795: while
2796: >r 2dup line-buffer r> compare 0=
2797: until
2798: else
2799: drop
2800: then
2801: 2drop ;
2802: @end example
2803:
2804: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
2805: the buffer at addr, and returns the number of bytes read, a flag that's
2806: true when the end of file is reached, and an error code.
2807:
2808: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2809: returns zero if both strings are equal. It returns a positive number if
2810: the first string is lexically greater, a negative if the second string
2811: is lexically greater.
2812:
2813: We haven't seen this loop here; it has two exits. Since the @code{while}
2814: exits with the number of bytes read on the stack, we have to clean up
2815: that separately; that's after the @code{else}.
2816:
2817: Usage example:
2818:
2819: @example
2820: s" The text I search is here" scan-file
2821: @end example
2822:
2823: @subsection Copy input to output
2824:
2825: @example
2826: : copy-file ( -- )
2827: begin
2828: line-buffer max-line fd-in read-line throw
2829: while
2830: line-buffer swap fd-out write-file throw
2831: repeat ;
2832: @end example
2833:
2834: @subsection Close files
2835:
2836: @example
2837: fd-in close-file throw
2838: fd-out close-file throw
2839: @end example
2840:
2841: Likewise, you can put that into definitions, too:
2842:
2843: @example
2844: : close-input ( -- ) fd-in close-file throw ;
2845: : close-output ( -- ) fd-out close-file throw ;
2846: @end example
2847:
2848: @assignment
2849: How could you modify @code{copy-file} so that it copies until a second line is
2850: matched? Can you write a program that extracts a section of a text file,
2851: given the line that starts and the line that terminates that section?
2852: @endassignment
2853:
2854: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
2855: @section Interpretation and Compilation Semantics and Immediacy
2856: @cindex semantics tutorial
2857: @cindex interpretation semantics tutorial
2858: @cindex compilation semantics tutorial
2859: @cindex immediate, tutorial
2860:
2861: When a word is compiled, it behaves differently from being interpreted.
2862: E.g., consider @code{+}:
2863:
2864: @example
2865: 1 2 + .
2866: : foo + ;
2867: @end example
2868:
2869: These two behaviours are known as compilation and interpretation
2870: semantics. For normal words (e.g., @code{+}), the compilation semantics
2871: is to append the interpretation semantics to the currently defined word
2872: (@code{foo} in the example above). I.e., when @code{foo} is executed
2873: later, the interpretation semantics of @code{+} (i.e., adding two
2874: numbers) will be performed.
2875:
2876: However, there are words with non-default compilation semantics, e.g.,
2877: the control-flow words like @code{if}. You can use @code{immediate} to
2878: change the compilation semantics of the last defined word to be equal to
2879: the interpretation semantics:
2880:
2881: @example
2882: : [FOO] ( -- )
2883: 5 . ; immediate
2884:
2885: [FOO]
2886: : bar ( -- )
2887: [FOO] ;
2888: bar
2889: see bar
2890: @end example
2891:
2892: Two conventions to mark words with non-default compilation semnatics are
2893: names with brackets (more frequently used) and to write them all in
2894: upper case (less frequently used).
2895:
2896: In Gforth (and many other systems) you can also remove the
2897: interpretation semantics with @code{compile-only} (the compilation
2898: semantics is derived from the original interpretation semantics):
2899:
2900: @example
2901: : flip ( -- )
2902: 6 . ; compile-only \ but not immediate
2903: flip
2904:
2905: : flop ( -- )
2906: flip ;
2907: flop
2908: @end example
2909:
2910: In this example the interpretation semantics of @code{flop} is equal to
2911: the original interpretation semantics of @code{flip}.
2912:
2913: The text interpreter has two states: in interpret state, it performs the
2914: interpretation semantics of words it encounters; in compile state, it
2915: performs the compilation semantics of these words.
2916:
2917: Among other things, @code{:} switches into compile state, and @code{;}
2918: switches back to interpret state. They contain the factors @code{]}
2919: (switch to compile state) and @code{[} (switch to interpret state), that
2920: do nothing but switch the state.
2921:
2922: @example
2923: : xxx ( -- )
2924: [ 5 . ]
2925: ;
2926:
2927: xxx
2928: see xxx
2929: @end example
2930:
2931: These brackets are also the source of the naming convention mentioned
2932: above.
2933:
2934: Reference: @ref{Interpretation and Compilation Semantics}.
2935:
2936:
2937: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2938: @section Execution Tokens
2939: @cindex execution tokens tutorial
2940: @cindex XT tutorial
2941:
2942: @code{' word} gives you the execution token (XT) of a word. The XT is a
2943: cell representing the interpretation semantics of a word. You can
2944: execute this semantics with @code{execute}:
2945:
2946: @example
2947: ' + .s
2948: 1 2 rot execute .
2949: @end example
2950:
2951: The XT is similar to a function pointer in C. However, parameter
2952: passing through the stack makes it a little more flexible:
2953:
2954: @example
2955: : map-array ( ... addr u xt -- ... )
2956: \ executes xt ( ... x -- ... ) for every element of the array starting
2957: \ at addr and containing u elements
2958: @{ xt @}
2959: cells over + swap ?do
2960: i @@ xt execute
2961: 1 cells +loop ;
2962:
2963: create a 3 , 4 , 2 , -1 , 4 ,
2964: a 5 ' . map-array .s
2965: 0 a 5 ' + map-array .
2966: s" max-n" environment? drop .s
2967: a 5 ' min map-array .
2968: @end example
2969:
2970: You can use map-array with the XTs of words that consume one element
2971: more than they produce. In theory you can also use it with other XTs,
2972: but the stack effect then depends on the size of the array, which is
2973: hard to understand.
2974:
2975: Since XTs are cell-sized, you can store them in memory and manipulate
2976: them on the stack like other cells. You can also compile the XT into a
2977: word with @code{compile,}:
2978:
2979: @example
2980: : foo1 ( n1 n2 -- n )
2981: [ ' + compile, ] ;
2982: see foo
2983: @end example
2984:
2985: This is non-standard, because @code{compile,} has no compilation
2986: semantics in the standard, but it works in good Forth systems. For the
2987: broken ones, use
2988:
2989: @example
2990: : [compile,] compile, ; immediate
2991:
2992: : foo1 ( n1 n2 -- n )
2993: [ ' + ] [compile,] ;
2994: see foo
2995: @end example
2996:
2997: @code{'} is a word with default compilation semantics; it parses the
2998: next word when its interpretation semantics are executed, not during
2999: compilation:
3000:
3001: @example
3002: : foo ( -- xt )
3003: ' ;
3004: see foo
3005: : bar ( ... "word" -- ... )
3006: ' execute ;
3007: see bar
3008: 1 2 bar + .
3009: @end example
3010:
3011: You often want to parse a word during compilation and compile its XT so
3012: it will be pushed on the stack at run-time. @code{[']} does this:
3013:
3014: @example
3015: : xt-+ ( -- xt )
3016: ['] + ;
3017: see xt-+
3018: 1 2 xt-+ execute .
3019: @end example
3020:
3021: Many programmers tend to see @code{'} and the word it parses as one
3022: unit, and expect it to behave like @code{[']} when compiled, and are
3023: confused by the actual behaviour. If you are, just remember that the
3024: Forth system just takes @code{'} as one unit and has no idea that it is
3025: a parsing word (attempts to convenience programmers in this issue have
3026: usually resulted in even worse pitfalls, see
3027: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
3028: @code{State}-smartness---Why it is evil and How to Exorcise it}).
3029:
3030: Note that the state of the interpreter does not come into play when
3031: creating and executing XTs. I.e., even when you execute @code{'} in
3032: compile state, it still gives you the interpretation semantics. And
3033: whatever that state is, @code{execute} performs the semantics
3034: represented by the XT (i.e., for XTs produced with @code{'} the
3035: interpretation semantics).
3036:
3037: Reference: @ref{Tokens for Words}.
3038:
3039:
3040: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
3041: @section Exceptions
3042: @cindex exceptions tutorial
3043:
3044: @code{throw ( n -- )} causes an exception unless n is zero.
3045:
3046: @example
3047: 100 throw .s
3048: 0 throw .s
3049: @end example
3050:
3051: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
3052: it catches exceptions and pushes the number of the exception on the
3053: stack (or 0, if the xt executed without exception). If there was an
3054: exception, the stacks have the same depth as when entering @code{catch}:
3055:
3056: @example
3057: .s
3058: 3 0 ' / catch .s
3059: 3 2 ' / catch .s
3060: @end example
3061:
3062: @assignment
3063: Try the same with @code{execute} instead of @code{catch}.
3064: @endassignment
3065:
3066: @code{Throw} always jumps to the dynamically next enclosing
3067: @code{catch}, even if it has to leave several call levels to achieve
3068: this:
3069:
3070: @example
3071: : foo 100 throw ;
3072: : foo1 foo ." after foo" ;
3073: : bar ['] foo1 catch ;
3074: bar .
3075: @end example
3076:
3077: It is often important to restore a value upon leaving a definition, even
3078: if the definition is left through an exception. You can ensure this
3079: like this:
3080:
3081: @example
3082: : ...
3083: save-x
3084: ['] word-changing-x catch ( ... n )
3085: restore-x
3086: ( ... n ) throw ;
3087: @end example
3088:
3089: Gforth provides an alternative syntax in addition to @code{catch}:
3090: @code{try ... recover ... endtry}. If the code between @code{try} and
3091: @code{recover} has an exception, the stack depths are restored, the
3092: exception number is pushed on the stack, and the code between
3093: @code{recover} and @code{endtry} is performed. E.g., the definition for
3094: @code{catch} is
3095:
3096: @example
3097: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
3098: try
3099: execute 0
3100: recover
3101: nip
3102: endtry ;
3103: @end example
3104:
3105: The equivalent to the restoration code above is
3106:
3107: @example
3108: : ...
3109: save-x
3110: try
3111: word-changing-x
3112: end-try
3113: restore-x
3114: throw ;
3115: @end example
3116:
3117: As you can see, the @code{recover} part is optional.
3118:
3119: Reference: @ref{Exception Handling}.
3120:
3121:
3122: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
3123: @section Defining Words
3124: @cindex defining words tutorial
3125: @cindex does> tutorial
3126: @cindex create...does> tutorial
3127:
3128: @c before semantics?
3129:
3130: @code{:}, @code{create}, and @code{variable} are definition words: They
3131: define other words. @code{Constant} is another definition word:
3132:
3133: @example
3134: 5 constant foo
3135: foo .
3136: @end example
3137:
3138: You can also use the prefixes @code{2} (double-cell) and @code{f}
3139: (floating point) with @code{variable} and @code{constant}.
3140:
3141: You can also define your own defining words. E.g.:
3142:
3143: @example
3144: : variable ( "name" -- )
3145: create 0 , ;
3146: @end example
3147:
3148: You can also define defining words that create words that do something
3149: other than just producing their address:
3150:
3151: @example
3152: : constant ( n "name" -- )
3153: create ,
3154: does> ( -- n )
3155: ( addr ) @@ ;
3156:
3157: 5 constant foo
3158: foo .
3159: @end example
3160:
3161: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3162: @code{does>} replaces @code{;}, but it also does something else: It
3163: changes the last defined word such that it pushes the address of the
3164: body of the word and then performs the code after the @code{does>}
3165: whenever it is called.
3166:
3167: In the example above, @code{constant} uses @code{,} to store 5 into the
3168: body of @code{foo}. When @code{foo} executes, it pushes the address of
3169: the body onto the stack, then (in the code after the @code{does>})
3170: fetches the 5 from there.
3171:
3172: The stack comment near the @code{does>} reflects the stack effect of the
3173: defined word, not the stack effect of the code after the @code{does>}
3174: (the difference is that the code expects the address of the body that
3175: the stack comment does not show).
3176:
3177: You can use these definition words to do factoring in cases that involve
3178: (other) definition words. E.g., a field offset is always added to an
3179: address. Instead of defining
3180:
3181: @example
3182: 2 cells constant offset-field1
3183: @end example
3184:
3185: and using this like
3186:
3187: @example
3188: ( addr ) offset-field1 +
3189: @end example
3190:
3191: you can define a definition word
3192:
3193: @example
3194: : simple-field ( n "name" -- )
3195: create ,
3196: does> ( n1 -- n1+n )
3197: ( addr ) @@ + ;
3198: @end example
3199:
3200: Definition and use of field offsets now look like this:
3201:
3202: @example
3203: 2 cells simple-field field1
3204: create mystruct 4 cells allot
3205: mystruct .s field1 .s drop
3206: @end example
3207:
3208: If you want to do something with the word without performing the code
3209: after the @code{does>}, you can access the body of a @code{create}d word
3210: with @code{>body ( xt -- addr )}:
3211:
3212: @example
3213: : value ( n "name" -- )
3214: create ,
3215: does> ( -- n1 )
3216: @@ ;
3217: : to ( n "name" -- )
3218: ' >body ! ;
3219:
3220: 5 value foo
3221: foo .
3222: 7 to foo
3223: foo .
3224: @end example
3225:
3226: @assignment
3227: Define @code{defer ( "name" -- )}, which creates a word that stores an
3228: XT (at the start the XT of @code{abort}), and upon execution
3229: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3230: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3231: recursion is one application of @code{defer}.
3232: @endassignment
3233:
3234: Reference: @ref{User-defined Defining Words}.
3235:
3236:
3237: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3238: @section Arrays and Records
3239: @cindex arrays tutorial
3240: @cindex records tutorial
3241: @cindex structs tutorial
3242:
3243: Forth has no standard words for defining data structures such as arrays
3244: and records (structs in C terminology), but you can build them yourself
3245: based on address arithmetic. You can also define words for defining
3246: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
3247:
3248: One of the first projects a Forth newcomer sets out upon when learning
3249: about defining words is an array defining word (possibly for
3250: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3251: learn something from it. However, don't be disappointed when you later
3252: learn that you have little use for these words (inappropriate use would
3253: be even worse). I have not yet found a set of useful array words yet;
3254: the needs are just too diverse, and named, global arrays (the result of
3255: naive use of defining words) are often not flexible enough (e.g.,
3256: consider how to pass them as parameters). Another such project is a set
3257: of words to help dealing with strings.
3258:
3259: On the other hand, there is a useful set of record words, and it has
3260: been defined in @file{compat/struct.fs}; these words are predefined in
3261: Gforth. They are explained in depth elsewhere in this manual (see
3262: @pxref{Structures}). The @code{simple-field} example above is
3263: simplified variant of fields in this package.
3264:
3265:
3266: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3267: @section @code{POSTPONE}
3268: @cindex postpone tutorial
3269:
3270: You can compile the compilation semantics (instead of compiling the
3271: interpretation semantics) of a word with @code{POSTPONE}:
3272:
3273: @example
3274: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3275: POSTPONE + ; immediate
3276: : foo ( n1 n2 -- n )
3277: MY-+ ;
3278: 1 2 foo .
3279: see foo
3280: @end example
3281:
3282: During the definition of @code{foo} the text interpreter performs the
3283: compilation semantics of @code{MY-+}, which performs the compilation
3284: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3285:
3286: This example also displays separate stack comments for the compilation
3287: semantics and for the stack effect of the compiled code. For words with
3288: default compilation semantics these stack effects are usually not
3289: displayed; the stack effect of the compilation semantics is always
3290: @code{( -- )} for these words, the stack effect for the compiled code is
3291: the stack effect of the interpretation semantics.
3292:
3293: Note that the state of the interpreter does not come into play when
3294: performing the compilation semantics in this way. You can also perform
3295: it interpretively, e.g.:
3296:
3297: @example
3298: : foo2 ( n1 n2 -- n )
3299: [ MY-+ ] ;
3300: 1 2 foo .
3301: see foo
3302: @end example
3303:
3304: However, there are some broken Forth systems where this does not always
3305: work, and therefore this practice was been declared non-standard in
3306: 1999.
3307: @c !! repair.fs
3308:
3309: Here is another example for using @code{POSTPONE}:
3310:
3311: @example
3312: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3313: POSTPONE negate POSTPONE + ; immediate compile-only
3314: : bar ( n1 n2 -- n )
3315: MY-- ;
3316: 2 1 bar .
3317: see bar
3318: @end example
3319:
3320: You can define @code{ENDIF} in this way:
3321:
3322: @example
3323: : ENDIF ( Compilation: orig -- )
3324: POSTPONE then ; immediate
3325: @end example
3326:
3327: @assignment
3328: Write @code{MY-2DUP} that has compilation semantics equivalent to
3329: @code{2dup}, but compiles @code{over over}.
3330: @endassignment
3331:
3332: @c !! @xref{Macros} for reference
3333:
3334:
3335: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3336: @section @code{Literal}
3337: @cindex literal tutorial
3338:
3339: You cannot @code{POSTPONE} numbers:
3340:
3341: @example
3342: : [FOO] POSTPONE 500 ; immediate
3343: @end example
3344:
3345: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
3346:
3347: @example
3348: : [FOO] ( compilation: --; run-time: -- n )
3349: 500 POSTPONE literal ; immediate
3350:
3351: : flip [FOO] ;
3352: flip .
3353: see flip
3354: @end example
3355:
3356: @code{LITERAL} consumes a number at compile-time (when it's compilation
3357: semantics are executed) and pushes it at run-time (when the code it
3358: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3359: number computed at compile time into the current word:
3360:
3361: @example
3362: : bar ( -- n )
3363: [ 2 2 + ] literal ;
3364: see bar
3365: @end example
3366:
3367: @assignment
3368: Write @code{]L} which allows writing the example above as @code{: bar (
3369: -- n ) [ 2 2 + ]L ;}
3370: @endassignment
3371:
3372: @c !! @xref{Macros} for reference
3373:
3374:
3375: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3376: @section Advanced macros
3377: @cindex macros, advanced tutorial
3378: @cindex run-time code generation, tutorial
3379:
3380: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3381: Execution Tokens}. It frequently performs @code{execute}, a relatively
3382: expensive operation in some Forth implementations. You can use
3383: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3384: and produce a word that contains the word to be performed directly:
3385:
3386: @c use ]] ... [[
3387: @example
3388: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3389: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3390: \ array beginning at addr and containing u elements
3391: @{ xt @}
3392: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
3393: POSTPONE i POSTPONE @@ xt compile,
3394: 1 cells POSTPONE literal POSTPONE +loop ;
3395:
3396: : sum-array ( addr u -- n )
3397: 0 rot rot [ ' + compile-map-array ] ;
3398: see sum-array
3399: a 5 sum-array .
3400: @end example
3401:
3402: You can use the full power of Forth for generating the code; here's an
3403: example where the code is generated in a loop:
3404:
3405: @example
3406: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3407: \ n2=n1+(addr1)*n, addr2=addr1+cell
3408: POSTPONE tuck POSTPONE @@
3409: POSTPONE literal POSTPONE * POSTPONE +
3410: POSTPONE swap POSTPONE cell+ ;
3411:
3412: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
3413: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
3414: 0 postpone literal postpone swap
3415: [ ' compile-vmul-step compile-map-array ]
3416: postpone drop ;
3417: see compile-vmul
3418:
3419: : a-vmul ( addr -- n )
3420: \ n=a*v, where v is a vector that's as long as a and starts at addr
3421: [ a 5 compile-vmul ] ;
3422: see a-vmul
3423: a a-vmul .
3424: @end example
3425:
3426: This example uses @code{compile-map-array} to show off, but you could
3427: also use @code{map-array} instead (try it now!).
3428:
3429: You can use this technique for efficient multiplication of large
3430: matrices. In matrix multiplication, you multiply every line of one
3431: matrix with every column of the other matrix. You can generate the code
3432: for one line once, and use it for every column. The only downside of
3433: this technique is that it is cumbersome to recover the memory consumed
3434: by the generated code when you are done (and in more complicated cases
3435: it is not possible portably).
3436:
3437: @c !! @xref{Macros} for reference
3438:
3439:
3440: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3441: @section Compilation Tokens
3442: @cindex compilation tokens, tutorial
3443: @cindex CT, tutorial
3444:
3445: This section is Gforth-specific. You can skip it.
3446:
3447: @code{' word compile,} compiles the interpretation semantics. For words
3448: with default compilation semantics this is the same as performing the
3449: compilation semantics. To represent the compilation semantics of other
3450: words (e.g., words like @code{if} that have no interpretation
3451: semantics), Gforth has the concept of a compilation token (CT,
3452: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3453: You can perform the compilation semantics represented by a CT with
3454: @code{execute}:
3455:
3456: @example
3457: : foo2 ( n1 n2 -- n )
3458: [ comp' + execute ] ;
3459: see foo
3460: @end example
3461:
3462: You can compile the compilation semantics represented by a CT with
3463: @code{postpone,}:
3464:
3465: @example
3466: : foo3 ( -- )
3467: [ comp' + postpone, ] ;
3468: see foo3
3469: @end example
3470:
3471: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
3472: @code{comp'} is particularly useful for words that have no
3473: interpretation semantics:
3474:
3475: @example
3476: ' if
3477: comp' if .s 2drop
3478: @end example
3479:
3480: Reference: @ref{Tokens for Words}.
3481:
3482:
3483: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3484: @section Wordlists and Search Order
3485: @cindex wordlists tutorial
3486: @cindex search order, tutorial
3487:
3488: The dictionary is not just a memory area that allows you to allocate
3489: memory with @code{allot}, it also contains the Forth words, arranged in
3490: several wordlists. When searching for a word in a wordlist,
3491: conceptually you start searching at the youngest and proceed towards
3492: older words (in reality most systems nowadays use hash-tables); i.e., if
3493: you define a word with the same name as an older word, the new word
3494: shadows the older word.
3495:
3496: Which wordlists are searched in which order is determined by the search
3497: order. You can display the search order with @code{order}. It displays
3498: first the search order, starting with the wordlist searched first, then
3499: it displays the wordlist that will contain newly defined words.
3500:
3501: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
3502:
3503: @example
3504: wordlist constant mywords
3505: @end example
3506:
3507: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3508: defined words (the @emph{current} wordlist):
3509:
3510: @example
3511: mywords set-current
3512: order
3513: @end example
3514:
3515: Gforth does not display a name for the wordlist in @code{mywords}
3516: because this wordlist was created anonymously with @code{wordlist}.
3517:
3518: You can get the current wordlist with @code{get-current ( -- wid)}. If
3519: you want to put something into a specific wordlist without overall
3520: effect on the current wordlist, this typically looks like this:
3521:
3522: @example
3523: get-current mywords set-current ( wid )
3524: create someword
3525: ( wid ) set-current
3526: @end example
3527:
3528: You can write the search order with @code{set-order ( wid1 .. widn n --
3529: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3530: searched wordlist is topmost.
3531:
3532: @example
3533: get-order mywords swap 1+ set-order
3534: order
3535: @end example
3536:
3537: Yes, the order of wordlists in the output of @code{order} is reversed
3538: from stack comments and the output of @code{.s} and thus unintuitive.
3539:
3540: @assignment
3541: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3542: wordlist to the search order. Define @code{previous ( -- )}, which
3543: removes the first searched wordlist from the search order. Experiment
3544: with boundary conditions (you will see some crashes or situations that
3545: are hard or impossible to leave).
3546: @endassignment
3547:
3548: The search order is a powerful foundation for providing features similar
3549: to Modula-2 modules and C++ namespaces. However, trying to modularize
3550: programs in this way has disadvantages for debugging and reuse/factoring
3551: that overcome the advantages in my experience (I don't do huge projects,
3552: though). These disadvantages are not so clear in other
3553: languages/programming environments, because these languages are not so
3554: strong in debugging and reuse.
3555:
3556: @c !! example
3557:
3558: Reference: @ref{Word Lists}.
3559:
3560: @c ******************************************************************
3561: @node Introduction, Words, Tutorial, Top
3562: @comment node-name, next, previous, up
3563: @chapter An Introduction to ANS Forth
3564: @cindex Forth - an introduction
3565:
3566: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3567: that it is slower-paced in its examples, but uses them to dive deep into
3568: explaining Forth internals (not covered by the Tutorial). Apart from
3569: that, this chapter covers far less material. It is suitable for reading
3570: without using a computer.
3571:
3572: The primary purpose of this manual is to document Gforth. However, since
3573: Forth is not a widely-known language and there is a lack of up-to-date
3574: teaching material, it seems worthwhile to provide some introductory
3575: material. For other sources of Forth-related
3576: information, see @ref{Forth-related information}.
3577:
3578: The examples in this section should work on any ANS Forth; the
3579: output shown was produced using Gforth. Each example attempts to
3580: reproduce the exact output that Gforth produces. If you try out the
3581: examples (and you should), what you should type is shown @kbd{like this}
3582: and Gforth's response is shown @code{like this}. The single exception is
3583: that, where the example shows @key{RET} it means that you should
3584: press the ``carriage return'' key. Unfortunately, some output formats for
3585: this manual cannot show the difference between @kbd{this} and
3586: @code{this} which will make trying out the examples harder (but not
3587: impossible).
3588:
3589: Forth is an unusual language. It provides an interactive development
3590: environment which includes both an interpreter and compiler. Forth
3591: programming style encourages you to break a problem down into many
3592: @cindex factoring
3593: small fragments (@dfn{factoring}), and then to develop and test each
3594: fragment interactively. Forth advocates assert that breaking the
3595: edit-compile-test cycle used by conventional programming languages can
3596: lead to great productivity improvements.
3597:
3598: @menu
3599: * Introducing the Text Interpreter::
3600: * Stacks and Postfix notation::
3601: * Your first definition::
3602: * How does that work?::
3603: * Forth is written in Forth::
3604: * Review - elements of a Forth system::
3605: * Where to go next::
3606: * Exercises::
3607: @end menu
3608:
3609: @comment ----------------------------------------------
3610: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3611: @section Introducing the Text Interpreter
3612: @cindex text interpreter
3613: @cindex outer interpreter
3614:
3615: @c IMO this is too detailed and the pace is too slow for
3616: @c an introduction. If you know German, take a look at
3617: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3618: @c to see how I do it - anton
3619:
3620: @c nac-> Where I have accepted your comments 100% and modified the text
3621: @c accordingly, I have deleted your comments. Elsewhere I have added a
3622: @c response like this to attempt to rationalise what I have done. Of
3623: @c course, this is a very clumsy mechanism for something that would be
3624: @c done far more efficiently over a beer. Please delete any dialogue
3625: @c you consider closed.
3626:
3627: When you invoke the Forth image, you will see a startup banner printed
3628: and nothing else (if you have Gforth installed on your system, try
3629: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
3630: its command line interpreter, which is called the @dfn{Text Interpreter}
3631: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
3632: about the text interpreter as you read through this chapter, for more
3633: detail @pxref{The Text Interpreter}).
3634:
3635: Although it's not obvious, Forth is actually waiting for your
3636: input. Type a number and press the @key{RET} key:
3637:
3638: @example
3639: @kbd{45@key{RET}} ok
3640: @end example
3641:
3642: Rather than give you a prompt to invite you to input something, the text
3643: interpreter prints a status message @i{after} it has processed a line
3644: of input. The status message in this case (``@code{ ok}'' followed by
3645: carriage-return) indicates that the text interpreter was able to process
3646: all of your input successfully. Now type something illegal:
3647:
3648: @example
3649: @kbd{qwer341@key{RET}}
3650: :1: Undefined word
3651: qwer341
3652: ^^^^^^^
3653: $400D2BA8 Bounce
3654: $400DBDA8 no.extensions
3655: @end example
3656:
3657: The exact text, other than the ``Undefined word'' may differ slightly on
3658: your system, but the effect is the same; when the text interpreter
3659: detects an error, it discards any remaining text on a line, resets
3660: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
3661: messages}.
3662:
3663: The text interpreter waits for you to press carriage-return, and then
3664: processes your input line. Starting at the beginning of the line, it
3665: breaks the line into groups of characters separated by spaces. For each
3666: group of characters in turn, it makes two attempts to do something:
3667:
3668: @itemize @bullet
3669: @item
3670: @cindex name dictionary
3671: It tries to treat it as a command. It does this by searching a @dfn{name
3672: dictionary}. If the group of characters matches an entry in the name
3673: dictionary, the name dictionary provides the text interpreter with
3674: information that allows the text interpreter perform some actions. In
3675: Forth jargon, we say that the group
3676: @cindex word
3677: @cindex definition
3678: @cindex execution token
3679: @cindex xt
3680: of characters names a @dfn{word}, that the dictionary search returns an
3681: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3682: word, and that the text interpreter executes the xt. Often, the terms
3683: @dfn{word} and @dfn{definition} are used interchangeably.
3684: @item
3685: If the text interpreter fails to find a match in the name dictionary, it
3686: tries to treat the group of characters as a number in the current number
3687: base (when you start up Forth, the current number base is base 10). If
3688: the group of characters legitimately represents a number, the text
3689: interpreter pushes the number onto a stack (we'll learn more about that
3690: in the next section).
3691: @end itemize
3692:
3693: If the text interpreter is unable to do either of these things with any
3694: group of characters, it discards the group of characters and the rest of
3695: the line, then prints an error message. If the text interpreter reaches
3696: the end of the line without error, it prints the status message ``@code{ ok}''
3697: followed by carriage-return.
3698:
3699: This is the simplest command we can give to the text interpreter:
3700:
3701: @example
3702: @key{RET} ok
3703: @end example
3704:
3705: The text interpreter did everything we asked it to do (nothing) without
3706: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3707: command:
3708:
3709: @example
3710: @kbd{12 dup fred dup@key{RET}}
3711: :1: Undefined word
3712: 12 dup fred dup
3713: ^^^^
3714: $400D2BA8 Bounce
3715: $400DBDA8 no.extensions
3716: @end example
3717:
3718: When you press the carriage-return key, the text interpreter starts to
3719: work its way along the line:
3720:
3721: @itemize @bullet
3722: @item
3723: When it gets to the space after the @code{2}, it takes the group of
3724: characters @code{12} and looks them up in the name
3725: dictionary@footnote{We can't tell if it found them or not, but assume
3726: for now that it did not}. There is no match for this group of characters
3727: in the name dictionary, so it tries to treat them as a number. It is
3728: able to do this successfully, so it puts the number, 12, ``on the stack''
3729: (whatever that means).
3730: @item
3731: The text interpreter resumes scanning the line and gets the next group
3732: of characters, @code{dup}. It looks it up in the name dictionary and
3733: (you'll have to take my word for this) finds it, and executes the word
3734: @code{dup} (whatever that means).
3735: @item
3736: Once again, the text interpreter resumes scanning the line and gets the
3737: group of characters @code{fred}. It looks them up in the name
3738: dictionary, but can't find them. It tries to treat them as a number, but
3739: they don't represent any legal number.
3740: @end itemize
3741:
3742: At this point, the text interpreter gives up and prints an error
3743: message. The error message shows exactly how far the text interpreter
3744: got in processing the line. In particular, it shows that the text
3745: interpreter made no attempt to do anything with the final character
3746: group, @code{dup}, even though we have good reason to believe that the
3747: text interpreter would have no problem looking that word up and
3748: executing it a second time.
3749:
3750:
3751: @comment ----------------------------------------------
3752: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3753: @section Stacks, postfix notation and parameter passing
3754: @cindex text interpreter
3755: @cindex outer interpreter
3756:
3757: In procedural programming languages (like C and Pascal), the
3758: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3759: functions or procedures are called with @dfn{explicit parameters}. For
3760: example, in C we might write:
3761:
3762: @example
3763: total = total + new_volume(length,height,depth);
3764: @end example
3765:
3766: @noindent
3767: where new_volume is a function-call to another piece of code, and total,
3768: length, height and depth are all variables. length, height and depth are
3769: parameters to the function-call.
3770:
3771: In Forth, the equivalent of the function or procedure is the
3772: @dfn{definition} and parameters are implicitly passed between
3773: definitions using a shared stack that is visible to the
3774: programmer. Although Forth does support variables, the existence of the
3775: stack means that they are used far less often than in most other
3776: programming languages. When the text interpreter encounters a number, it
3777: will place (@dfn{push}) it on the stack. There are several stacks (the
3778: actual number is implementation-dependent ...) and the particular stack
3779: used for any operation is implied unambiguously by the operation being
3780: performed. The stack used for all integer operations is called the @dfn{data
3781: stack} and, since this is the stack used most commonly, references to
3782: ``the data stack'' are often abbreviated to ``the stack''.
3783:
3784: The stacks have a last-in, first-out (LIFO) organisation. If you type:
3785:
3786: @example
3787: @kbd{1 2 3@key{RET}} ok
3788: @end example
3789:
3790: Then this instructs the text interpreter to placed three numbers on the
3791: (data) stack. An analogy for the behaviour of the stack is to take a
3792: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3793: the table. The 3 was the last card onto the pile (``last-in'') and if
3794: you take a card off the pile then, unless you're prepared to fiddle a
3795: bit, the card that you take off will be the 3 (``first-out''). The
3796: number that will be first-out of the stack is called the @dfn{top of
3797: stack}, which
3798: @cindex TOS definition
3799: is often abbreviated to @dfn{TOS}.
3800:
3801: To understand how parameters are passed in Forth, consider the
3802: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3803: be surprised to learn that this definition performs addition. More
3804: precisely, it adds two number together and produces a result. Where does
3805: it get the two numbers from? It takes the top two numbers off the
3806: stack. Where does it place the result? On the stack. You can act-out the
3807: behaviour of @code{+} with your playing cards like this:
3808:
3809: @itemize @bullet
3810: @item
3811: Pick up two cards from the stack on the table
3812: @item
3813: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3814: numbers''
3815: @item
3816: Decide that the answer is 5
3817: @item
3818: Shuffle the two cards back into the pack and find a 5
3819: @item
3820: Put a 5 on the remaining ace that's on the table.
3821: @end itemize
3822:
3823: If you don't have a pack of cards handy but you do have Forth running,
3824: you can use the definition @code{.s} to show the current state of the stack,
3825: without affecting the stack. Type:
3826:
3827: @example
3828: @kbd{clearstack 1 2 3@key{RET}} ok
3829: @kbd{.s@key{RET}} <3> 1 2 3 ok
3830: @end example
3831:
3832: The text interpreter looks up the word @code{clearstack} and executes
3833: it; it tidies up the stack and removes any entries that may have been
3834: left on it by earlier examples. The text interpreter pushes each of the
3835: three numbers in turn onto the stack. Finally, the text interpreter
3836: looks up the word @code{.s} and executes it. The effect of executing
3837: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3838: followed by a list of all the items on the stack; the item on the far
3839: right-hand side is the TOS.
3840:
3841: You can now type:
3842:
3843: @example
3844: @kbd{+ .s@key{RET}} <2> 1 5 ok
3845: @end example
3846:
3847: @noindent
3848: which is correct; there are now 2 items on the stack and the result of
3849: the addition is 5.
3850:
3851: If you're playing with cards, try doing a second addition: pick up the
3852: two cards, work out that their sum is 6, shuffle them into the pack,
3853: look for a 6 and place that on the table. You now have just one item on
3854: the stack. What happens if you try to do a third addition? Pick up the
3855: first card, pick up the second card -- ah! There is no second card. This
3856: is called a @dfn{stack underflow} and consitutes an error. If you try to
3857: do the same thing with Forth it will report an error (probably a Stack
3858: Underflow or an Invalid Memory Address error).
3859:
3860: The opposite situation to a stack underflow is a @dfn{stack overflow},
3861: which simply accepts that there is a finite amount of storage space
3862: reserved for the stack. To stretch the playing card analogy, if you had
3863: enough packs of cards and you piled the cards up on the table, you would
3864: eventually be unable to add another card; you'd hit the ceiling. Gforth
3865: allows you to set the maximum size of the stacks. In general, the only
3866: time that you will get a stack overflow is because a definition has a
3867: bug in it and is generating data on the stack uncontrollably.
3868:
3869: There's one final use for the playing card analogy. If you model your
3870: stack using a pack of playing cards, the maximum number of items on
3871: your stack will be 52 (I assume you didn't use the Joker). The maximum
3872: @i{value} of any item on the stack is 13 (the King). In fact, the only
3873: possible numbers are positive integer numbers 1 through 13; you can't
3874: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3875: think about some of the cards, you can accommodate different
3876: numbers. For example, you could think of the Jack as representing 0,
3877: the Queen as representing -1 and the King as representing -2. Your
3878: @i{range} remains unchanged (you can still only represent a total of 13
3879: numbers) but the numbers that you can represent are -2 through 10.
3880:
3881: In that analogy, the limit was the amount of information that a single
3882: stack entry could hold, and Forth has a similar limit. In Forth, the
3883: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3884: implementation dependent and affects the maximum value that a stack
3885: entry can hold. A Standard Forth provides a cell size of at least
3886: 16-bits, and most desktop systems use a cell size of 32-bits.
3887:
3888: Forth does not do any type checking for you, so you are free to
3889: manipulate and combine stack items in any way you wish. A convenient way
3890: of treating stack items is as 2's complement signed integers, and that
3891: is what Standard words like @code{+} do. Therefore you can type:
3892:
3893: @example
3894: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
3895: @end example
3896:
3897: If you use numbers and definitions like @code{+} in order to turn Forth
3898: into a great big pocket calculator, you will realise that it's rather
3899: different from a normal calculator. Rather than typing 2 + 3 = you had
3900: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3901: result). The terminology used to describe this difference is to say that
3902: your calculator uses @dfn{Infix Notation} (parameters and operators are
3903: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3904: operators are separate), also called @dfn{Reverse Polish Notation}.
3905:
3906: Whilst postfix notation might look confusing to begin with, it has
3907: several important advantages:
3908:
3909: @itemize @bullet
3910: @item
3911: it is unambiguous
3912: @item
3913: it is more concise
3914: @item
3915: it fits naturally with a stack-based system
3916: @end itemize
3917:
3918: To examine these claims in more detail, consider these sums:
3919:
3920: @example
3921: 6 + 5 * 4 =
3922: 4 * 5 + 6 =
3923: @end example
3924:
3925: If you're just learning maths or your maths is very rusty, you will
3926: probably come up with the answer 44 for the first and 26 for the
3927: second. If you are a bit of a whizz at maths you will remember the
3928: @i{convention} that multiplication takes precendence over addition, and
3929: you'd come up with the answer 26 both times. To explain the answer 26
3930: to someone who got the answer 44, you'd probably rewrite the first sum
3931: like this:
3932:
3933: @example
3934: 6 + (5 * 4) =
3935: @end example
3936:
3937: If what you really wanted was to perform the addition before the
3938: multiplication, you would have to use parentheses to force it.
3939:
3940: If you did the first two sums on a pocket calculator you would probably
3941: get the right answers, unless you were very cautious and entered them using
3942: these keystroke sequences:
3943:
3944: 6 + 5 = * 4 =
3945: 4 * 5 = + 6 =
3946:
3947: Postfix notation is unambiguous because the order that the operators
3948: are applied is always explicit; that also means that parentheses are
3949: never required. The operators are @i{active} (the act of quoting the
3950: operator makes the operation occur) which removes the need for ``=''.
3951:
3952: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3953: equivalent ways:
3954:
3955: @example
3956: 6 5 4 * + or:
3957: 5 4 * 6 +
3958: @end example
3959:
3960: An important thing that you should notice about this notation is that
3961: the @i{order} of the numbers does not change; if you want to subtract
3962: 2 from 10 you type @code{10 2 -}.
3963:
3964: The reason that Forth uses postfix notation is very simple to explain: it
3965: makes the implementation extremely simple, and it follows naturally from
3966: using the stack as a mechanism for passing parameters. Another way of
3967: thinking about this is to realise that all Forth definitions are
3968: @i{active}; they execute as they are encountered by the text
3969: interpreter. The result of this is that the syntax of Forth is trivially
3970: simple.
3971:
3972:
3973:
3974: @comment ----------------------------------------------
3975: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3976: @section Your first Forth definition
3977: @cindex first definition
3978:
3979: Until now, the examples we've seen have been trivial; we've just been
3980: using Forth as a bigger-than-pocket calculator. Also, each calculation
3981: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3982: again@footnote{That's not quite true. If you press the up-arrow key on
3983: your keyboard you should be able to scroll back to any earlier command,
3984: edit it and re-enter it.} In this section we'll see how to add new
3985: words to Forth's vocabulary.
3986:
3987: The easiest way to create a new word is to use a @dfn{colon
3988: definition}. We'll define a few and try them out before worrying too
3989: much about how they work. Try typing in these examples; be careful to
3990: copy the spaces accurately:
3991:
3992: @example
3993: : add-two 2 + . ;
3994: : greet ." Hello and welcome" ;
3995: : demo 5 add-two ;
3996: @end example
3997:
3998: @noindent
3999: Now try them out:
4000:
4001: @example
4002: @kbd{greet@key{RET}} Hello and welcome ok
4003: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
4004: @kbd{4 add-two@key{RET}} 6 ok
4005: @kbd{demo@key{RET}} 7 ok
4006: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
4007: @end example
4008:
4009: The first new thing that we've introduced here is the pair of words
4010: @code{:} and @code{;}. These are used to start and terminate a new
4011: definition, respectively. The first word after the @code{:} is the name
4012: for the new definition.
4013:
4014: As you can see from the examples, a definition is built up of words that
4015: have already been defined; Forth makes no distinction between
4016: definitions that existed when you started the system up, and those that
4017: you define yourself.
4018:
4019: The examples also introduce the words @code{.} (dot), @code{."}
4020: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
4021: the stack and displays it. It's like @code{.s} except that it only
4022: displays the top item of the stack and it is destructive; after it has
4023: executed, the number is no longer on the stack. There is always one
4024: space printed after the number, and no spaces before it. Dot-quote
4025: defines a string (a sequence of characters) that will be printed when
4026: the word is executed. The string can contain any printable characters
4027: except @code{"}. A @code{"} has a special function; it is not a Forth
4028: word but it acts as a delimiter (the way that delimiters work is
4029: described in the next section). Finally, @code{dup} duplicates the value
4030: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
4031:
4032: We already know that the text interpreter searches through the
4033: dictionary to locate names. If you've followed the examples earlier, you
4034: will already have a definition called @code{add-two}. Lets try modifying
4035: it by typing in a new definition:
4036:
4037: @example
4038: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
4039: @end example
4040:
4041: Forth recognised that we were defining a word that already exists, and
4042: printed a message to warn us of that fact. Let's try out the new
4043: definition:
4044:
4045: @example
4046: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
4047: @end example
4048:
4049: @noindent
4050: All that we've actually done here, though, is to create a new
4051: definition, with a particular name. The fact that there was already a
4052: definition with the same name did not make any difference to the way
4053: that the new definition was created (except that Forth printed a warning
4054: message). The old definition of add-two still exists (try @code{demo}
4055: again to see that this is true). Any new definition will use the new
4056: definition of @code{add-two}, but old definitions continue to use the
4057: version that already existed at the time that they were @code{compiled}.
4058:
4059: Before you go on to the next section, try defining and redefining some
4060: words of your own.
4061:
4062: @comment ----------------------------------------------
4063: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
4064: @section How does that work?
4065: @cindex parsing words
4066:
4067: @c That's pretty deep (IMO way too deep) for an introduction. - anton
4068:
4069: @c Is it a good idea to talk about the interpretation semantics of a
4070: @c number? We don't have an xt to go along with it. - anton
4071:
4072: @c Now that I have eliminated execution semantics, I wonder if it would not
4073: @c be better to keep them (or add run-time semantics), to make it easier to
4074: @c explain what compilation semantics usually does. - anton
4075:
4076: @c nac-> I removed the term ``default compilation sematics'' from the
4077: @c introductory chapter. Removing ``execution semantics'' was making
4078: @c everything simpler to explain, then I think the use of this term made
4079: @c everything more complex again. I replaced it with ``default
4080: @c semantics'' (which is used elsewhere in the manual) by which I mean
4081: @c ``a definition that has neither the immediate nor the compile-only
4082: @c flag set''.
4083:
4084: @c anton: I have eliminated default semantics (except in one place where it
4085: @c means "default interpretation and compilation semantics"), because it
4086: @c makes no sense in the presence of combined words. I reverted to
4087: @c "execution semantics" where necessary.
4088:
4089: @c nac-> I reworded big chunks of the ``how does that work''
4090: @c section (and, unusually for me, I think I even made it shorter!). See
4091: @c what you think -- I know I have not addressed your primary concern
4092: @c that it is too heavy-going for an introduction. From what I understood
4093: @c of your course notes it looks as though they might be a good framework.
4094: @c Things that I've tried to capture here are some things that came as a
4095: @c great revelation here when I first understood them. Also, I like the
4096: @c fact that a very simple code example shows up almost all of the issues
4097: @c that you need to understand to see how Forth works. That's unique and
4098: @c worthwhile to emphasise.
4099:
4100: @c anton: I think it's a good idea to present the details, especially those
4101: @c that you found to be a revelation, and probably the tutorial tries to be
4102: @c too superficial and does not get some of the things across that make
4103: @c Forth special. I do believe that most of the time these things should
4104: @c be discussed at the end of a section or in separate sections instead of
4105: @c in the middle of a section (e.g., the stuff you added in "User-defined
4106: @c defining words" leads in a completely different direction from the rest
4107: @c of the section).
4108:
4109: Now we're going to take another look at the definition of @code{add-two}
4110: from the previous section. From our knowledge of the way that the text
4111: interpreter works, we would have expected this result when we tried to
4112: define @code{add-two}:
4113:
4114: @example
4115: @kbd{: add-two 2 + . ;@key{RET}}
4116: ^^^^^^^
4117: Error: Undefined word
4118: @end example
4119:
4120: The reason that this didn't happen is bound up in the way that @code{:}
4121: works. The word @code{:} does two special things. The first special
4122: thing that it does prevents the text interpreter from ever seeing the
4123: characters @code{add-two}. The text interpreter uses a variable called
4124: @cindex modifying >IN
4125: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
4126: input line. When it encounters the word @code{:} it behaves in exactly
4127: the same way as it does for any other word; it looks it up in the name
4128: dictionary, finds its xt and executes it. When @code{:} executes, it
4129: looks at the input buffer, finds the word @code{add-two} and advances the
4130: value of @code{>IN} to point past it. It then does some other stuff
4131: associated with creating the new definition (including creating an entry
4132: for @code{add-two} in the name dictionary). When the execution of @code{:}
4133: completes, control returns to the text interpreter, which is oblivious
4134: to the fact that it has been tricked into ignoring part of the input
4135: line.
4136:
4137: @cindex parsing words
4138: Words like @code{:} -- words that advance the value of @code{>IN} and so
4139: prevent the text interpreter from acting on the whole of the input line
4140: -- are called @dfn{parsing words}.
4141:
4142: @cindex @code{state} - effect on the text interpreter
4143: @cindex text interpreter - effect of state
4144: The second special thing that @code{:} does is change the value of a
4145: variable called @code{state}, which affects the way that the text
4146: interpreter behaves. When Gforth starts up, @code{state} has the value
4147: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4148: colon definition (started with @code{:}), @code{state} is set to -1 and
4149: the text interpreter is said to be @dfn{compiling}.
4150:
4151: In this example, the text interpreter is compiling when it processes the
4152: string ``@code{2 + . ;}''. It still breaks the string down into
4153: character sequences in the same way. However, instead of pushing the
4154: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4155: into the definition of @code{add-two} that will make the number @code{2} get
4156: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4157: the behaviours of @code{+} and @code{.} are also compiled into the
4158: definition.
4159:
4160: One category of words don't get compiled. These so-called @dfn{immediate
4161: words} get executed (performed @i{now}) regardless of whether the text
4162: interpreter is interpreting or compiling. The word @code{;} is an
4163: immediate word. Rather than being compiled into the definition, it
4164: executes. Its effect is to terminate the current definition, which
4165: includes changing the value of @code{state} back to 0.
4166:
4167: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4168: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4169: definition.
4170:
4171: In Forth, every word or number can be described in terms of two
4172: properties:
4173:
4174: @itemize @bullet
4175: @item
4176: @cindex interpretation semantics
4177: Its @dfn{interpretation semantics} describe how it will behave when the
4178: text interpreter encounters it in @dfn{interpret} state. The
4179: interpretation semantics of a word are represented by an @dfn{execution
4180: token}.
4181: @item
4182: @cindex compilation semantics
4183: Its @dfn{compilation semantics} describe how it will behave when the
4184: text interpreter encounters it in @dfn{compile} state. The compilation
4185: semantics of a word are represented in an implementation-dependent way;
4186: Gforth uses a @dfn{compilation token}.
4187: @end itemize
4188:
4189: @noindent
4190: Numbers are always treated in a fixed way:
4191:
4192: @itemize @bullet
4193: @item
4194: When the number is @dfn{interpreted}, its behaviour is to push the
4195: number onto the stack.
4196: @item
4197: When the number is @dfn{compiled}, a piece of code is appended to the
4198: current definition that pushes the number when it runs. (In other words,
4199: the compilation semantics of a number are to postpone its interpretation
4200: semantics until the run-time of the definition that it is being compiled
4201: into.)
4202: @end itemize
4203:
4204: Words don't behave in such a regular way, but most have @i{default
4205: semantics} which means that they behave like this:
4206:
4207: @itemize @bullet
4208: @item
4209: The @dfn{interpretation semantics} of the word are to do something useful.
4210: @item
4211: The @dfn{compilation semantics} of the word are to append its
4212: @dfn{interpretation semantics} to the current definition (so that its
4213: run-time behaviour is to do something useful).
4214: @end itemize
4215:
4216: @cindex immediate words
4217: The actual behaviour of any particular word can be controlled by using
4218: the words @code{immediate} and @code{compile-only} when the word is
4219: defined. These words set flags in the name dictionary entry of the most
4220: recently defined word, and these flags are retrieved by the text
4221: interpreter when it finds the word in the name dictionary.
4222:
4223: A word that is marked as @dfn{immediate} has compilation semantics that
4224: are identical to its interpretation semantics. In other words, it
4225: behaves like this:
4226:
4227: @itemize @bullet
4228: @item
4229: The @dfn{interpretation semantics} of the word are to do something useful.
4230: @item
4231: The @dfn{compilation semantics} of the word are to do something useful
4232: (and actually the same thing); i.e., it is executed during compilation.
4233: @end itemize
4234:
4235: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4236: performing the interpretation semantics of the word directly; an attempt
4237: to do so will generate an error. It is never necessary to use
4238: @code{compile-only} (and it is not even part of ANS Forth, though it is
4239: provided by many implementations) but it is good etiquette to apply it
4240: to a word that will not behave correctly (and might have unexpected
4241: side-effects) in interpret state. For example, it is only legal to use
4242: the conditional word @code{IF} within a definition. If you forget this
4243: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4244: @code{compile-only} allows the text interpreter to generate a helpful
4245: error message rather than subjecting you to the consequences of your
4246: folly.
4247:
4248: This example shows the difference between an immediate and a
4249: non-immediate word:
4250:
4251: @example
4252: : show-state state @@ . ;
4253: : show-state-now show-state ; immediate
4254: : word1 show-state ;
4255: : word2 show-state-now ;
4256: @end example
4257:
4258: The word @code{immediate} after the definition of @code{show-state-now}
4259: makes that word an immediate word. These definitions introduce a new
4260: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4261: variable, and leaves it on the stack. Therefore, the behaviour of
4262: @code{show-state} is to print a number that represents the current value
4263: of @code{state}.
4264:
4265: When you execute @code{word1}, it prints the number 0, indicating that
4266: the system is interpreting. When the text interpreter compiled the
4267: definition of @code{word1}, it encountered @code{show-state} whose
4268: compilation semantics are to append its interpretation semantics to the
4269: current definition. When you execute @code{word1}, it performs the
4270: interpretation semantics of @code{show-state}. At the time that @code{word1}
4271: (and therefore @code{show-state}) are executed, the system is
4272: interpreting.
4273:
4274: When you pressed @key{RET} after entering the definition of @code{word2},
4275: you should have seen the number -1 printed, followed by ``@code{
4276: ok}''. When the text interpreter compiled the definition of
4277: @code{word2}, it encountered @code{show-state-now}, an immediate word,
4278: whose compilation semantics are therefore to perform its interpretation
4279: semantics. It is executed straight away (even before the text
4280: interpreter has moved on to process another group of characters; the
4281: @code{;} in this example). The effect of executing it are to display the
4282: value of @code{state} @i{at the time that the definition of}
4283: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4284: system is compiling at this time. If you execute @code{word2} it does
4285: nothing at all.
4286:
4287: @cindex @code{."}, how it works
4288: Before leaving the subject of immediate words, consider the behaviour of
4289: @code{."} in the definition of @code{greet}, in the previous
4290: section. This word is both a parsing word and an immediate word. Notice
4291: that there is a space between @code{."} and the start of the text
4292: @code{Hello and welcome}, but that there is no space between the last
4293: letter of @code{welcome} and the @code{"} character. The reason for this
4294: is that @code{."} is a Forth word; it must have a space after it so that
4295: the text interpreter can identify it. The @code{"} is not a Forth word;
4296: it is a @dfn{delimiter}. The examples earlier show that, when the string
4297: is displayed, there is neither a space before the @code{H} nor after the
4298: @code{e}. Since @code{."} is an immediate word, it executes at the time
4299: that @code{greet} is defined. When it executes, its behaviour is to
4300: search forward in the input line looking for the delimiter. When it
4301: finds the delimiter, it updates @code{>IN} to point past the
4302: delimiter. It also compiles some magic code into the definition of
4303: @code{greet}; the xt of a run-time routine that prints a text string. It
4304: compiles the string @code{Hello and welcome} into memory so that it is
4305: available to be printed later. When the text interpreter gains control,
4306: the next word it finds in the input stream is @code{;} and so it
4307: terminates the definition of @code{greet}.
4308:
4309:
4310: @comment ----------------------------------------------
4311: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4312: @section Forth is written in Forth
4313: @cindex structure of Forth programs
4314:
4315: When you start up a Forth compiler, a large number of definitions
4316: already exist. In Forth, you develop a new application using bottom-up
4317: programming techniques to create new definitions that are defined in
4318: terms of existing definitions. As you create each definition you can
4319: test and debug it interactively.
4320:
4321: If you have tried out the examples in this section, you will probably
4322: have typed them in by hand; when you leave Gforth, your definitions will
4323: be lost. You can avoid this by using a text editor to enter Forth source
4324: code into a file, and then loading code from the file using
4325: @code{include} (@pxref{Forth source files}). A Forth source file is
4326: processed by the text interpreter, just as though you had typed it in by
4327: hand@footnote{Actually, there are some subtle differences -- see
4328: @ref{The Text Interpreter}.}.
4329:
4330: Gforth also supports the traditional Forth alternative to using text
4331: files for program entry (@pxref{Blocks}).
4332:
4333: In common with many, if not most, Forth compilers, most of Gforth is
4334: actually written in Forth. All of the @file{.fs} files in the
4335: installation directory@footnote{For example,
4336: @file{/usr/local/share/gforth...}} are Forth source files, which you can
4337: study to see examples of Forth programming.
4338:
4339: Gforth maintains a history file that records every line that you type to
4340: the text interpreter. This file is preserved between sessions, and is
4341: used to provide a command-line recall facility. If you enter long
4342: definitions by hand, you can use a text editor to paste them out of the
4343: history file into a Forth source file for reuse at a later time
4344: (for more information @pxref{Command-line editing}).
4345:
4346:
4347: @comment ----------------------------------------------
4348: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4349: @section Review - elements of a Forth system
4350: @cindex elements of a Forth system
4351:
4352: To summarise this chapter:
4353:
4354: @itemize @bullet
4355: @item
4356: Forth programs use @dfn{factoring} to break a problem down into small
4357: fragments called @dfn{words} or @dfn{definitions}.
4358: @item
4359: Forth program development is an interactive process.
4360: @item
4361: The main command loop that accepts input, and controls both
4362: interpretation and compilation, is called the @dfn{text interpreter}
4363: (also known as the @dfn{outer interpreter}).
4364: @item
4365: Forth has a very simple syntax, consisting of words and numbers
4366: separated by spaces or carriage-return characters. Any additional syntax
4367: is imposed by @dfn{parsing words}.
4368: @item
4369: Forth uses a stack to pass parameters between words. As a result, it
4370: uses postfix notation.
4371: @item
4372: To use a word that has previously been defined, the text interpreter
4373: searches for the word in the @dfn{name dictionary}.
4374: @item
4375: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
4376: @item
4377: The text interpreter uses the value of @code{state} to select between
4378: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4379: semantics} of a word that it encounters.
4380: @item
4381: The relationship between the @dfn{interpretation semantics} and
4382: @dfn{compilation semantics} for a word
4383: depend upon the way in which the word was defined (for example, whether
4384: it is an @dfn{immediate} word).
4385: @item
4386: Forth definitions can be implemented in Forth (called @dfn{high-level
4387: definitions}) or in some other way (usually a lower-level language and
4388: as a result often called @dfn{low-level definitions}, @dfn{code
4389: definitions} or @dfn{primitives}).
4390: @item
4391: Many Forth systems are implemented mainly in Forth.
4392: @end itemize
4393:
4394:
4395: @comment ----------------------------------------------
4396: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
4397: @section Where To Go Next
4398: @cindex where to go next
4399:
4400: Amazing as it may seem, if you have read (and understood) this far, you
4401: know almost all the fundamentals about the inner workings of a Forth
4402: system. You certainly know enough to be able to read and understand the
4403: rest of this manual and the ANS Forth document, to learn more about the
4404: facilities that Forth in general and Gforth in particular provide. Even
4405: scarier, you know almost enough to implement your own Forth system.
4406: However, that's not a good idea just yet... better to try writing some
4407: programs in Gforth.
4408:
4409: Forth has such a rich vocabulary that it can be hard to know where to
4410: start in learning it. This section suggests a few sets of words that are
4411: enough to write small but useful programs. Use the word index in this
4412: document to learn more about each word, then try it out and try to write
4413: small definitions using it. Start by experimenting with these words:
4414:
4415: @itemize @bullet
4416: @item
4417: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4418: @item
4419: Comparison: @code{MIN MAX =}
4420: @item
4421: Logic: @code{AND OR XOR NOT}
4422: @item
4423: Stack manipulation: @code{DUP DROP SWAP OVER}
4424: @item
4425: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
4426: @item
4427: Input/Output: @code{. ." EMIT CR KEY}
4428: @item
4429: Defining words: @code{: ; CREATE}
4430: @item
4431: Memory allocation words: @code{ALLOT ,}
4432: @item
4433: Tools: @code{SEE WORDS .S MARKER}
4434: @end itemize
4435:
4436: When you have mastered those, go on to:
4437:
4438: @itemize @bullet
4439: @item
4440: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
4441: @item
4442: Memory access: @code{@@ !}
4443: @end itemize
4444:
4445: When you have mastered these, there's nothing for it but to read through
4446: the whole of this manual and find out what you've missed.
4447:
4448: @comment ----------------------------------------------
4449: @node Exercises, , Where to go next, Introduction
4450: @section Exercises
4451: @cindex exercises
4452:
4453: TODO: provide a set of programming excercises linked into the stuff done
4454: already and into other sections of the manual. Provide solutions to all
4455: the exercises in a .fs file in the distribution.
4456:
4457: @c Get some inspiration from Starting Forth and Kelly&Spies.
4458:
4459: @c excercises:
4460: @c 1. take inches and convert to feet and inches.
4461: @c 2. take temperature and convert from fahrenheight to celcius;
4462: @c may need to care about symmetric vs floored??
4463: @c 3. take input line and do character substitution
4464: @c to encipher or decipher
4465: @c 4. as above but work on a file for in and out
4466: @c 5. take input line and convert to pig-latin
4467: @c
4468: @c thing of sets of things to exercise then come up with
4469: @c problems that need those things.
4470:
4471:
4472: @c ******************************************************************
4473: @node Words, Error messages, Introduction, Top
4474: @chapter Forth Words
4475: @cindex words
4476:
4477: @menu
4478: * Notation::
4479: * Case insensitivity::
4480: * Comments::
4481: * Boolean Flags::
4482: * Arithmetic::
4483: * Stack Manipulation::
4484: * Memory::
4485: * Control Structures::
4486: * Defining Words::
4487: * Interpretation and Compilation Semantics::
4488: * Tokens for Words::
4489: * Compiling words::
4490: * The Text Interpreter::
4491: * Word Lists::
4492: * Environmental Queries::
4493: * Files::
4494: * Blocks::
4495: * Other I/O::
4496: * Locals::
4497: * Structures::
4498: * Object-oriented Forth::
4499: * Programming Tools::
4500: * Assembler and Code Words::
4501: * Threading Words::
4502: * Passing Commands to the OS::
4503: * Keeping track of Time::
4504: * Miscellaneous Words::
4505: @end menu
4506:
4507: @node Notation, Case insensitivity, Words, Words
4508: @section Notation
4509: @cindex notation of glossary entries
4510: @cindex format of glossary entries
4511: @cindex glossary notation format
4512: @cindex word glossary entry format
4513:
4514: The Forth words are described in this section in the glossary notation
4515: that has become a de-facto standard for Forth texts:
4516:
4517: @format
4518: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
4519: @end format
4520: @i{Description}
4521:
4522: @table @var
4523: @item word
4524: The name of the word.
4525:
4526: @item Stack effect
4527: @cindex stack effect
4528: The stack effect is written in the notation @code{@i{before} --
4529: @i{after}}, where @i{before} and @i{after} describe the top of
4530: stack entries before and after the execution of the word. The rest of
4531: the stack is not touched by the word. The top of stack is rightmost,
4532: i.e., a stack sequence is written as it is typed in. Note that Gforth
4533: uses a separate floating point stack, but a unified stack
4534: notation. Also, return stack effects are not shown in @i{stack
4535: effect}, but in @i{Description}. The name of a stack item describes
4536: the type and/or the function of the item. See below for a discussion of
4537: the types.
4538:
4539: All words have two stack effects: A compile-time stack effect and a
4540: run-time stack effect. The compile-time stack-effect of most words is
4541: @i{ -- }. If the compile-time stack-effect of a word deviates from
4542: this standard behaviour, or the word does other unusual things at
4543: compile time, both stack effects are shown; otherwise only the run-time
4544: stack effect is shown.
4545:
4546: @cindex pronounciation of words
4547: @item pronunciation
4548: How the word is pronounced.
4549:
4550: @cindex wordset
4551: @cindex environment wordset
4552: @item wordset
4553: The ANS Forth standard is divided into several word sets. A standard
4554: system need not support all of them. Therefore, in theory, the fewer
4555: word sets your program uses the more portable it will be. However, we
4556: suspect that most ANS Forth systems on personal machines will feature
4557: all word sets. Words that are not defined in ANS Forth have
4558: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
4559: describes words that will work in future releases of Gforth;
4560: @code{gforth-internal} words are more volatile. Environmental query
4561: strings are also displayed like words; you can recognize them by the
4562: @code{environment} in the word set field.
4563:
4564: @item Description
4565: A description of the behaviour of the word.
4566: @end table
4567:
4568: @cindex types of stack items
4569: @cindex stack item types
4570: The type of a stack item is specified by the character(s) the name
4571: starts with:
4572:
4573: @table @code
4574: @item f
4575: @cindex @code{f}, stack item type
4576: Boolean flags, i.e. @code{false} or @code{true}.
4577: @item c
4578: @cindex @code{c}, stack item type
4579: Char
4580: @item w
4581: @cindex @code{w}, stack item type
4582: Cell, can contain an integer or an address
4583: @item n
4584: @cindex @code{n}, stack item type
4585: signed integer
4586: @item u
4587: @cindex @code{u}, stack item type
4588: unsigned integer
4589: @item d
4590: @cindex @code{d}, stack item type
4591: double sized signed integer
4592: @item ud
4593: @cindex @code{ud}, stack item type
4594: double sized unsigned integer
4595: @item r
4596: @cindex @code{r}, stack item type
4597: Float (on the FP stack)
4598: @item a-
4599: @cindex @code{a_}, stack item type
4600: Cell-aligned address
4601: @item c-
4602: @cindex @code{c_}, stack item type
4603: Char-aligned address (note that a Char may have two bytes in Windows NT)
4604: @item f-
4605: @cindex @code{f_}, stack item type
4606: Float-aligned address
4607: @item df-
4608: @cindex @code{df_}, stack item type
4609: Address aligned for IEEE double precision float
4610: @item sf-
4611: @cindex @code{sf_}, stack item type
4612: Address aligned for IEEE single precision float
4613: @item xt
4614: @cindex @code{xt}, stack item type
4615: Execution token, same size as Cell
4616: @item wid
4617: @cindex @code{wid}, stack item type
4618: Word list ID, same size as Cell
4619: @item ior, wior
4620: @cindex ior type description
4621: @cindex wior type description
4622: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
4623: @item f83name
4624: @cindex @code{f83name}, stack item type
4625: Pointer to a name structure
4626: @item "
4627: @cindex @code{"}, stack item type
4628: string in the input stream (not on the stack). The terminating character
4629: is a blank by default. If it is not a blank, it is shown in @code{<>}
4630: quotes.
4631: @end table
4632:
4633: @comment ----------------------------------------------
4634: @node Case insensitivity, Comments, Notation, Words
4635: @section Case insensitivity
4636: @cindex case sensitivity
4637: @cindex upper and lower case
4638:
4639: Gforth is case-insensitive; you can enter definitions and invoke
4640: Standard words using upper, lower or mixed case (however,
4641: @pxref{core-idef, Implementation-defined options, Implementation-defined
4642: options}).
4643:
4644: ANS Forth only @i{requires} implementations to recognise Standard words
4645: when they are typed entirely in upper case. Therefore, a Standard
4646: program must use upper case for all Standard words. You can use whatever
4647: case you like for words that you define, but in a Standard program you
4648: have to use the words in the same case that you defined them.
4649:
4650: Gforth supports case sensitivity through @code{table}s (case-sensitive
4651: wordlists, @pxref{Word Lists}).
4652:
4653: Two people have asked how to convert Gforth to be case-sensitive; while
4654: we think this is a bad idea, you can change all wordlists into tables
4655: like this:
4656:
4657: @example
4658: ' table-find forth-wordlist wordlist-map @ !
4659: @end example
4660:
4661: Note that you now have to type the predefined words in the same case
4662: that we defined them, which are varying. You may want to convert them
4663: to your favourite case before doing this operation (I won't explain how,
4664: because if you are even contemplating doing this, you'd better have
4665: enough knowledge of Forth systems to know this already).
4666:
4667: @node Comments, Boolean Flags, Case insensitivity, Words
4668: @section Comments
4669: @cindex comments
4670:
4671: Forth supports two styles of comment; the traditional @i{in-line} comment,
4672: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
4673:
4674:
4675: doc-(
4676: doc-\
4677: doc-\G
4678:
4679:
4680: @node Boolean Flags, Arithmetic, Comments, Words
4681: @section Boolean Flags
4682: @cindex Boolean flags
4683:
4684: A Boolean flag is cell-sized. A cell with all bits clear represents the
4685: flag @code{false} and a flag with all bits set represents the flag
4686: @code{true}. Words that check a flag (for example, @code{IF}) will treat
4687: a cell that has @i{any} bit set as @code{true}.
4688: @c on and off to Memory?
4689: @c true and false to "Bitwise operations" or "Numeric comparison"?
4690:
4691: doc-true
4692: doc-false
4693: doc-on
4694: doc-off
4695:
4696:
4697: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
4698: @section Arithmetic
4699: @cindex arithmetic words
4700:
4701: @cindex division with potentially negative operands
4702: Forth arithmetic is not checked, i.e., you will not hear about integer
4703: overflow on addition or multiplication, you may hear about division by
4704: zero if you are lucky. The operator is written after the operands, but
4705: the operands are still in the original order. I.e., the infix @code{2-1}
4706: corresponds to @code{2 1 -}. Forth offers a variety of division
4707: operators. If you perform division with potentially negative operands,
4708: you do not want to use @code{/} or @code{/mod} with its undefined
4709: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4710: former, @pxref{Mixed precision}).
4711: @comment TODO discuss the different division forms and the std approach
4712:
4713: @menu
4714: * Single precision::
4715: * Double precision:: Double-cell integer arithmetic
4716: * Bitwise operations::
4717: * Numeric comparison::
4718: * Mixed precision:: Operations with single and double-cell integers
4719: * Floating Point::
4720: @end menu
4721:
4722: @node Single precision, Double precision, Arithmetic, Arithmetic
4723: @subsection Single precision
4724: @cindex single precision arithmetic words
4725:
4726: @c !! cell undefined
4727:
4728: By default, numbers in Forth are single-precision integers that are one
4729: cell in size. They can be signed or unsigned, depending upon how you
4730: treat them. For the rules used by the text interpreter for recognising
4731: single-precision integers see @ref{Number Conversion}.
4732:
4733: These words are all defined for signed operands, but some of them also
4734: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4735: @code{*}.
4736:
4737: doc-+
4738: doc-1+
4739: doc--
4740: doc-1-
4741: doc-*
4742: doc-/
4743: doc-mod
4744: doc-/mod
4745: doc-negate
4746: doc-abs
4747: doc-min
4748: doc-max
4749: doc-floored
4750:
4751:
4752: @node Double precision, Bitwise operations, Single precision, Arithmetic
4753: @subsection Double precision
4754: @cindex double precision arithmetic words
4755:
4756: For the rules used by the text interpreter for
4757: recognising double-precision integers, see @ref{Number Conversion}.
4758:
4759: A double precision number is represented by a cell pair, with the most
4760: significant cell at the TOS. It is trivial to convert an unsigned single
4761: to a double: simply push a @code{0} onto the TOS. Since numbers are
4762: represented by Gforth using 2's complement arithmetic, converting a
4763: signed single to a (signed) double requires sign-extension across the
4764: most significant cell. This can be achieved using @code{s>d}. The moral
4765: of the story is that you cannot convert a number without knowing whether
4766: it represents an unsigned or a signed number.
4767:
4768: These words are all defined for signed operands, but some of them also
4769: work for unsigned numbers: @code{d+}, @code{d-}.
4770:
4771: doc-s>d
4772: doc-d>s
4773: doc-d+
4774: doc-d-
4775: doc-dnegate
4776: doc-dabs
4777: doc-dmin
4778: doc-dmax
4779:
4780:
4781: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4782: @subsection Bitwise operations
4783: @cindex bitwise operation words
4784:
4785:
4786: doc-and
4787: doc-or
4788: doc-xor
4789: doc-invert
4790: doc-lshift
4791: doc-rshift
4792: doc-2*
4793: doc-d2*
4794: doc-2/
4795: doc-d2/
4796:
4797:
4798: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
4799: @subsection Numeric comparison
4800: @cindex numeric comparison words
4801:
4802: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4803: d0= d0<>}) work for for both signed and unsigned numbers.
4804:
4805: doc-<
4806: doc-<=
4807: doc-<>
4808: doc-=
4809: doc->
4810: doc->=
4811:
4812: doc-0<
4813: doc-0<=
4814: doc-0<>
4815: doc-0=
4816: doc-0>
4817: doc-0>=
4818:
4819: doc-u<
4820: doc-u<=
4821: @c u<> and u= exist but are the same as <> and =
4822: @c doc-u<>
4823: @c doc-u=
4824: doc-u>
4825: doc-u>=
4826:
4827: doc-within
4828:
4829: doc-d<
4830: doc-d<=
4831: doc-d<>
4832: doc-d=
4833: doc-d>
4834: doc-d>=
4835:
4836: doc-d0<
4837: doc-d0<=
4838: doc-d0<>
4839: doc-d0=
4840: doc-d0>
4841: doc-d0>=
4842:
4843: doc-du<
4844: doc-du<=
4845: @c du<> and du= exist but are the same as d<> and d=
4846: @c doc-du<>
4847: @c doc-du=
4848: doc-du>
4849: doc-du>=
4850:
4851:
4852: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
4853: @subsection Mixed precision
4854: @cindex mixed precision arithmetic words
4855:
4856:
4857: doc-m+
4858: doc-*/
4859: doc-*/mod
4860: doc-m*
4861: doc-um*
4862: doc-m*/
4863: doc-um/mod
4864: doc-fm/mod
4865: doc-sm/rem
4866:
4867:
4868: @node Floating Point, , Mixed precision, Arithmetic
4869: @subsection Floating Point
4870: @cindex floating point arithmetic words
4871:
4872: For the rules used by the text interpreter for
4873: recognising floating-point numbers see @ref{Number Conversion}.
4874:
4875: Gforth has a separate floating point stack, but the documentation uses
4876: the unified notation.@footnote{It's easy to generate the separate
4877: notation from that by just separating the floating-point numbers out:
4878: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4879: r3 )}.}
4880:
4881: @cindex floating-point arithmetic, pitfalls
4882: Floating point numbers have a number of unpleasant surprises for the
4883: unwary (e.g., floating point addition is not associative) and even a few
4884: for the wary. You should not use them unless you know what you are doing
4885: or you don't care that the results you get are totally bogus. If you
4886: want to learn about the problems of floating point numbers (and how to
4887: avoid them), you might start with @cite{David Goldberg,
4888: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4889: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4890: Surveys 23(1):5@minus{}48, March 1991}.
4891:
4892:
4893: doc-d>f
4894: doc-f>d
4895: doc-f+
4896: doc-f-
4897: doc-f*
4898: doc-f/
4899: doc-fnegate
4900: doc-fabs
4901: doc-fmax
4902: doc-fmin
4903: doc-floor
4904: doc-fround
4905: doc-f**
4906: doc-fsqrt
4907: doc-fexp
4908: doc-fexpm1
4909: doc-fln
4910: doc-flnp1
4911: doc-flog
4912: doc-falog
4913: doc-f2*
4914: doc-f2/
4915: doc-1/f
4916: doc-precision
4917: doc-set-precision
4918:
4919: @cindex angles in trigonometric operations
4920: @cindex trigonometric operations
4921: Angles in floating point operations are given in radians (a full circle
4922: has 2 pi radians).
4923:
4924: doc-fsin
4925: doc-fcos
4926: doc-fsincos
4927: doc-ftan
4928: doc-fasin
4929: doc-facos
4930: doc-fatan
4931: doc-fatan2
4932: doc-fsinh
4933: doc-fcosh
4934: doc-ftanh
4935: doc-fasinh
4936: doc-facosh
4937: doc-fatanh
4938: doc-pi
4939:
4940: @cindex equality of floats
4941: @cindex floating-point comparisons
4942: One particular problem with floating-point arithmetic is that comparison
4943: for equality often fails when you would expect it to succeed. For this
4944: reason approximate equality is often preferred (but you still have to
4945: know what you are doing). Also note that IEEE NaNs may compare
4946: differently from what you might expect. The comparison words are:
4947:
4948: doc-f~rel
4949: doc-f~abs
4950: doc-f~
4951: doc-f=
4952: doc-f<>
4953:
4954: doc-f<
4955: doc-f<=
4956: doc-f>
4957: doc-f>=
4958:
4959: doc-f0<
4960: doc-f0<=
4961: doc-f0<>
4962: doc-f0=
4963: doc-f0>
4964: doc-f0>=
4965:
4966:
4967: @node Stack Manipulation, Memory, Arithmetic, Words
4968: @section Stack Manipulation
4969: @cindex stack manipulation words
4970:
4971: @cindex floating-point stack in the standard
4972: Gforth maintains a number of separate stacks:
4973:
4974: @cindex data stack
4975: @cindex parameter stack
4976: @itemize @bullet
4977: @item
4978: A data stack (also known as the @dfn{parameter stack}) -- for
4979: characters, cells, addresses, and double cells.
4980:
4981: @cindex floating-point stack
4982: @item
4983: A floating point stack -- for holding floating point (FP) numbers.
4984:
4985: @cindex return stack
4986: @item
4987: A return stack -- for holding the return addresses of colon
4988: definitions and other (non-FP) data.
4989:
4990: @cindex locals stack
4991: @item
4992: A locals stack -- for holding local variables.
4993: @end itemize
4994:
4995: @menu
4996: * Data stack::
4997: * Floating point stack::
4998: * Return stack::
4999: * Locals stack::
5000: * Stack pointer manipulation::
5001: @end menu
5002:
5003: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
5004: @subsection Data stack
5005: @cindex data stack manipulation words
5006: @cindex stack manipulations words, data stack
5007:
5008:
5009: doc-drop
5010: doc-nip
5011: doc-dup
5012: doc-over
5013: doc-tuck
5014: doc-swap
5015: doc-pick
5016: doc-rot
5017: doc--rot
5018: doc-?dup
5019: doc-roll
5020: doc-2drop
5021: doc-2nip
5022: doc-2dup
5023: doc-2over
5024: doc-2tuck
5025: doc-2swap
5026: doc-2rot
5027:
5028:
5029: @node Floating point stack, Return stack, Data stack, Stack Manipulation
5030: @subsection Floating point stack
5031: @cindex floating-point stack manipulation words
5032: @cindex stack manipulation words, floating-point stack
5033:
5034: Whilst every sane Forth has a separate floating-point stack, it is not
5035: strictly required; an ANS Forth system could theoretically keep
5036: floating-point numbers on the data stack. As an additional difficulty,
5037: you don't know how many cells a floating-point number takes. It is
5038: reportedly possible to write words in a way that they work also for a
5039: unified stack model, but we do not recommend trying it. Instead, just
5040: say that your program has an environmental dependency on a separate
5041: floating-point stack.
5042:
5043: doc-floating-stack
5044:
5045: doc-fdrop
5046: doc-fnip
5047: doc-fdup
5048: doc-fover
5049: doc-ftuck
5050: doc-fswap
5051: doc-fpick
5052: doc-frot
5053:
5054:
5055: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
5056: @subsection Return stack
5057: @cindex return stack manipulation words
5058: @cindex stack manipulation words, return stack
5059:
5060: @cindex return stack and locals
5061: @cindex locals and return stack
5062: A Forth system is allowed to keep local variables on the
5063: return stack. This is reasonable, as local variables usually eliminate
5064: the need to use the return stack explicitly. So, if you want to produce
5065: a standard compliant program and you are using local variables in a
5066: word, forget about return stack manipulations in that word (refer to the
5067: standard document for the exact rules).
5068:
5069: doc->r
5070: doc-r>
5071: doc-r@
5072: doc-rdrop
5073: doc-2>r
5074: doc-2r>
5075: doc-2r@
5076: doc-2rdrop
5077:
5078:
5079: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
5080: @subsection Locals stack
5081:
5082: Gforth uses an extra locals stack. It is described, along with the
5083: reasons for its existence, in @ref{Locals implementation}.
5084:
5085: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
5086: @subsection Stack pointer manipulation
5087: @cindex stack pointer manipulation words
5088:
5089: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
5090: doc-sp0
5091: doc-sp@
5092: doc-sp!
5093: doc-fp0
5094: doc-fp@
5095: doc-fp!
5096: doc-rp0
5097: doc-rp@
5098: doc-rp!
5099: doc-lp0
5100: doc-lp@
5101: doc-lp!
5102:
5103:
5104: @node Memory, Control Structures, Stack Manipulation, Words
5105: @section Memory
5106: @cindex memory words
5107:
5108: @menu
5109: * Memory model::
5110: * Dictionary allocation::
5111: * Heap Allocation::
5112: * Memory Access::
5113: * Address arithmetic::
5114: * Memory Blocks::
5115: @end menu
5116:
5117: In addition to the standard Forth memory allocation words, there is also
5118: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
5119: garbage collector}.
5120:
5121: @node Memory model, Dictionary allocation, Memory, Memory
5122: @subsection ANS Forth and Gforth memory models
5123:
5124: @c The ANS Forth description is a mess (e.g., is the heap part of
5125: @c the dictionary?), so let's not stick to closely with it.
5126:
5127: ANS Forth considers a Forth system as consisting of several address
5128: spaces, of which only @dfn{data space} is managed and accessible with
5129: the memory words. Memory not necessarily in data space includes the
5130: stacks, the code (called code space) and the headers (called name
5131: space). In Gforth everything is in data space, but the code for the
5132: primitives is usually read-only.
5133:
5134: Data space is divided into a number of areas: The (data space portion of
5135: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
5136: refer to the search data structure embodied in word lists and headers,
5137: because it is used for looking up names, just as you would in a
5138: conventional dictionary.}, the heap, and a number of system-allocated
5139: buffers.
5140:
5141: @cindex address arithmetic restrictions, ANS vs. Gforth
5142: @cindex contiguous regions, ANS vs. Gforth
5143: In ANS Forth data space is also divided into contiguous regions. You
5144: can only use address arithmetic within a contiguous region, not between
5145: them. Usually each allocation gives you one contiguous region, but the
5146: dictionary allocation words have additional rules (@pxref{Dictionary
5147: allocation}).
5148:
5149: Gforth provides one big address space, and address arithmetic can be
5150: performed between any addresses. However, in the dictionary headers or
5151: code are interleaved with data, so almost the only contiguous data space
5152: regions there are those described by ANS Forth as contiguous; but you
5153: can be sure that the dictionary is allocated towards increasing
5154: addresses even between contiguous regions. The memory order of
5155: allocations in the heap is platform-dependent (and possibly different
5156: from one run to the next).
5157:
5158:
5159: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5160: @subsection Dictionary allocation
5161: @cindex reserving data space
5162: @cindex data space - reserving some
5163:
5164: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5165: you want to deallocate X, you also deallocate everything
5166: allocated after X.
5167:
5168: @cindex contiguous regions in dictionary allocation
5169: The allocations using the words below are contiguous and grow the region
5170: towards increasing addresses. Other words that allocate dictionary
5171: memory of any kind (i.e., defining words including @code{:noname}) end
5172: the contiguous region and start a new one.
5173:
5174: In ANS Forth only @code{create}d words are guaranteed to produce an
5175: address that is the start of the following contiguous region. In
5176: particular, the cell allocated by @code{variable} is not guaranteed to
5177: be contiguous with following @code{allot}ed memory.
5178:
5179: You can deallocate memory by using @code{allot} with a negative argument
5180: (with some restrictions, see @code{allot}). For larger deallocations use
5181: @code{marker}.
5182:
5183:
5184: doc-here
5185: doc-unused
5186: doc-allot
5187: doc-c,
5188: doc-f,
5189: doc-,
5190: doc-2,
5191:
5192: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5193: course you should allocate memory in an aligned way, too. I.e., before
5194: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5195: The words below align @code{here} if it is not already. Basically it is
5196: only already aligned for a type, if the last allocation was a multiple
5197: of the size of this type and if @code{here} was aligned for this type
5198: before.
5199:
5200: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5201: ANS Forth (@code{maxalign}ed in Gforth).
5202:
5203: doc-align
5204: doc-falign
5205: doc-sfalign
5206: doc-dfalign
5207: doc-maxalign
5208: doc-cfalign
5209:
5210:
5211: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5212: @subsection Heap allocation
5213: @cindex heap allocation
5214: @cindex dynamic allocation of memory
5215: @cindex memory-allocation word set
5216:
5217: @cindex contiguous regions and heap allocation
5218: Heap allocation supports deallocation of allocated memory in any
5219: order. Dictionary allocation is not affected by it (i.e., it does not
5220: end a contiguous region). In Gforth, these words are implemented using
5221: the standard C library calls malloc(), free() and resize().
5222:
5223: The memory region produced by one invocation of @code{allocate} or
5224: @code{resize} is internally contiguous. There is no contiguity between
5225: such a region and any other region (including others allocated from the
5226: heap).
5227:
5228: doc-allocate
5229: doc-free
5230: doc-resize
5231:
5232:
5233: @node Memory Access, Address arithmetic, Heap Allocation, Memory
5234: @subsection Memory Access
5235: @cindex memory access words
5236:
5237: doc-@
5238: doc-!
5239: doc-+!
5240: doc-c@
5241: doc-c!
5242: doc-2@
5243: doc-2!
5244: doc-f@
5245: doc-f!
5246: doc-sf@
5247: doc-sf!
5248: doc-df@
5249: doc-df!
5250:
5251:
5252: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5253: @subsection Address arithmetic
5254: @cindex address arithmetic words
5255:
5256: Address arithmetic is the foundation on which you can build data
5257: structures like arrays, records (@pxref{Structures}) and objects
5258: (@pxref{Object-oriented Forth}).
5259:
5260: @cindex address unit
5261: @cindex au (address unit)
5262: ANS Forth does not specify the sizes of the data types. Instead, it
5263: offers a number of words for computing sizes and doing address
5264: arithmetic. Address arithmetic is performed in terms of address units
5265: (aus); on most systems the address unit is one byte. Note that a
5266: character may have more than one au, so @code{chars} is no noop (on
5267: platforms where it is a noop, it compiles to nothing).
5268:
5269: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5270: you have the address of a cell, perform @code{1 cells +}, and you will
5271: have the address of the next cell.
5272:
5273: @cindex contiguous regions and address arithmetic
5274: In ANS Forth you can perform address arithmetic only within a contiguous
5275: region, i.e., if you have an address into one region, you can only add
5276: and subtract such that the result is still within the region; you can
5277: only subtract or compare addresses from within the same contiguous
5278: region. Reasons: several contiguous regions can be arranged in memory
5279: in any way; on segmented systems addresses may have unusual
5280: representations, such that address arithmetic only works within a
5281: region. Gforth provides a few more guarantees (linear address space,
5282: dictionary grows upwards), but in general I have found it easy to stay
5283: within contiguous regions (exception: computing and comparing to the
5284: address just beyond the end of an array).
5285:
5286: @cindex alignment of addresses for types
5287: ANS Forth also defines words for aligning addresses for specific
5288: types. Many computers require that accesses to specific data types
5289: must only occur at specific addresses; e.g., that cells may only be
5290: accessed at addresses divisible by 4. Even if a machine allows unaligned
5291: accesses, it can usually perform aligned accesses faster.
5292:
5293: For the performance-conscious: alignment operations are usually only
5294: necessary during the definition of a data structure, not during the
5295: (more frequent) accesses to it.
5296:
5297: ANS Forth defines no words for character-aligning addresses. This is not
5298: an oversight, but reflects the fact that addresses that are not
5299: char-aligned have no use in the standard and therefore will not be
5300: created.
5301:
5302: @cindex @code{CREATE} and alignment
5303: ANS Forth guarantees that addresses returned by @code{CREATE}d words
5304: are cell-aligned; in addition, Gforth guarantees that these addresses
5305: are aligned for all purposes.
5306:
5307: Note that the ANS Forth word @code{char} has nothing to do with address
5308: arithmetic.
5309:
5310:
5311: doc-chars
5312: doc-char+
5313: doc-cells
5314: doc-cell+
5315: doc-cell
5316: doc-aligned
5317: doc-floats
5318: doc-float+
5319: doc-float
5320: doc-faligned
5321: doc-sfloats
5322: doc-sfloat+
5323: doc-sfaligned
5324: doc-dfloats
5325: doc-dfloat+
5326: doc-dfaligned
5327: doc-maxaligned
5328: doc-cfaligned
5329: doc-address-unit-bits
5330:
5331:
5332: @node Memory Blocks, , Address arithmetic, Memory
5333: @subsection Memory Blocks
5334: @cindex memory block words
5335: @cindex character strings - moving and copying
5336:
5337: Memory blocks often represent character strings; For ways of storing
5338: character strings in memory see @ref{String Formats}. For other
5339: string-processing words see @ref{Displaying characters and strings}.
5340:
5341: A few of these words work on address unit blocks. In that case, you
5342: usually have to insert @code{CHARS} before the word when working on
5343: character strings. Most words work on character blocks, and expect a
5344: char-aligned address.
5345:
5346: When copying characters between overlapping memory regions, use
5347: @code{chars move} or choose carefully between @code{cmove} and
5348: @code{cmove>}.
5349:
5350: doc-move
5351: doc-erase
5352: doc-cmove
5353: doc-cmove>
5354: doc-fill
5355: doc-blank
5356: doc-compare
5357: doc-search
5358: doc--trailing
5359: doc-/string
5360: doc-bounds
5361:
5362: @comment TODO examples
5363:
5364:
5365: @node Control Structures, Defining Words, Memory, Words
5366: @section Control Structures
5367: @cindex control structures
5368:
5369: Control structures in Forth cannot be used interpretively, only in a
5370: colon definition@footnote{To be precise, they have no interpretation
5371: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5372: not like this limitation, but have not seen a satisfying way around it
5373: yet, although many schemes have been proposed.
5374:
5375: @menu
5376: * Selection:: IF ... ELSE ... ENDIF
5377: * Simple Loops:: BEGIN ...
5378: * Counted Loops:: DO
5379: * Arbitrary control structures::
5380: * Calls and returns::
5381: * Exception Handling::
5382: @end menu
5383:
5384: @node Selection, Simple Loops, Control Structures, Control Structures
5385: @subsection Selection
5386: @cindex selection control structures
5387: @cindex control structures for selection
5388:
5389: @cindex @code{IF} control structure
5390: @example
5391: @i{flag}
5392: IF
5393: @i{code}
5394: ENDIF
5395: @end example
5396: @noindent
5397:
5398: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5399: with any bit set represents truth) @i{code} is executed.
5400:
5401: @example
5402: @i{flag}
5403: IF
5404: @i{code1}
5405: ELSE
5406: @i{code2}
5407: ENDIF
5408: @end example
5409:
5410: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5411: executed.
5412:
5413: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5414: standard, and @code{ENDIF} is not, although it is quite popular. We
5415: recommend using @code{ENDIF}, because it is less confusing for people
5416: who also know other languages (and is not prone to reinforcing negative
5417: prejudices against Forth in these people). Adding @code{ENDIF} to a
5418: system that only supplies @code{THEN} is simple:
5419: @example
5420: : ENDIF POSTPONE then ; immediate
5421: @end example
5422:
5423: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5424: (adv.)} has the following meanings:
5425: @quotation
5426: ... 2b: following next after in order ... 3d: as a necessary consequence
5427: (if you were there, then you saw them).
5428: @end quotation
5429: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5430: and many other programming languages has the meaning 3d.]
5431:
5432: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
5433: you can avoid using @code{?dup}. Using these alternatives is also more
5434: efficient than using @code{?dup}. Definitions in ANS Forth
5435: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5436: @file{compat/control.fs}.
5437:
5438: @cindex @code{CASE} control structure
5439: @example
5440: @i{n}
5441: CASE
5442: @i{n1} OF @i{code1} ENDOF
5443: @i{n2} OF @i{code2} ENDOF
5444: @dots{}
5445: ( n ) @i{default-code} ( n )
5446: ENDCASE
5447: @end example
5448:
5449: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If no
5450: @i{ni} matches, the optional @i{default-code} is executed. The optional
5451: default case can be added by simply writing the code after the last
5452: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
5453: not consume it.
5454:
5455: @progstyle
5456: To keep the code understandable, you should ensure that on all paths
5457: through a selection construct the stack is changed in the same way
5458: (wrt. number and types of stack items consumed and pushed).
5459:
5460: @node Simple Loops, Counted Loops, Selection, Control Structures
5461: @subsection Simple Loops
5462: @cindex simple loops
5463: @cindex loops without count
5464:
5465: @cindex @code{WHILE} loop
5466: @example
5467: BEGIN
5468: @i{code1}
5469: @i{flag}
5470: WHILE
5471: @i{code2}
5472: REPEAT
5473: @end example
5474:
5475: @i{code1} is executed and @i{flag} is computed. If it is true,
5476: @i{code2} is executed and the loop is restarted; If @i{flag} is
5477: false, execution continues after the @code{REPEAT}.
5478:
5479: @cindex @code{UNTIL} loop
5480: @example
5481: BEGIN
5482: @i{code}
5483: @i{flag}
5484: UNTIL
5485: @end example
5486:
5487: @i{code} is executed. The loop is restarted if @code{flag} is false.
5488:
5489: @progstyle
5490: To keep the code understandable, a complete iteration of the loop should
5491: not change the number and types of the items on the stacks.
5492:
5493: @cindex endless loop
5494: @cindex loops, endless
5495: @example
5496: BEGIN
5497: @i{code}
5498: AGAIN
5499: @end example
5500:
5501: This is an endless loop.
5502:
5503: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5504: @subsection Counted Loops
5505: @cindex counted loops
5506: @cindex loops, counted
5507: @cindex @code{DO} loops
5508:
5509: The basic counted loop is:
5510: @example
5511: @i{limit} @i{start}
5512: ?DO
5513: @i{body}
5514: LOOP
5515: @end example
5516:
5517: This performs one iteration for every integer, starting from @i{start}
5518: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
5519: accessed with @code{i}. For example, the loop:
5520: @example
5521: 10 0 ?DO
5522: i .
5523: LOOP
5524: @end example
5525: @noindent
5526: prints @code{0 1 2 3 4 5 6 7 8 9}
5527:
5528: The index of the innermost loop can be accessed with @code{i}, the index
5529: of the next loop with @code{j}, and the index of the third loop with
5530: @code{k}.
5531:
5532:
5533: doc-i
5534: doc-j
5535: doc-k
5536:
5537:
5538: The loop control data are kept on the return stack, so there are some
5539: restrictions on mixing return stack accesses and counted loop words. In
5540: particuler, if you put values on the return stack outside the loop, you
5541: cannot read them inside the loop@footnote{well, not in a way that is
5542: portable.}. If you put values on the return stack within a loop, you
5543: have to remove them before the end of the loop and before accessing the
5544: index of the loop.
5545:
5546: There are several variations on the counted loop:
5547:
5548: @itemize @bullet
5549: @item
5550: @code{LEAVE} leaves the innermost counted loop immediately; execution
5551: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5552:
5553: @example
5554: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5555: @end example
5556: prints @code{0 1 2 3}
5557:
5558:
5559: @item
5560: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5561: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5562: return stack so @code{EXIT} can get to its return address. For example:
5563:
5564: @example
5565: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5566: @end example
5567: prints @code{0 1 2 3}
5568:
5569:
5570: @item
5571: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
5572: (and @code{LOOP} iterates until they become equal by wrap-around
5573: arithmetic). This behaviour is usually not what you want. Therefore,
5574: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
5575: @code{?DO}), which do not enter the loop if @i{start} is greater than
5576: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
5577: unsigned loop parameters.
5578:
5579: @item
5580: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5581: the loop, independent of the loop parameters. Do not use @code{DO}, even
5582: if you know that the loop is entered in any case. Such knowledge tends
5583: to become invalid during maintenance of a program, and then the
5584: @code{DO} will make trouble.
5585:
5586: @item
5587: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5588: index by @i{n} instead of by 1. The loop is terminated when the border
5589: between @i{limit-1} and @i{limit} is crossed. E.g.:
5590:
5591: @example
5592: 4 0 +DO i . 2 +LOOP
5593: @end example
5594: @noindent
5595: prints @code{0 2}
5596:
5597: @example
5598: 4 1 +DO i . 2 +LOOP
5599: @end example
5600: @noindent
5601: prints @code{1 3}
5602:
5603: @item
5604: @cindex negative increment for counted loops
5605: @cindex counted loops with negative increment
5606: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
5607:
5608: @example
5609: -1 0 ?DO i . -1 +LOOP
5610: @end example
5611: @noindent
5612: prints @code{0 -1}
5613:
5614: @example
5615: 0 0 ?DO i . -1 +LOOP
5616: @end example
5617: prints nothing.
5618:
5619: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5620: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5621: index by @i{u} each iteration. The loop is terminated when the border
5622: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
5623: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5624:
5625: @example
5626: -2 0 -DO i . 1 -LOOP
5627: @end example
5628: @noindent
5629: prints @code{0 -1}
5630:
5631: @example
5632: -1 0 -DO i . 1 -LOOP
5633: @end example
5634: @noindent
5635: prints @code{0}
5636:
5637: @example
5638: 0 0 -DO i . 1 -LOOP
5639: @end example
5640: @noindent
5641: prints nothing.
5642:
5643: @end itemize
5644:
5645: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
5646: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5647: for these words that uses only standard words is provided in
5648: @file{compat/loops.fs}.
5649:
5650:
5651: @cindex @code{FOR} loops
5652: Another counted loop is:
5653: @example
5654: @i{n}
5655: FOR
5656: @i{body}
5657: NEXT
5658: @end example
5659: This is the preferred loop of native code compiler writers who are too
5660: lazy to optimize @code{?DO} loops properly. This loop structure is not
5661: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5662: @code{i} produces values starting with @i{n} and ending with 0. Other
5663: Forth systems may behave differently, even if they support @code{FOR}
5664: loops. To avoid problems, don't use @code{FOR} loops.
5665:
5666: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5667: @subsection Arbitrary control structures
5668: @cindex control structures, user-defined
5669:
5670: @cindex control-flow stack
5671: ANS Forth permits and supports using control structures in a non-nested
5672: way. Information about incomplete control structures is stored on the
5673: control-flow stack. This stack may be implemented on the Forth data
5674: stack, and this is what we have done in Gforth.
5675:
5676: @cindex @code{orig}, control-flow stack item
5677: @cindex @code{dest}, control-flow stack item
5678: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5679: entry represents a backward branch target. A few words are the basis for
5680: building any control structure possible (except control structures that
5681: need storage, like calls, coroutines, and backtracking).
5682:
5683:
5684: doc-if
5685: doc-ahead
5686: doc-then
5687: doc-begin
5688: doc-until
5689: doc-again
5690: doc-cs-pick
5691: doc-cs-roll
5692:
5693:
5694: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5695: manipulate the control-flow stack in a portable way. Without them, you
5696: would need to know how many stack items are occupied by a control-flow
5697: entry (many systems use one cell. In Gforth they currently take three,
5698: but this may change in the future).
5699:
5700: Some standard control structure words are built from these words:
5701:
5702:
5703: doc-else
5704: doc-while
5705: doc-repeat
5706:
5707:
5708: @noindent
5709: Gforth adds some more control-structure words:
5710:
5711:
5712: doc-endif
5713: doc-?dup-if
5714: doc-?dup-0=-if
5715:
5716:
5717: @noindent
5718: Counted loop words constitute a separate group of words:
5719:
5720:
5721: doc-?do
5722: doc-+do
5723: doc-u+do
5724: doc--do
5725: doc-u-do
5726: doc-do
5727: doc-for
5728: doc-loop
5729: doc-+loop
5730: doc--loop
5731: doc-next
5732: doc-leave
5733: doc-?leave
5734: doc-unloop
5735: doc-done
5736:
5737:
5738: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5739: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
5740: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5741: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5742: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5743: resolved (by using one of the loop-ending words or @code{DONE}).
5744:
5745: @noindent
5746: Another group of control structure words are:
5747:
5748:
5749: doc-case
5750: doc-endcase
5751: doc-of
5752: doc-endof
5753:
5754:
5755: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5756: @code{CS-ROLL}.
5757:
5758: @subsubsection Programming Style
5759: @cindex control structures programming style
5760: @cindex programming style, arbitrary control structures
5761:
5762: In order to ensure readability we recommend that you do not create
5763: arbitrary control structures directly, but define new control structure
5764: words for the control structure you want and use these words in your
5765: program. For example, instead of writing:
5766:
5767: @example
5768: BEGIN
5769: ...
5770: IF [ 1 CS-ROLL ]
5771: ...
5772: AGAIN THEN
5773: @end example
5774:
5775: @noindent
5776: we recommend defining control structure words, e.g.,
5777:
5778: @example
5779: : WHILE ( DEST -- ORIG DEST )
5780: POSTPONE IF
5781: 1 CS-ROLL ; immediate
5782:
5783: : REPEAT ( orig dest -- )
5784: POSTPONE AGAIN
5785: POSTPONE THEN ; immediate
5786: @end example
5787:
5788: @noindent
5789: and then using these to create the control structure:
5790:
5791: @example
5792: BEGIN
5793: ...
5794: WHILE
5795: ...
5796: REPEAT
5797: @end example
5798:
5799: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5800: @code{WHILE} are predefined, so in this example it would not be
5801: necessary to define them.
5802:
5803: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5804: @subsection Calls and returns
5805: @cindex calling a definition
5806: @cindex returning from a definition
5807:
5808: @cindex recursive definitions
5809: A definition can be called simply be writing the name of the definition
5810: to be called. Normally a definition is invisible during its own
5811: definition. If you want to write a directly recursive definition, you
5812: can use @code{recursive} to make the current definition visible, or
5813: @code{recurse} to call the current definition directly.
5814:
5815:
5816: doc-recursive
5817: doc-recurse
5818:
5819:
5820: @comment TODO add example of the two recursion methods
5821: @quotation
5822: @progstyle
5823: I prefer using @code{recursive} to @code{recurse}, because calling the
5824: definition by name is more descriptive (if the name is well-chosen) than
5825: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5826: implementation, it is much better to read (and think) ``now sort the
5827: partitions'' than to read ``now do a recursive call''.
5828: @end quotation
5829:
5830: For mutual recursion, use @code{Defer}red words, like this:
5831:
5832: @example
5833: Defer foo
5834:
5835: : bar ( ... -- ... )
5836: ... foo ... ;
5837:
5838: :noname ( ... -- ... )
5839: ... bar ... ;
5840: IS foo
5841: @end example
5842:
5843: Deferred words are discussed in more detail in @ref{Deferred words}.
5844:
5845: The current definition returns control to the calling definition when
5846: the end of the definition is reached or @code{EXIT} is encountered.
5847:
5848: doc-exit
5849: doc-;s
5850:
5851:
5852: @node Exception Handling, , Calls and returns, Control Structures
5853: @subsection Exception Handling
5854: @cindex exceptions
5855:
5856: @c quit is a very bad idea for error handling,
5857: @c because it does not translate into a THROW
5858: @c it also does not belong into this chapter
5859:
5860: If a word detects an error condition that it cannot handle, it can
5861: @code{throw} an exception. In the simplest case, this will terminate
5862: your program, and report an appropriate error.
5863:
5864: doc-throw
5865:
5866: @code{Throw} consumes a cell-sized error number on the stack. There are
5867: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5868: Gforth (and most other systems) you can use the iors produced by various
5869: words as error numbers (e.g., a typical use of @code{allocate} is
5870: @code{allocate throw}). Gforth also provides the word @code{exception}
5871: to define your own error numbers (with decent error reporting); an ANS
5872: Forth version of this word (but without the error messages) is available
5873: in @code{compat/except.fs}. And finally, you can use your own error
5874: numbers (anything outside the range -4095..0), but won't get nice error
5875: messages, only numbers. For example, try:
5876:
5877: @example
5878: -10 throw \ ANS defined
5879: -267 throw \ system defined
5880: s" my error" exception throw \ user defined
5881: 7 throw \ arbitrary number
5882: @end example
5883:
5884: doc---exception-exception
5885:
5886: A common idiom to @code{THROW} a specific error if a flag is true is
5887: this:
5888:
5889: @example
5890: @code{( flag ) 0<> @i{errno} and throw}
5891: @end example
5892:
5893: Your program can provide exception handlers to catch exceptions. An
5894: exception handler can be used to correct the problem, or to clean up
5895: some data structures and just throw the exception to the next exception
5896: handler. Note that @code{throw} jumps to the dynamically innermost
5897: exception handler. The system's exception handler is outermost, and just
5898: prints an error and restarts command-line interpretation (or, in batch
5899: mode (i.e., while processing the shell command line), leaves Gforth).
5900:
5901: The ANS Forth way to catch exceptions is @code{catch}:
5902:
5903: doc-catch
5904:
5905: The most common use of exception handlers is to clean up the state when
5906: an error happens. E.g.,
5907:
5908: @example
5909: base @ >r hex \ actually the hex should be inside foo, or we h
5910: ['] foo catch ( nerror|0 )
5911: r> base !
5912: ( nerror|0 ) throw \ pass it on
5913: @end example
5914:
5915: A use of @code{catch} for handling the error @code{myerror} might look
5916: like this:
5917:
5918: @example
5919: ['] foo catch
5920: CASE
5921: myerror OF ... ( do something about it ) ENDOF
5922: dup throw \ default: pass other errors on, do nothing on non-errors
5923: ENDCASE
5924: @end example
5925:
5926: Having to wrap the code into a separate word is often cumbersome,
5927: therefore Gforth provides an alternative syntax:
5928:
5929: @example
5930: TRY
5931: @i{code1}
5932: RECOVER \ optional
5933: @i{code2} \ optional
5934: ENDTRY
5935: @end example
5936:
5937: This performs @i{Code1}. If @i{code1} completes normally, execution
5938: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5939: reset to the state during @code{try}, the throw value is pushed on the
5940: data stack, and execution constinues at @i{code2}, and finally falls
5941: through the @code{endtry} into the following code. If there is no
5942: @code{recover} clause, this works like an empty recover clause.
5943:
5944: doc-try
5945: doc-recover
5946: doc-endtry
5947:
5948: The cleanup example from above in this syntax:
5949:
5950: @example
5951: base @ >r TRY
5952: hex foo \ now the hex is placed correctly
5953: 0 \ value for throw
5954: ENDTRY
5955: r> base ! throw
5956: @end example
5957:
5958: And here's the error handling example:
5959:
5960: @example
5961: TRY
5962: foo
5963: RECOVER
5964: CASE
5965: myerror OF ... ( do something about it ) ENDOF
5966: throw \ pass other errors on
5967: ENDCASE
5968: ENDTRY
5969: @end example
5970:
5971: @progstyle
5972: As usual, you should ensure that the stack depth is statically known at
5973: the end: either after the @code{throw} for passing on errors, or after
5974: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5975: selection construct for handling the error).
5976:
5977: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5978: and you can provide an error message. @code{Abort} just produces an
5979: ``Aborted'' error.
5980:
5981: The problem with these words is that exception handlers cannot
5982: differentiate between different @code{abort"}s; they just look like
5983: @code{-2 throw} to them (the error message cannot be accessed by
5984: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5985: exception handlers.
5986:
5987: doc-abort"
5988: doc-abort
5989:
5990:
5991:
5992: @c -------------------------------------------------------------
5993: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
5994: @section Defining Words
5995: @cindex defining words
5996:
5997: Defining words are used to extend Forth by creating new entries in the dictionary.
5998:
5999: @menu
6000: * CREATE::
6001: * Variables:: Variables and user variables
6002: * Constants::
6003: * Values:: Initialised variables
6004: * Colon Definitions::
6005: * Anonymous Definitions:: Definitions without names
6006: * Supplying names:: Passing definition names as strings
6007: * User-defined Defining Words::
6008: * Deferred words:: Allow forward references
6009: * Aliases::
6010: @end menu
6011:
6012: @node CREATE, Variables, Defining Words, Defining Words
6013: @subsection @code{CREATE}
6014: @cindex simple defining words
6015: @cindex defining words, simple
6016:
6017: Defining words are used to create new entries in the dictionary. The
6018: simplest defining word is @code{CREATE}. @code{CREATE} is used like
6019: this:
6020:
6021: @example
6022: CREATE new-word1
6023: @end example
6024:
6025: @code{CREATE} is a parsing word, i.e., it takes an argument from the
6026: input stream (@code{new-word1} in our example). It generates a
6027: dictionary entry for @code{new-word1}. When @code{new-word1} is
6028: executed, all that it does is leave an address on the stack. The address
6029: represents the value of the data space pointer (@code{HERE}) at the time
6030: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
6031: associating a name with the address of a region of memory.
6032:
6033: doc-create
6034:
6035: Note that in ANS Forth guarantees only for @code{create} that its body
6036: is in dictionary data space (i.e., where @code{here}, @code{allot}
6037: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
6038: @code{create}d words can be modified with @code{does>}
6039: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
6040: can only be applied to @code{create}d words.
6041:
6042: By extending this example to reserve some memory in data space, we end
6043: up with something like a @i{variable}. Here are two different ways to do
6044: it:
6045:
6046: @example
6047: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
6048: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
6049: @end example
6050:
6051: The variable can be examined and modified using @code{@@} (``fetch'') and
6052: @code{!} (``store'') like this:
6053:
6054: @example
6055: new-word2 @@ . \ get address, fetch from it and display
6056: 1234 new-word2 ! \ new value, get address, store to it
6057: @end example
6058:
6059: @cindex arrays
6060: A similar mechanism can be used to create arrays. For example, an
6061: 80-character text input buffer:
6062:
6063: @example
6064: CREATE text-buf 80 chars allot
6065:
6066: text-buf 0 chars c@@ \ the 1st character (offset 0)
6067: text-buf 3 chars c@@ \ the 4th character (offset 3)
6068: @end example
6069:
6070: You can build arbitrarily complex data structures by allocating
6071: appropriate areas of memory. For further discussions of this, and to
6072: learn about some Gforth tools that make it easier,
6073: @xref{Structures}.
6074:
6075:
6076: @node Variables, Constants, CREATE, Defining Words
6077: @subsection Variables
6078: @cindex variables
6079:
6080: The previous section showed how a sequence of commands could be used to
6081: generate a variable. As a final refinement, the whole code sequence can
6082: be wrapped up in a defining word (pre-empting the subject of the next
6083: section), making it easier to create new variables:
6084:
6085: @example
6086: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
6087: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
6088:
6089: myvariableX foo \ variable foo starts off with an unknown value
6090: myvariable0 joe \ whilst joe is initialised to 0
6091:
6092: 45 3 * foo ! \ set foo to 135
6093: 1234 joe ! \ set joe to 1234
6094: 3 joe +! \ increment joe by 3.. to 1237
6095: @end example
6096:
6097: Not surprisingly, there is no need to define @code{myvariable}, since
6098: Forth already has a definition @code{Variable}. ANS Forth does not
6099: guarantee that a @code{Variable} is initialised when it is created
6100: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
6101: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
6102: like @code{myvariable0}). Forth also provides @code{2Variable} and
6103: @code{fvariable} for double and floating-point variables, respectively
6104: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
6105: store a boolean, you can use @code{on} and @code{off} to toggle its
6106: state.
6107:
6108: doc-variable
6109: doc-2variable
6110: doc-fvariable
6111:
6112: @cindex user variables
6113: @cindex user space
6114: The defining word @code{User} behaves in the same way as @code{Variable}.
6115: The difference is that it reserves space in @i{user (data) space} rather
6116: than normal data space. In a Forth system that has a multi-tasker, each
6117: task has its own set of user variables.
6118:
6119: doc-user
6120: @c doc-udp
6121: @c doc-uallot
6122:
6123: @comment TODO is that stuff about user variables strictly correct? Is it
6124: @comment just terminal tasks that have user variables?
6125: @comment should document tasker.fs (with some examples) elsewhere
6126: @comment in this manual, then expand on user space and user variables.
6127:
6128: @node Constants, Values, Variables, Defining Words
6129: @subsection Constants
6130: @cindex constants
6131:
6132: @code{Constant} allows you to declare a fixed value and refer to it by
6133: name. For example:
6134:
6135: @example
6136: 12 Constant INCHES-PER-FOOT
6137: 3E+08 fconstant SPEED-O-LIGHT
6138: @end example
6139:
6140: A @code{Variable} can be both read and written, so its run-time
6141: behaviour is to supply an address through which its current value can be
6142: manipulated. In contrast, the value of a @code{Constant} cannot be
6143: changed once it has been declared@footnote{Well, often it can be -- but
6144: not in a Standard, portable way. It's safer to use a @code{Value} (read
6145: on).} so it's not necessary to supply the address -- it is more
6146: efficient to return the value of the constant directly. That's exactly
6147: what happens; the run-time effect of a constant is to put its value on
6148: the top of the stack (You can find one
6149: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
6150:
6151: Forth also provides @code{2Constant} and @code{fconstant} for defining
6152: double and floating-point constants, respectively.
6153:
6154: doc-constant
6155: doc-2constant
6156: doc-fconstant
6157:
6158: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
6159: @c nac-> How could that not be true in an ANS Forth? You can't define a
6160: @c constant, use it and then delete the definition of the constant..
6161:
6162: @c anton->An ANS Forth system can compile a constant to a literal; On
6163: @c decompilation you would see only the number, just as if it had been used
6164: @c in the first place. The word will stay, of course, but it will only be
6165: @c used by the text interpreter (no run-time duties, except when it is
6166: @c POSTPONEd or somesuch).
6167:
6168: @c nac:
6169: @c I agree that it's rather deep, but IMO it is an important difference
6170: @c relative to other programming languages.. often it's annoying: it
6171: @c certainly changes my programming style relative to C.
6172:
6173: @c anton: In what way?
6174:
6175: Constants in Forth behave differently from their equivalents in other
6176: programming languages. In other languages, a constant (such as an EQU in
6177: assembler or a #define in C) only exists at compile-time; in the
6178: executable program the constant has been translated into an absolute
6179: number and, unless you are using a symbolic debugger, it's impossible to
6180: know what abstract thing that number represents. In Forth a constant has
6181: an entry in the header space and remains there after the code that uses
6182: it has been defined. In fact, it must remain in the dictionary since it
6183: has run-time duties to perform. For example:
6184:
6185: @example
6186: 12 Constant INCHES-PER-FOOT
6187: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6188: @end example
6189:
6190: @cindex in-lining of constants
6191: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6192: associated with the constant @code{INCHES-PER-FOOT}. If you use
6193: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6194: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6195: attempt to optimise constants by in-lining them where they are used. You
6196: can force Gforth to in-line a constant like this:
6197:
6198: @example
6199: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6200: @end example
6201:
6202: If you use @code{see} to decompile @i{this} version of
6203: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
6204: longer present. To understand how this works, read
6205: @ref{Interpret/Compile states}, and @ref{Literals}.
6206:
6207: In-lining constants in this way might improve execution time
6208: fractionally, and can ensure that a constant is now only referenced at
6209: compile-time. However, the definition of the constant still remains in
6210: the dictionary. Some Forth compilers provide a mechanism for controlling
6211: a second dictionary for holding transient words such that this second
6212: dictionary can be deleted later in order to recover memory
6213: space. However, there is no standard way of doing this.
6214:
6215:
6216: @node Values, Colon Definitions, Constants, Defining Words
6217: @subsection Values
6218: @cindex values
6219:
6220: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6221: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6222: (not in ANS Forth) you can access (and change) a @code{value} also with
6223: @code{>body}.
6224:
6225: Here are some
6226: examples:
6227:
6228: @example
6229: 12 Value APPLES \ Define APPLES with an initial value of 12
6230: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6231: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6232: APPLES \ puts 35 on the top of the stack.
6233: @end example
6234:
6235: doc-value
6236: doc-to
6237:
6238:
6239:
6240: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6241: @subsection Colon Definitions
6242: @cindex colon definitions
6243:
6244: @example
6245: : name ( ... -- ... )
6246: word1 word2 word3 ;
6247: @end example
6248:
6249: @noindent
6250: Creates a word called @code{name} that, upon execution, executes
6251: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
6252:
6253: The explanation above is somewhat superficial. For simple examples of
6254: colon definitions see @ref{Your first definition}. For an in-depth
6255: discussion of some of the issues involved, @xref{Interpretation and
6256: Compilation Semantics}.
6257:
6258: doc-:
6259: doc-;
6260:
6261:
6262: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
6263: @subsection Anonymous Definitions
6264: @cindex colon definitions
6265: @cindex defining words without name
6266:
6267: Sometimes you want to define an @dfn{anonymous word}; a word without a
6268: name. You can do this with:
6269:
6270: doc-:noname
6271:
6272: This leaves the execution token for the word on the stack after the
6273: closing @code{;}. Here's an example in which a deferred word is
6274: initialised with an @code{xt} from an anonymous colon definition:
6275:
6276: @example
6277: Defer deferred
6278: :noname ( ... -- ... )
6279: ... ;
6280: IS deferred
6281: @end example
6282:
6283: @noindent
6284: Gforth provides an alternative way of doing this, using two separate
6285: words:
6286:
6287: doc-noname
6288: @cindex execution token of last defined word
6289: doc-lastxt
6290:
6291: @noindent
6292: The previous example can be rewritten using @code{noname} and
6293: @code{lastxt}:
6294:
6295: @example
6296: Defer deferred
6297: noname : ( ... -- ... )
6298: ... ;
6299: lastxt IS deferred
6300: @end example
6301:
6302: @noindent
6303: @code{noname} works with any defining word, not just @code{:}.
6304:
6305: @code{lastxt} also works when the last word was not defined as
6306: @code{noname}. It does not work for combined words, though. It also has
6307: the useful property that is is valid as soon as the header for a
6308: definition has been built. Thus:
6309:
6310: @example
6311: lastxt . : foo [ lastxt . ] ; ' foo .
6312: @end example
6313:
6314: @noindent
6315: prints 3 numbers; the last two are the same.
6316:
6317: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6318: @subsection Supplying the name of a defined word
6319: @cindex names for defined words
6320: @cindex defining words, name given in a string
6321:
6322: By default, a defining word takes the name for the defined word from the
6323: input stream. Sometimes you want to supply the name from a string. You
6324: can do this with:
6325:
6326: doc-nextname
6327:
6328: For example:
6329:
6330: @example
6331: s" foo" nextname create
6332: @end example
6333:
6334: @noindent
6335: is equivalent to:
6336:
6337: @example
6338: create foo
6339: @end example
6340:
6341: @noindent
6342: @code{nextname} works with any defining word.
6343:
6344:
6345: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
6346: @subsection User-defined Defining Words
6347: @cindex user-defined defining words
6348: @cindex defining words, user-defined
6349:
6350: You can create a new defining word by wrapping defining-time code around
6351: an existing defining word and putting the sequence in a colon
6352: definition.
6353:
6354: @c anton: This example is very complex and leads in a quite different
6355: @c direction from the CREATE-DOES> stuff that follows. It should probably
6356: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6357: @c subsection of Defining Words)
6358:
6359: For example, suppose that you have a word @code{stats} that
6360: gathers statistics about colon definitions given the @i{xt} of the
6361: definition, and you want every colon definition in your application to
6362: make a call to @code{stats}. You can define and use a new version of
6363: @code{:} like this:
6364:
6365: @example
6366: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6367: ... ; \ other code
6368:
6369: : my: : lastxt postpone literal ['] stats compile, ;
6370:
6371: my: foo + - ;
6372: @end example
6373:
6374: When @code{foo} is defined using @code{my:} these steps occur:
6375:
6376: @itemize @bullet
6377: @item
6378: @code{my:} is executed.
6379: @item
6380: The @code{:} within the definition (the one between @code{my:} and
6381: @code{lastxt}) is executed, and does just what it always does; it parses
6382: the input stream for a name, builds a dictionary header for the name
6383: @code{foo} and switches @code{state} from interpret to compile.
6384: @item
6385: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
6386: being defined -- @code{foo} -- onto the stack.
6387: @item
6388: The code that was produced by @code{postpone literal} is executed; this
6389: causes the value on the stack to be compiled as a literal in the code
6390: area of @code{foo}.
6391: @item
6392: The code @code{['] stats} compiles a literal into the definition of
6393: @code{my:}. When @code{compile,} is executed, that literal -- the
6394: execution token for @code{stats} -- is layed down in the code area of
6395: @code{foo} , following the literal@footnote{Strictly speaking, the
6396: mechanism that @code{compile,} uses to convert an @i{xt} into something
6397: in the code area is implementation-dependent. A threaded implementation
6398: might spit out the execution token directly whilst another
6399: implementation might spit out a native code sequence.}.
6400: @item
6401: At this point, the execution of @code{my:} is complete, and control
6402: returns to the text interpreter. The text interpreter is in compile
6403: state, so subsequent text @code{+ -} is compiled into the definition of
6404: @code{foo} and the @code{;} terminates the definition as always.
6405: @end itemize
6406:
6407: You can use @code{see} to decompile a word that was defined using
6408: @code{my:} and see how it is different from a normal @code{:}
6409: definition. For example:
6410:
6411: @example
6412: : bar + - ; \ like foo but using : rather than my:
6413: see bar
6414: : bar
6415: + - ;
6416: see foo
6417: : foo
6418: 107645672 stats + - ;
6419:
6420: \ use ' stats . to show that 107645672 is the xt for stats
6421: @end example
6422:
6423: You can use techniques like this to make new defining words in terms of
6424: @i{any} existing defining word.
6425:
6426:
6427: @cindex defining defining words
6428: @cindex @code{CREATE} ... @code{DOES>}
6429: If you want the words defined with your defining words to behave
6430: differently from words defined with standard defining words, you can
6431: write your defining word like this:
6432:
6433: @example
6434: : def-word ( "name" -- )
6435: CREATE @i{code1}
6436: DOES> ( ... -- ... )
6437: @i{code2} ;
6438:
6439: def-word name
6440: @end example
6441:
6442: @cindex child words
6443: This fragment defines a @dfn{defining word} @code{def-word} and then
6444: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6445: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6446: is not executed at this time. The word @code{name} is sometimes called a
6447: @dfn{child} of @code{def-word}.
6448:
6449: When you execute @code{name}, the address of the body of @code{name} is
6450: put on the data stack and @i{code2} is executed (the address of the body
6451: of @code{name} is the address @code{HERE} returns immediately after the
6452: @code{CREATE}, i.e., the address a @code{create}d word returns by
6453: default).
6454:
6455: @c anton:
6456: @c www.dictionary.com says:
6457: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6458: @c several generations of absence, usually caused by the chance
6459: @c recombination of genes. 2.An individual or a part that exhibits
6460: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6461: @c of previous behavior after a period of absence.
6462: @c
6463: @c Doesn't seem to fit.
6464:
6465: @c @cindex atavism in child words
6466: You can use @code{def-word} to define a set of child words that behave
6467: similarly; they all have a common run-time behaviour determined by
6468: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6469: body of the child word. The structure of the data is common to all
6470: children of @code{def-word}, but the data values are specific -- and
6471: private -- to each child word. When a child word is executed, the
6472: address of its private data area is passed as a parameter on TOS to be
6473: used and manipulated@footnote{It is legitimate both to read and write to
6474: this data area.} by @i{code2}.
6475:
6476: The two fragments of code that make up the defining words act (are
6477: executed) at two completely separate times:
6478:
6479: @itemize @bullet
6480: @item
6481: At @i{define time}, the defining word executes @i{code1} to generate a
6482: child word
6483: @item
6484: At @i{child execution time}, when a child word is invoked, @i{code2}
6485: is executed, using parameters (data) that are private and specific to
6486: the child word.
6487: @end itemize
6488:
6489: Another way of understanding the behaviour of @code{def-word} and
6490: @code{name} is to say that, if you make the following definitions:
6491: @example
6492: : def-word1 ( "name" -- )
6493: CREATE @i{code1} ;
6494:
6495: : action1 ( ... -- ... )
6496: @i{code2} ;
6497:
6498: def-word1 name1
6499: @end example
6500:
6501: @noindent
6502: Then using @code{name1 action1} is equivalent to using @code{name}.
6503:
6504: The classic example is that you can define @code{CONSTANT} in this way:
6505:
6506: @example
6507: : CONSTANT ( w "name" -- )
6508: CREATE ,
6509: DOES> ( -- w )
6510: @@ ;
6511: @end example
6512:
6513: @comment There is a beautiful description of how this works and what
6514: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6515: @comment commentary on the Counting Fruits problem.
6516:
6517: When you create a constant with @code{5 CONSTANT five}, a set of
6518: define-time actions take place; first a new word @code{five} is created,
6519: then the value 5 is laid down in the body of @code{five} with
6520: @code{,}. When @code{five} is executed, the address of the body is put on
6521: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6522: no code of its own; it simply contains a data field and a pointer to the
6523: code that follows @code{DOES>} in its defining word. That makes words
6524: created in this way very compact.
6525:
6526: The final example in this section is intended to remind you that space
6527: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6528: both read and written by a Standard program@footnote{Exercise: use this
6529: example as a starting point for your own implementation of @code{Value}
6530: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6531: @code{[']}.}:
6532:
6533: @example
6534: : foo ( "name" -- )
6535: CREATE -1 ,
6536: DOES> ( -- )
6537: @@ . ;
6538:
6539: foo first-word
6540: foo second-word
6541:
6542: 123 ' first-word >BODY !
6543: @end example
6544:
6545: If @code{first-word} had been a @code{CREATE}d word, we could simply
6546: have executed it to get the address of its data field. However, since it
6547: was defined to have @code{DOES>} actions, its execution semantics are to
6548: perform those @code{DOES>} actions. To get the address of its data field
6549: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6550: translate the xt into the address of the data field. When you execute
6551: @code{first-word}, it will display @code{123}. When you execute
6552: @code{second-word} it will display @code{-1}.
6553:
6554: @cindex stack effect of @code{DOES>}-parts
6555: @cindex @code{DOES>}-parts, stack effect
6556: In the examples above the stack comment after the @code{DOES>} specifies
6557: the stack effect of the defined words, not the stack effect of the
6558: following code (the following code expects the address of the body on
6559: the top of stack, which is not reflected in the stack comment). This is
6560: the convention that I use and recommend (it clashes a bit with using
6561: locals declarations for stack effect specification, though).
6562:
6563: @menu
6564: * CREATE..DOES> applications::
6565: * CREATE..DOES> details::
6566: * Advanced does> usage example::
6567: @end menu
6568:
6569: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
6570: @subsubsection Applications of @code{CREATE..DOES>}
6571: @cindex @code{CREATE} ... @code{DOES>}, applications
6572:
6573: You may wonder how to use this feature. Here are some usage patterns:
6574:
6575: @cindex factoring similar colon definitions
6576: When you see a sequence of code occurring several times, and you can
6577: identify a meaning, you will factor it out as a colon definition. When
6578: you see similar colon definitions, you can factor them using
6579: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6580: that look very similar:
6581: @example
6582: : ori, ( reg-target reg-source n -- )
6583: 0 asm-reg-reg-imm ;
6584: : andi, ( reg-target reg-source n -- )
6585: 1 asm-reg-reg-imm ;
6586: @end example
6587:
6588: @noindent
6589: This could be factored with:
6590: @example
6591: : reg-reg-imm ( op-code -- )
6592: CREATE ,
6593: DOES> ( reg-target reg-source n -- )
6594: @@ asm-reg-reg-imm ;
6595:
6596: 0 reg-reg-imm ori,
6597: 1 reg-reg-imm andi,
6598: @end example
6599:
6600: @cindex currying
6601: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6602: supply a part of the parameters for a word (known as @dfn{currying} in
6603: the functional language community). E.g., @code{+} needs two
6604: parameters. Creating versions of @code{+} with one parameter fixed can
6605: be done like this:
6606:
6607: @example
6608: : curry+ ( n1 "name" -- )
6609: CREATE ,
6610: DOES> ( n2 -- n1+n2 )
6611: @@ + ;
6612:
6613: 3 curry+ 3+
6614: -2 curry+ 2-
6615: @end example
6616:
6617: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
6618: @subsubsection The gory details of @code{CREATE..DOES>}
6619: @cindex @code{CREATE} ... @code{DOES>}, details
6620:
6621: doc-does>
6622:
6623: @cindex @code{DOES>} in a separate definition
6624: This means that you need not use @code{CREATE} and @code{DOES>} in the
6625: same definition; you can put the @code{DOES>}-part in a separate
6626: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
6627: @example
6628: : does1
6629: DOES> ( ... -- ... )
6630: ... ;
6631:
6632: : does2
6633: DOES> ( ... -- ... )
6634: ... ;
6635:
6636: : def-word ( ... -- ... )
6637: create ...
6638: IF
6639: does1
6640: ELSE
6641: does2
6642: ENDIF ;
6643: @end example
6644:
6645: In this example, the selection of whether to use @code{does1} or
6646: @code{does2} is made at definition-time; at the time that the child word is
6647: @code{CREATE}d.
6648:
6649: @cindex @code{DOES>} in interpretation state
6650: In a standard program you can apply a @code{DOES>}-part only if the last
6651: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6652: will override the behaviour of the last word defined in any case. In a
6653: standard program, you can use @code{DOES>} only in a colon
6654: definition. In Gforth, you can also use it in interpretation state, in a
6655: kind of one-shot mode; for example:
6656: @example
6657: CREATE name ( ... -- ... )
6658: @i{initialization}
6659: DOES>
6660: @i{code} ;
6661: @end example
6662:
6663: @noindent
6664: is equivalent to the standard:
6665: @example
6666: :noname
6667: DOES>
6668: @i{code} ;
6669: CREATE name EXECUTE ( ... -- ... )
6670: @i{initialization}
6671: @end example
6672:
6673: doc->body
6674:
6675: @node Advanced does> usage example, , CREATE..DOES> details, User-defined Defining Words
6676: @subsubsection Advanced does> usage example
6677:
6678: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6679: for disassembling instructions, that follow a very repetetive scheme:
6680:
6681: @example
6682: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6683: @var{entry-num} cells @var{table} + !
6684: @end example
6685:
6686: Of course, this inspires the idea to factor out the commonalities to
6687: allow a definition like
6688:
6689: @example
6690: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6691: @end example
6692:
6693: The parameters @var{disasm-operands} and @var{table} are usually
6694: correlated. Moreover, before I wrote the disassembler, there already
6695: existed code that defines instructions like this:
6696:
6697: @example
6698: @var{entry-num} @var{inst-format} @var{inst-name}
6699: @end example
6700:
6701: This code comes from the assembler and resides in
6702: @file{arch/mips/insts.fs}.
6703:
6704: So I had to define the @var{inst-format} words that performed the scheme
6705: above when executed. At first I chose to use run-time code-generation:
6706:
6707: @example
6708: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6709: :noname Postpone @var{disasm-operands}
6710: name Postpone sliteral Postpone type Postpone ;
6711: swap cells @var{table} + ! ;
6712: @end example
6713:
6714: Note that this supplies the other two parameters of the scheme above.
6715:
6716: An alternative would have been to write this using
6717: @code{create}/@code{does>}:
6718:
6719: @example
6720: : @var{inst-format} ( entry-num "name" -- )
6721: here name string, ( entry-num c-addr ) \ parse and save "name"
6722: noname create , ( entry-num )
6723: lastxt swap cells @var{table} + !
6724: does> ( addr w -- )
6725: \ disassemble instruction w at addr
6726: @@ >r
6727: @var{disasm-operands}
6728: r> count type ;
6729: @end example
6730:
6731: Somehow the first solution is simpler, mainly because it's simpler to
6732: shift a string from definition-time to use-time with @code{sliteral}
6733: than with @code{string,} and friends.
6734:
6735: I wrote a lot of words following this scheme and soon thought about
6736: factoring out the commonalities among them. Note that this uses a
6737: two-level defining word, i.e., a word that defines ordinary defining
6738: words.
6739:
6740: This time a solution involving @code{postpone} and friends seemed more
6741: difficult (try it as an exercise), so I decided to use a
6742: @code{create}/@code{does>} word; since I was already at it, I also used
6743: @code{create}/@code{does>} for the lower level (try using
6744: @code{postpone} etc. as an exercise), resulting in the following
6745: definition:
6746:
6747: @example
6748: : define-format ( disasm-xt table-xt -- )
6749: \ define an instruction format that uses disasm-xt for
6750: \ disassembling and enters the defined instructions into table
6751: \ table-xt
6752: create 2,
6753: does> ( u "inst" -- )
6754: \ defines an anonymous word for disassembling instruction inst,
6755: \ and enters it as u-th entry into table-xt
6756: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6757: noname create 2, \ define anonymous word
6758: execute lastxt swap ! \ enter xt of defined word into table-xt
6759: does> ( addr w -- )
6760: \ disassemble instruction w at addr
6761: 2@@ >r ( addr w disasm-xt R: c-addr )
6762: execute ( R: c-addr ) \ disassemble operands
6763: r> count type ; \ print name
6764: @end example
6765:
6766: Note that the tables here (in contrast to above) do the @code{cells +}
6767: by themselves (that's why you have to pass an xt). This word is used in
6768: the following way:
6769:
6770: @example
6771: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6772: @end example
6773:
6774: As shown above, the defined instruction format is then used like this:
6775:
6776: @example
6777: @var{entry-num} @var{inst-format} @var{inst-name}
6778: @end example
6779:
6780: In terms of currying, this kind of two-level defining word provides the
6781: parameters in three stages: first @var{disasm-operands} and @var{table},
6782: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6783: the instruction to be disassembled.
6784:
6785: Of course this did not quite fit all the instruction format names used
6786: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6787: the parameters into the right form.
6788:
6789: If you have trouble following this section, don't worry. First, this is
6790: involved and takes time (and probably some playing around) to
6791: understand; second, this is the first two-level
6792: @code{create}/@code{does>} word I have written in seventeen years of
6793: Forth; and if I did not have @file{insts.fs} to start with, I may well
6794: have elected to use just a one-level defining word (with some repeating
6795: of parameters when using the defining word). So it is not necessary to
6796: understand this, but it may improve your understanding of Forth.
6797:
6798:
6799: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6800: @subsection Deferred words
6801: @cindex deferred words
6802:
6803: The defining word @code{Defer} allows you to define a word by name
6804: without defining its behaviour; the definition of its behaviour is
6805: deferred. Here are two situation where this can be useful:
6806:
6807: @itemize @bullet
6808: @item
6809: Where you want to allow the behaviour of a word to be altered later, and
6810: for all precompiled references to the word to change when its behaviour
6811: is changed.
6812: @item
6813: For mutual recursion; @xref{Calls and returns}.
6814: @end itemize
6815:
6816: In the following example, @code{foo} always invokes the version of
6817: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6818: always invokes the version that prints ``@code{Hello}''. There is no way
6819: of getting @code{foo} to use the later version without re-ordering the
6820: source code and recompiling it.
6821:
6822: @example
6823: : greet ." Good morning" ;
6824: : foo ... greet ... ;
6825: : greet ." Hello" ;
6826: : bar ... greet ... ;
6827: @end example
6828:
6829: This problem can be solved by defining @code{greet} as a @code{Defer}red
6830: word. The behaviour of a @code{Defer}red word can be defined and
6831: redefined at any time by using @code{IS} to associate the xt of a
6832: previously-defined word with it. The previous example becomes:
6833:
6834: @example
6835: Defer greet ( -- )
6836: : foo ... greet ... ;
6837: : bar ... greet ... ;
6838: : greet1 ( -- ) ." Good morning" ;
6839: : greet2 ( -- ) ." Hello" ;
6840: ' greet2 <IS> greet \ make greet behave like greet2
6841: @end example
6842:
6843: @progstyle
6844: You should write a stack comment for every deferred word, and put only
6845: XTs into deferred words that conform to this stack effect. Otherwise
6846: it's too difficult to use the deferred word.
6847:
6848: A deferred word can be used to improve the statistics-gathering example
6849: from @ref{User-defined Defining Words}; rather than edit the
6850: application's source code to change every @code{:} to a @code{my:}, do
6851: this:
6852:
6853: @example
6854: : real: : ; \ retain access to the original
6855: defer : \ redefine as a deferred word
6856: ' my: <IS> : \ use special version of :
6857: \
6858: \ load application here
6859: \
6860: ' real: <IS> : \ go back to the original
6861: @end example
6862:
6863:
6864: One thing to note is that @code{<IS>} consumes its name when it is
6865: executed. If you want to specify the name at compile time, use
6866: @code{[IS]}:
6867:
6868: @example
6869: : set-greet ( xt -- )
6870: [IS] greet ;
6871:
6872: ' greet1 set-greet
6873: @end example
6874:
6875: A deferred word can only inherit execution semantics from the xt
6876: (because that is all that an xt can represent -- for more discussion of
6877: this @pxref{Tokens for Words}); by default it will have default
6878: interpretation and compilation semantics deriving from this execution
6879: semantics. However, you can change the interpretation and compilation
6880: semantics of the deferred word in the usual ways:
6881:
6882: @example
6883: : bar .... ; compile-only
6884: Defer fred immediate
6885: Defer jim
6886:
6887: ' bar <IS> jim \ jim has default semantics
6888: ' bar <IS> fred \ fred is immediate
6889: @end example
6890:
6891: doc-defer
6892: doc-<is>
6893: doc-[is]
6894: doc-is
6895: @comment TODO document these: what's defers [is]
6896: doc-what's
6897: doc-defers
6898:
6899: @c Use @code{words-deferred} to see a list of deferred words.
6900:
6901: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
6902: are provided in @file{compat/defer.fs}.
6903:
6904:
6905: @node Aliases, , Deferred words, Defining Words
6906: @subsection Aliases
6907: @cindex aliases
6908:
6909: The defining word @code{Alias} allows you to define a word by name that
6910: has the same behaviour as some other word. Here are two situation where
6911: this can be useful:
6912:
6913: @itemize @bullet
6914: @item
6915: When you want access to a word's definition from a different word list
6916: (for an example of this, see the definition of the @code{Root} word list
6917: in the Gforth source).
6918: @item
6919: When you want to create a synonym; a definition that can be known by
6920: either of two names (for example, @code{THEN} and @code{ENDIF} are
6921: aliases).
6922: @end itemize
6923:
6924: Like deferred words, an alias has default compilation and interpretation
6925: semantics at the beginning (not the modifications of the other word),
6926: but you can change them in the usual ways (@code{immediate},
6927: @code{compile-only}). For example:
6928:
6929: @example
6930: : foo ... ; immediate
6931:
6932: ' foo Alias bar \ bar is not an immediate word
6933: ' foo Alias fooby immediate \ fooby is an immediate word
6934: @end example
6935:
6936: Words that are aliases have the same xt, different headers in the
6937: dictionary, and consequently different name tokens (@pxref{Tokens for
6938: Words}) and possibly different immediate flags. An alias can only have
6939: default or immediate compilation semantics; you can define aliases for
6940: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
6941:
6942: doc-alias
6943:
6944:
6945: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6946: @section Interpretation and Compilation Semantics
6947: @cindex semantics, interpretation and compilation
6948:
6949: @c !! state and ' are used without explanation
6950: @c example for immediate/compile-only? or is the tutorial enough
6951:
6952: @cindex interpretation semantics
6953: The @dfn{interpretation semantics} of a (named) word are what the text
6954: interpreter does when it encounters the word in interpret state. It also
6955: appears in some other contexts, e.g., the execution token returned by
6956: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6957: (in other words, @code{' @i{word} execute} is equivalent to
6958: interpret-state text interpretation of @code{@i{word}}).
6959:
6960: @cindex compilation semantics
6961: The @dfn{compilation semantics} of a (named) word are what the text
6962: interpreter does when it encounters the word in compile state. It also
6963: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6964: compiles@footnote{In standard terminology, ``appends to the current
6965: definition''.} the compilation semantics of @i{word}.
6966:
6967: @cindex execution semantics
6968: The standard also talks about @dfn{execution semantics}. They are used
6969: only for defining the interpretation and compilation semantics of many
6970: words. By default, the interpretation semantics of a word are to
6971: @code{execute} its execution semantics, and the compilation semantics of
6972: a word are to @code{compile,} its execution semantics.@footnote{In
6973: standard terminology: The default interpretation semantics are its
6974: execution semantics; the default compilation semantics are to append its
6975: execution semantics to the execution semantics of the current
6976: definition.}
6977:
6978: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6979: the text interpreter, ticked, or @code{postpone}d, so they have no
6980: interpretation or compilation semantics. Their behaviour is represented
6981: by their XT (@pxref{Tokens for Words}), and we call it execution
6982: semantics, too.
6983:
6984: @comment TODO expand, make it co-operate with new sections on text interpreter.
6985:
6986: @cindex immediate words
6987: @cindex compile-only words
6988: You can change the semantics of the most-recently defined word:
6989:
6990:
6991: doc-immediate
6992: doc-compile-only
6993: doc-restrict
6994:
6995: By convention, words with non-default compilation semantics (e.g.,
6996: immediate words) often have names surrounded with brackets (e.g.,
6997: @code{[']}, @pxref{Execution token}).
6998:
6999: Note that ticking (@code{'}) a compile-only word gives an error
7000: (``Interpreting a compile-only word'').
7001:
7002: @menu
7003: * Combined words::
7004: @end menu
7005:
7006:
7007: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
7008: @subsection Combined Words
7009: @cindex combined words
7010:
7011: Gforth allows you to define @dfn{combined words} -- words that have an
7012: arbitrary combination of interpretation and compilation semantics.
7013:
7014: doc-interpret/compile:
7015:
7016: This feature was introduced for implementing @code{TO} and @code{S"}. I
7017: recommend that you do not define such words, as cute as they may be:
7018: they make it hard to get at both parts of the word in some contexts.
7019: E.g., assume you want to get an execution token for the compilation
7020: part. Instead, define two words, one that embodies the interpretation
7021: part, and one that embodies the compilation part. Once you have done
7022: that, you can define a combined word with @code{interpret/compile:} for
7023: the convenience of your users.
7024:
7025: You might try to use this feature to provide an optimizing
7026: implementation of the default compilation semantics of a word. For
7027: example, by defining:
7028: @example
7029: :noname
7030: foo bar ;
7031: :noname
7032: POSTPONE foo POSTPONE bar ;
7033: interpret/compile: opti-foobar
7034: @end example
7035:
7036: @noindent
7037: as an optimizing version of:
7038:
7039: @example
7040: : foobar
7041: foo bar ;
7042: @end example
7043:
7044: Unfortunately, this does not work correctly with @code{[compile]},
7045: because @code{[compile]} assumes that the compilation semantics of all
7046: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
7047: opti-foobar} would compile compilation semantics, whereas
7048: @code{[compile] foobar} would compile interpretation semantics.
7049:
7050: @cindex state-smart words (are a bad idea)
7051: @anchor{state-smartness}
7052: Some people try to use @dfn{state-smart} words to emulate the feature provided
7053: by @code{interpret/compile:} (words are state-smart if they check
7054: @code{STATE} during execution). E.g., they would try to code
7055: @code{foobar} like this:
7056:
7057: @example
7058: : foobar
7059: STATE @@
7060: IF ( compilation state )
7061: POSTPONE foo POSTPONE bar
7062: ELSE
7063: foo bar
7064: ENDIF ; immediate
7065: @end example
7066:
7067: Although this works if @code{foobar} is only processed by the text
7068: interpreter, it does not work in other contexts (like @code{'} or
7069: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
7070: for a state-smart word, not for the interpretation semantics of the
7071: original @code{foobar}; when you execute this execution token (directly
7072: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
7073: state, the result will not be what you expected (i.e., it will not
7074: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
7075: write them@footnote{For a more detailed discussion of this topic, see
7076: M. Anton Ertl,
7077: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
7078: it is Evil and How to Exorcise it}}, EuroForth '98.}!
7079:
7080: @cindex defining words with arbitrary semantics combinations
7081: It is also possible to write defining words that define words with
7082: arbitrary combinations of interpretation and compilation semantics. In
7083: general, they look like this:
7084:
7085: @example
7086: : def-word
7087: create-interpret/compile
7088: @i{code1}
7089: interpretation>
7090: @i{code2}
7091: <interpretation
7092: compilation>
7093: @i{code3}
7094: <compilation ;
7095: @end example
7096:
7097: For a @i{word} defined with @code{def-word}, the interpretation
7098: semantics are to push the address of the body of @i{word} and perform
7099: @i{code2}, and the compilation semantics are to push the address of
7100: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
7101: can also be defined like this (except that the defined constants don't
7102: behave correctly when @code{[compile]}d):
7103:
7104: @example
7105: : constant ( n "name" -- )
7106: create-interpret/compile
7107: ,
7108: interpretation> ( -- n )
7109: @@
7110: <interpretation
7111: compilation> ( compilation. -- ; run-time. -- n )
7112: @@ postpone literal
7113: <compilation ;
7114: @end example
7115:
7116:
7117: doc-create-interpret/compile
7118: doc-interpretation>
7119: doc-<interpretation
7120: doc-compilation>
7121: doc-<compilation
7122:
7123:
7124: Words defined with @code{interpret/compile:} and
7125: @code{create-interpret/compile} have an extended header structure that
7126: differs from other words; however, unless you try to access them with
7127: plain address arithmetic, you should not notice this. Words for
7128: accessing the header structure usually know how to deal with this; e.g.,
7129: @code{'} @i{word} @code{>body} also gives you the body of a word created
7130: with @code{create-interpret/compile}.
7131:
7132:
7133: @c -------------------------------------------------------------
7134: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
7135: @section Tokens for Words
7136: @cindex tokens for words
7137:
7138: This section describes the creation and use of tokens that represent
7139: words.
7140:
7141: @menu
7142: * Execution token:: represents execution/interpretation semantics
7143: * Compilation token:: represents compilation semantics
7144: * Name token:: represents named words
7145: @end menu
7146:
7147: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7148: @subsection Execution token
7149:
7150: @cindex xt
7151: @cindex execution token
7152: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7153: You can use @code{execute} to invoke this behaviour.
7154:
7155: @cindex tick (')
7156: You can use @code{'} to get an execution token that represents the
7157: interpretation semantics of a named word:
7158:
7159: @example
7160: 5 ' .
7161: execute
7162: @end example
7163:
7164: doc-'
7165:
7166: @code{'} parses at run-time; there is also a word @code{[']} that parses
7167: when it is compiled, and compiles the resulting XT:
7168:
7169: @example
7170: : foo ['] . execute ;
7171: 5 foo
7172: : bar ' execute ; \ by contrast,
7173: 5 bar . \ ' parses "." when bar executes
7174: @end example
7175:
7176: doc-[']
7177:
7178: If you want the execution token of @i{word}, write @code{['] @i{word}}
7179: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7180: @code{'} and @code{[']} behave somewhat unusually by complaining about
7181: compile-only words (because these words have no interpretation
7182: semantics). You might get what you want by using @code{COMP' @i{word}
7183: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7184: token}).
7185:
7186: Another way to get an XT is @code{:noname} or @code{lastxt}
7187: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7188: for the only behaviour the word has (the execution semantics). For
7189: named words, @code{lastxt} produces an XT for the same behaviour it
7190: would produce if the word was defined anonymously.
7191:
7192: @example
7193: :noname ." hello" ;
7194: execute
7195: @end example
7196:
7197: An XT occupies one cell and can be manipulated like any other cell.
7198:
7199: @cindex code field address
7200: @cindex CFA
7201: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7202: operations that produce or consume it). For old hands: In Gforth, the
7203: XT is implemented as a code field address (CFA).
7204:
7205: doc-execute
7206: doc-perform
7207:
7208: @node Compilation token, Name token, Execution token, Tokens for Words
7209: @subsection Compilation token
7210:
7211: @cindex compilation token
7212: @cindex CT (compilation token)
7213: Gforth represents the compilation semantics of a named word by a
7214: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7215: @i{xt} is an execution token. The compilation semantics represented by
7216: the compilation token can be performed with @code{execute}, which
7217: consumes the whole compilation token, with an additional stack effect
7218: determined by the represented compilation semantics.
7219:
7220: At present, the @i{w} part of a compilation token is an execution token,
7221: and the @i{xt} part represents either @code{execute} or
7222: @code{compile,}@footnote{Depending upon the compilation semantics of the
7223: word. If the word has default compilation semantics, the @i{xt} will
7224: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7225: @i{xt} will represent @code{execute}.}. However, don't rely on that
7226: knowledge, unless necessary; future versions of Gforth may introduce
7227: unusual compilation tokens (e.g., a compilation token that represents
7228: the compilation semantics of a literal).
7229:
7230: You can perform the compilation semantics represented by the compilation
7231: token with @code{execute}. You can compile the compilation semantics
7232: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7233: equivalent to @code{postpone @i{word}}.
7234:
7235: doc-[comp']
7236: doc-comp'
7237: doc-postpone,
7238:
7239: @node Name token, , Compilation token, Tokens for Words
7240: @subsection Name token
7241:
7242: @cindex name token
7243: @cindex name field address
7244: @cindex NFA
7245: Gforth represents named words by the @dfn{name token}, (@i{nt}). In
7246: Gforth, the abstract data type @emph{name token} is implemented as a
7247: name field address (NFA).
7248:
7249: doc-find-name
7250: doc-name>int
7251: doc-name?int
7252: doc-name>comp
7253: doc-name>string
7254:
7255: @c ----------------------------------------------------------
7256: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7257: @section Compiling words
7258: @cindex compiling words
7259: @cindex macros
7260:
7261: In contrast to most other languages, Forth has no strict boundary
7262: between compilation and run-time. E.g., you can run arbitrary code
7263: between defining words (or for computing data used by defining words
7264: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7265: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7266: running arbitrary code while compiling a colon definition (exception:
7267: you must not allot dictionary space).
7268:
7269: @menu
7270: * Literals:: Compiling data values
7271: * Macros:: Compiling words
7272: @end menu
7273:
7274: @node Literals, Macros, Compiling words, Compiling words
7275: @subsection Literals
7276: @cindex Literals
7277:
7278: The simplest and most frequent example is to compute a literal during
7279: compilation. E.g., the following definition prints an array of strings,
7280: one string per line:
7281:
7282: @example
7283: : .strings ( addr u -- ) \ gforth
7284: 2* cells bounds U+DO
7285: cr i 2@@ type
7286: 2 cells +LOOP ;
7287: @end example
7288:
7289: With a simple-minded compiler like Gforth's, this computes @code{2
7290: cells} on every loop iteration. You can compute this value once and for
7291: all at compile time and compile it into the definition like this:
7292:
7293: @example
7294: : .strings ( addr u -- ) \ gforth
7295: 2* cells bounds U+DO
7296: cr i 2@@ type
7297: [ 2 cells ] literal +LOOP ;
7298: @end example
7299:
7300: @code{[} switches the text interpreter to interpret state (you will get
7301: an @code{ok} prompt if you type this example interactively and insert a
7302: newline between @code{[} and @code{]}), so it performs the
7303: interpretation semantics of @code{2 cells}; this computes a number.
7304: @code{]} switches the text interpreter back into compile state. It then
7305: performs @code{Literal}'s compilation semantics, which are to compile
7306: this number into the current word. You can decompile the word with
7307: @code{see .strings} to see the effect on the compiled code.
7308:
7309: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7310: *} in this way.
7311:
7312: doc-[
7313: doc-]
7314: doc-literal
7315: doc-]L
7316:
7317: There are also words for compiling other data types than single cells as
7318: literals:
7319:
7320: doc-2literal
7321: doc-fliteral
7322: doc-sliteral
7323:
7324: @cindex colon-sys, passing data across @code{:}
7325: @cindex @code{:}, passing data across
7326: You might be tempted to pass data from outside a colon definition to the
7327: inside on the data stack. This does not work, because @code{:} puhes a
7328: colon-sys, making stuff below unaccessible. E.g., this does not work:
7329:
7330: @example
7331: 5 : foo literal ; \ error: "unstructured"
7332: @end example
7333:
7334: Instead, you have to pass the value in some other way, e.g., through a
7335: variable:
7336:
7337: @example
7338: variable temp
7339: 5 temp !
7340: : foo [ temp @@ ] literal ;
7341: @end example
7342:
7343:
7344: @node Macros, , Literals, Compiling words
7345: @subsection Macros
7346: @cindex Macros
7347: @cindex compiling compilation semantics
7348:
7349: @code{Literal} and friends compile data values into the current
7350: definition. You can also write words that compile other words into the
7351: current definition. E.g.,
7352:
7353: @example
7354: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7355: POSTPONE + ;
7356:
7357: : foo ( n1 n2 -- n )
7358: [ compile-+ ] ;
7359: 1 2 foo .
7360: @end example
7361:
7362: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7363: What happens in this example? @code{Postpone} compiles the compilation
7364: semantics of @code{+} into @code{compile-+}; later the text interpreter
7365: executes @code{compile-+} and thus the compilation semantics of +, which
7366: compile (the execution semantics of) @code{+} into
7367: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7368: should only be executed in compile state, so this example is not
7369: guaranteed to work on all standard systems, but on any decent system it
7370: will work.}
7371:
7372: doc-postpone
7373: doc-[compile]
7374:
7375: Compiling words like @code{compile-+} are usually immediate (or similar)
7376: so you do not have to switch to interpret state to execute them;
7377: mopifying the last example accordingly produces:
7378:
7379: @example
7380: : [compile-+] ( compilation: --; interpretation: -- )
7381: \ compiled code: ( n1 n2 -- n )
7382: POSTPONE + ; immediate
7383:
7384: : foo ( n1 n2 -- n )
7385: [compile-+] ;
7386: 1 2 foo .
7387: @end example
7388:
7389: Immediate compiling words are similar to macros in other languages (in
7390: particular, Lisp). The important differences to macros in, e.g., C are:
7391:
7392: @itemize @bullet
7393:
7394: @item
7395: You use the same language for defining and processing macros, not a
7396: separate preprocessing language and processor.
7397:
7398: @item
7399: Consequently, the full power of Forth is available in macro definitions.
7400: E.g., you can perform arbitrarily complex computations, or generate
7401: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7402: Tutorial}). This power is very useful when writing a parser generators
7403: or other code-generating software.
7404:
7405: @item
7406: Macros defined using @code{postpone} etc. deal with the language at a
7407: higher level than strings; name binding happens at macro definition
7408: time, so you can avoid the pitfalls of name collisions that can happen
7409: in C macros. Of course, Forth is a liberal language and also allows to
7410: shoot yourself in the foot with text-interpreted macros like
7411:
7412: @example
7413: : [compile-+] s" +" evaluate ; immediate
7414: @end example
7415:
7416: Apart from binding the name at macro use time, using @code{evaluate}
7417: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7418: @end itemize
7419:
7420: You may want the macro to compile a number into a word. The word to do
7421: it is @code{literal}, but you have to @code{postpone} it, so its
7422: compilation semantics take effect when the macro is executed, not when
7423: it is compiled:
7424:
7425: @example
7426: : [compile-5] ( -- ) \ compiled code: ( -- n )
7427: 5 POSTPONE literal ; immediate
7428:
7429: : foo [compile-5] ;
7430: foo .
7431: @end example
7432:
7433: You may want to pass parameters to a macro, that the macro should
7434: compile into the current definition. If the parameter is a number, then
7435: you can use @code{postpone literal} (similar for other values).
7436:
7437: If you want to pass a word that is to be compiled, the usual way is to
7438: pass an execution token and @code{compile,} it:
7439:
7440: @example
7441: : twice1 ( xt -- ) \ compiled code: ... -- ...
7442: dup compile, compile, ;
7443:
7444: : 2+ ( n1 -- n2 )
7445: [ ' 1+ twice1 ] ;
7446: @end example
7447:
7448: doc-compile,
7449:
7450: An alternative available in Gforth, that allows you to pass compile-only
7451: words as parameters is to use the compilation token (@pxref{Compilation
7452: token}). The same example in this technique:
7453:
7454: @example
7455: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7456: 2dup 2>r execute 2r> execute ;
7457:
7458: : 2+ ( n1 -- n2 )
7459: [ comp' 1+ twice ] ;
7460: @end example
7461:
7462: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7463: works even if the executed compilation semantics has an effect on the
7464: data stack.
7465:
7466: You can also define complete definitions with these words; this provides
7467: an alternative to using @code{does>} (@pxref{User-defined Defining
7468: Words}). E.g., instead of
7469:
7470: @example
7471: : curry+ ( n1 "name" -- )
7472: CREATE ,
7473: DOES> ( n2 -- n1+n2 )
7474: @@ + ;
7475: @end example
7476:
7477: you could define
7478:
7479: @example
7480: : curry+ ( n1 "name" -- )
7481: \ name execution: ( n2 -- n1+n2 )
7482: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
7483:
7484: -3 curry+ 3-
7485: see 3-
7486: @end example
7487:
7488: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7489: colon-sys on the data stack that makes everything below it unaccessible.
7490:
7491: This way of writing defining words is sometimes more, sometimes less
7492: convenient than using @code{does>} (@pxref{Advanced does> usage
7493: example}). One advantage of this method is that it can be optimized
7494: better, because the compiler knows that the value compiled with
7495: @code{literal} is fixed, whereas the data associated with a
7496: @code{create}d word can be changed.
7497:
7498: @c ----------------------------------------------------------
7499: @node The Text Interpreter, Word Lists, Compiling words, Words
7500: @section The Text Interpreter
7501: @cindex interpreter - outer
7502: @cindex text interpreter
7503: @cindex outer interpreter
7504:
7505: @c Should we really describe all these ugly details? IMO the text
7506: @c interpreter should be much cleaner, but that may not be possible within
7507: @c ANS Forth. - anton
7508: @c nac-> I wanted to explain how it works to show how you can exploit
7509: @c it in your own programs. When I was writing a cross-compiler, figuring out
7510: @c some of these gory details was very helpful to me. None of the textbooks
7511: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7512: @c seems to positively avoid going into too much detail for some of
7513: @c the internals.
7514:
7515: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7516: @c it is; for the ugly details, I would prefer another place. I wonder
7517: @c whether we should have a chapter before "Words" that describes some
7518: @c basic concepts referred to in words, and a chapter after "Words" that
7519: @c describes implementation details.
7520:
7521: The text interpreter@footnote{This is an expanded version of the
7522: material in @ref{Introducing the Text Interpreter}.} is an endless loop
7523: that processes input from the current input device. It is also called
7524: the outer interpreter, in contrast to the inner interpreter
7525: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7526: implementations.
7527:
7528: @cindex interpret state
7529: @cindex compile state
7530: The text interpreter operates in one of two states: @dfn{interpret
7531: state} and @dfn{compile state}. The current state is defined by the
7532: aptly-named variable @code{state}.
7533:
7534: This section starts by describing how the text interpreter behaves when
7535: it is in interpret state, processing input from the user input device --
7536: the keyboard. This is the mode that a Forth system is in after it starts
7537: up.
7538:
7539: @cindex input buffer
7540: @cindex terminal input buffer
7541: The text interpreter works from an area of memory called the @dfn{input
7542: buffer}@footnote{When the text interpreter is processing input from the
7543: keyboard, this area of memory is called the @dfn{terminal input buffer}
7544: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7545: @code{#TIB}.}, which stores your keyboard input when you press the
7546: @key{RET} key. Starting at the beginning of the input buffer, it skips
7547: leading spaces (called @dfn{delimiters}) then parses a string (a
7548: sequence of non-space characters) until it reaches either a space
7549: character or the end of the buffer. Having parsed a string, it makes two
7550: attempts to process it:
7551:
7552: @cindex dictionary
7553: @itemize @bullet
7554: @item
7555: It looks for the string in a @dfn{dictionary} of definitions. If the
7556: string is found, the string names a @dfn{definition} (also known as a
7557: @dfn{word}) and the dictionary search returns information that allows
7558: the text interpreter to perform the word's @dfn{interpretation
7559: semantics}. In most cases, this simply means that the word will be
7560: executed.
7561: @item
7562: If the string is not found in the dictionary, the text interpreter
7563: attempts to treat it as a number, using the rules described in
7564: @ref{Number Conversion}. If the string represents a legal number in the
7565: current radix, the number is pushed onto a parameter stack (the data
7566: stack for integers, the floating-point stack for floating-point
7567: numbers).
7568: @end itemize
7569:
7570: If both attempts fail, or if the word is found in the dictionary but has
7571: no interpretation semantics@footnote{This happens if the word was
7572: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7573: remainder of the input buffer, issues an error message and waits for
7574: more input. If one of the attempts succeeds, the text interpreter
7575: repeats the parsing process until the whole of the input buffer has been
7576: processed, at which point it prints the status message ``@code{ ok}''
7577: and waits for more input.
7578:
7579: @c anton: this should be in the input stream subsection (or below it)
7580:
7581: @cindex parse area
7582: The text interpreter keeps track of its position in the input buffer by
7583: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7584: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7585: of the input buffer. The region from offset @code{>IN @@} to the end of
7586: the input buffer is called the @dfn{parse area}@footnote{In other words,
7587: the text interpreter processes the contents of the input buffer by
7588: parsing strings from the parse area until the parse area is empty.}.
7589: This example shows how @code{>IN} changes as the text interpreter parses
7590: the input buffer:
7591:
7592: @example
7593: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7594: CR ." ->" TYPE ." <-" ; IMMEDIATE
7595:
7596: 1 2 3 remaining + remaining .
7597:
7598: : foo 1 2 3 remaining SWAP remaining ;
7599: @end example
7600:
7601: @noindent
7602: The result is:
7603:
7604: @example
7605: ->+ remaining .<-
7606: ->.<-5 ok
7607:
7608: ->SWAP remaining ;-<
7609: ->;<- ok
7610: @end example
7611:
7612: @cindex parsing words
7613: The value of @code{>IN} can also be modified by a word in the input
7614: buffer that is executed by the text interpreter. This means that a word
7615: can ``trick'' the text interpreter into either skipping a section of the
7616: input buffer@footnote{This is how parsing words work.} or into parsing a
7617: section twice. For example:
7618:
7619: @example
7620: : lat ." <<foo>>" ;
7621: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
7622: @end example
7623:
7624: @noindent
7625: When @code{flat} is executed, this output is produced@footnote{Exercise
7626: for the reader: what would happen if the @code{3} were replaced with
7627: @code{4}?}:
7628:
7629: @example
7630: <<bar>><<foo>>
7631: @end example
7632:
7633: This technique can be used to work around some of the interoperability
7634: problems of parsing words. Of course, it's better to avoid parsing
7635: words where possible.
7636:
7637: @noindent
7638: Two important notes about the behaviour of the text interpreter:
7639:
7640: @itemize @bullet
7641: @item
7642: It processes each input string to completion before parsing additional
7643: characters from the input buffer.
7644: @item
7645: It treats the input buffer as a read-only region (and so must your code).
7646: @end itemize
7647:
7648: @noindent
7649: When the text interpreter is in compile state, its behaviour changes in
7650: these ways:
7651:
7652: @itemize @bullet
7653: @item
7654: If a parsed string is found in the dictionary, the text interpreter will
7655: perform the word's @dfn{compilation semantics}. In most cases, this
7656: simply means that the execution semantics of the word will be appended
7657: to the current definition.
7658: @item
7659: When a number is encountered, it is compiled into the current definition
7660: (as a literal) rather than being pushed onto a parameter stack.
7661: @item
7662: If an error occurs, @code{state} is modified to put the text interpreter
7663: back into interpret state.
7664: @item
7665: Each time a line is entered from the keyboard, Gforth prints
7666: ``@code{ compiled}'' rather than `` @code{ok}''.
7667: @end itemize
7668:
7669: @cindex text interpreter - input sources
7670: When the text interpreter is using an input device other than the
7671: keyboard, its behaviour changes in these ways:
7672:
7673: @itemize @bullet
7674: @item
7675: When the parse area is empty, the text interpreter attempts to refill
7676: the input buffer from the input source. When the input source is
7677: exhausted, the input source is set back to the previous input source.
7678: @item
7679: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7680: time the parse area is emptied.
7681: @item
7682: If an error occurs, the input source is set back to the user input
7683: device.
7684: @end itemize
7685:
7686: You can read about this in more detail in @ref{Input Sources}.
7687:
7688: doc->in
7689: doc-source
7690:
7691: doc-tib
7692: doc-#tib
7693:
7694:
7695: @menu
7696: * Input Sources::
7697: * Number Conversion::
7698: * Interpret/Compile states::
7699: * Interpreter Directives::
7700: @end menu
7701:
7702: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7703: @subsection Input Sources
7704: @cindex input sources
7705: @cindex text interpreter - input sources
7706:
7707: By default, the text interpreter processes input from the user input
7708: device (the keyboard) when Forth starts up. The text interpreter can
7709: process input from any of these sources:
7710:
7711: @itemize @bullet
7712: @item
7713: The user input device -- the keyboard.
7714: @item
7715: A file, using the words described in @ref{Forth source files}.
7716: @item
7717: A block, using the words described in @ref{Blocks}.
7718: @item
7719: A text string, using @code{evaluate}.
7720: @end itemize
7721:
7722: A program can identify the current input device from the values of
7723: @code{source-id} and @code{blk}.
7724:
7725:
7726: doc-source-id
7727: doc-blk
7728:
7729: doc-save-input
7730: doc-restore-input
7731:
7732: doc-evaluate
7733:
7734:
7735:
7736: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
7737: @subsection Number Conversion
7738: @cindex number conversion
7739: @cindex double-cell numbers, input format
7740: @cindex input format for double-cell numbers
7741: @cindex single-cell numbers, input format
7742: @cindex input format for single-cell numbers
7743: @cindex floating-point numbers, input format
7744: @cindex input format for floating-point numbers
7745:
7746: This section describes the rules that the text interpreter uses when it
7747: tries to convert a string into a number.
7748:
7749: Let <digit> represent any character that is a legal digit in the current
7750: number base@footnote{For example, 0-9 when the number base is decimal or
7751: 0-9, A-F when the number base is hexadecimal.}.
7752:
7753: Let <decimal digit> represent any character in the range 0-9.
7754:
7755: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7756: in the braces (@i{a} or @i{b} or neither).
7757:
7758: Let * represent any number of instances of the previous character
7759: (including none).
7760:
7761: Let any other character represent itself.
7762:
7763: @noindent
7764: Now, the conversion rules are:
7765:
7766: @itemize @bullet
7767: @item
7768: A string of the form <digit><digit>* is treated as a single-precision
7769: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
7770: @item
7771: A string of the form -<digit><digit>* is treated as a single-precision
7772: (cell-sized) negative integer, and is represented using 2's-complement
7773: arithmetic. Examples are -45 -5681 -0
7774: @item
7775: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
7776: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7777: (all three of these represent the same number).
7778: @item
7779: A string of the form -<digit><digit>*.<digit>* is treated as a
7780: double-precision (double-cell-sized) negative integer, and is
7781: represented using 2's-complement arithmetic. Examples are -3465. -3.465
7782: -34.65 (all three of these represent the same number).
7783: @item
7784: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7785: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
7786: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
7787: number) +12.E-4
7788: @end itemize
7789:
7790: By default, the number base used for integer number conversion is given
7791: by the contents of the variable @code{base}. Note that a lot of
7792: confusion can result from unexpected values of @code{base}. If you
7793: change @code{base} anywhere, make sure to save the old value and restore
7794: it afterwards. In general I recommend keeping @code{base} decimal, and
7795: using the prefixes described below for the popular non-decimal bases.
7796:
7797: doc-dpl
7798: doc-base
7799: doc-hex
7800: doc-decimal
7801:
7802:
7803: @cindex '-prefix for character strings
7804: @cindex &-prefix for decimal numbers
7805: @cindex %-prefix for binary numbers
7806: @cindex $-prefix for hexadecimal numbers
7807: Gforth allows you to override the value of @code{base} by using a
7808: prefix@footnote{Some Forth implementations provide a similar scheme by
7809: implementing @code{$} etc. as parsing words that process the subsequent
7810: number in the input stream and push it onto the stack. For example, see
7811: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7812: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7813: is required between the prefix and the number.} before the first digit
7814: of an (integer) number. Four prefixes are supported:
7815:
7816: @itemize @bullet
7817: @item
7818: @code{&} -- decimal
7819: @item
7820: @code{%} -- binary
7821: @item
7822: @code{$} -- hexadecimal
7823: @item
7824: @code{'} -- base @code{max-char+1}
7825: @end itemize
7826:
7827: Here are some examples, with the equivalent decimal number shown after
7828: in braces:
7829:
7830: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
7831: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
7832: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
7833: &905 (905), $abc (2478), $ABC (2478).
7834:
7835: @cindex number conversion - traps for the unwary
7836: @noindent
7837: Number conversion has a number of traps for the unwary:
7838:
7839: @itemize @bullet
7840: @item
7841: You cannot determine the current number base using the code sequence
7842: @code{base @@ .} -- the number base is always 10 in the current number
7843: base. Instead, use something like @code{base @@ dec.}
7844: @item
7845: If the number base is set to a value greater than 14 (for example,
7846: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7847: it to be intepreted as either a single-precision integer or a
7848: floating-point number (Gforth treats it as an integer). The ambiguity
7849: can be resolved by explicitly stating the sign of the mantissa and/or
7850: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7851: ambiguity arises; either representation will be treated as a
7852: floating-point number.
7853: @item
7854: There is a word @code{bin} but it does @i{not} set the number base!
7855: It is used to specify file types.
7856: @item
7857: ANS Forth requires the @code{.} of a double-precision number to be the
7858: final character in the string. Gforth allows the @code{.} to be
7859: anywhere after the first digit.
7860: @item
7861: The number conversion process does not check for overflow.
7862: @item
7863: In an ANS Forth program @code{base} is required to be decimal when
7864: converting floating-point numbers. In Gforth, number conversion to
7865: floating-point numbers always uses base &10, irrespective of the value
7866: of @code{base}.
7867: @end itemize
7868:
7869: You can read numbers into your programs with the words described in
7870: @ref{Input}.
7871:
7872: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
7873: @subsection Interpret/Compile states
7874: @cindex Interpret/Compile states
7875:
7876: A standard program is not permitted to change @code{state}
7877: explicitly. However, it can change @code{state} implicitly, using the
7878: words @code{[} and @code{]}. When @code{[} is executed it switches
7879: @code{state} to interpret state, and therefore the text interpreter
7880: starts interpreting. When @code{]} is executed it switches @code{state}
7881: to compile state and therefore the text interpreter starts
7882: compiling. The most common usage for these words is for switching into
7883: interpret state and back from within a colon definition; this technique
7884: can be used to compile a literal (for an example, @pxref{Literals}) or
7885: for conditional compilation (for an example, @pxref{Interpreter
7886: Directives}).
7887:
7888:
7889: @c This is a bad example: It's non-standard, and it's not necessary.
7890: @c However, I can't think of a good example for switching into compile
7891: @c state when there is no current word (@code{state}-smart words are not a
7892: @c good reason). So maybe we should use an example for switching into
7893: @c interpret @code{state} in a colon def. - anton
7894: @c nac-> I agree. I started out by putting in the example, then realised
7895: @c that it was non-ANS, so wrote more words around it. I hope this
7896: @c re-written version is acceptable to you. I do want to keep the example
7897: @c as it is helpful for showing what is and what is not portable, particularly
7898: @c where it outlaws a style in common use.
7899:
7900: @c anton: it's more important to show what's portable. After we have done
7901: @c that, we can also show what's not. In any case, I have written a
7902: @c section Compiling Words which also deals with [ ].
7903:
7904: @code{[} and @code{]} also give you the ability to switch into compile
7905: state and back, but we cannot think of any useful Standard application
7906: for this ability. Pre-ANS Forth textbooks have examples like this:
7907:
7908: @example
7909: : AA ." this is A" ;
7910: : BB ." this is B" ;
7911: : CC ." this is C" ;
7912:
7913: create table ] aa bb cc [
7914:
7915: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7916: cells table + @ execute ;
7917: @end example
7918:
7919: This example builds a jump table; @code{0 go} will display ``@code{this
7920: is A}''. Using @code{[} and @code{]} in this example is equivalent to
7921: defining @code{table} like this:
7922:
7923: @example
7924: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7925: @end example
7926:
7927: The problem with this code is that the definition of @code{table} is not
7928: portable -- it @i{compile}s execution tokens into code space. Whilst it
7929: @i{may} work on systems where code space and data space co-incide, the
7930: Standard only allows data space to be assigned for a @code{CREATE}d
7931: word. In addition, the Standard only allows @code{@@} to access data
7932: space, whilst this example is using it to access code space. The only
7933: portable, Standard way to build this table is to build it in data space,
7934: like this:
7935:
7936: @example
7937: create table ' aa , ' bb , ' cc ,
7938: @end example
7939:
7940: doc-state
7941:
7942:
7943: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
7944: @subsection Interpreter Directives
7945: @cindex interpreter directives
7946: @cindex conditional compilation
7947:
7948: These words are usually used in interpret state; typically to control
7949: which parts of a source file are processed by the text
7950: interpreter. There are only a few ANS Forth Standard words, but Gforth
7951: supplements these with a rich set of immediate control structure words
7952: to compensate for the fact that the non-immediate versions can only be
7953: used in compile state (@pxref{Control Structures}). Typical usages:
7954:
7955: @example
7956: FALSE Constant HAVE-ASSEMBLER
7957: .
7958: .
7959: HAVE-ASSEMBLER [IF]
7960: : ASSEMBLER-FEATURE
7961: ...
7962: ;
7963: [ENDIF]
7964: .
7965: .
7966: : SEE
7967: ... \ general-purpose SEE code
7968: [ HAVE-ASSEMBLER [IF] ]
7969: ... \ assembler-specific SEE code
7970: [ [ENDIF] ]
7971: ;
7972: @end example
7973:
7974:
7975: doc-[IF]
7976: doc-[ELSE]
7977: doc-[THEN]
7978: doc-[ENDIF]
7979:
7980: doc-[IFDEF]
7981: doc-[IFUNDEF]
7982:
7983: doc-[?DO]
7984: doc-[DO]
7985: doc-[FOR]
7986: doc-[LOOP]
7987: doc-[+LOOP]
7988: doc-[NEXT]
7989:
7990: doc-[BEGIN]
7991: doc-[UNTIL]
7992: doc-[AGAIN]
7993: doc-[WHILE]
7994: doc-[REPEAT]
7995:
7996:
7997: @c -------------------------------------------------------------
7998: @node Word Lists, Environmental Queries, The Text Interpreter, Words
7999: @section Word Lists
8000: @cindex word lists
8001: @cindex header space
8002:
8003: A wordlist is a list of named words; you can add new words and look up
8004: words by name (and you can remove words in a restricted way with
8005: markers). Every named (and @code{reveal}ed) word is in one wordlist.
8006:
8007: @cindex search order stack
8008: The text interpreter searches the wordlists present in the search order
8009: (a stack of wordlists), from the top to the bottom. Within each
8010: wordlist, the search starts conceptually at the newest word; i.e., if
8011: two words in a wordlist have the same name, the newer word is found.
8012:
8013: @cindex compilation word list
8014: New words are added to the @dfn{compilation wordlist} (aka current
8015: wordlist).
8016:
8017: @cindex wid
8018: A word list is identified by a cell-sized word list identifier (@i{wid})
8019: in much the same way as a file is identified by a file handle. The
8020: numerical value of the wid has no (portable) meaning, and might change
8021: from session to session.
8022:
8023: The ANS Forth ``Search order'' word set is intended to provide a set of
8024: low-level tools that allow various different schemes to be
8025: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
8026: word. @file{compat/vocabulary.fs} provides an implementation in ANS
8027: Forth.
8028:
8029: @comment TODO: locals section refers to here, saying that every word list (aka
8030: @comment vocabulary) has its own methods for searching etc. Need to document that.
8031: @c anton: but better in a separate subsection on wordlist internals
8032:
8033: @comment TODO: document markers, reveal, tables, mappedwordlist
8034:
8035: @comment the gforthman- prefix is used to pick out the true definition of a
8036: @comment word from the source files, rather than some alias.
8037:
8038: doc-forth-wordlist
8039: doc-definitions
8040: doc-get-current
8041: doc-set-current
8042: doc-get-order
8043: doc---gforthman-set-order
8044: doc-wordlist
8045: doc-table
8046: doc->order
8047: doc-previous
8048: doc-also
8049: doc---gforthman-forth
8050: doc-only
8051: doc---gforthman-order
8052:
8053: doc-find
8054: doc-search-wordlist
8055:
8056: doc-words
8057: doc-vlist
8058: @c doc-words-deferred
8059:
8060: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
8061: doc-root
8062: doc-vocabulary
8063: doc-seal
8064: doc-vocs
8065: doc-current
8066: doc-context
8067:
8068:
8069: @menu
8070: * Vocabularies::
8071: * Why use word lists?::
8072: * Word list example::
8073: @end menu
8074:
8075: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8076: @subsection Vocabularies
8077: @cindex Vocabularies, detailed explanation
8078:
8079: Here is an example of creating and using a new wordlist using ANS
8080: Forth words:
8081:
8082: @example
8083: wordlist constant my-new-words-wordlist
8084: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8085:
8086: \ add it to the search order
8087: also my-new-words
8088:
8089: \ alternatively, add it to the search order and make it
8090: \ the compilation word list
8091: also my-new-words definitions
8092: \ type "order" to see the problem
8093: @end example
8094:
8095: The problem with this example is that @code{order} has no way to
8096: associate the name @code{my-new-words} with the wid of the word list (in
8097: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8098: that has no associated name). There is no Standard way of associating a
8099: name with a wid.
8100:
8101: In Gforth, this example can be re-coded using @code{vocabulary}, which
8102: associates a name with a wid:
8103:
8104: @example
8105: vocabulary my-new-words
8106:
8107: \ add it to the search order
8108: also my-new-words
8109:
8110: \ alternatively, add it to the search order and make it
8111: \ the compilation word list
8112: my-new-words definitions
8113: \ type "order" to see that the problem is solved
8114: @end example
8115:
8116:
8117: @node Why use word lists?, Word list example, Vocabularies, Word Lists
8118: @subsection Why use word lists?
8119: @cindex word lists - why use them?
8120:
8121: Here are some reasons why people use wordlists:
8122:
8123: @itemize @bullet
8124:
8125: @c anton: Gforth's hashing implementation makes the search speed
8126: @c independent from the number of words. But it is linear with the number
8127: @c of wordlists that have to be searched, so in effect using more wordlists
8128: @c actually slows down compilation.
8129:
8130: @c @item
8131: @c To improve compilation speed by reducing the number of header space
8132: @c entries that must be searched. This is achieved by creating a new
8133: @c word list that contains all of the definitions that are used in the
8134: @c definition of a Forth system but which would not usually be used by
8135: @c programs running on that system. That word list would be on the search
8136: @c list when the Forth system was compiled but would be removed from the
8137: @c search list for normal operation. This can be a useful technique for
8138: @c low-performance systems (for example, 8-bit processors in embedded
8139: @c systems) but is unlikely to be necessary in high-performance desktop
8140: @c systems.
8141:
8142: @item
8143: To prevent a set of words from being used outside the context in which
8144: they are valid. Two classic examples of this are an integrated editor
8145: (all of the edit commands are defined in a separate word list; the
8146: search order is set to the editor word list when the editor is invoked;
8147: the old search order is restored when the editor is terminated) and an
8148: integrated assembler (the op-codes for the machine are defined in a
8149: separate word list which is used when a @code{CODE} word is defined).
8150:
8151: @item
8152: To organize the words of an application or library into a user-visible
8153: set (in @code{forth-wordlist} or some other common wordlist) and a set
8154: of helper words used just for the implementation (hidden in a separate
8155: wordlist). This keeps @code{words}' output smaller, separates
8156: implementation and interface, and reduces the chance of name conflicts
8157: within the common wordlist.
8158:
8159: @item
8160: To prevent a name-space clash between multiple definitions with the same
8161: name. For example, when building a cross-compiler you might have a word
8162: @code{IF} that generates conditional code for your target system. By
8163: placing this definition in a different word list you can control whether
8164: the host system's @code{IF} or the target system's @code{IF} get used in
8165: any particular context by controlling the order of the word lists on the
8166: search order stack.
8167:
8168: @end itemize
8169:
8170: The downsides of using wordlists are:
8171:
8172: @itemize
8173:
8174: @item
8175: Debugging becomes more cumbersome.
8176:
8177: @item
8178: Name conflicts worked around with wordlists are still there, and you
8179: have to arrange the search order carefully to get the desired results;
8180: if you forget to do that, you get hard-to-find errors (as in any case
8181: where you read the code differently from the compiler; @code{see} can
8182: help seeing which of several possible words the name resolves to in such
8183: cases). @code{See} displays just the name of the words, not what
8184: wordlist they belong to, so it might be misleading. Using unique names
8185: is a better approach to avoid name conflicts.
8186:
8187: @item
8188: You have to explicitly undo any changes to the search order. In many
8189: cases it would be more convenient if this happened implicitly. Gforth
8190: currently does not provide such a feature, but it may do so in the
8191: future.
8192: @end itemize
8193:
8194:
8195: @node Word list example, , Why use word lists?, Word Lists
8196: @subsection Word list example
8197: @cindex word lists - example
8198:
8199: The following example is from the
8200: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8201: garbage collector} and uses wordlists to separate public words from
8202: helper words:
8203:
8204: @example
8205: get-current ( wid )
8206: vocabulary garbage-collector also garbage-collector definitions
8207: ... \ define helper words
8208: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8209: ... \ define the public (i.e., API) words
8210: \ they can refer to the helper words
8211: previous \ restore original search order (helper words become invisible)
8212: @end example
8213:
8214: @c -------------------------------------------------------------
8215: @node Environmental Queries, Files, Word Lists, Words
8216: @section Environmental Queries
8217: @cindex environmental queries
8218:
8219: ANS Forth introduced the idea of ``environmental queries'' as a way
8220: for a program running on a system to determine certain characteristics of the system.
8221: The Standard specifies a number of strings that might be recognised by a system.
8222:
8223: The Standard requires that the header space used for environmental queries
8224: be distinct from the header space used for definitions.
8225:
8226: Typically, environmental queries are supported by creating a set of
8227: definitions in a word list that is @i{only} used during environmental
8228: queries; that is what Gforth does. There is no Standard way of adding
8229: definitions to the set of recognised environmental queries, but any
8230: implementation that supports the loading of optional word sets must have
8231: some mechanism for doing this (after loading the word set, the
8232: associated environmental query string must return @code{true}). In
8233: Gforth, the word list used to honour environmental queries can be
8234: manipulated just like any other word list.
8235:
8236:
8237: doc-environment?
8238: doc-environment-wordlist
8239:
8240: doc-gforth
8241: doc-os-class
8242:
8243:
8244: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8245: returning two items on the stack, querying it using @code{environment?}
8246: will return an additional item; the @code{true} flag that shows that the
8247: string was recognised.
8248:
8249: @comment TODO Document the standard strings or note where they are documented herein
8250:
8251: Here are some examples of using environmental queries:
8252:
8253: @example
8254: s" address-unit-bits" environment? 0=
8255: [IF]
8256: cr .( environmental attribute address-units-bits unknown... ) cr
8257: [ELSE]
8258: drop \ ensure balanced stack effect
8259: [THEN]
8260:
8261: \ this might occur in the prelude of a standard program that uses THROW
8262: s" exception" environment? [IF]
8263: 0= [IF]
8264: : throw abort" exception thrown" ;
8265: [THEN]
8266: [ELSE] \ we don't know, so make sure
8267: : throw abort" exception thrown" ;
8268: [THEN]
8269:
8270: s" gforth" environment? [IF] .( Gforth version ) TYPE
8271: [ELSE] .( Not Gforth..) [THEN]
8272:
8273: \ a program using v*
8274: s" gforth" environment? [IF]
8275: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8276: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8277: >r swap 2swap swap 0e r> 0 ?DO
8278: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8279: LOOP
8280: 2drop 2drop ;
8281: [THEN]
8282: [ELSE] \
8283: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8284: ...
8285: [THEN]
8286: @end example
8287:
8288: Here is an example of adding a definition to the environment word list:
8289:
8290: @example
8291: get-current environment-wordlist set-current
8292: true constant block
8293: true constant block-ext
8294: set-current
8295: @end example
8296:
8297: You can see what definitions are in the environment word list like this:
8298:
8299: @example
8300: environment-wordlist >order words previous
8301: @end example
8302:
8303:
8304: @c -------------------------------------------------------------
8305: @node Files, Blocks, Environmental Queries, Words
8306: @section Files
8307: @cindex files
8308: @cindex I/O - file-handling
8309:
8310: Gforth provides facilities for accessing files that are stored in the
8311: host operating system's file-system. Files that are processed by Gforth
8312: can be divided into two categories:
8313:
8314: @itemize @bullet
8315: @item
8316: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
8317: @item
8318: Files that are processed by some other program (@dfn{general files}).
8319: @end itemize
8320:
8321: @menu
8322: * Forth source files::
8323: * General files::
8324: * Search Paths::
8325: @end menu
8326:
8327: @c -------------------------------------------------------------
8328: @node Forth source files, General files, Files, Files
8329: @subsection Forth source files
8330: @cindex including files
8331: @cindex Forth source files
8332:
8333: The simplest way to interpret the contents of a file is to use one of
8334: these two formats:
8335:
8336: @example
8337: include mysource.fs
8338: s" mysource.fs" included
8339: @end example
8340:
8341: You usually want to include a file only if it is not included already
8342: (by, say, another source file). In that case, you can use one of these
8343: three formats:
8344:
8345: @example
8346: require mysource.fs
8347: needs mysource.fs
8348: s" mysource.fs" required
8349: @end example
8350:
8351: @cindex stack effect of included files
8352: @cindex including files, stack effect
8353: It is good practice to write your source files such that interpreting them
8354: does not change the stack. Source files designed in this way can be used with
8355: @code{required} and friends without complications. For example:
8356:
8357: @example
8358: 1024 require foo.fs drop
8359: @end example
8360:
8361: Here you want to pass the argument 1024 (e.g., a buffer size) to
8362: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8363: ), which allows its use with @code{require}. Of course with such
8364: parameters to required files, you have to ensure that the first
8365: @code{require} fits for all uses (i.e., @code{require} it early in the
8366: master load file).
8367:
8368: doc-include-file
8369: doc-included
8370: doc-included?
8371: doc-include
8372: doc-required
8373: doc-require
8374: doc-needs
8375: @c doc-init-included-files @c internal
8376: doc-sourcefilename
8377: doc-sourceline#
8378:
8379: A definition in ANS Forth for @code{required} is provided in
8380: @file{compat/required.fs}.
8381:
8382: @c -------------------------------------------------------------
8383: @node General files, Search Paths, Forth source files, Files
8384: @subsection General files
8385: @cindex general files
8386: @cindex file-handling
8387:
8388: Files are opened/created by name and type. The following file access
8389: methods (FAMs) are recognised:
8390:
8391: @cindex fam (file access method)
8392: doc-r/o
8393: doc-r/w
8394: doc-w/o
8395: doc-bin
8396:
8397:
8398: When a file is opened/created, it returns a file identifier,
8399: @i{wfileid} that is used for all other file commands. All file
8400: commands also return a status value, @i{wior}, that is 0 for a
8401: successful operation and an implementation-defined non-zero value in the
8402: case of an error.
8403:
8404:
8405: doc-open-file
8406: doc-create-file
8407:
8408: doc-close-file
8409: doc-delete-file
8410: doc-rename-file
8411: doc-read-file
8412: doc-read-line
8413: doc-write-file
8414: doc-write-line
8415: doc-emit-file
8416: doc-flush-file
8417:
8418: doc-file-status
8419: doc-file-position
8420: doc-reposition-file
8421: doc-file-size
8422: doc-resize-file
8423:
8424:
8425: @c ---------------------------------------------------------
8426: @node Search Paths, , General files, Files
8427: @subsection Search Paths
8428: @cindex path for @code{included}
8429: @cindex file search path
8430: @cindex @code{include} search path
8431: @cindex search path for files
8432:
8433: If you specify an absolute filename (i.e., a filename starting with
8434: @file{/} or @file{~}, or with @file{:} in the second position (as in
8435: @samp{C:...})) for @code{included} and friends, that file is included
8436: just as you would expect.
8437:
8438: If the filename starts with @file{./}, this refers to the directory that
8439: the present file was @code{included} from. This allows files to include
8440: other files relative to their own position (irrespective of the current
8441: working directory or the absolute position). This feature is essential
8442: for libraries consisting of several files, where a file may include
8443: other files from the library. It corresponds to @code{#include "..."}
8444: in C. If the current input source is not a file, @file{.} refers to the
8445: directory of the innermost file being included, or, if there is no file
8446: being included, to the current working directory.
8447:
8448: For relative filenames (not starting with @file{./}), Gforth uses a
8449: search path similar to Forth's search order (@pxref{Word Lists}). It
8450: tries to find the given filename in the directories present in the path,
8451: and includes the first one it finds. There are separate search paths for
8452: Forth source files and general files. If the search path contains the
8453: directory @file{.}, this refers to the directory of the current file, or
8454: the working directory, as if the file had been specified with @file{./}.
8455:
8456: Use @file{~+} to refer to the current working directory (as in the
8457: @code{bash}).
8458:
8459: @c anton: fold the following subsubsections into this subsection?
8460:
8461: @menu
8462: * Source Search Paths::
8463: * General Search Paths::
8464: @end menu
8465:
8466: @c ---------------------------------------------------------
8467: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8468: @subsubsection Source Search Paths
8469: @cindex search path control, source files
8470:
8471: The search path is initialized when you start Gforth (@pxref{Invoking
8472: Gforth}). You can display it and change it using @code{fpath} in
8473: combination with the general path handling words.
8474:
8475: doc-fpath
8476: @c the functionality of the following words is easily available through
8477: @c fpath and the general path words. The may go away.
8478: @c doc-.fpath
8479: @c doc-fpath+
8480: @c doc-fpath=
8481: @c doc-open-fpath-file
8482:
8483: @noindent
8484: Here is an example of using @code{fpath} and @code{require}:
8485:
8486: @example
8487: fpath path= /usr/lib/forth/|./
8488: require timer.fs
8489: @end example
8490:
8491:
8492: @c ---------------------------------------------------------
8493: @node General Search Paths, , Source Search Paths, Search Paths
8494: @subsubsection General Search Paths
8495: @cindex search path control, source files
8496:
8497: Your application may need to search files in several directories, like
8498: @code{included} does. To facilitate this, Gforth allows you to define
8499: and use your own search paths, by providing generic equivalents of the
8500: Forth search path words:
8501:
8502: doc-open-path-file
8503: doc-path-allot
8504: doc-clear-path
8505: doc-also-path
8506: doc-.path
8507: doc-path+
8508: doc-path=
8509:
8510: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
8511:
8512: Here's an example of creating an empty search path:
8513: @c
8514: @example
8515: create mypath 500 path-allot \ maximum length 500 chars (is checked)
8516: @end example
8517:
8518: @c -------------------------------------------------------------
8519: @node Blocks, Other I/O, Files, Words
8520: @section Blocks
8521: @cindex I/O - blocks
8522: @cindex blocks
8523:
8524: When you run Gforth on a modern desk-top computer, it runs under the
8525: control of an operating system which provides certain services. One of
8526: these services is @var{file services}, which allows Forth source code
8527: and data to be stored in files and read into Gforth (@pxref{Files}).
8528:
8529: Traditionally, Forth has been an important programming language on
8530: systems where it has interfaced directly to the underlying hardware with
8531: no intervening operating system. Forth provides a mechanism, called
8532: @dfn{blocks}, for accessing mass storage on such systems.
8533:
8534: A block is a 1024-byte data area, which can be used to hold data or
8535: Forth source code. No structure is imposed on the contents of the
8536: block. A block is identified by its number; blocks are numbered
8537: contiguously from 1 to an implementation-defined maximum.
8538:
8539: A typical system that used blocks but no operating system might use a
8540: single floppy-disk drive for mass storage, with the disks formatted to
8541: provide 256-byte sectors. Blocks would be implemented by assigning the
8542: first four sectors of the disk to block 1, the second four sectors to
8543: block 2 and so on, up to the limit of the capacity of the disk. The disk
8544: would not contain any file system information, just the set of blocks.
8545:
8546: @cindex blocks file
8547: On systems that do provide file services, blocks are typically
8548: implemented by storing a sequence of blocks within a single @dfn{blocks
8549: file}. The size of the blocks file will be an exact multiple of 1024
8550: bytes, corresponding to the number of blocks it contains. This is the
8551: mechanism that Gforth uses.
8552:
8553: @cindex @file{blocks.fb}
8554: Only one blocks file can be open at a time. If you use block words without
8555: having specified a blocks file, Gforth defaults to the blocks file
8556: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
8557: locate a blocks file (@pxref{Source Search Paths}).
8558:
8559: @cindex block buffers
8560: When you read and write blocks under program control, Gforth uses a
8561: number of @dfn{block buffers} as intermediate storage. These buffers are
8562: not used when you use @code{load} to interpret the contents of a block.
8563:
8564: The behaviour of the block buffers is analagous to that of a cache.
8565: Each block buffer has three states:
8566:
8567: @itemize @bullet
8568: @item
8569: Unassigned
8570: @item
8571: Assigned-clean
8572: @item
8573: Assigned-dirty
8574: @end itemize
8575:
8576: Initially, all block buffers are @i{unassigned}. In order to access a
8577: block, the block (specified by its block number) must be assigned to a
8578: block buffer.
8579:
8580: The assignment of a block to a block buffer is performed by @code{block}
8581: or @code{buffer}. Use @code{block} when you wish to modify the existing
8582: contents of a block. Use @code{buffer} when you don't care about the
8583: existing contents of the block@footnote{The ANS Forth definition of
8584: @code{buffer} is intended not to cause disk I/O; if the data associated
8585: with the particular block is already stored in a block buffer due to an
8586: earlier @code{block} command, @code{buffer} will return that block
8587: buffer and the existing contents of the block will be
8588: available. Otherwise, @code{buffer} will simply assign a new, empty
8589: block buffer for the block.}.
8590:
8591: Once a block has been assigned to a block buffer using @code{block} or
8592: @code{buffer}, that block buffer becomes the @i{current block
8593: buffer}. Data may only be manipulated (read or written) within the
8594: current block buffer.
8595:
8596: When the contents of the current block buffer has been modified it is
8597: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
8598: either abandon the changes (by doing nothing) or mark the block as
8599: changed (assigned-dirty), using @code{update}. Using @code{update} does
8600: not change the blocks file; it simply changes a block buffer's state to
8601: @i{assigned-dirty}. The block will be written implicitly when it's
8602: buffer is needed for another block, or explicitly by @code{flush} or
8603: @code{save-buffers}.
8604:
8605: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8606: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8607: @code{flush}.
8608:
8609: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
8610: algorithm to assign a block buffer to a block. That means that any
8611: particular block can only be assigned to one specific block buffer,
8612: called (for the particular operation) the @i{victim buffer}. If the
8613: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8614: the new block immediately. If it is @i{assigned-dirty} its current
8615: contents are written back to the blocks file on disk before it is
8616: allocated to the new block.
8617:
8618: Although no structure is imposed on the contents of a block, it is
8619: traditional to display the contents as 16 lines each of 64 characters. A
8620: block provides a single, continuous stream of input (for example, it
8621: acts as a single parse area) -- there are no end-of-line characters
8622: within a block, and no end-of-file character at the end of a
8623: block. There are two consequences of this:
8624:
8625: @itemize @bullet
8626: @item
8627: The last character of one line wraps straight into the first character
8628: of the following line
8629: @item
8630: The word @code{\} -- comment to end of line -- requires special
8631: treatment; in the context of a block it causes all characters until the
8632: end of the current 64-character ``line'' to be ignored.
8633: @end itemize
8634:
8635: In Gforth, when you use @code{block} with a non-existent block number,
8636: the current blocks file will be extended to the appropriate size and the
8637: block buffer will be initialised with spaces.
8638:
8639: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8640: for details) but doesn't encourage the use of blocks; the mechanism is
8641: only provided for backward compatibility -- ANS Forth requires blocks to
8642: be available when files are.
8643:
8644: Common techniques that are used when working with blocks include:
8645:
8646: @itemize @bullet
8647: @item
8648: A screen editor that allows you to edit blocks without leaving the Forth
8649: environment.
8650: @item
8651: Shadow screens; where every code block has an associated block
8652: containing comments (for example: code in odd block numbers, comments in
8653: even block numbers). Typically, the block editor provides a convenient
8654: mechanism to toggle between code and comments.
8655: @item
8656: Load blocks; a single block (typically block 1) contains a number of
8657: @code{thru} commands which @code{load} the whole of the application.
8658: @end itemize
8659:
8660: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8661: integrated into a Forth programming environment.
8662:
8663: @comment TODO what about errors on open-blocks?
8664:
8665: doc-open-blocks
8666: doc-use
8667: doc-block-offset
8668: doc-get-block-fid
8669: doc-block-position
8670:
8671: doc-list
8672: doc-scr
8673:
8674: doc---gforthman-block
8675: doc-buffer
8676:
8677: doc-empty-buffers
8678: doc-empty-buffer
8679: doc-update
8680: doc-updated?
8681: doc-save-buffers
8682: doc-save-buffer
8683: doc-flush
8684:
8685: doc-load
8686: doc-thru
8687: doc-+load
8688: doc-+thru
8689: doc---gforthman--->
8690: doc-block-included
8691:
8692:
8693: @c -------------------------------------------------------------
8694: @node Other I/O, Locals, Blocks, Words
8695: @section Other I/O
8696: @cindex I/O - keyboard and display
8697:
8698: @menu
8699: * Simple numeric output:: Predefined formats
8700: * Formatted numeric output:: Formatted (pictured) output
8701: * String Formats:: How Forth stores strings in memory
8702: * Displaying characters and strings:: Other stuff
8703: * Input:: Input
8704: @end menu
8705:
8706: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8707: @subsection Simple numeric output
8708: @cindex numeric output - simple/free-format
8709:
8710: The simplest output functions are those that display numbers from the
8711: data or floating-point stacks. Floating-point output is always displayed
8712: using base 10. Numbers displayed from the data stack use the value stored
8713: in @code{base}.
8714:
8715:
8716: doc-.
8717: doc-dec.
8718: doc-hex.
8719: doc-u.
8720: doc-.r
8721: doc-u.r
8722: doc-d.
8723: doc-ud.
8724: doc-d.r
8725: doc-ud.r
8726: doc-f.
8727: doc-fe.
8728: doc-fs.
8729:
8730:
8731: Examples of printing the number 1234.5678E23 in the different floating-point output
8732: formats are shown below:
8733:
8734: @example
8735: f. 123456779999999000000000000.
8736: fe. 123.456779999999E24
8737: fs. 1.23456779999999E26
8738: @end example
8739:
8740:
8741: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8742: @subsection Formatted numeric output
8743: @cindex formatted numeric output
8744: @cindex pictured numeric output
8745: @cindex numeric output - formatted
8746:
8747: Forth traditionally uses a technique called @dfn{pictured numeric
8748: output} for formatted printing of integers. In this technique, digits
8749: are extracted from the number (using the current output radix defined by
8750: @code{base}), converted to ASCII codes and appended to a string that is
8751: built in a scratch-pad area of memory (@pxref{core-idef,
8752: Implementation-defined options, Implementation-defined
8753: options}). Arbitrary characters can be appended to the string during the
8754: extraction process. The completed string is specified by an address
8755: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8756: under program control.
8757:
8758: All of the integer output words described in the previous section
8759: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8760: numeric output.
8761:
8762: Three important things to remember about pictured numeric output:
8763:
8764: @itemize @bullet
8765: @item
8766: It always operates on double-precision numbers; to display a
8767: single-precision number, convert it first (for ways of doing this
8768: @pxref{Double precision}).
8769: @item
8770: It always treats the double-precision number as though it were
8771: unsigned. The examples below show ways of printing signed numbers.
8772: @item
8773: The string is built up from right to left; least significant digit first.
8774: @end itemize
8775:
8776:
8777: doc-<#
8778: doc-<<#
8779: doc-#
8780: doc-#s
8781: doc-hold
8782: doc-sign
8783: doc-#>
8784: doc-#>>
8785:
8786: doc-represent
8787:
8788:
8789: @noindent
8790: Here are some examples of using pictured numeric output:
8791:
8792: @example
8793: : my-u. ( u -- )
8794: \ Simplest use of pns.. behaves like Standard u.
8795: 0 \ convert to unsigned double
8796: <<# \ start conversion
8797: #s \ convert all digits
8798: #> \ complete conversion
8799: TYPE SPACE \ display, with trailing space
8800: #>> ; \ release hold area
8801:
8802: : cents-only ( u -- )
8803: 0 \ convert to unsigned double
8804: <<# \ start conversion
8805: # # \ convert two least-significant digits
8806: #> \ complete conversion, discard other digits
8807: TYPE SPACE \ display, with trailing space
8808: #>> ; \ release hold area
8809:
8810: : dollars-and-cents ( u -- )
8811: 0 \ convert to unsigned double
8812: <<# \ start conversion
8813: # # \ convert two least-significant digits
8814: [char] . hold \ insert decimal point
8815: #s \ convert remaining digits
8816: [char] $ hold \ append currency symbol
8817: #> \ complete conversion
8818: TYPE SPACE \ display, with trailing space
8819: #>> ; \ release hold area
8820:
8821: : my-. ( n -- )
8822: \ handling negatives.. behaves like Standard .
8823: s>d \ convert to signed double
8824: swap over dabs \ leave sign byte followed by unsigned double
8825: <<# \ start conversion
8826: #s \ convert all digits
8827: rot sign \ get at sign byte, append "-" if needed
8828: #> \ complete conversion
8829: TYPE SPACE \ display, with trailing space
8830: #>> ; \ release hold area
8831:
8832: : account. ( n -- )
8833: \ accountants don't like minus signs, they use parentheses
8834: \ for negative numbers
8835: s>d \ convert to signed double
8836: swap over dabs \ leave sign byte followed by unsigned double
8837: <<# \ start conversion
8838: 2 pick \ get copy of sign byte
8839: 0< IF [char] ) hold THEN \ right-most character of output
8840: #s \ convert all digits
8841: rot \ get at sign byte
8842: 0< IF [char] ( hold THEN
8843: #> \ complete conversion
8844: TYPE SPACE \ display, with trailing space
8845: #>> ; \ release hold area
8846:
8847: @end example
8848:
8849: Here are some examples of using these words:
8850:
8851: @example
8852: 1 my-u. 1
8853: hex -1 my-u. decimal FFFFFFFF
8854: 1 cents-only 01
8855: 1234 cents-only 34
8856: 2 dollars-and-cents $0.02
8857: 1234 dollars-and-cents $12.34
8858: 123 my-. 123
8859: -123 my. -123
8860: 123 account. 123
8861: -456 account. (456)
8862: @end example
8863:
8864:
8865: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8866: @subsection String Formats
8867: @cindex strings - see character strings
8868: @cindex character strings - formats
8869: @cindex I/O - see character strings
8870: @cindex counted strings
8871:
8872: @c anton: this does not really belong here; maybe the memory section,
8873: @c or the principles chapter
8874:
8875: Forth commonly uses two different methods for representing character
8876: strings:
8877:
8878: @itemize @bullet
8879: @item
8880: @cindex address of counted string
8881: @cindex counted string
8882: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8883: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8884: string and the string occupies the subsequent @i{n} char addresses in
8885: memory.
8886: @item
8887: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8888: of the string in characters, and @i{c-addr} is the address of the
8889: first byte of the string.
8890: @end itemize
8891:
8892: ANS Forth encourages the use of the second format when representing
8893: strings.
8894:
8895:
8896: doc-count
8897:
8898:
8899: For words that move, copy and search for strings see @ref{Memory
8900: Blocks}. For words that display characters and strings see
8901: @ref{Displaying characters and strings}.
8902:
8903: @node Displaying characters and strings, Input, String Formats, Other I/O
8904: @subsection Displaying characters and strings
8905: @cindex characters - compiling and displaying
8906: @cindex character strings - compiling and displaying
8907:
8908: This section starts with a glossary of Forth words and ends with a set
8909: of examples.
8910:
8911:
8912: doc-bl
8913: doc-space
8914: doc-spaces
8915: doc-emit
8916: doc-toupper
8917: doc-."
8918: doc-.(
8919: doc-type
8920: doc-typewhite
8921: doc-cr
8922: @cindex cursor control
8923: doc-at-xy
8924: doc-page
8925: doc-s"
8926: doc-c"
8927: doc-char
8928: doc-[char]
8929:
8930:
8931: @noindent
8932: As an example, consider the following text, stored in a file @file{test.fs}:
8933:
8934: @example
8935: .( text-1)
8936: : my-word
8937: ." text-2" cr
8938: .( text-3)
8939: ;
8940:
8941: ." text-4"
8942:
8943: : my-char
8944: [char] ALPHABET emit
8945: char emit
8946: ;
8947: @end example
8948:
8949: When you load this code into Gforth, the following output is generated:
8950:
8951: @example
8952: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
8953: @end example
8954:
8955: @itemize @bullet
8956: @item
8957: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8958: is an immediate word; it behaves in the same way whether it is used inside
8959: or outside a colon definition.
8960: @item
8961: Message @code{text-4} is displayed because of Gforth's added interpretation
8962: semantics for @code{."}.
8963: @item
8964: Message @code{text-2} is @i{not} displayed, because the text interpreter
8965: performs the compilation semantics for @code{."} within the definition of
8966: @code{my-word}.
8967: @end itemize
8968:
8969: Here are some examples of executing @code{my-word} and @code{my-char}:
8970:
8971: @example
8972: @kbd{my-word @key{RET}} text-2
8973: ok
8974: @kbd{my-char fred @key{RET}} Af ok
8975: @kbd{my-char jim @key{RET}} Aj ok
8976: @end example
8977:
8978: @itemize @bullet
8979: @item
8980: Message @code{text-2} is displayed because of the run-time behaviour of
8981: @code{."}.
8982: @item
8983: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8984: on the stack at run-time. @code{emit} always displays the character
8985: when @code{my-char} is executed.
8986: @item
8987: @code{char} parses a string at run-time and the second @code{emit} displays
8988: the first character of the string.
8989: @item
8990: If you type @code{see my-char} you can see that @code{[char]} discarded
8991: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8992: definition of @code{my-char}.
8993: @end itemize
8994:
8995:
8996:
8997: @node Input, , Displaying characters and strings, Other I/O
8998: @subsection Input
8999: @cindex input
9000: @cindex I/O - see input
9001: @cindex parsing a string
9002:
9003: For ways of storing character strings in memory see @ref{String Formats}.
9004:
9005: @comment TODO examples for >number >float accept key key? pad parse word refill
9006: @comment then index them
9007:
9008:
9009: doc-key
9010: doc-key?
9011: doc-ekey
9012: doc-ekey?
9013: doc-ekey>char
9014: doc->number
9015: doc->float
9016: doc-accept
9017: doc-pad
9018: @c anton: these belong in the input stream section
9019: doc-parse
9020: doc-word
9021: doc-sword
9022: doc-name
9023: doc-refill
9024: @comment obsolescent words..
9025: doc-convert
9026: doc-query
9027: doc-expect
9028: doc-span
9029:
9030:
9031: @c -------------------------------------------------------------
9032: @node Locals, Structures, Other I/O, Words
9033: @section Locals
9034: @cindex locals
9035:
9036: Local variables can make Forth programming more enjoyable and Forth
9037: programs easier to read. Unfortunately, the locals of ANS Forth are
9038: laden with restrictions. Therefore, we provide not only the ANS Forth
9039: locals wordset, but also our own, more powerful locals wordset (we
9040: implemented the ANS Forth locals wordset through our locals wordset).
9041:
9042: The ideas in this section have also been published in M. Anton Ertl,
9043: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9044: Automatic Scoping of Local Variables}}, EuroForth '94.
9045:
9046: @menu
9047: * Gforth locals::
9048: * ANS Forth locals::
9049: @end menu
9050:
9051: @node Gforth locals, ANS Forth locals, Locals, Locals
9052: @subsection Gforth locals
9053: @cindex Gforth locals
9054: @cindex locals, Gforth style
9055:
9056: Locals can be defined with
9057:
9058: @example
9059: @{ local1 local2 ... -- comment @}
9060: @end example
9061: or
9062: @example
9063: @{ local1 local2 ... @}
9064: @end example
9065:
9066: E.g.,
9067: @example
9068: : max @{ n1 n2 -- n3 @}
9069: n1 n2 > if
9070: n1
9071: else
9072: n2
9073: endif ;
9074: @end example
9075:
9076: The similarity of locals definitions with stack comments is intended. A
9077: locals definition often replaces the stack comment of a word. The order
9078: of the locals corresponds to the order in a stack comment and everything
9079: after the @code{--} is really a comment.
9080:
9081: This similarity has one disadvantage: It is too easy to confuse locals
9082: declarations with stack comments, causing bugs and making them hard to
9083: find. However, this problem can be avoided by appropriate coding
9084: conventions: Do not use both notations in the same program. If you do,
9085: they should be distinguished using additional means, e.g. by position.
9086:
9087: @cindex types of locals
9088: @cindex locals types
9089: The name of the local may be preceded by a type specifier, e.g.,
9090: @code{F:} for a floating point value:
9091:
9092: @example
9093: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9094: \ complex multiplication
9095: Ar Br f* Ai Bi f* f-
9096: Ar Bi f* Ai Br f* f+ ;
9097: @end example
9098:
9099: @cindex flavours of locals
9100: @cindex locals flavours
9101: @cindex value-flavoured locals
9102: @cindex variable-flavoured locals
9103: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9104: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9105: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9106: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9107: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9108: produces its address (which becomes invalid when the variable's scope is
9109: left). E.g., the standard word @code{emit} can be defined in terms of
9110: @code{type} like this:
9111:
9112: @example
9113: : emit @{ C^ char* -- @}
9114: char* 1 type ;
9115: @end example
9116:
9117: @cindex default type of locals
9118: @cindex locals, default type
9119: A local without type specifier is a @code{W:} local. Both flavours of
9120: locals are initialized with values from the data or FP stack.
9121:
9122: Currently there is no way to define locals with user-defined data
9123: structures, but we are working on it.
9124:
9125: Gforth allows defining locals everywhere in a colon definition. This
9126: poses the following questions:
9127:
9128: @menu
9129: * Where are locals visible by name?::
9130: * How long do locals live?::
9131: * Locals programming style::
9132: * Locals implementation::
9133: @end menu
9134:
9135: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9136: @subsubsection Where are locals visible by name?
9137: @cindex locals visibility
9138: @cindex visibility of locals
9139: @cindex scope of locals
9140:
9141: Basically, the answer is that locals are visible where you would expect
9142: it in block-structured languages, and sometimes a little longer. If you
9143: want to restrict the scope of a local, enclose its definition in
9144: @code{SCOPE}...@code{ENDSCOPE}.
9145:
9146:
9147: doc-scope
9148: doc-endscope
9149:
9150:
9151: These words behave like control structure words, so you can use them
9152: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9153: arbitrary ways.
9154:
9155: If you want a more exact answer to the visibility question, here's the
9156: basic principle: A local is visible in all places that can only be
9157: reached through the definition of the local@footnote{In compiler
9158: construction terminology, all places dominated by the definition of the
9159: local.}. In other words, it is not visible in places that can be reached
9160: without going through the definition of the local. E.g., locals defined
9161: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9162: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9163: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
9164:
9165: The reasoning behind this solution is: We want to have the locals
9166: visible as long as it is meaningful. The user can always make the
9167: visibility shorter by using explicit scoping. In a place that can
9168: only be reached through the definition of a local, the meaning of a
9169: local name is clear. In other places it is not: How is the local
9170: initialized at the control flow path that does not contain the
9171: definition? Which local is meant, if the same name is defined twice in
9172: two independent control flow paths?
9173:
9174: This should be enough detail for nearly all users, so you can skip the
9175: rest of this section. If you really must know all the gory details and
9176: options, read on.
9177:
9178: In order to implement this rule, the compiler has to know which places
9179: are unreachable. It knows this automatically after @code{AHEAD},
9180: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9181: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9182: compiler that the control flow never reaches that place. If
9183: @code{UNREACHABLE} is not used where it could, the only consequence is
9184: that the visibility of some locals is more limited than the rule above
9185: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9186: lie to the compiler), buggy code will be produced.
9187:
9188:
9189: doc-unreachable
9190:
9191:
9192: Another problem with this rule is that at @code{BEGIN}, the compiler
9193: does not know which locals will be visible on the incoming
9194: back-edge. All problems discussed in the following are due to this
9195: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9196: loops as examples; the discussion also applies to @code{?DO} and other
9197: loops). Perhaps the most insidious example is:
9198: @example
9199: AHEAD
9200: BEGIN
9201: x
9202: [ 1 CS-ROLL ] THEN
9203: @{ x @}
9204: ...
9205: UNTIL
9206: @end example
9207:
9208: This should be legal according to the visibility rule. The use of
9209: @code{x} can only be reached through the definition; but that appears
9210: textually below the use.
9211:
9212: From this example it is clear that the visibility rules cannot be fully
9213: implemented without major headaches. Our implementation treats common
9214: cases as advertised and the exceptions are treated in a safe way: The
9215: compiler makes a reasonable guess about the locals visible after a
9216: @code{BEGIN}; if it is too pessimistic, the
9217: user will get a spurious error about the local not being defined; if the
9218: compiler is too optimistic, it will notice this later and issue a
9219: warning. In the case above the compiler would complain about @code{x}
9220: being undefined at its use. You can see from the obscure examples in
9221: this section that it takes quite unusual control structures to get the
9222: compiler into trouble, and even then it will often do fine.
9223:
9224: If the @code{BEGIN} is reachable from above, the most optimistic guess
9225: is that all locals visible before the @code{BEGIN} will also be
9226: visible after the @code{BEGIN}. This guess is valid for all loops that
9227: are entered only through the @code{BEGIN}, in particular, for normal
9228: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9229: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9230: compiler. When the branch to the @code{BEGIN} is finally generated by
9231: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9232: warns the user if it was too optimistic:
9233: @example
9234: IF
9235: @{ x @}
9236: BEGIN
9237: \ x ?
9238: [ 1 cs-roll ] THEN
9239: ...
9240: UNTIL
9241: @end example
9242:
9243: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9244: optimistically assumes that it lives until the @code{THEN}. It notices
9245: this difference when it compiles the @code{UNTIL} and issues a
9246: warning. The user can avoid the warning, and make sure that @code{x}
9247: is not used in the wrong area by using explicit scoping:
9248: @example
9249: IF
9250: SCOPE
9251: @{ x @}
9252: ENDSCOPE
9253: BEGIN
9254: [ 1 cs-roll ] THEN
9255: ...
9256: UNTIL
9257: @end example
9258:
9259: Since the guess is optimistic, there will be no spurious error messages
9260: about undefined locals.
9261:
9262: If the @code{BEGIN} is not reachable from above (e.g., after
9263: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9264: optimistic guess, as the locals visible after the @code{BEGIN} may be
9265: defined later. Therefore, the compiler assumes that no locals are
9266: visible after the @code{BEGIN}. However, the user can use
9267: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9268: visible at the BEGIN as at the point where the top control-flow stack
9269: item was created.
9270:
9271:
9272: doc-assume-live
9273:
9274:
9275: @noindent
9276: E.g.,
9277: @example
9278: @{ x @}
9279: AHEAD
9280: ASSUME-LIVE
9281: BEGIN
9282: x
9283: [ 1 CS-ROLL ] THEN
9284: ...
9285: UNTIL
9286: @end example
9287:
9288: Other cases where the locals are defined before the @code{BEGIN} can be
9289: handled by inserting an appropriate @code{CS-ROLL} before the
9290: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9291: behind the @code{ASSUME-LIVE}).
9292:
9293: Cases where locals are defined after the @code{BEGIN} (but should be
9294: visible immediately after the @code{BEGIN}) can only be handled by
9295: rearranging the loop. E.g., the ``most insidious'' example above can be
9296: arranged into:
9297: @example
9298: BEGIN
9299: @{ x @}
9300: ... 0=
9301: WHILE
9302: x
9303: REPEAT
9304: @end example
9305:
9306: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9307: @subsubsection How long do locals live?
9308: @cindex locals lifetime
9309: @cindex lifetime of locals
9310:
9311: The right answer for the lifetime question would be: A local lives at
9312: least as long as it can be accessed. For a value-flavoured local this
9313: means: until the end of its visibility. However, a variable-flavoured
9314: local could be accessed through its address far beyond its visibility
9315: scope. Ultimately, this would mean that such locals would have to be
9316: garbage collected. Since this entails un-Forth-like implementation
9317: complexities, I adopted the same cowardly solution as some other
9318: languages (e.g., C): The local lives only as long as it is visible;
9319: afterwards its address is invalid (and programs that access it
9320: afterwards are erroneous).
9321:
9322: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9323: @subsubsection Locals programming style
9324: @cindex locals programming style
9325: @cindex programming style, locals
9326:
9327: The freedom to define locals anywhere has the potential to change
9328: programming styles dramatically. In particular, the need to use the
9329: return stack for intermediate storage vanishes. Moreover, all stack
9330: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9331: determined arguments) can be eliminated: If the stack items are in the
9332: wrong order, just write a locals definition for all of them; then
9333: write the items in the order you want.
9334:
9335: This seems a little far-fetched and eliminating stack manipulations is
9336: unlikely to become a conscious programming objective. Still, the number
9337: of stack manipulations will be reduced dramatically if local variables
9338: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9339: a traditional implementation of @code{max}).
9340:
9341: This shows one potential benefit of locals: making Forth programs more
9342: readable. Of course, this benefit will only be realized if the
9343: programmers continue to honour the principle of factoring instead of
9344: using the added latitude to make the words longer.
9345:
9346: @cindex single-assignment style for locals
9347: Using @code{TO} can and should be avoided. Without @code{TO},
9348: every value-flavoured local has only a single assignment and many
9349: advantages of functional languages apply to Forth. I.e., programs are
9350: easier to analyse, to optimize and to read: It is clear from the
9351: definition what the local stands for, it does not turn into something
9352: different later.
9353:
9354: E.g., a definition using @code{TO} might look like this:
9355: @example
9356: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9357: u1 u2 min 0
9358: ?do
9359: addr1 c@@ addr2 c@@ -
9360: ?dup-if
9361: unloop exit
9362: then
9363: addr1 char+ TO addr1
9364: addr2 char+ TO addr2
9365: loop
9366: u1 u2 - ;
9367: @end example
9368: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9369: every loop iteration. @code{strcmp} is a typical example of the
9370: readability problems of using @code{TO}. When you start reading
9371: @code{strcmp}, you think that @code{addr1} refers to the start of the
9372: string. Only near the end of the loop you realize that it is something
9373: else.
9374:
9375: This can be avoided by defining two locals at the start of the loop that
9376: are initialized with the right value for the current iteration.
9377: @example
9378: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9379: addr1 addr2
9380: u1 u2 min 0
9381: ?do @{ s1 s2 @}
9382: s1 c@@ s2 c@@ -
9383: ?dup-if
9384: unloop exit
9385: then
9386: s1 char+ s2 char+
9387: loop
9388: 2drop
9389: u1 u2 - ;
9390: @end example
9391: Here it is clear from the start that @code{s1} has a different value
9392: in every loop iteration.
9393:
9394: @node Locals implementation, , Locals programming style, Gforth locals
9395: @subsubsection Locals implementation
9396: @cindex locals implementation
9397: @cindex implementation of locals
9398:
9399: @cindex locals stack
9400: Gforth uses an extra locals stack. The most compelling reason for
9401: this is that the return stack is not float-aligned; using an extra stack
9402: also eliminates the problems and restrictions of using the return stack
9403: as locals stack. Like the other stacks, the locals stack grows toward
9404: lower addresses. A few primitives allow an efficient implementation:
9405:
9406:
9407: doc-@local#
9408: doc-f@local#
9409: doc-laddr#
9410: doc-lp+!#
9411: doc-lp!
9412: doc->l
9413: doc-f>l
9414:
9415:
9416: In addition to these primitives, some specializations of these
9417: primitives for commonly occurring inline arguments are provided for
9418: efficiency reasons, e.g., @code{@@local0} as specialization of
9419: @code{@@local#} for the inline argument 0. The following compiling words
9420: compile the right specialized version, or the general version, as
9421: appropriate:
9422:
9423:
9424: doc-compile-@local
9425: doc-compile-f@local
9426: doc-compile-lp+!
9427:
9428:
9429: Combinations of conditional branches and @code{lp+!#} like
9430: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9431: is taken) are provided for efficiency and correctness in loops.
9432:
9433: A special area in the dictionary space is reserved for keeping the
9434: local variable names. @code{@{} switches the dictionary pointer to this
9435: area and @code{@}} switches it back and generates the locals
9436: initializing code. @code{W:} etc.@ are normal defining words. This
9437: special area is cleared at the start of every colon definition.
9438:
9439: @cindex word list for defining locals
9440: A special feature of Gforth's dictionary is used to implement the
9441: definition of locals without type specifiers: every word list (aka
9442: vocabulary) has its own methods for searching
9443: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9444: with a special search method: When it is searched for a word, it
9445: actually creates that word using @code{W:}. @code{@{} changes the search
9446: order to first search the word list containing @code{@}}, @code{W:} etc.,
9447: and then the word list for defining locals without type specifiers.
9448:
9449: The lifetime rules support a stack discipline within a colon
9450: definition: The lifetime of a local is either nested with other locals
9451: lifetimes or it does not overlap them.
9452:
9453: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9454: pointer manipulation is generated. Between control structure words
9455: locals definitions can push locals onto the locals stack. @code{AGAIN}
9456: is the simplest of the other three control flow words. It has to
9457: restore the locals stack depth of the corresponding @code{BEGIN}
9458: before branching. The code looks like this:
9459: @format
9460: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9461: @code{branch} <begin>
9462: @end format
9463:
9464: @code{UNTIL} is a little more complicated: If it branches back, it
9465: must adjust the stack just like @code{AGAIN}. But if it falls through,
9466: the locals stack must not be changed. The compiler generates the
9467: following code:
9468: @format
9469: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9470: @end format
9471: The locals stack pointer is only adjusted if the branch is taken.
9472:
9473: @code{THEN} can produce somewhat inefficient code:
9474: @format
9475: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9476: <orig target>:
9477: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9478: @end format
9479: The second @code{lp+!#} adjusts the locals stack pointer from the
9480: level at the @i{orig} point to the level after the @code{THEN}. The
9481: first @code{lp+!#} adjusts the locals stack pointer from the current
9482: level to the level at the orig point, so the complete effect is an
9483: adjustment from the current level to the right level after the
9484: @code{THEN}.
9485:
9486: @cindex locals information on the control-flow stack
9487: @cindex control-flow stack items, locals information
9488: In a conventional Forth implementation a dest control-flow stack entry
9489: is just the target address and an orig entry is just the address to be
9490: patched. Our locals implementation adds a word list to every orig or dest
9491: item. It is the list of locals visible (or assumed visible) at the point
9492: described by the entry. Our implementation also adds a tag to identify
9493: the kind of entry, in particular to differentiate between live and dead
9494: (reachable and unreachable) orig entries.
9495:
9496: A few unusual operations have to be performed on locals word lists:
9497:
9498:
9499: doc-common-list
9500: doc-sub-list?
9501: doc-list-size
9502:
9503:
9504: Several features of our locals word list implementation make these
9505: operations easy to implement: The locals word lists are organised as
9506: linked lists; the tails of these lists are shared, if the lists
9507: contain some of the same locals; and the address of a name is greater
9508: than the address of the names behind it in the list.
9509:
9510: Another important implementation detail is the variable
9511: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9512: determine if they can be reached directly or only through the branch
9513: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9514: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9515: definition, by @code{BEGIN} and usually by @code{THEN}.
9516:
9517: Counted loops are similar to other loops in most respects, but
9518: @code{LEAVE} requires special attention: It performs basically the same
9519: service as @code{AHEAD}, but it does not create a control-flow stack
9520: entry. Therefore the information has to be stored elsewhere;
9521: traditionally, the information was stored in the target fields of the
9522: branches created by the @code{LEAVE}s, by organizing these fields into a
9523: linked list. Unfortunately, this clever trick does not provide enough
9524: space for storing our extended control flow information. Therefore, we
9525: introduce another stack, the leave stack. It contains the control-flow
9526: stack entries for all unresolved @code{LEAVE}s.
9527:
9528: Local names are kept until the end of the colon definition, even if
9529: they are no longer visible in any control-flow path. In a few cases
9530: this may lead to increased space needs for the locals name area, but
9531: usually less than reclaiming this space would cost in code size.
9532:
9533:
9534: @node ANS Forth locals, , Gforth locals, Locals
9535: @subsection ANS Forth locals
9536: @cindex locals, ANS Forth style
9537:
9538: The ANS Forth locals wordset does not define a syntax for locals, but
9539: words that make it possible to define various syntaxes. One of the
9540: possible syntaxes is a subset of the syntax we used in the Gforth locals
9541: wordset, i.e.:
9542:
9543: @example
9544: @{ local1 local2 ... -- comment @}
9545: @end example
9546: @noindent
9547: or
9548: @example
9549: @{ local1 local2 ... @}
9550: @end example
9551:
9552: The order of the locals corresponds to the order in a stack comment. The
9553: restrictions are:
9554:
9555: @itemize @bullet
9556: @item
9557: Locals can only be cell-sized values (no type specifiers are allowed).
9558: @item
9559: Locals can be defined only outside control structures.
9560: @item
9561: Locals can interfere with explicit usage of the return stack. For the
9562: exact (and long) rules, see the standard. If you don't use return stack
9563: accessing words in a definition using locals, you will be all right. The
9564: purpose of this rule is to make locals implementation on the return
9565: stack easier.
9566: @item
9567: The whole definition must be in one line.
9568: @end itemize
9569:
9570: Locals defined in ANS Forth behave like @code{VALUE}s
9571: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9572: name produces their value. Their value can be changed using @code{TO}.
9573:
9574: Since the syntax above is supported by Gforth directly, you need not do
9575: anything to use it. If you want to port a program using this syntax to
9576: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9577: syntax on the other system.
9578:
9579: Note that a syntax shown in the standard, section A.13 looks
9580: similar, but is quite different in having the order of locals
9581: reversed. Beware!
9582:
9583: The ANS Forth locals wordset itself consists of one word:
9584:
9585: doc-(local)
9586:
9587: The ANS Forth locals extension wordset defines a syntax using
9588: @code{locals|}, but it is so awful that we strongly recommend not to use
9589: it. We have implemented this syntax to make porting to Gforth easy, but
9590: do not document it here. The problem with this syntax is that the locals
9591: are defined in an order reversed with respect to the standard stack
9592: comment notation, making programs harder to read, and easier to misread
9593: and miswrite. The only merit of this syntax is that it is easy to
9594: implement using the ANS Forth locals wordset.
9595:
9596:
9597: @c ----------------------------------------------------------
9598: @node Structures, Object-oriented Forth, Locals, Words
9599: @section Structures
9600: @cindex structures
9601: @cindex records
9602:
9603: This section presents the structure package that comes with Gforth. A
9604: version of the package implemented in ANS Forth is available in
9605: @file{compat/struct.fs}. This package was inspired by a posting on
9606: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9607: possibly John Hayes). A version of this section has been published in
9608: M. Anton Ertl,
9609: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9610: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9611: 13--16. Marcel Hendrix provided helpful comments.
9612:
9613: @menu
9614: * Why explicit structure support?::
9615: * Structure Usage::
9616: * Structure Naming Convention::
9617: * Structure Implementation::
9618: * Structure Glossary::
9619: @end menu
9620:
9621: @node Why explicit structure support?, Structure Usage, Structures, Structures
9622: @subsection Why explicit structure support?
9623:
9624: @cindex address arithmetic for structures
9625: @cindex structures using address arithmetic
9626: If we want to use a structure containing several fields, we could simply
9627: reserve memory for it, and access the fields using address arithmetic
9628: (@pxref{Address arithmetic}). As an example, consider a structure with
9629: the following fields
9630:
9631: @table @code
9632: @item a
9633: is a float
9634: @item b
9635: is a cell
9636: @item c
9637: is a float
9638: @end table
9639:
9640: Given the (float-aligned) base address of the structure we get the
9641: address of the field
9642:
9643: @table @code
9644: @item a
9645: without doing anything further.
9646: @item b
9647: with @code{float+}
9648: @item c
9649: with @code{float+ cell+ faligned}
9650: @end table
9651:
9652: It is easy to see that this can become quite tiring.
9653:
9654: Moreover, it is not very readable, because seeing a
9655: @code{cell+} tells us neither which kind of structure is
9656: accessed nor what field is accessed; we have to somehow infer the kind
9657: of structure, and then look up in the documentation, which field of
9658: that structure corresponds to that offset.
9659:
9660: Finally, this kind of address arithmetic also causes maintenance
9661: troubles: If you add or delete a field somewhere in the middle of the
9662: structure, you have to find and change all computations for the fields
9663: afterwards.
9664:
9665: So, instead of using @code{cell+} and friends directly, how
9666: about storing the offsets in constants:
9667:
9668: @example
9669: 0 constant a-offset
9670: 0 float+ constant b-offset
9671: 0 float+ cell+ faligned c-offset
9672: @end example
9673:
9674: Now we can get the address of field @code{x} with @code{x-offset
9675: +}. This is much better in all respects. Of course, you still
9676: have to change all later offset definitions if you add a field. You can
9677: fix this by declaring the offsets in the following way:
9678:
9679: @example
9680: 0 constant a-offset
9681: a-offset float+ constant b-offset
9682: b-offset cell+ faligned constant c-offset
9683: @end example
9684:
9685: Since we always use the offsets with @code{+}, we could use a defining
9686: word @code{cfield} that includes the @code{+} in the action of the
9687: defined word:
9688:
9689: @example
9690: : cfield ( n "name" -- )
9691: create ,
9692: does> ( name execution: addr1 -- addr2 )
9693: @@ + ;
9694:
9695: 0 cfield a
9696: 0 a float+ cfield b
9697: 0 b cell+ faligned cfield c
9698: @end example
9699:
9700: Instead of @code{x-offset +}, we now simply write @code{x}.
9701:
9702: The structure field words now can be used quite nicely. However,
9703: their definition is still a bit cumbersome: We have to repeat the
9704: name, the information about size and alignment is distributed before
9705: and after the field definitions etc. The structure package presented
9706: here addresses these problems.
9707:
9708: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9709: @subsection Structure Usage
9710: @cindex structure usage
9711:
9712: @cindex @code{field} usage
9713: @cindex @code{struct} usage
9714: @cindex @code{end-struct} usage
9715: You can define a structure for a (data-less) linked list with:
9716: @example
9717: struct
9718: cell% field list-next
9719: end-struct list%
9720: @end example
9721:
9722: With the address of the list node on the stack, you can compute the
9723: address of the field that contains the address of the next node with
9724: @code{list-next}. E.g., you can determine the length of a list
9725: with:
9726:
9727: @example
9728: : list-length ( list -- n )
9729: \ "list" is a pointer to the first element of a linked list
9730: \ "n" is the length of the list
9731: 0 BEGIN ( list1 n1 )
9732: over
9733: WHILE ( list1 n1 )
9734: 1+ swap list-next @@ swap
9735: REPEAT
9736: nip ;
9737: @end example
9738:
9739: You can reserve memory for a list node in the dictionary with
9740: @code{list% %allot}, which leaves the address of the list node on the
9741: stack. For the equivalent allocation on the heap you can use @code{list%
9742: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9743: use @code{list% %allocate}). You can get the the size of a list
9744: node with @code{list% %size} and its alignment with @code{list%
9745: %alignment}.
9746:
9747: Note that in ANS Forth the body of a @code{create}d word is
9748: @code{aligned} but not necessarily @code{faligned};
9749: therefore, if you do a:
9750:
9751: @example
9752: create @emph{name} foo% %allot drop
9753: @end example
9754:
9755: @noindent
9756: then the memory alloted for @code{foo%} is guaranteed to start at the
9757: body of @code{@emph{name}} only if @code{foo%} contains only character,
9758: cell and double fields. Therefore, if your structure contains floats,
9759: better use
9760:
9761: @example
9762: foo% %allot constant @emph{name}
9763: @end example
9764:
9765: @cindex structures containing structures
9766: You can include a structure @code{foo%} as a field of
9767: another structure, like this:
9768: @example
9769: struct
9770: ...
9771: foo% field ...
9772: ...
9773: end-struct ...
9774: @end example
9775:
9776: @cindex structure extension
9777: @cindex extended records
9778: Instead of starting with an empty structure, you can extend an
9779: existing structure. E.g., a plain linked list without data, as defined
9780: above, is hardly useful; You can extend it to a linked list of integers,
9781: like this:@footnote{This feature is also known as @emph{extended
9782: records}. It is the main innovation in the Oberon language; in other
9783: words, adding this feature to Modula-2 led Wirth to create a new
9784: language, write a new compiler etc. Adding this feature to Forth just
9785: required a few lines of code.}
9786:
9787: @example
9788: list%
9789: cell% field intlist-int
9790: end-struct intlist%
9791: @end example
9792:
9793: @code{intlist%} is a structure with two fields:
9794: @code{list-next} and @code{intlist-int}.
9795:
9796: @cindex structures containing arrays
9797: You can specify an array type containing @emph{n} elements of
9798: type @code{foo%} like this:
9799:
9800: @example
9801: foo% @emph{n} *
9802: @end example
9803:
9804: You can use this array type in any place where you can use a normal
9805: type, e.g., when defining a @code{field}, or with
9806: @code{%allot}.
9807:
9808: @cindex first field optimization
9809: The first field is at the base address of a structure and the word for
9810: this field (e.g., @code{list-next}) actually does not change the address
9811: on the stack. You may be tempted to leave it away in the interest of
9812: run-time and space efficiency. This is not necessary, because the
9813: structure package optimizes this case: If you compile a first-field
9814: words, no code is generated. So, in the interest of readability and
9815: maintainability you should include the word for the field when accessing
9816: the field.
9817:
9818:
9819: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9820: @subsection Structure Naming Convention
9821: @cindex structure naming convention
9822:
9823: The field names that come to (my) mind are often quite generic, and,
9824: if used, would cause frequent name clashes. E.g., many structures
9825: probably contain a @code{counter} field. The structure names
9826: that come to (my) mind are often also the logical choice for the names
9827: of words that create such a structure.
9828:
9829: Therefore, I have adopted the following naming conventions:
9830:
9831: @itemize @bullet
9832: @cindex field naming convention
9833: @item
9834: The names of fields are of the form
9835: @code{@emph{struct}-@emph{field}}, where
9836: @code{@emph{struct}} is the basic name of the structure, and
9837: @code{@emph{field}} is the basic name of the field. You can
9838: think of field words as converting the (address of the)
9839: structure into the (address of the) field.
9840:
9841: @cindex structure naming convention
9842: @item
9843: The names of structures are of the form
9844: @code{@emph{struct}%}, where
9845: @code{@emph{struct}} is the basic name of the structure.
9846: @end itemize
9847:
9848: This naming convention does not work that well for fields of extended
9849: structures; e.g., the integer list structure has a field
9850: @code{intlist-int}, but has @code{list-next}, not
9851: @code{intlist-next}.
9852:
9853: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9854: @subsection Structure Implementation
9855: @cindex structure implementation
9856: @cindex implementation of structures
9857:
9858: The central idea in the implementation is to pass the data about the
9859: structure being built on the stack, not in some global
9860: variable. Everything else falls into place naturally once this design
9861: decision is made.
9862:
9863: The type description on the stack is of the form @emph{align
9864: size}. Keeping the size on the top-of-stack makes dealing with arrays
9865: very simple.
9866:
9867: @code{field} is a defining word that uses @code{Create}
9868: and @code{DOES>}. The body of the field contains the offset
9869: of the field, and the normal @code{DOES>} action is simply:
9870:
9871: @example
9872: @@ +
9873: @end example
9874:
9875: @noindent
9876: i.e., add the offset to the address, giving the stack effect
9877: @i{addr1 -- addr2} for a field.
9878:
9879: @cindex first field optimization, implementation
9880: This simple structure is slightly complicated by the optimization
9881: for fields with offset 0, which requires a different
9882: @code{DOES>}-part (because we cannot rely on there being
9883: something on the stack if such a field is invoked during
9884: compilation). Therefore, we put the different @code{DOES>}-parts
9885: in separate words, and decide which one to invoke based on the
9886: offset. For a zero offset, the field is basically a noop; it is
9887: immediate, and therefore no code is generated when it is compiled.
9888:
9889: @node Structure Glossary, , Structure Implementation, Structures
9890: @subsection Structure Glossary
9891: @cindex structure glossary
9892:
9893:
9894: doc-%align
9895: doc-%alignment
9896: doc-%alloc
9897: doc-%allocate
9898: doc-%allot
9899: doc-cell%
9900: doc-char%
9901: doc-dfloat%
9902: doc-double%
9903: doc-end-struct
9904: doc-field
9905: doc-float%
9906: doc-naligned
9907: doc-sfloat%
9908: doc-%size
9909: doc-struct
9910:
9911:
9912: @c -------------------------------------------------------------
9913: @node Object-oriented Forth, Programming Tools, Structures, Words
9914: @section Object-oriented Forth
9915:
9916: Gforth comes with three packages for object-oriented programming:
9917: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9918: is preloaded, so you have to @code{include} them before use. The most
9919: important differences between these packages (and others) are discussed
9920: in @ref{Comparison with other object models}. All packages are written
9921: in ANS Forth and can be used with any other ANS Forth.
9922:
9923: @menu
9924: * Why object-oriented programming?::
9925: * Object-Oriented Terminology::
9926: * Objects::
9927: * OOF::
9928: * Mini-OOF::
9929: * Comparison with other object models::
9930: @end menu
9931:
9932: @c ----------------------------------------------------------------
9933: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9934: @subsection Why object-oriented programming?
9935: @cindex object-oriented programming motivation
9936: @cindex motivation for object-oriented programming
9937:
9938: Often we have to deal with several data structures (@emph{objects}),
9939: that have to be treated similarly in some respects, but differently in
9940: others. Graphical objects are the textbook example: circles, triangles,
9941: dinosaurs, icons, and others, and we may want to add more during program
9942: development. We want to apply some operations to any graphical object,
9943: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9944: has to do something different for every kind of object.
9945: @comment TODO add some other operations eg perimeter, area
9946: @comment and tie in to concrete examples later..
9947:
9948: We could implement @code{draw} as a big @code{CASE}
9949: control structure that executes the appropriate code depending on the
9950: kind of object to be drawn. This would be not be very elegant, and,
9951: moreover, we would have to change @code{draw} every time we add
9952: a new kind of graphical object (say, a spaceship).
9953:
9954: What we would rather do is: When defining spaceships, we would tell
9955: the system: ``Here's how you @code{draw} a spaceship; you figure
9956: out the rest''.
9957:
9958: This is the problem that all systems solve that (rightfully) call
9959: themselves object-oriented; the object-oriented packages presented here
9960: solve this problem (and not much else).
9961: @comment TODO ?list properties of oo systems.. oo vs o-based?
9962:
9963: @c ------------------------------------------------------------------------
9964: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
9965: @subsection Object-Oriented Terminology
9966: @cindex object-oriented terminology
9967: @cindex terminology for object-oriented programming
9968:
9969: This section is mainly for reference, so you don't have to understand
9970: all of it right away. The terminology is mainly Smalltalk-inspired. In
9971: short:
9972:
9973: @table @emph
9974: @cindex class
9975: @item class
9976: a data structure definition with some extras.
9977:
9978: @cindex object
9979: @item object
9980: an instance of the data structure described by the class definition.
9981:
9982: @cindex instance variables
9983: @item instance variables
9984: fields of the data structure.
9985:
9986: @cindex selector
9987: @cindex method selector
9988: @cindex virtual function
9989: @item selector
9990: (or @emph{method selector}) a word (e.g.,
9991: @code{draw}) that performs an operation on a variety of data
9992: structures (classes). A selector describes @emph{what} operation to
9993: perform. In C++ terminology: a (pure) virtual function.
9994:
9995: @cindex method
9996: @item method
9997: the concrete definition that performs the operation
9998: described by the selector for a specific class. A method specifies
9999: @emph{how} the operation is performed for a specific class.
10000:
10001: @cindex selector invocation
10002: @cindex message send
10003: @cindex invoking a selector
10004: @item selector invocation
10005: a call of a selector. One argument of the call (the TOS (top-of-stack))
10006: is used for determining which method is used. In Smalltalk terminology:
10007: a message (consisting of the selector and the other arguments) is sent
10008: to the object.
10009:
10010: @cindex receiving object
10011: @item receiving object
10012: the object used for determining the method executed by a selector
10013: invocation. In the @file{objects.fs} model, it is the object that is on
10014: the TOS when the selector is invoked. (@emph{Receiving} comes from
10015: the Smalltalk @emph{message} terminology.)
10016:
10017: @cindex child class
10018: @cindex parent class
10019: @cindex inheritance
10020: @item child class
10021: a class that has (@emph{inherits}) all properties (instance variables,
10022: selectors, methods) from a @emph{parent class}. In Smalltalk
10023: terminology: The subclass inherits from the superclass. In C++
10024: terminology: The derived class inherits from the base class.
10025:
10026: @end table
10027:
10028: @c If you wonder about the message sending terminology, it comes from
10029: @c a time when each object had it's own task and objects communicated via
10030: @c message passing; eventually the Smalltalk developers realized that
10031: @c they can do most things through simple (indirect) calls. They kept the
10032: @c terminology.
10033:
10034: @c --------------------------------------------------------------
10035: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10036: @subsection The @file{objects.fs} model
10037: @cindex objects
10038: @cindex object-oriented programming
10039:
10040: @cindex @file{objects.fs}
10041: @cindex @file{oof.fs}
10042:
10043: This section describes the @file{objects.fs} package. This material also
10044: has been published in M. Anton Ertl,
10045: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10046: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10047: 37--43.
10048: @c McKewan's and Zsoter's packages
10049:
10050: This section assumes that you have read @ref{Structures}.
10051:
10052: The techniques on which this model is based have been used to implement
10053: the parser generator, Gray, and have also been used in Gforth for
10054: implementing the various flavours of word lists (hashed or not,
10055: case-sensitive or not, special-purpose word lists for locals etc.).
10056:
10057:
10058: @menu
10059: * Properties of the Objects model::
10060: * Basic Objects Usage::
10061: * The Objects base class::
10062: * Creating objects::
10063: * Object-Oriented Programming Style::
10064: * Class Binding::
10065: * Method conveniences::
10066: * Classes and Scoping::
10067: * Dividing classes::
10068: * Object Interfaces::
10069: * Objects Implementation::
10070: * Objects Glossary::
10071: @end menu
10072:
10073: Marcel Hendrix provided helpful comments on this section.
10074:
10075: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10076: @subsubsection Properties of the @file{objects.fs} model
10077: @cindex @file{objects.fs} properties
10078:
10079: @itemize @bullet
10080: @item
10081: It is straightforward to pass objects on the stack. Passing
10082: selectors on the stack is a little less convenient, but possible.
10083:
10084: @item
10085: Objects are just data structures in memory, and are referenced by their
10086: address. You can create words for objects with normal defining words
10087: like @code{constant}. Likewise, there is no difference between instance
10088: variables that contain objects and those that contain other data.
10089:
10090: @item
10091: Late binding is efficient and easy to use.
10092:
10093: @item
10094: It avoids parsing, and thus avoids problems with state-smartness
10095: and reduced extensibility; for convenience there are a few parsing
10096: words, but they have non-parsing counterparts. There are also a few
10097: defining words that parse. This is hard to avoid, because all standard
10098: defining words parse (except @code{:noname}); however, such
10099: words are not as bad as many other parsing words, because they are not
10100: state-smart.
10101:
10102: @item
10103: It does not try to incorporate everything. It does a few things and does
10104: them well (IMO). In particular, this model was not designed to support
10105: information hiding (although it has features that may help); you can use
10106: a separate package for achieving this.
10107:
10108: @item
10109: It is layered; you don't have to learn and use all features to use this
10110: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10111: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10112: are optional and independent of each other.
10113:
10114: @item
10115: An implementation in ANS Forth is available.
10116:
10117: @end itemize
10118:
10119:
10120: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10121: @subsubsection Basic @file{objects.fs} Usage
10122: @cindex basic objects usage
10123: @cindex objects, basic usage
10124:
10125: You can define a class for graphical objects like this:
10126:
10127: @cindex @code{class} usage
10128: @cindex @code{end-class} usage
10129: @cindex @code{selector} usage
10130: @example
10131: object class \ "object" is the parent class
10132: selector draw ( x y graphical -- )
10133: end-class graphical
10134: @end example
10135:
10136: This code defines a class @code{graphical} with an
10137: operation @code{draw}. We can perform the operation
10138: @code{draw} on any @code{graphical} object, e.g.:
10139:
10140: @example
10141: 100 100 t-rex draw
10142: @end example
10143:
10144: @noindent
10145: where @code{t-rex} is a word (say, a constant) that produces a
10146: graphical object.
10147:
10148: @comment TODO add a 2nd operation eg perimeter.. and use for
10149: @comment a concrete example
10150:
10151: @cindex abstract class
10152: How do we create a graphical object? With the present definitions,
10153: we cannot create a useful graphical object. The class
10154: @code{graphical} describes graphical objects in general, but not
10155: any concrete graphical object type (C++ users would call it an
10156: @emph{abstract class}); e.g., there is no method for the selector
10157: @code{draw} in the class @code{graphical}.
10158:
10159: For concrete graphical objects, we define child classes of the
10160: class @code{graphical}, e.g.:
10161:
10162: @cindex @code{overrides} usage
10163: @cindex @code{field} usage in class definition
10164: @example
10165: graphical class \ "graphical" is the parent class
10166: cell% field circle-radius
10167:
10168: :noname ( x y circle -- )
10169: circle-radius @@ draw-circle ;
10170: overrides draw
10171:
10172: :noname ( n-radius circle -- )
10173: circle-radius ! ;
10174: overrides construct
10175:
10176: end-class circle
10177: @end example
10178:
10179: Here we define a class @code{circle} as a child of @code{graphical},
10180: with field @code{circle-radius} (which behaves just like a field
10181: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10182: for the selectors @code{draw} and @code{construct} (@code{construct} is
10183: defined in @code{object}, the parent class of @code{graphical}).
10184:
10185: Now we can create a circle on the heap (i.e.,
10186: @code{allocate}d memory) with:
10187:
10188: @cindex @code{heap-new} usage
10189: @example
10190: 50 circle heap-new constant my-circle
10191: @end example
10192:
10193: @noindent
10194: @code{heap-new} invokes @code{construct}, thus
10195: initializing the field @code{circle-radius} with 50. We can draw
10196: this new circle at (100,100) with:
10197:
10198: @example
10199: 100 100 my-circle draw
10200: @end example
10201:
10202: @cindex selector invocation, restrictions
10203: @cindex class definition, restrictions
10204: Note: You can only invoke a selector if the object on the TOS
10205: (the receiving object) belongs to the class where the selector was
10206: defined or one of its descendents; e.g., you can invoke
10207: @code{draw} only for objects belonging to @code{graphical}
10208: or its descendents (e.g., @code{circle}). Immediately before
10209: @code{end-class}, the search order has to be the same as
10210: immediately after @code{class}.
10211:
10212: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10213: @subsubsection The @file{object.fs} base class
10214: @cindex @code{object} class
10215:
10216: When you define a class, you have to specify a parent class. So how do
10217: you start defining classes? There is one class available from the start:
10218: @code{object}. It is ancestor for all classes and so is the
10219: only class that has no parent. It has two selectors: @code{construct}
10220: and @code{print}.
10221:
10222: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10223: @subsubsection Creating objects
10224: @cindex creating objects
10225: @cindex object creation
10226: @cindex object allocation options
10227:
10228: @cindex @code{heap-new} discussion
10229: @cindex @code{dict-new} discussion
10230: @cindex @code{construct} discussion
10231: You can create and initialize an object of a class on the heap with
10232: @code{heap-new} ( ... class -- object ) and in the dictionary
10233: (allocation with @code{allot}) with @code{dict-new} (
10234: ... class -- object ). Both words invoke @code{construct}, which
10235: consumes the stack items indicated by "..." above.
10236:
10237: @cindex @code{init-object} discussion
10238: @cindex @code{class-inst-size} discussion
10239: If you want to allocate memory for an object yourself, you can get its
10240: alignment and size with @code{class-inst-size 2@@} ( class --
10241: align size ). Once you have memory for an object, you can initialize
10242: it with @code{init-object} ( ... class object -- );
10243: @code{construct} does only a part of the necessary work.
10244:
10245: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10246: @subsubsection Object-Oriented Programming Style
10247: @cindex object-oriented programming style
10248: @cindex programming style, object-oriented
10249:
10250: This section is not exhaustive.
10251:
10252: @cindex stack effects of selectors
10253: @cindex selectors and stack effects
10254: In general, it is a good idea to ensure that all methods for the
10255: same selector have the same stack effect: when you invoke a selector,
10256: you often have no idea which method will be invoked, so, unless all
10257: methods have the same stack effect, you will not know the stack effect
10258: of the selector invocation.
10259:
10260: One exception to this rule is methods for the selector
10261: @code{construct}. We know which method is invoked, because we
10262: specify the class to be constructed at the same place. Actually, I
10263: defined @code{construct} as a selector only to give the users a
10264: convenient way to specify initialization. The way it is used, a
10265: mechanism different from selector invocation would be more natural
10266: (but probably would take more code and more space to explain).
10267:
10268: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10269: @subsubsection Class Binding
10270: @cindex class binding
10271: @cindex early binding
10272:
10273: @cindex late binding
10274: Normal selector invocations determine the method at run-time depending
10275: on the class of the receiving object. This run-time selection is called
10276: @i{late binding}.
10277:
10278: Sometimes it's preferable to invoke a different method. For example,
10279: you might want to use the simple method for @code{print}ing
10280: @code{object}s instead of the possibly long-winded @code{print} method
10281: of the receiver class. You can achieve this by replacing the invocation
10282: of @code{print} with:
10283:
10284: @cindex @code{[bind]} usage
10285: @example
10286: [bind] object print
10287: @end example
10288:
10289: @noindent
10290: in compiled code or:
10291:
10292: @cindex @code{bind} usage
10293: @example
10294: bind object print
10295: @end example
10296:
10297: @cindex class binding, alternative to
10298: @noindent
10299: in interpreted code. Alternatively, you can define the method with a
10300: name (e.g., @code{print-object}), and then invoke it through the
10301: name. Class binding is just a (often more convenient) way to achieve
10302: the same effect; it avoids name clutter and allows you to invoke
10303: methods directly without naming them first.
10304:
10305: @cindex superclass binding
10306: @cindex parent class binding
10307: A frequent use of class binding is this: When we define a method
10308: for a selector, we often want the method to do what the selector does
10309: in the parent class, and a little more. There is a special word for
10310: this purpose: @code{[parent]}; @code{[parent]
10311: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10312: selector}}, where @code{@emph{parent}} is the parent
10313: class of the current class. E.g., a method definition might look like:
10314:
10315: @cindex @code{[parent]} usage
10316: @example
10317: :noname
10318: dup [parent] foo \ do parent's foo on the receiving object
10319: ... \ do some more
10320: ; overrides foo
10321: @end example
10322:
10323: @cindex class binding as optimization
10324: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10325: March 1997), Andrew McKewan presents class binding as an optimization
10326: technique. I recommend not using it for this purpose unless you are in
10327: an emergency. Late binding is pretty fast with this model anyway, so the
10328: benefit of using class binding is small; the cost of using class binding
10329: where it is not appropriate is reduced maintainability.
10330:
10331: While we are at programming style questions: You should bind
10332: selectors only to ancestor classes of the receiving object. E.g., say,
10333: you know that the receiving object is of class @code{foo} or its
10334: descendents; then you should bind only to @code{foo} and its
10335: ancestors.
10336:
10337: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10338: @subsubsection Method conveniences
10339: @cindex method conveniences
10340:
10341: In a method you usually access the receiving object pretty often. If
10342: you define the method as a plain colon definition (e.g., with
10343: @code{:noname}), you may have to do a lot of stack
10344: gymnastics. To avoid this, you can define the method with @code{m:
10345: ... ;m}. E.g., you could define the method for
10346: @code{draw}ing a @code{circle} with
10347:
10348: @cindex @code{this} usage
10349: @cindex @code{m:} usage
10350: @cindex @code{;m} usage
10351: @example
10352: m: ( x y circle -- )
10353: ( x y ) this circle-radius @@ draw-circle ;m
10354: @end example
10355:
10356: @cindex @code{exit} in @code{m: ... ;m}
10357: @cindex @code{exitm} discussion
10358: @cindex @code{catch} in @code{m: ... ;m}
10359: When this method is executed, the receiver object is removed from the
10360: stack; you can access it with @code{this} (admittedly, in this
10361: example the use of @code{m: ... ;m} offers no advantage). Note
10362: that I specify the stack effect for the whole method (i.e. including
10363: the receiver object), not just for the code between @code{m:}
10364: and @code{;m}. You cannot use @code{exit} in
10365: @code{m:...;m}; instead, use
10366: @code{exitm}.@footnote{Moreover, for any word that calls
10367: @code{catch} and was defined before loading
10368: @code{objects.fs}, you have to redefine it like I redefined
10369: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10370:
10371: @cindex @code{inst-var} usage
10372: You will frequently use sequences of the form @code{this
10373: @emph{field}} (in the example above: @code{this
10374: circle-radius}). If you use the field only in this way, you can
10375: define it with @code{inst-var} and eliminate the
10376: @code{this} before the field name. E.g., the @code{circle}
10377: class above could also be defined with:
10378:
10379: @example
10380: graphical class
10381: cell% inst-var radius
10382:
10383: m: ( x y circle -- )
10384: radius @@ draw-circle ;m
10385: overrides draw
10386:
10387: m: ( n-radius circle -- )
10388: radius ! ;m
10389: overrides construct
10390:
10391: end-class circle
10392: @end example
10393:
10394: @code{radius} can only be used in @code{circle} and its
10395: descendent classes and inside @code{m:...;m}.
10396:
10397: @cindex @code{inst-value} usage
10398: You can also define fields with @code{inst-value}, which is
10399: to @code{inst-var} what @code{value} is to
10400: @code{variable}. You can change the value of such a field with
10401: @code{[to-inst]}. E.g., we could also define the class
10402: @code{circle} like this:
10403:
10404: @example
10405: graphical class
10406: inst-value radius
10407:
10408: m: ( x y circle -- )
10409: radius draw-circle ;m
10410: overrides draw
10411:
10412: m: ( n-radius circle -- )
10413: [to-inst] radius ;m
10414: overrides construct
10415:
10416: end-class circle
10417: @end example
10418:
10419: @c !! :m is easy to confuse with m:. Another name would be better.
10420:
10421: @c Finally, you can define named methods with @code{:m}. One use of this
10422: @c feature is the definition of words that occur only in one class and are
10423: @c not intended to be overridden, but which still need method context
10424: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10425: @c would be bound frequently, if defined anonymously.
10426:
10427:
10428: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10429: @subsubsection Classes and Scoping
10430: @cindex classes and scoping
10431: @cindex scoping and classes
10432:
10433: Inheritance is frequent, unlike structure extension. This exacerbates
10434: the problem with the field name convention (@pxref{Structure Naming
10435: Convention}): One always has to remember in which class the field was
10436: originally defined; changing a part of the class structure would require
10437: changes for renaming in otherwise unaffected code.
10438:
10439: @cindex @code{inst-var} visibility
10440: @cindex @code{inst-value} visibility
10441: To solve this problem, I added a scoping mechanism (which was not in my
10442: original charter): A field defined with @code{inst-var} (or
10443: @code{inst-value}) is visible only in the class where it is defined and in
10444: the descendent classes of this class. Using such fields only makes
10445: sense in @code{m:}-defined methods in these classes anyway.
10446:
10447: This scoping mechanism allows us to use the unadorned field name,
10448: because name clashes with unrelated words become much less likely.
10449:
10450: @cindex @code{protected} discussion
10451: @cindex @code{private} discussion
10452: Once we have this mechanism, we can also use it for controlling the
10453: visibility of other words: All words defined after
10454: @code{protected} are visible only in the current class and its
10455: descendents. @code{public} restores the compilation
10456: (i.e. @code{current}) word list that was in effect before. If you
10457: have several @code{protected}s without an intervening
10458: @code{public} or @code{set-current}, @code{public}
10459: will restore the compilation word list in effect before the first of
10460: these @code{protected}s.
10461:
10462: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10463: @subsubsection Dividing classes
10464: @cindex Dividing classes
10465: @cindex @code{methods}...@code{end-methods}
10466:
10467: You may want to do the definition of methods separate from the
10468: definition of the class, its selectors, fields, and instance variables,
10469: i.e., separate the implementation from the definition. You can do this
10470: in the following way:
10471:
10472: @example
10473: graphical class
10474: inst-value radius
10475: end-class circle
10476:
10477: ... \ do some other stuff
10478:
10479: circle methods \ now we are ready
10480:
10481: m: ( x y circle -- )
10482: radius draw-circle ;m
10483: overrides draw
10484:
10485: m: ( n-radius circle -- )
10486: [to-inst] radius ;m
10487: overrides construct
10488:
10489: end-methods
10490: @end example
10491:
10492: You can use several @code{methods}...@code{end-methods} sections. The
10493: only things you can do to the class in these sections are: defining
10494: methods, and overriding the class's selectors. You must not define new
10495: selectors or fields.
10496:
10497: Note that you often have to override a selector before using it. In
10498: particular, you usually have to override @code{construct} with a new
10499: method before you can invoke @code{heap-new} and friends. E.g., you
10500: must not create a circle before the @code{overrides construct} sequence
10501: in the example above.
10502:
10503: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10504: @subsubsection Object Interfaces
10505: @cindex object interfaces
10506: @cindex interfaces for objects
10507:
10508: In this model you can only call selectors defined in the class of the
10509: receiving objects or in one of its ancestors. If you call a selector
10510: with a receiving object that is not in one of these classes, the
10511: result is undefined; if you are lucky, the program crashes
10512: immediately.
10513:
10514: @cindex selectors common to hardly-related classes
10515: Now consider the case when you want to have a selector (or several)
10516: available in two classes: You would have to add the selector to a
10517: common ancestor class, in the worst case to @code{object}. You
10518: may not want to do this, e.g., because someone else is responsible for
10519: this ancestor class.
10520:
10521: The solution for this problem is interfaces. An interface is a
10522: collection of selectors. If a class implements an interface, the
10523: selectors become available to the class and its descendents. A class
10524: can implement an unlimited number of interfaces. For the problem
10525: discussed above, we would define an interface for the selector(s), and
10526: both classes would implement the interface.
10527:
10528: As an example, consider an interface @code{storage} for
10529: writing objects to disk and getting them back, and a class
10530: @code{foo} that implements it. The code would look like this:
10531:
10532: @cindex @code{interface} usage
10533: @cindex @code{end-interface} usage
10534: @cindex @code{implementation} usage
10535: @example
10536: interface
10537: selector write ( file object -- )
10538: selector read1 ( file object -- )
10539: end-interface storage
10540:
10541: bar class
10542: storage implementation
10543:
10544: ... overrides write
10545: ... overrides read1
10546: ...
10547: end-class foo
10548: @end example
10549:
10550: @noindent
10551: (I would add a word @code{read} @i{( file -- object )} that uses
10552: @code{read1} internally, but that's beyond the point illustrated
10553: here.)
10554:
10555: Note that you cannot use @code{protected} in an interface; and
10556: of course you cannot define fields.
10557:
10558: In the Neon model, all selectors are available for all classes;
10559: therefore it does not need interfaces. The price you pay in this model
10560: is slower late binding, and therefore, added complexity to avoid late
10561: binding.
10562:
10563: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10564: @subsubsection @file{objects.fs} Implementation
10565: @cindex @file{objects.fs} implementation
10566:
10567: @cindex @code{object-map} discussion
10568: An object is a piece of memory, like one of the data structures
10569: described with @code{struct...end-struct}. It has a field
10570: @code{object-map} that points to the method map for the object's
10571: class.
10572:
10573: @cindex method map
10574: @cindex virtual function table
10575: The @emph{method map}@footnote{This is Self terminology; in C++
10576: terminology: virtual function table.} is an array that contains the
10577: execution tokens (@i{xt}s) of the methods for the object's class. Each
10578: selector contains an offset into a method map.
10579:
10580: @cindex @code{selector} implementation, class
10581: @code{selector} is a defining word that uses
10582: @code{CREATE} and @code{DOES>}. The body of the
10583: selector contains the offset; the @code{DOES>} action for a
10584: class selector is, basically:
10585:
10586: @example
10587: ( object addr ) @@ over object-map @@ + @@ execute
10588: @end example
10589:
10590: Since @code{object-map} is the first field of the object, it
10591: does not generate any code. As you can see, calling a selector has a
10592: small, constant cost.
10593:
10594: @cindex @code{current-interface} discussion
10595: @cindex class implementation and representation
10596: A class is basically a @code{struct} combined with a method
10597: map. During the class definition the alignment and size of the class
10598: are passed on the stack, just as with @code{struct}s, so
10599: @code{field} can also be used for defining class
10600: fields. However, passing more items on the stack would be
10601: inconvenient, so @code{class} builds a data structure in memory,
10602: which is accessed through the variable
10603: @code{current-interface}. After its definition is complete, the
10604: class is represented on the stack by a pointer (e.g., as parameter for
10605: a child class definition).
10606:
10607: A new class starts off with the alignment and size of its parent,
10608: and a copy of the parent's method map. Defining new fields extends the
10609: size and alignment; likewise, defining new selectors extends the
10610: method map. @code{overrides} just stores a new @i{xt} in the method
10611: map at the offset given by the selector.
10612:
10613: @cindex class binding, implementation
10614: Class binding just gets the @i{xt} at the offset given by the selector
10615: from the class's method map and @code{compile,}s (in the case of
10616: @code{[bind]}) it.
10617:
10618: @cindex @code{this} implementation
10619: @cindex @code{catch} and @code{this}
10620: @cindex @code{this} and @code{catch}
10621: I implemented @code{this} as a @code{value}. At the
10622: start of an @code{m:...;m} method the old @code{this} is
10623: stored to the return stack and restored at the end; and the object on
10624: the TOS is stored @code{TO this}. This technique has one
10625: disadvantage: If the user does not leave the method via
10626: @code{;m}, but via @code{throw} or @code{exit},
10627: @code{this} is not restored (and @code{exit} may
10628: crash). To deal with the @code{throw} problem, I have redefined
10629: @code{catch} to save and restore @code{this}; the same
10630: should be done with any word that can catch an exception. As for
10631: @code{exit}, I simply forbid it (as a replacement, there is
10632: @code{exitm}).
10633:
10634: @cindex @code{inst-var} implementation
10635: @code{inst-var} is just the same as @code{field}, with
10636: a different @code{DOES>} action:
10637: @example
10638: @@ this +
10639: @end example
10640: Similar for @code{inst-value}.
10641:
10642: @cindex class scoping implementation
10643: Each class also has a word list that contains the words defined with
10644: @code{inst-var} and @code{inst-value}, and its protected
10645: words. It also has a pointer to its parent. @code{class} pushes
10646: the word lists of the class and all its ancestors onto the search order stack,
10647: and @code{end-class} drops them.
10648:
10649: @cindex interface implementation
10650: An interface is like a class without fields, parent and protected
10651: words; i.e., it just has a method map. If a class implements an
10652: interface, its method map contains a pointer to the method map of the
10653: interface. The positive offsets in the map are reserved for class
10654: methods, therefore interface map pointers have negative
10655: offsets. Interfaces have offsets that are unique throughout the
10656: system, unlike class selectors, whose offsets are only unique for the
10657: classes where the selector is available (invokable).
10658:
10659: This structure means that interface selectors have to perform one
10660: indirection more than class selectors to find their method. Their body
10661: contains the interface map pointer offset in the class method map, and
10662: the method offset in the interface method map. The
10663: @code{does>} action for an interface selector is, basically:
10664:
10665: @example
10666: ( object selector-body )
10667: 2dup selector-interface @@ ( object selector-body object interface-offset )
10668: swap object-map @@ + @@ ( object selector-body map )
10669: swap selector-offset @@ + @@ execute
10670: @end example
10671:
10672: where @code{object-map} and @code{selector-offset} are
10673: first fields and generate no code.
10674:
10675: As a concrete example, consider the following code:
10676:
10677: @example
10678: interface
10679: selector if1sel1
10680: selector if1sel2
10681: end-interface if1
10682:
10683: object class
10684: if1 implementation
10685: selector cl1sel1
10686: cell% inst-var cl1iv1
10687:
10688: ' m1 overrides construct
10689: ' m2 overrides if1sel1
10690: ' m3 overrides if1sel2
10691: ' m4 overrides cl1sel2
10692: end-class cl1
10693:
10694: create obj1 object dict-new drop
10695: create obj2 cl1 dict-new drop
10696: @end example
10697:
10698: The data structure created by this code (including the data structure
10699: for @code{object}) is shown in the
10700: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10701: @comment TODO add this diagram..
10702:
10703: @node Objects Glossary, , Objects Implementation, Objects
10704: @subsubsection @file{objects.fs} Glossary
10705: @cindex @file{objects.fs} Glossary
10706:
10707:
10708: doc---objects-bind
10709: doc---objects-<bind>
10710: doc---objects-bind'
10711: doc---objects-[bind]
10712: doc---objects-class
10713: doc---objects-class->map
10714: doc---objects-class-inst-size
10715: doc---objects-class-override!
10716: doc---objects-class-previous
10717: doc---objects-class>order
10718: doc---objects-construct
10719: doc---objects-current'
10720: doc---objects-[current]
10721: doc---objects-current-interface
10722: doc---objects-dict-new
10723: doc---objects-end-class
10724: doc---objects-end-class-noname
10725: doc---objects-end-interface
10726: doc---objects-end-interface-noname
10727: doc---objects-end-methods
10728: doc---objects-exitm
10729: doc---objects-heap-new
10730: doc---objects-implementation
10731: doc---objects-init-object
10732: doc---objects-inst-value
10733: doc---objects-inst-var
10734: doc---objects-interface
10735: doc---objects-m:
10736: doc---objects-:m
10737: doc---objects-;m
10738: doc---objects-method
10739: doc---objects-methods
10740: doc---objects-object
10741: doc---objects-overrides
10742: doc---objects-[parent]
10743: doc---objects-print
10744: doc---objects-protected
10745: doc---objects-public
10746: doc---objects-selector
10747: doc---objects-this
10748: doc---objects-<to-inst>
10749: doc---objects-[to-inst]
10750: doc---objects-to-this
10751: doc---objects-xt-new
10752:
10753:
10754: @c -------------------------------------------------------------
10755: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10756: @subsection The @file{oof.fs} model
10757: @cindex oof
10758: @cindex object-oriented programming
10759:
10760: @cindex @file{objects.fs}
10761: @cindex @file{oof.fs}
10762:
10763: This section describes the @file{oof.fs} package.
10764:
10765: The package described in this section has been used in bigFORTH since 1991, and
10766: used for two large applications: a chromatographic system used to
10767: create new medicaments, and a graphic user interface library (MINOS).
10768:
10769: You can find a description (in German) of @file{oof.fs} in @cite{Object
10770: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10771: 10(2), 1994.
10772:
10773: @menu
10774: * Properties of the OOF model::
10775: * Basic OOF Usage::
10776: * The OOF base class::
10777: * Class Declaration::
10778: * Class Implementation::
10779: @end menu
10780:
10781: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10782: @subsubsection Properties of the @file{oof.fs} model
10783: @cindex @file{oof.fs} properties
10784:
10785: @itemize @bullet
10786: @item
10787: This model combines object oriented programming with information
10788: hiding. It helps you writing large application, where scoping is
10789: necessary, because it provides class-oriented scoping.
10790:
10791: @item
10792: Named objects, object pointers, and object arrays can be created,
10793: selector invocation uses the ``object selector'' syntax. Selector invocation
10794: to objects and/or selectors on the stack is a bit less convenient, but
10795: possible.
10796:
10797: @item
10798: Selector invocation and instance variable usage of the active object is
10799: straightforward, since both make use of the active object.
10800:
10801: @item
10802: Late binding is efficient and easy to use.
10803:
10804: @item
10805: State-smart objects parse selectors. However, extensibility is provided
10806: using a (parsing) selector @code{postpone} and a selector @code{'}.
10807:
10808: @item
10809: An implementation in ANS Forth is available.
10810:
10811: @end itemize
10812:
10813:
10814: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10815: @subsubsection Basic @file{oof.fs} Usage
10816: @cindex @file{oof.fs} usage
10817:
10818: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
10819:
10820: You can define a class for graphical objects like this:
10821:
10822: @cindex @code{class} usage
10823: @cindex @code{class;} usage
10824: @cindex @code{method} usage
10825: @example
10826: object class graphical \ "object" is the parent class
10827: method draw ( x y graphical -- )
10828: class;
10829: @end example
10830:
10831: This code defines a class @code{graphical} with an
10832: operation @code{draw}. We can perform the operation
10833: @code{draw} on any @code{graphical} object, e.g.:
10834:
10835: @example
10836: 100 100 t-rex draw
10837: @end example
10838:
10839: @noindent
10840: where @code{t-rex} is an object or object pointer, created with e.g.
10841: @code{graphical : t-rex}.
10842:
10843: @cindex abstract class
10844: How do we create a graphical object? With the present definitions,
10845: we cannot create a useful graphical object. The class
10846: @code{graphical} describes graphical objects in general, but not
10847: any concrete graphical object type (C++ users would call it an
10848: @emph{abstract class}); e.g., there is no method for the selector
10849: @code{draw} in the class @code{graphical}.
10850:
10851: For concrete graphical objects, we define child classes of the
10852: class @code{graphical}, e.g.:
10853:
10854: @example
10855: graphical class circle \ "graphical" is the parent class
10856: cell var circle-radius
10857: how:
10858: : draw ( x y -- )
10859: circle-radius @@ draw-circle ;
10860:
10861: : init ( n-radius -- (
10862: circle-radius ! ;
10863: class;
10864: @end example
10865:
10866: Here we define a class @code{circle} as a child of @code{graphical},
10867: with a field @code{circle-radius}; it defines new methods for the
10868: selectors @code{draw} and @code{init} (@code{init} is defined in
10869: @code{object}, the parent class of @code{graphical}).
10870:
10871: Now we can create a circle in the dictionary with:
10872:
10873: @example
10874: 50 circle : my-circle
10875: @end example
10876:
10877: @noindent
10878: @code{:} invokes @code{init}, thus initializing the field
10879: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10880: with:
10881:
10882: @example
10883: 100 100 my-circle draw
10884: @end example
10885:
10886: @cindex selector invocation, restrictions
10887: @cindex class definition, restrictions
10888: Note: You can only invoke a selector if the receiving object belongs to
10889: the class where the selector was defined or one of its descendents;
10890: e.g., you can invoke @code{draw} only for objects belonging to
10891: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10892: mechanism will check if you try to invoke a selector that is not
10893: defined in this class hierarchy, so you'll get an error at compilation
10894: time.
10895:
10896:
10897: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10898: @subsubsection The @file{oof.fs} base class
10899: @cindex @file{oof.fs} base class
10900:
10901: When you define a class, you have to specify a parent class. So how do
10902: you start defining classes? There is one class available from the start:
10903: @code{object}. You have to use it as ancestor for all classes. It is the
10904: only class that has no parent. Classes are also objects, except that
10905: they don't have instance variables; class manipulation such as
10906: inheritance or changing definitions of a class is handled through
10907: selectors of the class @code{object}.
10908:
10909: @code{object} provides a number of selectors:
10910:
10911: @itemize @bullet
10912: @item
10913: @code{class} for subclassing, @code{definitions} to add definitions
10914: later on, and @code{class?} to get type informations (is the class a
10915: subclass of the class passed on the stack?).
10916:
10917: doc---object-class
10918: doc---object-definitions
10919: doc---object-class?
10920:
10921:
10922: @item
10923: @code{init} and @code{dispose} as constructor and destructor of the
10924: object. @code{init} is invocated after the object's memory is allocated,
10925: while @code{dispose} also handles deallocation. Thus if you redefine
10926: @code{dispose}, you have to call the parent's dispose with @code{super
10927: dispose}, too.
10928:
10929: doc---object-init
10930: doc---object-dispose
10931:
10932:
10933: @item
10934: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10935: @code{[]} to create named and unnamed objects and object arrays or
10936: object pointers.
10937:
10938: doc---object-new
10939: doc---object-new[]
10940: doc---object-:
10941: doc---object-ptr
10942: doc---object-asptr
10943: doc---object-[]
10944:
10945:
10946: @item
10947: @code{::} and @code{super} for explicit scoping. You should use explicit
10948: scoping only for super classes or classes with the same set of instance
10949: variables. Explicitly-scoped selectors use early binding.
10950:
10951: doc---object-::
10952: doc---object-super
10953:
10954:
10955: @item
10956: @code{self} to get the address of the object
10957:
10958: doc---object-self
10959:
10960:
10961: @item
10962: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10963: pointers and instance defers.
10964:
10965: doc---object-bind
10966: doc---object-bound
10967: doc---object-link
10968: doc---object-is
10969:
10970:
10971: @item
10972: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10973: form the stack, and @code{postpone} to generate selector invocation code.
10974:
10975: doc---object-'
10976: doc---object-postpone
10977:
10978:
10979: @item
10980: @code{with} and @code{endwith} to select the active object from the
10981: stack, and enable its scope. Using @code{with} and @code{endwith}
10982: also allows you to create code using selector @code{postpone} without being
10983: trapped by the state-smart objects.
10984:
10985: doc---object-with
10986: doc---object-endwith
10987:
10988:
10989: @end itemize
10990:
10991: @node Class Declaration, Class Implementation, The OOF base class, OOF
10992: @subsubsection Class Declaration
10993: @cindex class declaration
10994:
10995: @itemize @bullet
10996: @item
10997: Instance variables
10998:
10999: doc---oof-var
11000:
11001:
11002: @item
11003: Object pointers
11004:
11005: doc---oof-ptr
11006: doc---oof-asptr
11007:
11008:
11009: @item
11010: Instance defers
11011:
11012: doc---oof-defer
11013:
11014:
11015: @item
11016: Method selectors
11017:
11018: doc---oof-early
11019: doc---oof-method
11020:
11021:
11022: @item
11023: Class-wide variables
11024:
11025: doc---oof-static
11026:
11027:
11028: @item
11029: End declaration
11030:
11031: doc---oof-how:
11032: doc---oof-class;
11033:
11034:
11035: @end itemize
11036:
11037: @c -------------------------------------------------------------
11038: @node Class Implementation, , Class Declaration, OOF
11039: @subsubsection Class Implementation
11040: @cindex class implementation
11041:
11042: @c -------------------------------------------------------------
11043: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11044: @subsection The @file{mini-oof.fs} model
11045: @cindex mini-oof
11046:
11047: Gforth's third object oriented Forth package is a 12-liner. It uses a
11048: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
11049: and reduces to the bare minimum of features. This is based on a posting
11050: of Bernd Paysan in comp.lang.forth.
11051:
11052: @menu
11053: * Basic Mini-OOF Usage::
11054: * Mini-OOF Example::
11055: * Mini-OOF Implementation::
11056: @end menu
11057:
11058: @c -------------------------------------------------------------
11059: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11060: @subsubsection Basic @file{mini-oof.fs} Usage
11061: @cindex mini-oof usage
11062:
11063: There is a base class (@code{class}, which allocates one cell for the
11064: object pointer) plus seven other words: to define a method, a variable,
11065: a class; to end a class, to resolve binding, to allocate an object and
11066: to compile a class method.
11067: @comment TODO better description of the last one
11068:
11069:
11070: doc-object
11071: doc-method
11072: doc-var
11073: doc-class
11074: doc-end-class
11075: doc-defines
11076: doc-new
11077: doc-::
11078:
11079:
11080:
11081: @c -------------------------------------------------------------
11082: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11083: @subsubsection Mini-OOF Example
11084: @cindex mini-oof example
11085:
11086: A short example shows how to use this package. This example, in slightly
11087: extended form, is supplied as @file{moof-exm.fs}
11088: @comment TODO could flesh this out with some comments from the Forthwrite article
11089:
11090: @example
11091: object class
11092: method init
11093: method draw
11094: end-class graphical
11095: @end example
11096:
11097: This code defines a class @code{graphical} with an
11098: operation @code{draw}. We can perform the operation
11099: @code{draw} on any @code{graphical} object, e.g.:
11100:
11101: @example
11102: 100 100 t-rex draw
11103: @end example
11104:
11105: where @code{t-rex} is an object or object pointer, created with e.g.
11106: @code{graphical new Constant t-rex}.
11107:
11108: For concrete graphical objects, we define child classes of the
11109: class @code{graphical}, e.g.:
11110:
11111: @example
11112: graphical class
11113: cell var circle-radius
11114: end-class circle \ "graphical" is the parent class
11115:
11116: :noname ( x y -- )
11117: circle-radius @@ draw-circle ; circle defines draw
11118: :noname ( r -- )
11119: circle-radius ! ; circle defines init
11120: @end example
11121:
11122: There is no implicit init method, so we have to define one. The creation
11123: code of the object now has to call init explicitely.
11124:
11125: @example
11126: circle new Constant my-circle
11127: 50 my-circle init
11128: @end example
11129:
11130: It is also possible to add a function to create named objects with
11131: automatic call of @code{init}, given that all objects have @code{init}
11132: on the same place:
11133:
11134: @example
11135: : new: ( .. o "name" -- )
11136: new dup Constant init ;
11137: 80 circle new: large-circle
11138: @end example
11139:
11140: We can draw this new circle at (100,100) with:
11141:
11142: @example
11143: 100 100 my-circle draw
11144: @end example
11145:
11146: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11147: @subsubsection @file{mini-oof.fs} Implementation
11148:
11149: Object-oriented systems with late binding typically use a
11150: ``vtable''-approach: the first variable in each object is a pointer to a
11151: table, which contains the methods as function pointers. The vtable
11152: may also contain other information.
11153:
11154: So first, let's declare selectors:
11155:
11156: @example
11157: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
11158: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11159: @end example
11160:
11161: During selector declaration, the number of selectors and instance
11162: variables is on the stack (in address units). @code{method} creates one
11163: selector and increments the selector number. To execute a selector, it
11164: takes the object, fetches the vtable pointer, adds the offset, and
11165: executes the method @i{xt} stored there. Each selector takes the object
11166: it is invoked with as top of stack parameter; it passes the parameters
11167: (including the object) unchanged to the appropriate method which should
11168: consume that object.
11169:
11170: Now, we also have to declare instance variables
11171:
11172: @example
11173: : var ( m v size "name" -- m v' ) Create over , +
11174: DOES> ( o -- addr ) @@ + ;
11175: @end example
11176:
11177: As before, a word is created with the current offset. Instance
11178: variables can have different sizes (cells, floats, doubles, chars), so
11179: all we do is take the size and add it to the offset. If your machine
11180: has alignment restrictions, put the proper @code{aligned} or
11181: @code{faligned} before the variable, to adjust the variable
11182: offset. That's why it is on the top of stack.
11183:
11184: We need a starting point (the base object) and some syntactic sugar:
11185:
11186: @example
11187: Create object 1 cells , 2 cells ,
11188: : class ( class -- class selectors vars ) dup 2@@ ;
11189: @end example
11190:
11191: For inheritance, the vtable of the parent object has to be
11192: copied when a new, derived class is declared. This gives all the
11193: methods of the parent class, which can be overridden, though.
11194:
11195: @example
11196: : end-class ( class selectors vars "name" -- )
11197: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11198: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11199: @end example
11200:
11201: The first line creates the vtable, initialized with
11202: @code{noop}s. The second line is the inheritance mechanism, it
11203: copies the xts from the parent vtable.
11204:
11205: We still have no way to define new methods, let's do that now:
11206:
11207: @example
11208: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11209: @end example
11210:
11211: To allocate a new object, we need a word, too:
11212:
11213: @example
11214: : new ( class -- o ) here over @@ allot swap over ! ;
11215: @end example
11216:
11217: Sometimes derived classes want to access the method of the
11218: parent object. There are two ways to achieve this with Mini-OOF:
11219: first, you could use named words, and second, you could look up the
11220: vtable of the parent object.
11221:
11222: @example
11223: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11224: @end example
11225:
11226:
11227: Nothing can be more confusing than a good example, so here is
11228: one. First let's declare a text object (called
11229: @code{button}), that stores text and position:
11230:
11231: @example
11232: object class
11233: cell var text
11234: cell var len
11235: cell var x
11236: cell var y
11237: method init
11238: method draw
11239: end-class button
11240: @end example
11241:
11242: @noindent
11243: Now, implement the two methods, @code{draw} and @code{init}:
11244:
11245: @example
11246: :noname ( o -- )
11247: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11248: button defines draw
11249: :noname ( addr u o -- )
11250: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11251: button defines init
11252: @end example
11253:
11254: @noindent
11255: To demonstrate inheritance, we define a class @code{bold-button}, with no
11256: new data and no new selectors:
11257:
11258: @example
11259: button class
11260: end-class bold-button
11261:
11262: : bold 27 emit ." [1m" ;
11263: : normal 27 emit ." [0m" ;
11264: @end example
11265:
11266: @noindent
11267: The class @code{bold-button} has a different draw method to
11268: @code{button}, but the new method is defined in terms of the draw method
11269: for @code{button}:
11270:
11271: @example
11272: :noname bold [ button :: draw ] normal ; bold-button defines draw
11273: @end example
11274:
11275: @noindent
11276: Finally, create two objects and apply selectors:
11277:
11278: @example
11279: button new Constant foo
11280: s" thin foo" foo init
11281: page
11282: foo draw
11283: bold-button new Constant bar
11284: s" fat bar" bar init
11285: 1 bar y !
11286: bar draw
11287: @end example
11288:
11289:
11290: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11291: @subsection Comparison with other object models
11292: @cindex comparison of object models
11293: @cindex object models, comparison
11294:
11295: Many object-oriented Forth extensions have been proposed (@cite{A survey
11296: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11297: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11298: relation of the object models described here to two well-known and two
11299: closely-related (by the use of method maps) models. Andras Zsoter
11300: helped us with this section.
11301:
11302: @cindex Neon model
11303: The most popular model currently seems to be the Neon model (see
11304: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11305: 1997) by Andrew McKewan) but this model has a number of limitations
11306: @footnote{A longer version of this critique can be
11307: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11308: Dimensions, May 1997) by Anton Ertl.}:
11309:
11310: @itemize @bullet
11311: @item
11312: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11313: to pass objects on the stack.
11314:
11315: @item
11316: It requires that the selector parses the input stream (at
11317: compile time); this leads to reduced extensibility and to bugs that are
11318: hard to find.
11319:
11320: @item
11321: It allows using every selector on every object; this eliminates the
11322: need for interfaces, but makes it harder to create efficient
11323: implementations.
11324: @end itemize
11325:
11326: @cindex Pountain's object-oriented model
11327: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11328: Press, London, 1987) by Dick Pountain. However, it is not really about
11329: object-oriented programming, because it hardly deals with late
11330: binding. Instead, it focuses on features like information hiding and
11331: overloading that are characteristic of modular languages like Ada (83).
11332:
11333: @cindex Zsoter's object-oriented model
11334: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11335: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11336: describes a model that makes heavy use of an active object (like
11337: @code{this} in @file{objects.fs}): The active object is not only used
11338: for accessing all fields, but also specifies the receiving object of
11339: every selector invocation; you have to change the active object
11340: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11341: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11342: the method entry point is unnecessary with Zsoter's model, because the
11343: receiving object is the active object already. On the other hand, the
11344: explicit change is absolutely necessary in that model, because otherwise
11345: no one could ever change the active object. An ANS Forth implementation
11346: of this model is available through
11347: @uref{http://www.forth.org/oopf.html}.
11348:
11349: @cindex @file{oof.fs}, differences to other models
11350: The @file{oof.fs} model combines information hiding and overloading
11351: resolution (by keeping names in various word lists) with object-oriented
11352: programming. It sets the active object implicitly on method entry, but
11353: also allows explicit changing (with @code{>o...o>} or with
11354: @code{with...endwith}). It uses parsing and state-smart objects and
11355: classes for resolving overloading and for early binding: the object or
11356: class parses the selector and determines the method from this. If the
11357: selector is not parsed by an object or class, it performs a call to the
11358: selector for the active object (late binding), like Zsoter's model.
11359: Fields are always accessed through the active object. The big
11360: disadvantage of this model is the parsing and the state-smartness, which
11361: reduces extensibility and increases the opportunities for subtle bugs;
11362: essentially, you are only safe if you never tick or @code{postpone} an
11363: object or class (Bernd disagrees, but I (Anton) am not convinced).
11364:
11365: @cindex @file{mini-oof.fs}, differences to other models
11366: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11367: version of the @file{objects.fs} model, but syntactically it is a
11368: mixture of the @file{objects.fs} and @file{oof.fs} models.
11369:
11370:
11371: @c -------------------------------------------------------------
11372: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11373: @section Programming Tools
11374: @cindex programming tools
11375:
11376: @c !! move this and assembler down below OO stuff.
11377:
11378: @menu
11379: * Examining::
11380: * Forgetting words::
11381: * Debugging:: Simple and quick.
11382: * Assertions:: Making your programs self-checking.
11383: * Singlestep Debugger:: Executing your program word by word.
11384: @end menu
11385:
11386: @node Examining, Forgetting words, Programming Tools, Programming Tools
11387: @subsection Examining data and code
11388: @cindex examining data and code
11389: @cindex data examination
11390: @cindex code examination
11391:
11392: The following words inspect the stack non-destructively:
11393:
11394: doc-.s
11395: doc-f.s
11396:
11397: There is a word @code{.r} but it does @i{not} display the return stack!
11398: It is used for formatted numeric output (@pxref{Simple numeric output}).
11399:
11400: doc-depth
11401: doc-fdepth
11402: doc-clearstack
11403:
11404: The following words inspect memory.
11405:
11406: doc-?
11407: doc-dump
11408:
11409: And finally, @code{see} allows to inspect code:
11410:
11411: doc-see
11412: doc-xt-see
11413:
11414: @node Forgetting words, Debugging, Examining, Programming Tools
11415: @subsection Forgetting words
11416: @cindex words, forgetting
11417: @cindex forgeting words
11418:
11419: @c anton: other, maybe better places for this subsection: Defining Words;
11420: @c Dictionary allocation. At least a reference should be there.
11421:
11422: Forth allows you to forget words (and everything that was alloted in the
11423: dictonary after them) in a LIFO manner.
11424:
11425: doc-marker
11426:
11427: The most common use of this feature is during progam development: when
11428: you change a source file, forget all the words it defined and load it
11429: again (since you also forget everything defined after the source file
11430: was loaded, you have to reload that, too). Note that effects like
11431: storing to variables and destroyed system words are not undone when you
11432: forget words. With a system like Gforth, that is fast enough at
11433: starting up and compiling, I find it more convenient to exit and restart
11434: Gforth, as this gives me a clean slate.
11435:
11436: Here's an example of using @code{marker} at the start of a source file
11437: that you are debugging; it ensures that you only ever have one copy of
11438: the file's definitions compiled at any time:
11439:
11440: @example
11441: [IFDEF] my-code
11442: my-code
11443: [ENDIF]
11444:
11445: marker my-code
11446: init-included-files
11447:
11448: \ .. definitions start here
11449: \ .
11450: \ .
11451: \ end
11452: @end example
11453:
11454:
11455: @node Debugging, Assertions, Forgetting words, Programming Tools
11456: @subsection Debugging
11457: @cindex debugging
11458:
11459: Languages with a slow edit/compile/link/test development loop tend to
11460: require sophisticated tracing/stepping debuggers to facilate debugging.
11461:
11462: A much better (faster) way in fast-compiling languages is to add
11463: printing code at well-selected places, let the program run, look at
11464: the output, see where things went wrong, add more printing code, etc.,
11465: until the bug is found.
11466:
11467: The simple debugging aids provided in @file{debugs.fs}
11468: are meant to support this style of debugging.
11469:
11470: The word @code{~~} prints debugging information (by default the source
11471: location and the stack contents). It is easy to insert. If you use Emacs
11472: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11473: query-replace them with nothing). The deferred words
11474: @code{printdebugdata} and @code{printdebugline} control the output of
11475: @code{~~}. The default source location output format works well with
11476: Emacs' compilation mode, so you can step through the program at the
11477: source level using @kbd{C-x `} (the advantage over a stepping debugger
11478: is that you can step in any direction and you know where the crash has
11479: happened or where the strange data has occurred).
11480:
11481: doc-~~
11482: doc-printdebugdata
11483: doc-printdebugline
11484:
11485: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11486: @subsection Assertions
11487: @cindex assertions
11488:
11489: It is a good idea to make your programs self-checking, especially if you
11490: make an assumption that may become invalid during maintenance (for
11491: example, that a certain field of a data structure is never zero). Gforth
11492: supports @dfn{assertions} for this purpose. They are used like this:
11493:
11494: @example
11495: assert( @i{flag} )
11496: @end example
11497:
11498: The code between @code{assert(} and @code{)} should compute a flag, that
11499: should be true if everything is alright and false otherwise. It should
11500: not change anything else on the stack. The overall stack effect of the
11501: assertion is @code{( -- )}. E.g.
11502:
11503: @example
11504: assert( 1 1 + 2 = ) \ what we learn in school
11505: assert( dup 0<> ) \ assert that the top of stack is not zero
11506: assert( false ) \ this code should not be reached
11507: @end example
11508:
11509: The need for assertions is different at different times. During
11510: debugging, we want more checking, in production we sometimes care more
11511: for speed. Therefore, assertions can be turned off, i.e., the assertion
11512: becomes a comment. Depending on the importance of an assertion and the
11513: time it takes to check it, you may want to turn off some assertions and
11514: keep others turned on. Gforth provides several levels of assertions for
11515: this purpose:
11516:
11517:
11518: doc-assert0(
11519: doc-assert1(
11520: doc-assert2(
11521: doc-assert3(
11522: doc-assert(
11523: doc-)
11524:
11525:
11526: The variable @code{assert-level} specifies the highest assertions that
11527: are turned on. I.e., at the default @code{assert-level} of one,
11528: @code{assert0(} and @code{assert1(} assertions perform checking, while
11529: @code{assert2(} and @code{assert3(} assertions are treated as comments.
11530:
11531: The value of @code{assert-level} is evaluated at compile-time, not at
11532: run-time. Therefore you cannot turn assertions on or off at run-time;
11533: you have to set the @code{assert-level} appropriately before compiling a
11534: piece of code. You can compile different pieces of code at different
11535: @code{assert-level}s (e.g., a trusted library at level 1 and
11536: newly-written code at level 3).
11537:
11538:
11539: doc-assert-level
11540:
11541:
11542: If an assertion fails, a message compatible with Emacs' compilation mode
11543: is produced and the execution is aborted (currently with @code{ABORT"}.
11544: If there is interest, we will introduce a special throw code. But if you
11545: intend to @code{catch} a specific condition, using @code{throw} is
11546: probably more appropriate than an assertion).
11547:
11548: Definitions in ANS Forth for these assertion words are provided
11549: in @file{compat/assert.fs}.
11550:
11551:
11552: @node Singlestep Debugger, , Assertions, Programming Tools
11553: @subsection Singlestep Debugger
11554: @cindex singlestep Debugger
11555: @cindex debugging Singlestep
11556:
11557: When you create a new word there's often the need to check whether it
11558: behaves correctly or not. You can do this by typing @code{dbg
11559: badword}. A debug session might look like this:
11560:
11561: @example
11562: : badword 0 DO i . LOOP ; ok
11563: 2 dbg badword
11564: : badword
11565: Scanning code...
11566:
11567: Nesting debugger ready!
11568:
11569: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11570: 400D4740 8049F68 DO -> [ 0 ]
11571: 400D4744 804A0C8 i -> [ 1 ] 00000
11572: 400D4748 400C5E60 . -> 0 [ 0 ]
11573: 400D474C 8049D0C LOOP -> [ 0 ]
11574: 400D4744 804A0C8 i -> [ 1 ] 00001
11575: 400D4748 400C5E60 . -> 1 [ 0 ]
11576: 400D474C 8049D0C LOOP -> [ 0 ]
11577: 400D4758 804B384 ; -> ok
11578: @end example
11579:
11580: Each line displayed is one step. You always have to hit return to
11581: execute the next word that is displayed. If you don't want to execute
11582: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11583: an overview what keys are available:
11584:
11585: @table @i
11586:
11587: @item @key{RET}
11588: Next; Execute the next word.
11589:
11590: @item n
11591: Nest; Single step through next word.
11592:
11593: @item u
11594: Unnest; Stop debugging and execute rest of word. If we got to this word
11595: with nest, continue debugging with the calling word.
11596:
11597: @item d
11598: Done; Stop debugging and execute rest.
11599:
11600: @item s
11601: Stop; Abort immediately.
11602:
11603: @end table
11604:
11605: Debugging large application with this mechanism is very difficult, because
11606: you have to nest very deeply into the program before the interesting part
11607: begins. This takes a lot of time.
11608:
11609: To do it more directly put a @code{BREAK:} command into your source code.
11610: When program execution reaches @code{BREAK:} the single step debugger is
11611: invoked and you have all the features described above.
11612:
11613: If you have more than one part to debug it is useful to know where the
11614: program has stopped at the moment. You can do this by the
11615: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11616: string is typed out when the ``breakpoint'' is reached.
11617:
11618:
11619: doc-dbg
11620: doc-break:
11621: doc-break"
11622:
11623:
11624:
11625: @c -------------------------------------------------------------
11626: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11627: @section Assembler and Code Words
11628: @cindex assembler
11629: @cindex code words
11630:
11631: @menu
11632: * Code and ;code::
11633: * Common Assembler:: Assembler Syntax
11634: * Common Disassembler::
11635: * 386 Assembler:: Deviations and special cases
11636: * Alpha Assembler:: Deviations and special cases
11637: * MIPS assembler:: Deviations and special cases
11638: * Other assemblers:: How to write them
11639: @end menu
11640:
11641: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11642: @subsection @code{Code} and @code{;code}
11643:
11644: Gforth provides some words for defining primitives (words written in
11645: machine code), and for defining the machine-code equivalent of
11646: @code{DOES>}-based defining words. However, the machine-independent
11647: nature of Gforth poses a few problems: First of all, Gforth runs on
11648: several architectures, so it can provide no standard assembler. What's
11649: worse is that the register allocation not only depends on the processor,
11650: but also on the @code{gcc} version and options used.
11651:
11652: The words that Gforth offers encapsulate some system dependences (e.g.,
11653: the header structure), so a system-independent assembler may be used in
11654: Gforth. If you do not have an assembler, you can compile machine code
11655: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11656: because these words emit stuff in @i{data} space; it works because
11657: Gforth has unified code/data spaces. Assembler isn't likely to be
11658: portable anyway.}.
11659:
11660:
11661: doc-assembler
11662: doc-init-asm
11663: doc-code
11664: doc-end-code
11665: doc-;code
11666: doc-flush-icache
11667:
11668:
11669: If @code{flush-icache} does not work correctly, @code{code} words
11670: etc. will not work (reliably), either.
11671:
11672: The typical usage of these @code{code} words can be shown most easily by
11673: analogy to the equivalent high-level defining words:
11674:
11675: @example
11676: : foo code foo
11677: <high-level Forth words> <assembler>
11678: ; end-code
11679:
11680: : bar : bar
11681: <high-level Forth words> <high-level Forth words>
11682: CREATE CREATE
11683: <high-level Forth words> <high-level Forth words>
11684: DOES> ;code
11685: <high-level Forth words> <assembler>
11686: ; end-code
11687: @end example
11688:
11689: @c anton: the following stuff is also in "Common Assembler", in less detail.
11690:
11691: @cindex registers of the inner interpreter
11692: In the assembly code you will want to refer to the inner interpreter's
11693: registers (e.g., the data stack pointer) and you may want to use other
11694: registers for temporary storage. Unfortunately, the register allocation
11695: is installation-dependent.
11696:
11697: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
11698: (return stack pointer) are in different places in @code{gforth} and
11699: @code{gforth-fast}. This means that you cannot write a @code{NEXT}
11700: routine that works on both versions; so for doing @code{NEXT}, I
11701: recomment jumping to @code{' noop >code-address}, which contains nothing
11702: but a @code{NEXT}.
11703:
11704: For general accesses to the inner interpreter's registers, the easiest
11705: solution is to use explicit register declarations (@pxref{Explicit Reg
11706: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11707: all of the inner interpreter's registers: You have to compile Gforth
11708: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11709: the appropriate declarations must be present in the @code{machine.h}
11710: file (see @code{mips.h} for an example; you can find a full list of all
11711: declarable register symbols with @code{grep register engine.c}). If you
11712: give explicit registers to all variables that are declared at the
11713: beginning of @code{engine()}, you should be able to use the other
11714: caller-saved registers for temporary storage. Alternatively, you can use
11715: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11716: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11717: reserve a register (however, this restriction on register allocation may
11718: slow Gforth significantly).
11719:
11720: If this solution is not viable (e.g., because @code{gcc} does not allow
11721: you to explicitly declare all the registers you need), you have to find
11722: out by looking at the code where the inner interpreter's registers
11723: reside and which registers can be used for temporary storage. You can
11724: get an assembly listing of the engine's code with @code{make engine.s}.
11725:
11726: In any case, it is good practice to abstract your assembly code from the
11727: actual register allocation. E.g., if the data stack pointer resides in
11728: register @code{$17}, create an alias for this register called @code{sp},
11729: and use that in your assembly code.
11730:
11731: @cindex code words, portable
11732: Another option for implementing normal and defining words efficiently
11733: is to add the desired functionality to the source of Gforth. For normal
11734: words you just have to edit @file{primitives} (@pxref{Automatic
11735: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11736: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11737: @file{prims2x.fs}, and possibly @file{cross.fs}.
11738:
11739: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11740: @subsection Common Assembler
11741:
11742: The assemblers in Gforth generally use a postfix syntax, i.e., the
11743: instruction name follows the operands.
11744:
11745: The operands are passed in the usual order (the same that is used in the
11746: manual of the architecture). Since they all are Forth words, they have
11747: to be separated by spaces; you can also use Forth words to compute the
11748: operands.
11749:
11750: The instruction names usually end with a @code{,}. This makes it easier
11751: to visually separate instructions if you put several of them on one
11752: line; it also avoids shadowing other Forth words (e.g., @code{and}).
11753:
11754: Registers are usually specified by number; e.g., (decimal) @code{11}
11755: specifies registers R11 and F11 on the Alpha architecture (which one,
11756: depends on the instruction). The usual names are also available, e.g.,
11757: @code{s2} for R11 on Alpha.
11758:
11759: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11760: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11761: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11762: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
11763: conditions are specified in a way specific to each assembler.
11764:
11765: Note that the register assignments of the Gforth engine can change
11766: between Gforth versions, or even between different compilations of the
11767: same Gforth version (e.g., if you use a different GCC version). So if
11768: you want to refer to Gforth's registers (e.g., the stack pointer or
11769: TOS), I recommend defining your own words for refering to these
11770: registers, and using them later on; then you can easily adapt to a
11771: changed register assignment. The stability of the register assignment
11772: is usually better if you build Gforth with @code{--enable-force-reg}.
11773:
11774: In particular, the return stack pointer and the instruction pointer are
11775: in memory in @code{gforth}, and usually in registers in
11776: @code{gforth-fast}. The most common use of these registers is to
11777: dispatch to the next word (the @code{next} routine). A portable way to
11778: do this is to jump to @code{' noop >code-address} (of course, this is
11779: less efficient than integrating the @code{next} code and scheduling it
11780: well).
11781:
11782: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11783: @subsection Common Disassembler
11784:
11785: You can disassemble a @code{code} word with @code{see}
11786: (@pxref{Debugging}). You can disassemble a section of memory with
11787:
11788: doc-disasm
11789:
11790: The disassembler generally produces output that can be fed into the
11791: assembler (i.e., same syntax, etc.). It also includes additional
11792: information in comments. In particular, the address of the instruction
11793: is given in a comment before the instruction.
11794:
11795: @code{See} may display more or less than the actual code of the word,
11796: because the recognition of the end of the code is unreliable. You can
11797: use @code{disasm} if it did not display enough. It may display more, if
11798: the code word is not immediately followed by a named word. If you have
11799: something else there, you can follow the word with @code{align last @ ,}
11800: to ensure that the end is recognized.
11801:
11802: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11803: @subsection 386 Assembler
11804:
11805: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11806: available under GPL, and originally part of bigFORTH.
11807:
11808: The 386 disassembler included in Gforth was written by Andrew McKewan
11809: and is in the public domain.
11810:
11811: The disassembler displays code in prefix Intel syntax.
11812:
11813: The assembler uses a postfix syntax with reversed parameters.
11814:
11815: The assembler includes all instruction of the Athlon, i.e. 486 core
11816: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11817: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11818: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
11819:
11820: There are several prefixes to switch between different operation sizes,
11821: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11822: double-word accesses. Addressing modes can be switched with @code{.wa}
11823: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11824: need a prefix for byte register names (@code{AL} et al).
11825:
11826: For floating point operations, the prefixes are @code{.fs} (IEEE
11827: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11828: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
11829:
11830: The MMX opcodes don't have size prefixes, they are spelled out like in
11831: the Intel assembler. Instead of move from and to memory, there are
11832: PLDQ/PLDD and PSTQ/PSTD.
11833:
11834: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11835: ax. Immediate values are indicated by postfixing them with @code{#},
11836: e.g., @code{3 #}. Here are some examples of addressing modes:
11837:
11838: @example
11839: 3 # \ immediate
11840: 1000 #) \ absolute
11841: ax \ register
11842: 100 di d) \ 100[edi]
11843: 4 bx cx di) \ 4[ebx][ecx]
11844: di ax *4 i) \ [edi][eax*4]
11845: 20 ax *4 i#) \ 20[eax*4]
11846: @end example
11847:
11848: Some example of instructions are:
11849:
11850: @example
11851: ax bx mov \ move ebx,eax
11852: 3 # ax mov \ mov eax,3
11853: 100 di ) ax mov \ mov eax,100[edi]
11854: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
11855: .w ax bx mov \ mov bx,ax
11856: @end example
11857:
11858: The following forms are supported for binary instructions:
11859:
11860: @example
11861: <reg> <reg> <inst>
11862: <n> # <reg> <inst>
11863: <mem> <reg> <inst>
11864: <reg> <mem> <inst>
11865: @end example
11866:
11867: Immediate to memory is not supported. The shift/rotate syntax is:
11868:
11869: @example
11870: <reg/mem> 1 # shl \ shortens to shift without immediate
11871: <reg/mem> 4 # shl
11872: <reg/mem> cl shl
11873: @end example
11874:
11875: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11876: the byte version.
11877:
11878: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11879: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11880: pc < >= <= >}. (Note that most of these words shadow some Forth words
11881: when @code{assembler} is in front of @code{forth} in the search path,
11882: e.g., in @code{code} words). Currently the control structure words use
11883: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11884: to shuffle them (you can also use @code{swap} etc.).
11885:
11886: Here is an example of a @code{code} word (assumes that the stack pointer
11887: is in esi and the TOS is in ebx):
11888:
11889: @example
11890: code my+ ( n1 n2 -- n )
11891: 4 si D) bx add
11892: 4 # si add
11893: Next
11894: end-code
11895: @end example
11896:
11897: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11898: @subsection Alpha Assembler
11899:
11900: The Alpha assembler and disassembler were originally written by Bernd
11901: Thallner.
11902:
11903: The register names @code{a0}--@code{a5} are not available to avoid
11904: shadowing hex numbers.
11905:
11906: Immediate forms of arithmetic instructions are distinguished by a
11907: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11908: does not count as arithmetic instruction).
11909:
11910: You have to specify all operands to an instruction, even those that
11911: other assemblers consider optional, e.g., the destination register for
11912: @code{br,}, or the destination register and hint for @code{jmp,}.
11913:
11914: You can specify conditions for @code{if,} by removing the first @code{b}
11915: and the trailing @code{,} from a branch with a corresponding name; e.g.,
11916:
11917: @example
11918: 11 fgt if, \ if F11>0e
11919: ...
11920: endif,
11921: @end example
11922:
11923: @code{fbgt,} gives @code{fgt}.
11924:
11925: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11926: @subsection MIPS assembler
11927:
11928: The MIPS assembler was originally written by Christian Pirker.
11929:
11930: Currently the assembler and disassembler only cover the MIPS-I
11931: architecture (R3000), and don't support FP instructions.
11932:
11933: The register names @code{$a0}--@code{$a3} are not available to avoid
11934: shadowing hex numbers.
11935:
11936: Because there is no way to distinguish registers from immediate values,
11937: you have to explicitly use the immediate forms of instructions, i.e.,
11938: @code{addiu,}, not just @code{addu,} (@command{as} does this
11939: implicitly).
11940:
11941: If the architecture manual specifies several formats for the instruction
11942: (e.g., for @code{jalr,}), you usually have to use the one with more
11943: arguments (i.e., two for @code{jalr,}). When in doubt, see
11944: @code{arch/mips/testasm.fs} for an example of correct use.
11945:
11946: Branches and jumps in the MIPS architecture have a delay slot. You have
11947: to fill it yourself (the simplest way is to use @code{nop,}), the
11948: assembler does not do it for you (unlike @command{as}). Even
11949: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
11950: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
11951: and @code{then,} just specify branch targets, they are not affected.
11952:
11953: Note that you must not put branches, jumps, or @code{li,} into the delay
11954: slot: @code{li,} may expand to several instructions, and control flow
11955: instructions may not be put into the branch delay slot in any case.
11956:
11957: For branches the argument specifying the target is a relative address;
11958: You have to add the address of the delay slot to get the absolute
11959: address.
11960:
11961: The MIPS architecture also has load delay slots and restrictions on
11962: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
11963: yourself to satisfy these restrictions, the assembler does not do it for
11964: you.
11965:
11966: You can specify the conditions for @code{if,} etc. by taking a
11967: conditional branch and leaving away the @code{b} at the start and the
11968: @code{,} at the end. E.g.,
11969:
11970: @example
11971: 4 5 eq if,
11972: ... \ do something if $4 equals $5
11973: then,
11974: @end example
11975:
11976: @node Other assemblers, , MIPS assembler, Assembler and Code Words
11977: @subsection Other assemblers
11978:
11979: If you want to contribute another assembler/disassembler, please contact
11980: us (@email{bug-gforth@@gnu.org}) to check if we have such an assembler
11981: already. If you are writing them from scratch, please use a similar
11982: syntax style as the one we use (i.e., postfix, commas at the end of the
11983: instruction names, @pxref{Common Assembler}); make the output of the
11984: disassembler be valid input for the assembler, and keep the style
11985: similar to the style we used.
11986:
11987: Hints on implementation: The most important part is to have a good test
11988: suite that contains all instructions. Once you have that, the rest is
11989: easy. For actual coding you can take a look at
11990: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
11991: the assembler and disassembler, avoiding redundancy and some potential
11992: bugs. You can also look at that file (and @pxref{Advanced does> usage
11993: example}) to get ideas how to factor a disassembler.
11994:
11995: Start with the disassembler, because it's easier to reuse data from the
11996: disassembler for the assembler than the other way round.
11997:
11998: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
11999: how simple it can be.
12000:
12001: @c -------------------------------------------------------------
12002: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12003: @section Threading Words
12004: @cindex threading words
12005:
12006: @cindex code address
12007: These words provide access to code addresses and other threading stuff
12008: in Gforth (and, possibly, other interpretive Forths). It more or less
12009: abstracts away the differences between direct and indirect threading
12010: (and, for direct threading, the machine dependences). However, at
12011: present this wordset is still incomplete. It is also pretty low-level;
12012: some day it will hopefully be made unnecessary by an internals wordset
12013: that abstracts implementation details away completely.
12014:
12015: The terminology used here stems from indirect threaded Forth systems; in
12016: such a system, the XT of a word is represented by the CFA (code field
12017: address) of a word; the CFA points to a cell that contains the code
12018: address. The code address is the address of some machine code that
12019: performs the run-time action of invoking the word (e.g., the
12020: @code{dovar:} routine pushes the address of the body of the word (a
12021: variable) on the stack
12022: ).
12023:
12024: @cindex code address
12025: @cindex code field address
12026: In an indirect threaded Forth, you can get the code address of @i{name}
12027: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12028: >code-address}, independent of the threading method.
12029:
12030: doc-threading-method
12031: doc->code-address
12032: doc-code-address!
12033:
12034: @cindex @code{does>}-handler
12035: @cindex @code{does>}-code
12036: For a word defined with @code{DOES>}, the code address usually points to
12037: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12038: routine (in Gforth on some platforms, it can also point to the dodoes
12039: routine itself). What you are typically interested in, though, is
12040: whether a word is a @code{DOES>}-defined word, and what Forth code it
12041: executes; @code{>does-code} tells you that.
12042:
12043: doc->does-code
12044:
12045: To create a @code{DOES>}-defined word with the following basic words,
12046: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12047: @code{/does-handler} aus behind you have to place your executable Forth
12048: code. Finally you have to create a word and modify its behaviour with
12049: @code{does-handler!}.
12050:
12051: doc-does-code!
12052: doc-does-handler!
12053: doc-/does-handler
12054:
12055: The code addresses produced by various defining words are produced by
12056: the following words:
12057:
12058: doc-docol:
12059: doc-docon:
12060: doc-dovar:
12061: doc-douser:
12062: doc-dodefer:
12063: doc-dofield:
12064:
12065: @c -------------------------------------------------------------
12066: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
12067: @section Passing Commands to the Operating System
12068: @cindex operating system - passing commands
12069: @cindex shell commands
12070:
12071: Gforth allows you to pass an arbitrary string to the host operating
12072: system shell (if such a thing exists) for execution.
12073:
12074:
12075: doc-sh
12076: doc-system
12077: doc-$?
12078: doc-getenv
12079:
12080:
12081: @c -------------------------------------------------------------
12082: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12083: @section Keeping track of Time
12084: @cindex time-related words
12085:
12086: doc-ms
12087: doc-time&date
12088: doc-utime
12089: doc-cputime
12090:
12091:
12092: @c -------------------------------------------------------------
12093: @node Miscellaneous Words, , Keeping track of Time, Words
12094: @section Miscellaneous Words
12095: @cindex miscellaneous words
12096:
12097: @comment TODO find homes for these
12098:
12099: These section lists the ANS Forth words that are not documented
12100: elsewhere in this manual. Ultimately, they all need proper homes.
12101:
12102: doc-quit
12103:
12104: The following ANS Forth words are not currently supported by Gforth
12105: (@pxref{ANS conformance}):
12106:
12107: @code{EDITOR}
12108: @code{EMIT?}
12109: @code{FORGET}
12110:
12111: @c ******************************************************************
12112: @node Error messages, Tools, Words, Top
12113: @chapter Error messages
12114: @cindex error messages
12115: @cindex backtrace
12116:
12117: A typical Gforth error message looks like this:
12118:
12119: @example
12120: in file included from \evaluated string/:-1
12121: in file included from ./yyy.fs:1
12122: ./xxx.fs:4: Invalid memory address
12123: bar
12124: ^^^
12125: Backtrace:
12126: $400E664C @@
12127: $400E6664 foo
12128: @end example
12129:
12130: The message identifying the error is @code{Invalid memory address}. The
12131: error happened when text-interpreting line 4 of the file
12132: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12133: word on the line where the error happened, is pointed out (with
12134: @code{^^^}).
12135:
12136: The file containing the error was included in line 1 of @file{./yyy.fs},
12137: and @file{yyy.fs} was included from a non-file (in this case, by giving
12138: @file{yyy.fs} as command-line parameter to Gforth).
12139:
12140: At the end of the error message you find a return stack dump that can be
12141: interpreted as a backtrace (possibly empty). On top you find the top of
12142: the return stack when the @code{throw} happened, and at the bottom you
12143: find the return stack entry just above the return stack of the topmost
12144: text interpreter.
12145:
12146: To the right of most return stack entries you see a guess for the word
12147: that pushed that return stack entry as its return address. This gives a
12148: backtrace. In our case we see that @code{bar} called @code{foo}, and
12149: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12150: address} exception).
12151:
12152: Note that the backtrace is not perfect: We don't know which return stack
12153: entries are return addresses (so we may get false positives); and in
12154: some cases (e.g., for @code{abort"}) we cannot determine from the return
12155: address the word that pushed the return address, so for some return
12156: addresses you see no names in the return stack dump.
12157:
12158: @cindex @code{catch} and backtraces
12159: The return stack dump represents the return stack at the time when a
12160: specific @code{throw} was executed. In programs that make use of
12161: @code{catch}, it is not necessarily clear which @code{throw} should be
12162: used for the return stack dump (e.g., consider one @code{throw} that
12163: indicates an error, which is caught, and during recovery another error
12164: happens; which @code{throw} should be used for the stack dump?). Gforth
12165: presents the return stack dump for the first @code{throw} after the last
12166: executed (not returned-to) @code{catch}; this works well in the usual
12167: case.
12168:
12169: @cindex @code{gforth-fast} and backtraces
12170: @cindex @code{gforth-fast}, difference from @code{gforth}
12171: @cindex backtraces with @code{gforth-fast}
12172: @cindex return stack dump with @code{gforth-fast}
12173: @code{Gforth} is able to do a return stack dump for throws generated
12174: from primitives (e.g., invalid memory address, stack empty etc.);
12175: @code{gforth-fast} is only able to do a return stack dump from a
12176: directly called @code{throw} (including @code{abort} etc.). This is the
12177: only difference (apart from a speed factor of between 1.15 (K6-2) and
12178: 2 (21264)) between @code{gforth} and @code{gforth-fast}. Given an
12179: exception caused by a primitive in @code{gforth-fast}, you will
12180: typically see no return stack dump at all; however, if the exception is
12181: caught by @code{catch} (e.g., for restoring some state), and then
12182: @code{throw}n again, the return stack dump will be for the first such
12183: @code{throw}.
12184:
12185: @c ******************************************************************
12186: @node Tools, ANS conformance, Error messages, Top
12187: @chapter Tools
12188:
12189: @menu
12190: * ANS Report:: Report the words used, sorted by wordset.
12191: @end menu
12192:
12193: See also @ref{Emacs and Gforth}.
12194:
12195: @node ANS Report, , Tools, Tools
12196: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12197: @cindex @file{ans-report.fs}
12198: @cindex report the words used in your program
12199: @cindex words used in your program
12200:
12201: If you want to label a Forth program as ANS Forth Program, you must
12202: document which wordsets the program uses; for extension wordsets, it is
12203: helpful to list the words the program requires from these wordsets
12204: (because Forth systems are allowed to provide only some words of them).
12205:
12206: The @file{ans-report.fs} tool makes it easy for you to determine which
12207: words from which wordset and which non-ANS words your application
12208: uses. You simply have to include @file{ans-report.fs} before loading the
12209: program you want to check. After loading your program, you can get the
12210: report with @code{print-ans-report}. A typical use is to run this as
12211: batch job like this:
12212: @example
12213: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12214: @end example
12215:
12216: The output looks like this (for @file{compat/control.fs}):
12217: @example
12218: The program uses the following words
12219: from CORE :
12220: : POSTPONE THEN ; immediate ?dup IF 0=
12221: from BLOCK-EXT :
12222: \
12223: from FILE :
12224: (
12225: @end example
12226:
12227: @subsection Caveats
12228:
12229: Note that @file{ans-report.fs} just checks which words are used, not whether
12230: they are used in an ANS Forth conforming way!
12231:
12232: Some words are defined in several wordsets in the
12233: standard. @file{ans-report.fs} reports them for only one of the
12234: wordsets, and not necessarily the one you expect. It depends on usage
12235: which wordset is the right one to specify. E.g., if you only use the
12236: compilation semantics of @code{S"}, it is a Core word; if you also use
12237: its interpretation semantics, it is a File word.
12238:
12239: @c ******************************************************************
12240: @node ANS conformance, Standard vs Extensions, Tools, Top
12241: @chapter ANS conformance
12242: @cindex ANS conformance of Gforth
12243:
12244: To the best of our knowledge, Gforth is an
12245:
12246: ANS Forth System
12247: @itemize @bullet
12248: @item providing the Core Extensions word set
12249: @item providing the Block word set
12250: @item providing the Block Extensions word set
12251: @item providing the Double-Number word set
12252: @item providing the Double-Number Extensions word set
12253: @item providing the Exception word set
12254: @item providing the Exception Extensions word set
12255: @item providing the Facility word set
12256: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
12257: @item providing the File Access word set
12258: @item providing the File Access Extensions word set
12259: @item providing the Floating-Point word set
12260: @item providing the Floating-Point Extensions word set
12261: @item providing the Locals word set
12262: @item providing the Locals Extensions word set
12263: @item providing the Memory-Allocation word set
12264: @item providing the Memory-Allocation Extensions word set (that one's easy)
12265: @item providing the Programming-Tools word set
12266: @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
12267: @item providing the Search-Order word set
12268: @item providing the Search-Order Extensions word set
12269: @item providing the String word set
12270: @item providing the String Extensions word set (another easy one)
12271: @end itemize
12272:
12273: @cindex system documentation
12274: In addition, ANS Forth systems are required to document certain
12275: implementation choices. This chapter tries to meet these
12276: requirements. In many cases it gives a way to ask the system for the
12277: information instead of providing the information directly, in
12278: particular, if the information depends on the processor, the operating
12279: system or the installation options chosen, or if they are likely to
12280: change during the maintenance of Gforth.
12281:
12282: @comment The framework for the rest has been taken from pfe.
12283:
12284: @menu
12285: * The Core Words::
12286: * The optional Block word set::
12287: * The optional Double Number word set::
12288: * The optional Exception word set::
12289: * The optional Facility word set::
12290: * The optional File-Access word set::
12291: * The optional Floating-Point word set::
12292: * The optional Locals word set::
12293: * The optional Memory-Allocation word set::
12294: * The optional Programming-Tools word set::
12295: * The optional Search-Order word set::
12296: @end menu
12297:
12298:
12299: @c =====================================================================
12300: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12301: @comment node-name, next, previous, up
12302: @section The Core Words
12303: @c =====================================================================
12304: @cindex core words, system documentation
12305: @cindex system documentation, core words
12306:
12307: @menu
12308: * core-idef:: Implementation Defined Options
12309: * core-ambcond:: Ambiguous Conditions
12310: * core-other:: Other System Documentation
12311: @end menu
12312:
12313: @c ---------------------------------------------------------------------
12314: @node core-idef, core-ambcond, The Core Words, The Core Words
12315: @subsection Implementation Defined Options
12316: @c ---------------------------------------------------------------------
12317: @cindex core words, implementation-defined options
12318: @cindex implementation-defined options, core words
12319:
12320:
12321: @table @i
12322: @item (Cell) aligned addresses:
12323: @cindex cell-aligned addresses
12324: @cindex aligned addresses
12325: processor-dependent. Gforth's alignment words perform natural alignment
12326: (e.g., an address aligned for a datum of size 8 is divisible by
12327: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12328:
12329: @item @code{EMIT} and non-graphic characters:
12330: @cindex @code{EMIT} and non-graphic characters
12331: @cindex non-graphic characters and @code{EMIT}
12332: The character is output using the C library function (actually, macro)
12333: @code{putc}.
12334:
12335: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12336: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12337: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12338: @cindex @code{ACCEPT}, editing
12339: @cindex @code{EXPECT}, editing
12340: This is modeled on the GNU readline library (@pxref{Readline
12341: Interaction, , Command Line Editing, readline, The GNU Readline
12342: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12343: producing a full word completion every time you type it (instead of
12344: producing the common prefix of all completions). @xref{Command-line editing}.
12345:
12346: @item character set:
12347: @cindex character set
12348: The character set of your computer and display device. Gforth is
12349: 8-bit-clean (but some other component in your system may make trouble).
12350:
12351: @item Character-aligned address requirements:
12352: @cindex character-aligned address requirements
12353: installation-dependent. Currently a character is represented by a C
12354: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12355: (Comments on that requested).
12356:
12357: @item character-set extensions and matching of names:
12358: @cindex character-set extensions and matching of names
12359: @cindex case-sensitivity for name lookup
12360: @cindex name lookup, case-sensitivity
12361: @cindex locale and case-sensitivity
12362: Any character except the ASCII NUL character can be used in a
12363: name. Matching is case-insensitive (except in @code{TABLE}s). The
12364: matching is performed using the C library function @code{strncasecmp}, whose
12365: function is probably influenced by the locale. E.g., the @code{C} locale
12366: does not know about accents and umlauts, so they are matched
12367: case-sensitively in that locale. For portability reasons it is best to
12368: write programs such that they work in the @code{C} locale. Then one can
12369: use libraries written by a Polish programmer (who might use words
12370: containing ISO Latin-2 encoded characters) and by a French programmer
12371: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12372: funny results for some of the words (which ones, depends on the font you
12373: are using)). Also, the locale you prefer may not be available in other
12374: operating systems. Hopefully, Unicode will solve these problems one day.
12375:
12376: @item conditions under which control characters match a space delimiter:
12377: @cindex space delimiters
12378: @cindex control characters as delimiters
12379: If @code{WORD} is called with the space character as a delimiter, all
12380: white-space characters (as identified by the C macro @code{isspace()})
12381: are delimiters. @code{PARSE}, on the other hand, treats space like other
12382: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
12383: like @code{PARSE} otherwise. @code{Name}, which is used by the outer
12384: interpreter (aka text interpreter) by default, treats all white-space
12385: characters as delimiters.
12386:
12387: @item format of the control-flow stack:
12388: @cindex control-flow stack, format
12389: The data stack is used as control-flow stack. The size of a control-flow
12390: stack item in cells is given by the constant @code{cs-item-size}. At the
12391: time of this writing, an item consists of a (pointer to a) locals list
12392: (third), an address in the code (second), and a tag for identifying the
12393: item (TOS). The following tags are used: @code{defstart},
12394: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12395: @code{scopestart}.
12396:
12397: @item conversion of digits > 35
12398: @cindex digits > 35
12399: The characters @code{[\]^_'} are the digits with the decimal value
12400: 36@minus{}41. There is no way to input many of the larger digits.
12401:
12402: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12403: @cindex @code{EXPECT}, display after end of input
12404: @cindex @code{ACCEPT}, display after end of input
12405: The cursor is moved to the end of the entered string. If the input is
12406: terminated using the @kbd{Return} key, a space is typed.
12407:
12408: @item exception abort sequence of @code{ABORT"}:
12409: @cindex exception abort sequence of @code{ABORT"}
12410: @cindex @code{ABORT"}, exception abort sequence
12411: The error string is stored into the variable @code{"error} and a
12412: @code{-2 throw} is performed.
12413:
12414: @item input line terminator:
12415: @cindex input line terminator
12416: @cindex line terminator on input
12417: @cindex newline character on input
12418: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12419: lines. One of these characters is typically produced when you type the
12420: @kbd{Enter} or @kbd{Return} key.
12421:
12422: @item maximum size of a counted string:
12423: @cindex maximum size of a counted string
12424: @cindex counted string, maximum size
12425: @code{s" /counted-string" environment? drop .}. Currently 255 characters
12426: on all platforms, but this may change.
12427:
12428: @item maximum size of a parsed string:
12429: @cindex maximum size of a parsed string
12430: @cindex parsed string, maximum size
12431: Given by the constant @code{/line}. Currently 255 characters.
12432:
12433: @item maximum size of a definition name, in characters:
12434: @cindex maximum size of a definition name, in characters
12435: @cindex name, maximum length
12436: 31
12437:
12438: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12439: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12440: @cindex @code{ENVIRONMENT?} string length, maximum
12441: 31
12442:
12443: @item method of selecting the user input device:
12444: @cindex user input device, method of selecting
12445: The user input device is the standard input. There is currently no way to
12446: change it from within Gforth. However, the input can typically be
12447: redirected in the command line that starts Gforth.
12448:
12449: @item method of selecting the user output device:
12450: @cindex user output device, method of selecting
12451: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
12452: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12453: output when the user output device is a terminal, otherwise the output
12454: is buffered.
12455:
12456: @item methods of dictionary compilation:
12457: What are we expected to document here?
12458:
12459: @item number of bits in one address unit:
12460: @cindex number of bits in one address unit
12461: @cindex address unit, size in bits
12462: @code{s" address-units-bits" environment? drop .}. 8 in all current
12463: platforms.
12464:
12465: @item number representation and arithmetic:
12466: @cindex number representation and arithmetic
12467: Processor-dependent. Binary two's complement on all current platforms.
12468:
12469: @item ranges for integer types:
12470: @cindex ranges for integer types
12471: @cindex integer types, ranges
12472: Installation-dependent. Make environmental queries for @code{MAX-N},
12473: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12474: unsigned (and positive) types is 0. The lower bound for signed types on
12475: two's complement and one's complement machines machines can be computed
12476: by adding 1 to the upper bound.
12477:
12478: @item read-only data space regions:
12479: @cindex read-only data space regions
12480: @cindex data-space, read-only regions
12481: The whole Forth data space is writable.
12482:
12483: @item size of buffer at @code{WORD}:
12484: @cindex size of buffer at @code{WORD}
12485: @cindex @code{WORD} buffer size
12486: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12487: shared with the pictured numeric output string. If overwriting
12488: @code{PAD} is acceptable, it is as large as the remaining dictionary
12489: space, although only as much can be sensibly used as fits in a counted
12490: string.
12491:
12492: @item size of one cell in address units:
12493: @cindex cell size
12494: @code{1 cells .}.
12495:
12496: @item size of one character in address units:
12497: @cindex char size
12498: @code{1 chars .}. 1 on all current platforms.
12499:
12500: @item size of the keyboard terminal buffer:
12501: @cindex size of the keyboard terminal buffer
12502: @cindex terminal buffer, size
12503: Varies. You can determine the size at a specific time using @code{lp@@
12504: tib - .}. It is shared with the locals stack and TIBs of files that
12505: include the current file. You can change the amount of space for TIBs
12506: and locals stack at Gforth startup with the command line option
12507: @code{-l}.
12508:
12509: @item size of the pictured numeric output buffer:
12510: @cindex size of the pictured numeric output buffer
12511: @cindex pictured numeric output buffer, size
12512: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12513: shared with @code{WORD}.
12514:
12515: @item size of the scratch area returned by @code{PAD}:
12516: @cindex size of the scratch area returned by @code{PAD}
12517: @cindex @code{PAD} size
12518: The remainder of dictionary space. @code{unused pad here - - .}.
12519:
12520: @item system case-sensitivity characteristics:
12521: @cindex case-sensitivity characteristics
12522: Dictionary searches are case-insensitive (except in
12523: @code{TABLE}s). However, as explained above under @i{character-set
12524: extensions}, the matching for non-ASCII characters is determined by the
12525: locale you are using. In the default @code{C} locale all non-ASCII
12526: characters are matched case-sensitively.
12527:
12528: @item system prompt:
12529: @cindex system prompt
12530: @cindex prompt
12531: @code{ ok} in interpret state, @code{ compiled} in compile state.
12532:
12533: @item division rounding:
12534: @cindex division rounding
12535: installation dependent. @code{s" floored" environment? drop .}. We leave
12536: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12537: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12538:
12539: @item values of @code{STATE} when true:
12540: @cindex @code{STATE} values
12541: -1.
12542:
12543: @item values returned after arithmetic overflow:
12544: On two's complement machines, arithmetic is performed modulo
12545: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12546: arithmetic (with appropriate mapping for signed types). Division by zero
12547: typically results in a @code{-55 throw} (Floating-point unidentified
12548: fault) or @code{-10 throw} (divide by zero).
12549:
12550: @item whether the current definition can be found after @t{DOES>}:
12551: @cindex @t{DOES>}, visibility of current definition
12552: No.
12553:
12554: @end table
12555:
12556: @c ---------------------------------------------------------------------
12557: @node core-ambcond, core-other, core-idef, The Core Words
12558: @subsection Ambiguous conditions
12559: @c ---------------------------------------------------------------------
12560: @cindex core words, ambiguous conditions
12561: @cindex ambiguous conditions, core words
12562:
12563: @table @i
12564:
12565: @item a name is neither a word nor a number:
12566: @cindex name not found
12567: @cindex undefined word
12568: @code{-13 throw} (Undefined word).
12569:
12570: @item a definition name exceeds the maximum length allowed:
12571: @cindex word name too long
12572: @code{-19 throw} (Word name too long)
12573:
12574: @item addressing a region not inside the various data spaces of the forth system:
12575: @cindex Invalid memory address
12576: The stacks, code space and header space are accessible. Machine code space is
12577: typically readable. Accessing other addresses gives results dependent on
12578: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12579: address).
12580:
12581: @item argument type incompatible with parameter:
12582: @cindex argument type mismatch
12583: This is usually not caught. Some words perform checks, e.g., the control
12584: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12585: mismatch).
12586:
12587: @item attempting to obtain the execution token of a word with undefined execution semantics:
12588: @cindex Interpreting a compile-only word, for @code{'} etc.
12589: @cindex execution token of words with undefined execution semantics
12590: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12591: get an execution token for @code{compile-only-error} (which performs a
12592: @code{-14 throw} when executed).
12593:
12594: @item dividing by zero:
12595: @cindex dividing by zero
12596: @cindex floating point unidentified fault, integer division
12597: On some platforms, this produces a @code{-10 throw} (Division by
12598: zero); on other systems, this typically results in a @code{-55 throw}
12599: (Floating-point unidentified fault).
12600:
12601: @item insufficient data stack or return stack space:
12602: @cindex insufficient data stack or return stack space
12603: @cindex stack overflow
12604: @cindex address alignment exception, stack overflow
12605: @cindex Invalid memory address, stack overflow
12606: Depending on the operating system, the installation, and the invocation
12607: of Gforth, this is either checked by the memory management hardware, or
12608: it is not checked. If it is checked, you typically get a @code{-3 throw}
12609: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12610: throw} (Invalid memory address) (depending on the platform and how you
12611: achieved the overflow) as soon as the overflow happens. If it is not
12612: checked, overflows typically result in mysterious illegal memory
12613: accesses, producing @code{-9 throw} (Invalid memory address) or
12614: @code{-23 throw} (Address alignment exception); they might also destroy
12615: the internal data structure of @code{ALLOCATE} and friends, resulting in
12616: various errors in these words.
12617:
12618: @item insufficient space for loop control parameters:
12619: @cindex insufficient space for loop control parameters
12620: Like other return stack overflows.
12621:
12622: @item insufficient space in the dictionary:
12623: @cindex insufficient space in the dictionary
12624: @cindex dictionary overflow
12625: If you try to allot (either directly with @code{allot}, or indirectly
12626: with @code{,}, @code{create} etc.) more memory than available in the
12627: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12628: to access memory beyond the end of the dictionary, the results are
12629: similar to stack overflows.
12630:
12631: @item interpreting a word with undefined interpretation semantics:
12632: @cindex interpreting a word with undefined interpretation semantics
12633: @cindex Interpreting a compile-only word
12634: For some words, we have defined interpretation semantics. For the
12635: others: @code{-14 throw} (Interpreting a compile-only word).
12636:
12637: @item modifying the contents of the input buffer or a string literal:
12638: @cindex modifying the contents of the input buffer or a string literal
12639: These are located in writable memory and can be modified.
12640:
12641: @item overflow of the pictured numeric output string:
12642: @cindex overflow of the pictured numeric output string
12643: @cindex pictured numeric output string, overflow
12644: @code{-17 throw} (Pictured numeric ouput string overflow).
12645:
12646: @item parsed string overflow:
12647: @cindex parsed string overflow
12648: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12649:
12650: @item producing a result out of range:
12651: @cindex result out of range
12652: On two's complement machines, arithmetic is performed modulo
12653: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12654: arithmetic (with appropriate mapping for signed types). Division by zero
12655: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12656: throw} (floating point unidentified fault). @code{convert} and
12657: @code{>number} currently overflow silently.
12658:
12659: @item reading from an empty data or return stack:
12660: @cindex stack empty
12661: @cindex stack underflow
12662: @cindex return stack underflow
12663: The data stack is checked by the outer (aka text) interpreter after
12664: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12665: underflow) is performed. Apart from that, stacks may be checked or not,
12666: depending on operating system, installation, and invocation. If they are
12667: caught by a check, they typically result in @code{-4 throw} (Stack
12668: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12669: (Invalid memory address), depending on the platform and which stack
12670: underflows and by how much. Note that even if the system uses checking
12671: (through the MMU), your program may have to underflow by a significant
12672: number of stack items to trigger the reaction (the reason for this is
12673: that the MMU, and therefore the checking, works with a page-size
12674: granularity). If there is no checking, the symptoms resulting from an
12675: underflow are similar to those from an overflow. Unbalanced return
12676: stack errors can result in a variety of symptoms, including @code{-9 throw}
12677: (Invalid memory address) and Illegal Instruction (typically @code{-260
12678: throw}).
12679:
12680: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12681: @cindex unexpected end of the input buffer
12682: @cindex zero-length string as a name
12683: @cindex Attempt to use zero-length string as a name
12684: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12685: use zero-length string as a name). Words like @code{'} probably will not
12686: find what they search. Note that it is possible to create zero-length
12687: names with @code{nextname} (should it not?).
12688:
12689: @item @code{>IN} greater than input buffer:
12690: @cindex @code{>IN} greater than input buffer
12691: The next invocation of a parsing word returns a string with length 0.
12692:
12693: @item @code{RECURSE} appears after @code{DOES>}:
12694: @cindex @code{RECURSE} appears after @code{DOES>}
12695: Compiles a recursive call to the defining word, not to the defined word.
12696:
12697: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12698: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
12699: @cindex argument type mismatch, @code{RESTORE-INPUT}
12700: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12701: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12702: the end of the file was reached), its source-id may be
12703: reused. Therefore, restoring an input source specification referencing a
12704: closed file may lead to unpredictable results instead of a @code{-12
12705: THROW}.
12706:
12707: In the future, Gforth may be able to restore input source specifications
12708: from other than the current input source.
12709:
12710: @item data space containing definitions gets de-allocated:
12711: @cindex data space containing definitions gets de-allocated
12712: Deallocation with @code{allot} is not checked. This typically results in
12713: memory access faults or execution of illegal instructions.
12714:
12715: @item data space read/write with incorrect alignment:
12716: @cindex data space read/write with incorrect alignment
12717: @cindex alignment faults
12718: @cindex address alignment exception
12719: Processor-dependent. Typically results in a @code{-23 throw} (Address
12720: alignment exception). Under Linux-Intel on a 486 or later processor with
12721: alignment turned on, incorrect alignment results in a @code{-9 throw}
12722: (Invalid memory address). There are reportedly some processors with
12723: alignment restrictions that do not report violations.
12724:
12725: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12726: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12727: Like other alignment errors.
12728:
12729: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12730: Like other stack underflows.
12731:
12732: @item loop control parameters not available:
12733: @cindex loop control parameters not available
12734: Not checked. The counted loop words simply assume that the top of return
12735: stack items are loop control parameters and behave accordingly.
12736:
12737: @item most recent definition does not have a name (@code{IMMEDIATE}):
12738: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12739: @cindex last word was headerless
12740: @code{abort" last word was headerless"}.
12741:
12742: @item name not defined by @code{VALUE} used by @code{TO}:
12743: @cindex name not defined by @code{VALUE} used by @code{TO}
12744: @cindex @code{TO} on non-@code{VALUE}s
12745: @cindex Invalid name argument, @code{TO}
12746: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12747: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12748:
12749: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12750: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
12751: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
12752: @code{-13 throw} (Undefined word)
12753:
12754: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12755: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12756: Gforth behaves as if they were of the same type. I.e., you can predict
12757: the behaviour by interpreting all parameters as, e.g., signed.
12758:
12759: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12760: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12761: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12762: compilation semantics of @code{TO}.
12763:
12764: @item String longer than a counted string returned by @code{WORD}:
12765: @cindex string longer than a counted string returned by @code{WORD}
12766: @cindex @code{WORD}, string overflow
12767: Not checked. The string will be ok, but the count will, of course,
12768: contain only the least significant bits of the length.
12769:
12770: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12771: @cindex @code{LSHIFT}, large shift counts
12772: @cindex @code{RSHIFT}, large shift counts
12773: Processor-dependent. Typical behaviours are returning 0 and using only
12774: the low bits of the shift count.
12775:
12776: @item word not defined via @code{CREATE}:
12777: @cindex @code{>BODY} of non-@code{CREATE}d words
12778: @code{>BODY} produces the PFA of the word no matter how it was defined.
12779:
12780: @cindex @code{DOES>} of non-@code{CREATE}d words
12781: @code{DOES>} changes the execution semantics of the last defined word no
12782: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12783: @code{CREATE , DOES>}.
12784:
12785: @item words improperly used outside @code{<#} and @code{#>}:
12786: Not checked. As usual, you can expect memory faults.
12787:
12788: @end table
12789:
12790:
12791: @c ---------------------------------------------------------------------
12792: @node core-other, , core-ambcond, The Core Words
12793: @subsection Other system documentation
12794: @c ---------------------------------------------------------------------
12795: @cindex other system documentation, core words
12796: @cindex core words, other system documentation
12797:
12798: @table @i
12799: @item nonstandard words using @code{PAD}:
12800: @cindex @code{PAD} use by nonstandard words
12801: None.
12802:
12803: @item operator's terminal facilities available:
12804: @cindex operator's terminal facilities available
12805: After processing the OS's command line, Gforth goes into interactive mode,
12806: and you can give commands to Gforth interactively. The actual facilities
12807: available depend on how you invoke Gforth.
12808:
12809: @item program data space available:
12810: @cindex program data space available
12811: @cindex data space available
12812: @code{UNUSED .} gives the remaining dictionary space. The total
12813: dictionary space can be specified with the @code{-m} switch
12814: (@pxref{Invoking Gforth}) when Gforth starts up.
12815:
12816: @item return stack space available:
12817: @cindex return stack space available
12818: You can compute the total return stack space in cells with
12819: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12820: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12821:
12822: @item stack space available:
12823: @cindex stack space available
12824: You can compute the total data stack space in cells with
12825: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12826: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12827:
12828: @item system dictionary space required, in address units:
12829: @cindex system dictionary space required, in address units
12830: Type @code{here forthstart - .} after startup. At the time of this
12831: writing, this gives 80080 (bytes) on a 32-bit system.
12832: @end table
12833:
12834:
12835: @c =====================================================================
12836: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12837: @section The optional Block word set
12838: @c =====================================================================
12839: @cindex system documentation, block words
12840: @cindex block words, system documentation
12841:
12842: @menu
12843: * block-idef:: Implementation Defined Options
12844: * block-ambcond:: Ambiguous Conditions
12845: * block-other:: Other System Documentation
12846: @end menu
12847:
12848:
12849: @c ---------------------------------------------------------------------
12850: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12851: @subsection Implementation Defined Options
12852: @c ---------------------------------------------------------------------
12853: @cindex implementation-defined options, block words
12854: @cindex block words, implementation-defined options
12855:
12856: @table @i
12857: @item the format for display by @code{LIST}:
12858: @cindex @code{LIST} display format
12859: First the screen number is displayed, then 16 lines of 64 characters,
12860: each line preceded by the line number.
12861:
12862: @item the length of a line affected by @code{\}:
12863: @cindex length of a line affected by @code{\}
12864: @cindex @code{\}, line length in blocks
12865: 64 characters.
12866: @end table
12867:
12868:
12869: @c ---------------------------------------------------------------------
12870: @node block-ambcond, block-other, block-idef, The optional Block word set
12871: @subsection Ambiguous conditions
12872: @c ---------------------------------------------------------------------
12873: @cindex block words, ambiguous conditions
12874: @cindex ambiguous conditions, block words
12875:
12876: @table @i
12877: @item correct block read was not possible:
12878: @cindex block read not possible
12879: Typically results in a @code{throw} of some OS-derived value (between
12880: -512 and -2048). If the blocks file was just not long enough, blanks are
12881: supplied for the missing portion.
12882:
12883: @item I/O exception in block transfer:
12884: @cindex I/O exception in block transfer
12885: @cindex block transfer, I/O exception
12886: Typically results in a @code{throw} of some OS-derived value (between
12887: -512 and -2048).
12888:
12889: @item invalid block number:
12890: @cindex invalid block number
12891: @cindex block number invalid
12892: @code{-35 throw} (Invalid block number)
12893:
12894: @item a program directly alters the contents of @code{BLK}:
12895: @cindex @code{BLK}, altering @code{BLK}
12896: The input stream is switched to that other block, at the same
12897: position. If the storing to @code{BLK} happens when interpreting
12898: non-block input, the system will get quite confused when the block ends.
12899:
12900: @item no current block buffer for @code{UPDATE}:
12901: @cindex @code{UPDATE}, no current block buffer
12902: @code{UPDATE} has no effect.
12903:
12904: @end table
12905:
12906: @c ---------------------------------------------------------------------
12907: @node block-other, , block-ambcond, The optional Block word set
12908: @subsection Other system documentation
12909: @c ---------------------------------------------------------------------
12910: @cindex other system documentation, block words
12911: @cindex block words, other system documentation
12912:
12913: @table @i
12914: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12915: No restrictions (yet).
12916:
12917: @item the number of blocks available for source and data:
12918: depends on your disk space.
12919:
12920: @end table
12921:
12922:
12923: @c =====================================================================
12924: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12925: @section The optional Double Number word set
12926: @c =====================================================================
12927: @cindex system documentation, double words
12928: @cindex double words, system documentation
12929:
12930: @menu
12931: * double-ambcond:: Ambiguous Conditions
12932: @end menu
12933:
12934:
12935: @c ---------------------------------------------------------------------
12936: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
12937: @subsection Ambiguous conditions
12938: @c ---------------------------------------------------------------------
12939: @cindex double words, ambiguous conditions
12940: @cindex ambiguous conditions, double words
12941:
12942: @table @i
12943: @item @i{d} outside of range of @i{n} in @code{D>S}:
12944: @cindex @code{D>S}, @i{d} out of range of @i{n}
12945: The least significant cell of @i{d} is produced.
12946:
12947: @end table
12948:
12949:
12950: @c =====================================================================
12951: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
12952: @section The optional Exception word set
12953: @c =====================================================================
12954: @cindex system documentation, exception words
12955: @cindex exception words, system documentation
12956:
12957: @menu
12958: * exception-idef:: Implementation Defined Options
12959: @end menu
12960:
12961:
12962: @c ---------------------------------------------------------------------
12963: @node exception-idef, , The optional Exception word set, The optional Exception word set
12964: @subsection Implementation Defined Options
12965: @c ---------------------------------------------------------------------
12966: @cindex implementation-defined options, exception words
12967: @cindex exception words, implementation-defined options
12968:
12969: @table @i
12970: @item @code{THROW}-codes used in the system:
12971: @cindex @code{THROW}-codes used in the system
12972: The codes -256@minus{}-511 are used for reporting signals. The mapping
12973: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
12974: codes -512@minus{}-2047 are used for OS errors (for file and memory
12975: allocation operations). The mapping from OS error numbers to throw codes
12976: is -512@minus{}@code{errno}. One side effect of this mapping is that
12977: undefined OS errors produce a message with a strange number; e.g.,
12978: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
12979: @end table
12980:
12981: @c =====================================================================
12982: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
12983: @section The optional Facility word set
12984: @c =====================================================================
12985: @cindex system documentation, facility words
12986: @cindex facility words, system documentation
12987:
12988: @menu
12989: * facility-idef:: Implementation Defined Options
12990: * facility-ambcond:: Ambiguous Conditions
12991: @end menu
12992:
12993:
12994: @c ---------------------------------------------------------------------
12995: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
12996: @subsection Implementation Defined Options
12997: @c ---------------------------------------------------------------------
12998: @cindex implementation-defined options, facility words
12999: @cindex facility words, implementation-defined options
13000:
13001: @table @i
13002: @item encoding of keyboard events (@code{EKEY}):
13003: @cindex keyboard events, encoding in @code{EKEY}
13004: @cindex @code{EKEY}, encoding of keyboard events
13005: Keys corresponding to ASCII characters are encoded as ASCII characters.
13006: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13007: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13008: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13009: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
13010:
13011:
13012: @item duration of a system clock tick:
13013: @cindex duration of a system clock tick
13014: @cindex clock tick duration
13015: System dependent. With respect to @code{MS}, the time is specified in
13016: microseconds. How well the OS and the hardware implement this, is
13017: another question.
13018:
13019: @item repeatability to be expected from the execution of @code{MS}:
13020: @cindex repeatability to be expected from the execution of @code{MS}
13021: @cindex @code{MS}, repeatability to be expected
13022: System dependent. On Unix, a lot depends on load. If the system is
13023: lightly loaded, and the delay is short enough that Gforth does not get
13024: swapped out, the performance should be acceptable. Under MS-DOS and
13025: other single-tasking systems, it should be good.
13026:
13027: @end table
13028:
13029:
13030: @c ---------------------------------------------------------------------
13031: @node facility-ambcond, , facility-idef, The optional Facility word set
13032: @subsection Ambiguous conditions
13033: @c ---------------------------------------------------------------------
13034: @cindex facility words, ambiguous conditions
13035: @cindex ambiguous conditions, facility words
13036:
13037: @table @i
13038: @item @code{AT-XY} can't be performed on user output device:
13039: @cindex @code{AT-XY} can't be performed on user output device
13040: Largely terminal dependent. No range checks are done on the arguments.
13041: No errors are reported. You may see some garbage appearing, you may see
13042: simply nothing happen.
13043:
13044: @end table
13045:
13046:
13047: @c =====================================================================
13048: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13049: @section The optional File-Access word set
13050: @c =====================================================================
13051: @cindex system documentation, file words
13052: @cindex file words, system documentation
13053:
13054: @menu
13055: * file-idef:: Implementation Defined Options
13056: * file-ambcond:: Ambiguous Conditions
13057: @end menu
13058:
13059: @c ---------------------------------------------------------------------
13060: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13061: @subsection Implementation Defined Options
13062: @c ---------------------------------------------------------------------
13063: @cindex implementation-defined options, file words
13064: @cindex file words, implementation-defined options
13065:
13066: @table @i
13067: @item file access methods used:
13068: @cindex file access methods used
13069: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13070: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13071: @code{wb}): The file is cleared, if it exists, and created, if it does
13072: not (with both @code{open-file} and @code{create-file}). Under Unix
13073: @code{create-file} creates a file with 666 permissions modified by your
13074: umask.
13075:
13076: @item file exceptions:
13077: @cindex file exceptions
13078: The file words do not raise exceptions (except, perhaps, memory access
13079: faults when you pass illegal addresses or file-ids).
13080:
13081: @item file line terminator:
13082: @cindex file line terminator
13083: System-dependent. Gforth uses C's newline character as line
13084: terminator. What the actual character code(s) of this are is
13085: system-dependent.
13086:
13087: @item file name format:
13088: @cindex file name format
13089: System dependent. Gforth just uses the file name format of your OS.
13090:
13091: @item information returned by @code{FILE-STATUS}:
13092: @cindex @code{FILE-STATUS}, returned information
13093: @code{FILE-STATUS} returns the most powerful file access mode allowed
13094: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13095: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13096: along with the returned mode.
13097:
13098: @item input file state after an exception when including source:
13099: @cindex exception when including source
13100: All files that are left via the exception are closed.
13101:
13102: @item @i{ior} values and meaning:
13103: @cindex @i{ior} values and meaning
13104: @cindex @i{wior} values and meaning
13105: The @i{ior}s returned by the file and memory allocation words are
13106: intended as throw codes. They typically are in the range
13107: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
13108: @i{ior}s is -512@minus{}@i{errno}.
13109:
13110: @item maximum depth of file input nesting:
13111: @cindex maximum depth of file input nesting
13112: @cindex file input nesting, maximum depth
13113: limited by the amount of return stack, locals/TIB stack, and the number
13114: of open files available. This should not give you troubles.
13115:
13116: @item maximum size of input line:
13117: @cindex maximum size of input line
13118: @cindex input line size, maximum
13119: @code{/line}. Currently 255.
13120:
13121: @item methods of mapping block ranges to files:
13122: @cindex mapping block ranges to files
13123: @cindex files containing blocks
13124: @cindex blocks in files
13125: By default, blocks are accessed in the file @file{blocks.fb} in the
13126: current working directory. The file can be switched with @code{USE}.
13127:
13128: @item number of string buffers provided by @code{S"}:
13129: @cindex @code{S"}, number of string buffers
13130: 1
13131:
13132: @item size of string buffer used by @code{S"}:
13133: @cindex @code{S"}, size of string buffer
13134: @code{/line}. currently 255.
13135:
13136: @end table
13137:
13138: @c ---------------------------------------------------------------------
13139: @node file-ambcond, , file-idef, The optional File-Access word set
13140: @subsection Ambiguous conditions
13141: @c ---------------------------------------------------------------------
13142: @cindex file words, ambiguous conditions
13143: @cindex ambiguous conditions, file words
13144:
13145: @table @i
13146: @item attempting to position a file outside its boundaries:
13147: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13148: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13149: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13150:
13151: @item attempting to read from file positions not yet written:
13152: @cindex reading from file positions not yet written
13153: End-of-file, i.e., zero characters are read and no error is reported.
13154:
13155: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13156: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
13157: An appropriate exception may be thrown, but a memory fault or other
13158: problem is more probable.
13159:
13160: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13161: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13162: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13163: The @i{ior} produced by the operation, that discovered the problem, is
13164: thrown.
13165:
13166: @item named file cannot be opened (@code{INCLUDED}):
13167: @cindex @code{INCLUDED}, named file cannot be opened
13168: The @i{ior} produced by @code{open-file} is thrown.
13169:
13170: @item requesting an unmapped block number:
13171: @cindex unmapped block numbers
13172: There are no unmapped legal block numbers. On some operating systems,
13173: writing a block with a large number may overflow the file system and
13174: have an error message as consequence.
13175:
13176: @item using @code{source-id} when @code{blk} is non-zero:
13177: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13178: @code{source-id} performs its function. Typically it will give the id of
13179: the source which loaded the block. (Better ideas?)
13180:
13181: @end table
13182:
13183:
13184: @c =====================================================================
13185: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13186: @section The optional Floating-Point word set
13187: @c =====================================================================
13188: @cindex system documentation, floating-point words
13189: @cindex floating-point words, system documentation
13190:
13191: @menu
13192: * floating-idef:: Implementation Defined Options
13193: * floating-ambcond:: Ambiguous Conditions
13194: @end menu
13195:
13196:
13197: @c ---------------------------------------------------------------------
13198: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13199: @subsection Implementation Defined Options
13200: @c ---------------------------------------------------------------------
13201: @cindex implementation-defined options, floating-point words
13202: @cindex floating-point words, implementation-defined options
13203:
13204: @table @i
13205: @item format and range of floating point numbers:
13206: @cindex format and range of floating point numbers
13207: @cindex floating point numbers, format and range
13208: System-dependent; the @code{double} type of C.
13209:
13210: @item results of @code{REPRESENT} when @i{float} is out of range:
13211: @cindex @code{REPRESENT}, results when @i{float} is out of range
13212: System dependent; @code{REPRESENT} is implemented using the C library
13213: function @code{ecvt()} and inherits its behaviour in this respect.
13214:
13215: @item rounding or truncation of floating-point numbers:
13216: @cindex rounding of floating-point numbers
13217: @cindex truncation of floating-point numbers
13218: @cindex floating-point numbers, rounding or truncation
13219: System dependent; the rounding behaviour is inherited from the hosting C
13220: compiler. IEEE-FP-based (i.e., most) systems by default round to
13221: nearest, and break ties by rounding to even (i.e., such that the last
13222: bit of the mantissa is 0).
13223:
13224: @item size of floating-point stack:
13225: @cindex floating-point stack size
13226: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13227: the floating-point stack (in floats). You can specify this on startup
13228: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13229:
13230: @item width of floating-point stack:
13231: @cindex floating-point stack width
13232: @code{1 floats}.
13233:
13234: @end table
13235:
13236:
13237: @c ---------------------------------------------------------------------
13238: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13239: @subsection Ambiguous conditions
13240: @c ---------------------------------------------------------------------
13241: @cindex floating-point words, ambiguous conditions
13242: @cindex ambiguous conditions, floating-point words
13243:
13244: @table @i
13245: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13246: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13247: System-dependent. Typically results in a @code{-23 THROW} like other
13248: alignment violations.
13249:
13250: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13251: @cindex @code{f@@} used with an address that is not float aligned
13252: @cindex @code{f!} used with an address that is not float aligned
13253: System-dependent. Typically results in a @code{-23 THROW} like other
13254: alignment violations.
13255:
13256: @item floating-point result out of range:
13257: @cindex floating-point result out of range
13258: System-dependent. Can result in a @code{-43 throw} (floating point
13259: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13260: (floating point inexact result), @code{-55 THROW} (Floating-point
13261: unidentified fault), or can produce a special value representing, e.g.,
13262: Infinity.
13263:
13264: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13265: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13266: System-dependent. Typically results in an alignment fault like other
13267: alignment violations.
13268:
13269: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13270: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
13271: The floating-point number is converted into decimal nonetheless.
13272:
13273: @item Both arguments are equal to zero (@code{FATAN2}):
13274: @cindex @code{FATAN2}, both arguments are equal to zero
13275: System-dependent. @code{FATAN2} is implemented using the C library
13276: function @code{atan2()}.
13277:
13278: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13279: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13280: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
13281: because of small errors and the tan will be a very large (or very small)
13282: but finite number.
13283:
13284: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13285: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
13286: The result is rounded to the nearest float.
13287:
13288: @item dividing by zero:
13289: @cindex dividing by zero, floating-point
13290: @cindex floating-point dividing by zero
13291: @cindex floating-point unidentified fault, FP divide-by-zero
13292: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13293: (floating point divide by zero) or @code{-55 throw} (Floating-point
13294: unidentified fault).
13295:
13296: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13297: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13298: System dependent. On IEEE-FP based systems the number is converted into
13299: an infinity.
13300:
13301: @item @i{float}<1 (@code{FACOSH}):
13302: @cindex @code{FACOSH}, @i{float}<1
13303: @cindex floating-point unidentified fault, @code{FACOSH}
13304: Platform-dependent; on IEEE-FP systems typically produces a NaN.
13305:
13306: @item @i{float}=<-1 (@code{FLNP1}):
13307: @cindex @code{FLNP1}, @i{float}=<-1
13308: @cindex floating-point unidentified fault, @code{FLNP1}
13309: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13310: negative infinity for @i{float}=-1).
13311:
13312: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13313: @cindex @code{FLN}, @i{float}=<0
13314: @cindex @code{FLOG}, @i{float}=<0
13315: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
13316: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13317: negative infinity for @i{float}=0).
13318:
13319: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13320: @cindex @code{FASINH}, @i{float}<0
13321: @cindex @code{FSQRT}, @i{float}<0
13322: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
13323: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13324: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13325: C library?).
13326:
13327: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13328: @cindex @code{FACOS}, |@i{float}|>1
13329: @cindex @code{FASIN}, |@i{float}|>1
13330: @cindex @code{FATANH}, |@i{float}|>1
13331: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
13332: Platform-dependent; IEEE-FP systems typically produce a NaN.
13333:
13334: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13335: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
13336: @cindex floating-point unidentified fault, @code{F>D}
13337: Platform-dependent; typically, some double number is produced and no
13338: error is reported.
13339:
13340: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13341: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
13342: @code{Precision} characters of the numeric output area are used. If
13343: @code{precision} is too high, these words will smash the data or code
13344: close to @code{here}.
13345: @end table
13346:
13347: @c =====================================================================
13348: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13349: @section The optional Locals word set
13350: @c =====================================================================
13351: @cindex system documentation, locals words
13352: @cindex locals words, system documentation
13353:
13354: @menu
13355: * locals-idef:: Implementation Defined Options
13356: * locals-ambcond:: Ambiguous Conditions
13357: @end menu
13358:
13359:
13360: @c ---------------------------------------------------------------------
13361: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13362: @subsection Implementation Defined Options
13363: @c ---------------------------------------------------------------------
13364: @cindex implementation-defined options, locals words
13365: @cindex locals words, implementation-defined options
13366:
13367: @table @i
13368: @item maximum number of locals in a definition:
13369: @cindex maximum number of locals in a definition
13370: @cindex locals, maximum number in a definition
13371: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13372: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13373: characters. The number of locals in a definition is bounded by the size
13374: of locals-buffer, which contains the names of the locals.
13375:
13376: @end table
13377:
13378:
13379: @c ---------------------------------------------------------------------
13380: @node locals-ambcond, , locals-idef, The optional Locals word set
13381: @subsection Ambiguous conditions
13382: @c ---------------------------------------------------------------------
13383: @cindex locals words, ambiguous conditions
13384: @cindex ambiguous conditions, locals words
13385:
13386: @table @i
13387: @item executing a named local in interpretation state:
13388: @cindex local in interpretation state
13389: @cindex Interpreting a compile-only word, for a local
13390: Locals have no interpretation semantics. If you try to perform the
13391: interpretation semantics, you will get a @code{-14 throw} somewhere
13392: (Interpreting a compile-only word). If you perform the compilation
13393: semantics, the locals access will be compiled (irrespective of state).
13394:
13395: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
13396: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13397: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13398: @cindex Invalid name argument, @code{TO}
13399: @code{-32 throw} (Invalid name argument)
13400:
13401: @end table
13402:
13403:
13404: @c =====================================================================
13405: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13406: @section The optional Memory-Allocation word set
13407: @c =====================================================================
13408: @cindex system documentation, memory-allocation words
13409: @cindex memory-allocation words, system documentation
13410:
13411: @menu
13412: * memory-idef:: Implementation Defined Options
13413: @end menu
13414:
13415:
13416: @c ---------------------------------------------------------------------
13417: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13418: @subsection Implementation Defined Options
13419: @c ---------------------------------------------------------------------
13420: @cindex implementation-defined options, memory-allocation words
13421: @cindex memory-allocation words, implementation-defined options
13422:
13423: @table @i
13424: @item values and meaning of @i{ior}:
13425: @cindex @i{ior} values and meaning
13426: The @i{ior}s returned by the file and memory allocation words are
13427: intended as throw codes. They typically are in the range
13428: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
13429: @i{ior}s is -512@minus{}@i{errno}.
13430:
13431: @end table
13432:
13433: @c =====================================================================
13434: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13435: @section The optional Programming-Tools word set
13436: @c =====================================================================
13437: @cindex system documentation, programming-tools words
13438: @cindex programming-tools words, system documentation
13439:
13440: @menu
13441: * programming-idef:: Implementation Defined Options
13442: * programming-ambcond:: Ambiguous Conditions
13443: @end menu
13444:
13445:
13446: @c ---------------------------------------------------------------------
13447: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13448: @subsection Implementation Defined Options
13449: @c ---------------------------------------------------------------------
13450: @cindex implementation-defined options, programming-tools words
13451: @cindex programming-tools words, implementation-defined options
13452:
13453: @table @i
13454: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13455: @cindex @code{;CODE} ending sequence
13456: @cindex @code{CODE} ending sequence
13457: @code{END-CODE}
13458:
13459: @item manner of processing input following @code{;CODE} and @code{CODE}:
13460: @cindex @code{;CODE}, processing input
13461: @cindex @code{CODE}, processing input
13462: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13463: the input is processed by the text interpreter, (starting) in interpret
13464: state.
13465:
13466: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13467: @cindex @code{ASSEMBLER}, search order capability
13468: The ANS Forth search order word set.
13469:
13470: @item source and format of display by @code{SEE}:
13471: @cindex @code{SEE}, source and format of output
13472: The source for @code{see} is the executable code used by the inner
13473: interpreter. The current @code{see} tries to output Forth source code
13474: (and on some platforms, assembly code for primitives) as well as
13475: possible.
13476:
13477: @end table
13478:
13479: @c ---------------------------------------------------------------------
13480: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13481: @subsection Ambiguous conditions
13482: @c ---------------------------------------------------------------------
13483: @cindex programming-tools words, ambiguous conditions
13484: @cindex ambiguous conditions, programming-tools words
13485:
13486: @table @i
13487:
13488: @item deleting the compilation word list (@code{FORGET}):
13489: @cindex @code{FORGET}, deleting the compilation word list
13490: Not implemented (yet).
13491:
13492: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13493: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13494: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
13495: @cindex control-flow stack underflow
13496: This typically results in an @code{abort"} with a descriptive error
13497: message (may change into a @code{-22 throw} (Control structure mismatch)
13498: in the future). You may also get a memory access error. If you are
13499: unlucky, this ambiguous condition is not caught.
13500:
13501: @item @i{name} can't be found (@code{FORGET}):
13502: @cindex @code{FORGET}, @i{name} can't be found
13503: Not implemented (yet).
13504:
13505: @item @i{name} not defined via @code{CREATE}:
13506: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
13507: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13508: the execution semantics of the last defined word no matter how it was
13509: defined.
13510:
13511: @item @code{POSTPONE} applied to @code{[IF]}:
13512: @cindex @code{POSTPONE} applied to @code{[IF]}
13513: @cindex @code{[IF]} and @code{POSTPONE}
13514: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13515: equivalent to @code{[IF]}.
13516:
13517: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13518: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13519: Continue in the same state of conditional compilation in the next outer
13520: input source. Currently there is no warning to the user about this.
13521:
13522: @item removing a needed definition (@code{FORGET}):
13523: @cindex @code{FORGET}, removing a needed definition
13524: Not implemented (yet).
13525:
13526: @end table
13527:
13528:
13529: @c =====================================================================
13530: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13531: @section The optional Search-Order word set
13532: @c =====================================================================
13533: @cindex system documentation, search-order words
13534: @cindex search-order words, system documentation
13535:
13536: @menu
13537: * search-idef:: Implementation Defined Options
13538: * search-ambcond:: Ambiguous Conditions
13539: @end menu
13540:
13541:
13542: @c ---------------------------------------------------------------------
13543: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13544: @subsection Implementation Defined Options
13545: @c ---------------------------------------------------------------------
13546: @cindex implementation-defined options, search-order words
13547: @cindex search-order words, implementation-defined options
13548:
13549: @table @i
13550: @item maximum number of word lists in search order:
13551: @cindex maximum number of word lists in search order
13552: @cindex search order, maximum depth
13553: @code{s" wordlists" environment? drop .}. Currently 16.
13554:
13555: @item minimum search order:
13556: @cindex minimum search order
13557: @cindex search order, minimum
13558: @code{root root}.
13559:
13560: @end table
13561:
13562: @c ---------------------------------------------------------------------
13563: @node search-ambcond, , search-idef, The optional Search-Order word set
13564: @subsection Ambiguous conditions
13565: @c ---------------------------------------------------------------------
13566: @cindex search-order words, ambiguous conditions
13567: @cindex ambiguous conditions, search-order words
13568:
13569: @table @i
13570: @item changing the compilation word list (during compilation):
13571: @cindex changing the compilation word list (during compilation)
13572: @cindex compilation word list, change before definition ends
13573: The word is entered into the word list that was the compilation word list
13574: at the start of the definition. Any changes to the name field (e.g.,
13575: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13576: are applied to the latest defined word (as reported by @code{last} or
13577: @code{lastxt}), if possible, irrespective of the compilation word list.
13578:
13579: @item search order empty (@code{previous}):
13580: @cindex @code{previous}, search order empty
13581: @cindex vocstack empty, @code{previous}
13582: @code{abort" Vocstack empty"}.
13583:
13584: @item too many word lists in search order (@code{also}):
13585: @cindex @code{also}, too many word lists in search order
13586: @cindex vocstack full, @code{also}
13587: @code{abort" Vocstack full"}.
13588:
13589: @end table
13590:
13591: @c ***************************************************************
13592: @node Standard vs Extensions, Model, ANS conformance, Top
13593: @chapter Should I use Gforth extensions?
13594: @cindex Gforth extensions
13595:
13596: As you read through the rest of this manual, you will see documentation
13597: for @i{Standard} words, and documentation for some appealing Gforth
13598: @i{extensions}. You might ask yourself the question: @i{``Should I
13599: restrict myself to the standard, or should I use the extensions?''}
13600:
13601: The answer depends on the goals you have for the program you are working
13602: on:
13603:
13604: @itemize @bullet
13605:
13606: @item Is it just for yourself or do you want to share it with others?
13607:
13608: @item
13609: If you want to share it, do the others all use Gforth?
13610:
13611: @item
13612: If it is just for yourself, do you want to restrict yourself to Gforth?
13613:
13614: @end itemize
13615:
13616: If restricting the program to Gforth is ok, then there is no reason not
13617: to use extensions. It is still a good idea to keep to the standard
13618: where it is easy, in case you want to reuse these parts in another
13619: program that you want to be portable.
13620:
13621: If you want to be able to port the program to other Forth systems, there
13622: are the following points to consider:
13623:
13624: @itemize @bullet
13625:
13626: @item
13627: Most Forth systems that are being maintained support the ANS Forth
13628: standard. So if your program complies with the standard, it will be
13629: portable among many systems.
13630:
13631: @item
13632: A number of the Gforth extensions can be implemented in ANS Forth using
13633: public-domain files provided in the @file{compat/} directory. These are
13634: mentioned in the text in passing. There is no reason not to use these
13635: extensions, your program will still be ANS Forth compliant; just include
13636: the appropriate compat files with your program.
13637:
13638: @item
13639: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13640: analyse your program and determine what non-Standard words it relies
13641: upon. However, it does not check whether you use standard words in a
13642: non-standard way.
13643:
13644: @item
13645: Some techniques are not standardized by ANS Forth, and are hard or
13646: impossible to implement in a standard way, but can be implemented in
13647: most Forth systems easily, and usually in similar ways (e.g., accessing
13648: word headers). Forth has a rich historical precedent for programmers
13649: taking advantage of implementation-dependent features of their tools
13650: (for example, relying on a knowledge of the dictionary
13651: structure). Sometimes these techniques are necessary to extract every
13652: last bit of performance from the hardware, sometimes they are just a
13653: programming shorthand.
13654:
13655: @item
13656: Does using a Gforth extension save more work than the porting this part
13657: to other Forth systems (if any) will cost?
13658:
13659: @item
13660: Is the additional functionality worth the reduction in portability and
13661: the additional porting problems?
13662:
13663: @end itemize
13664:
13665: In order to perform these consideratios, you need to know what's
13666: standard and what's not. This manual generally states if something is
13667: non-standard, but the authoritative source is the
13668: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
13669: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13670: into the thought processes of the technical committee.
13671:
13672: Note also that portability between Forth systems is not the only
13673: portability issue; there is also the issue of portability between
13674: different platforms (processor/OS combinations).
13675:
13676: @c ***************************************************************
13677: @node Model, Integrating Gforth, Standard vs Extensions, Top
13678: @chapter Model
13679:
13680: This chapter has yet to be written. It will contain information, on
13681: which internal structures you can rely.
13682:
13683: @c ***************************************************************
13684: @node Integrating Gforth, Emacs and Gforth, Model, Top
13685: @chapter Integrating Gforth into C programs
13686:
13687: This is not yet implemented.
13688:
13689: Several people like to use Forth as scripting language for applications
13690: that are otherwise written in C, C++, or some other language.
13691:
13692: The Forth system ATLAST provides facilities for embedding it into
13693: applications; unfortunately it has several disadvantages: most
13694: importantly, it is not based on ANS Forth, and it is apparently dead
13695: (i.e., not developed further and not supported). The facilities
13696: provided by Gforth in this area are inspired by ATLAST's facilities, so
13697: making the switch should not be hard.
13698:
13699: We also tried to design the interface such that it can easily be
13700: implemented by other Forth systems, so that we may one day arrive at a
13701: standardized interface. Such a standard interface would allow you to
13702: replace the Forth system without having to rewrite C code.
13703:
13704: You embed the Gforth interpreter by linking with the library
13705: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13706: global symbols in this library that belong to the interface, have the
13707: prefix @code{forth_}. (Global symbols that are used internally have the
13708: prefix @code{gforth_}).
13709:
13710: You can include the declarations of Forth types and the functions and
13711: variables of the interface with @code{#include <forth.h>}.
13712:
13713: Types.
13714:
13715: Variables.
13716:
13717: Data and FP Stack pointer. Area sizes.
13718:
13719: functions.
13720:
13721: forth_init(imagefile)
13722: forth_evaluate(string) exceptions?
13723: forth_goto(address) (or forth_execute(xt)?)
13724: forth_continue() (a corountining mechanism)
13725:
13726: Adding primitives.
13727:
13728: No checking.
13729:
13730: Signals?
13731:
13732: Accessing the Stacks
13733:
13734: @c ******************************************************************
13735: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13736: @chapter Emacs and Gforth
13737: @cindex Emacs and Gforth
13738:
13739: @cindex @file{gforth.el}
13740: @cindex @file{forth.el}
13741: @cindex Rydqvist, Goran
13742: @cindex comment editing commands
13743: @cindex @code{\}, editing with Emacs
13744: @cindex debug tracer editing commands
13745: @cindex @code{~~}, removal with Emacs
13746: @cindex Forth mode in Emacs
13747: Gforth comes with @file{gforth.el}, an improved version of
13748: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
13749: improvements are:
13750:
13751: @itemize @bullet
13752: @item
13753: A better (but still not perfect) handling of indentation.
13754: @item
13755: Comment paragraph filling (@kbd{M-q})
13756: @item
13757: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13758: @item
13759: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
13760: @item
13761: Support of the @code{info-lookup} feature for looking up the
13762: documentation of a word.
13763: @end itemize
13764:
13765: I left the stuff I do not use alone, even though some of it only makes
13766: sense for TILE. To get a description of these features, enter Forth mode
13767: and type @kbd{C-h m}.
13768:
13769: @cindex source location of error or debugging output in Emacs
13770: @cindex error output, finding the source location in Emacs
13771: @cindex debugging output, finding the source location in Emacs
13772: In addition, Gforth supports Emacs quite well: The source code locations
13773: given in error messages, debugging output (from @code{~~}) and failed
13774: assertion messages are in the right format for Emacs' compilation mode
13775: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13776: Manual}) so the source location corresponding to an error or other
13777: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13778: @kbd{C-c C-c} for the error under the cursor).
13779:
13780: @cindex @file{TAGS} file
13781: @cindex @file{etags.fs}
13782: @cindex viewing the source of a word in Emacs
13783: @cindex @code{require}, placement in files
13784: @cindex @code{include}, placement in files
13785: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
13786: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
13787: contains the definitions of all words defined afterwards. You can then
13788: find the source for a word using @kbd{M-.}. Note that emacs can use
13789: several tags files at the same time (e.g., one for the Gforth sources
13790: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13791: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13792: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
13793: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
13794: with @file{etags.fs}, you should avoid putting definitions both before
13795: and after @code{require} etc., otherwise you will see the same file
13796: visited several times by commands like @code{tags-search}.
13797:
13798: @cindex viewing the documentation of a word in Emacs
13799: @cindex context-sensitive help
13800: Moreover, for words documented in this manual, you can look up the
13801: glossary entry quickly by using @kbd{C-h TAB}
13802: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13803: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
13804: later and does not work for words containing @code{:}.
13805:
13806:
13807: @cindex @file{.emacs}
13808: To get all these benefits, add the following lines to your @file{.emacs}
13809: file:
13810:
13811: @example
13812: (autoload 'forth-mode "gforth.el")
13813: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
13814: @end example
13815:
13816: @c ******************************************************************
13817: @node Image Files, Engine, Emacs and Gforth, Top
13818: @chapter Image Files
13819: @cindex image file
13820: @cindex @file{.fi} files
13821: @cindex precompiled Forth code
13822: @cindex dictionary in persistent form
13823: @cindex persistent form of dictionary
13824:
13825: An image file is a file containing an image of the Forth dictionary,
13826: i.e., compiled Forth code and data residing in the dictionary. By
13827: convention, we use the extension @code{.fi} for image files.
13828:
13829: @menu
13830: * Image Licensing Issues:: Distribution terms for images.
13831: * Image File Background:: Why have image files?
13832: * Non-Relocatable Image Files:: don't always work.
13833: * Data-Relocatable Image Files:: are better.
13834: * Fully Relocatable Image Files:: better yet.
13835: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
13836: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
13837: * Modifying the Startup Sequence:: and turnkey applications.
13838: @end menu
13839:
13840: @node Image Licensing Issues, Image File Background, Image Files, Image Files
13841: @section Image Licensing Issues
13842: @cindex license for images
13843: @cindex image license
13844:
13845: An image created with @code{gforthmi} (@pxref{gforthmi}) or
13846: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
13847: original image; i.e., according to copyright law it is a derived work of
13848: the original image.
13849:
13850: Since Gforth is distributed under the GNU GPL, the newly created image
13851: falls under the GNU GPL, too. In particular, this means that if you
13852: distribute the image, you have to make all of the sources for the image
13853: available, including those you wrote. For details see @ref{License, ,
13854: GNU General Public License (Section 3)}.
13855:
13856: If you create an image with @code{cross} (@pxref{cross.fs}), the image
13857: contains only code compiled from the sources you gave it; if none of
13858: these sources is under the GPL, the terms discussed above do not apply
13859: to the image. However, if your image needs an engine (a gforth binary)
13860: that is under the GPL, you should make sure that you distribute both in
13861: a way that is at most a @emph{mere aggregation}, if you don't want the
13862: terms of the GPL to apply to the image.
13863:
13864: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
13865: @section Image File Background
13866: @cindex image file background
13867:
13868: Gforth consists not only of primitives (in the engine), but also of
13869: definitions written in Forth. Since the Forth compiler itself belongs to
13870: those definitions, it is not possible to start the system with the
13871: engine and the Forth source alone. Therefore we provide the Forth
13872: code as an image file in nearly executable form. When Gforth starts up,
13873: a C routine loads the image file into memory, optionally relocates the
13874: addresses, then sets up the memory (stacks etc.) according to
13875: information in the image file, and (finally) starts executing Forth
13876: code.
13877:
13878: The image file variants represent different compromises between the
13879: goals of making it easy to generate image files and making them
13880: portable.
13881:
13882: @cindex relocation at run-time
13883: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
13884: run-time. This avoids many of the complications discussed below (image
13885: files are data relocatable without further ado), but costs performance
13886: (one addition per memory access).
13887:
13888: @cindex relocation at load-time
13889: By contrast, the Gforth loader performs relocation at image load time. The
13890: loader also has to replace tokens that represent primitive calls with the
13891: appropriate code-field addresses (or code addresses in the case of
13892: direct threading).
13893:
13894: There are three kinds of image files, with different degrees of
13895: relocatability: non-relocatable, data-relocatable, and fully relocatable
13896: image files.
13897:
13898: @cindex image file loader
13899: @cindex relocating loader
13900: @cindex loader for image files
13901: These image file variants have several restrictions in common; they are
13902: caused by the design of the image file loader:
13903:
13904: @itemize @bullet
13905: @item
13906: There is only one segment; in particular, this means, that an image file
13907: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
13908: them). The contents of the stacks are not represented, either.
13909:
13910: @item
13911: The only kinds of relocation supported are: adding the same offset to
13912: all cells that represent data addresses; and replacing special tokens
13913: with code addresses or with pieces of machine code.
13914:
13915: If any complex computations involving addresses are performed, the
13916: results cannot be represented in the image file. Several applications that
13917: use such computations come to mind:
13918: @itemize @minus
13919: @item
13920: Hashing addresses (or data structures which contain addresses) for table
13921: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
13922: purpose, you will have no problem, because the hash tables are
13923: recomputed automatically when the system is started. If you use your own
13924: hash tables, you will have to do something similar.
13925:
13926: @item
13927: There's a cute implementation of doubly-linked lists that uses
13928: @code{XOR}ed addresses. You could represent such lists as singly-linked
13929: in the image file, and restore the doubly-linked representation on
13930: startup.@footnote{In my opinion, though, you should think thrice before
13931: using a doubly-linked list (whatever implementation).}
13932:
13933: @item
13934: The code addresses of run-time routines like @code{docol:} cannot be
13935: represented in the image file (because their tokens would be replaced by
13936: machine code in direct threaded implementations). As a workaround,
13937: compute these addresses at run-time with @code{>code-address} from the
13938: executions tokens of appropriate words (see the definitions of
13939: @code{docol:} and friends in @file{kernel/getdoers.fs}).
13940:
13941: @item
13942: On many architectures addresses are represented in machine code in some
13943: shifted or mangled form. You cannot put @code{CODE} words that contain
13944: absolute addresses in this form in a relocatable image file. Workarounds
13945: are representing the address in some relative form (e.g., relative to
13946: the CFA, which is present in some register), or loading the address from
13947: a place where it is stored in a non-mangled form.
13948: @end itemize
13949: @end itemize
13950:
13951: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
13952: @section Non-Relocatable Image Files
13953: @cindex non-relocatable image files
13954: @cindex image file, non-relocatable
13955:
13956: These files are simple memory dumps of the dictionary. They are specific
13957: to the executable (i.e., @file{gforth} file) they were created
13958: with. What's worse, they are specific to the place on which the
13959: dictionary resided when the image was created. Now, there is no
13960: guarantee that the dictionary will reside at the same place the next
13961: time you start Gforth, so there's no guarantee that a non-relocatable
13962: image will work the next time (Gforth will complain instead of crashing,
13963: though).
13964:
13965: You can create a non-relocatable image file with
13966:
13967:
13968: doc-savesystem
13969:
13970:
13971: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
13972: @section Data-Relocatable Image Files
13973: @cindex data-relocatable image files
13974: @cindex image file, data-relocatable
13975:
13976: These files contain relocatable data addresses, but fixed code addresses
13977: (instead of tokens). They are specific to the executable (i.e.,
13978: @file{gforth} file) they were created with. For direct threading on some
13979: architectures (e.g., the i386), data-relocatable images do not work. You
13980: get a data-relocatable image, if you use @file{gforthmi} with a
13981: Gforth binary that is not doubly indirect threaded (@pxref{Fully
13982: Relocatable Image Files}).
13983:
13984: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
13985: @section Fully Relocatable Image Files
13986: @cindex fully relocatable image files
13987: @cindex image file, fully relocatable
13988:
13989: @cindex @file{kern*.fi}, relocatability
13990: @cindex @file{gforth.fi}, relocatability
13991: These image files have relocatable data addresses, and tokens for code
13992: addresses. They can be used with different binaries (e.g., with and
13993: without debugging) on the same machine, and even across machines with
13994: the same data formats (byte order, cell size, floating point
13995: format). However, they are usually specific to the version of Gforth
13996: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
13997: are fully relocatable.
13998:
13999: There are two ways to create a fully relocatable image file:
14000:
14001: @menu
14002: * gforthmi:: The normal way
14003: * cross.fs:: The hard way
14004: @end menu
14005:
14006: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14007: @subsection @file{gforthmi}
14008: @cindex @file{comp-i.fs}
14009: @cindex @file{gforthmi}
14010:
14011: You will usually use @file{gforthmi}. If you want to create an
14012: image @i{file} that contains everything you would load by invoking
14013: Gforth with @code{gforth @i{options}}, you simply say:
14014: @example
14015: gforthmi @i{file} @i{options}
14016: @end example
14017:
14018: E.g., if you want to create an image @file{asm.fi} that has the file
14019: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14020: like this:
14021:
14022: @example
14023: gforthmi asm.fi asm.fs
14024: @end example
14025:
14026: @file{gforthmi} is implemented as a sh script and works like this: It
14027: produces two non-relocatable images for different addresses and then
14028: compares them. Its output reflects this: first you see the output (if
14029: any) of the two Gforth invocations that produce the non-relocatable image
14030: files, then you see the output of the comparing program: It displays the
14031: offset used for data addresses and the offset used for code addresses;
14032: moreover, for each cell that cannot be represented correctly in the
14033: image files, it displays a line like this:
14034:
14035: @example
14036: 78DC BFFFFA50 BFFFFA40
14037: @end example
14038:
14039: This means that at offset $78dc from @code{forthstart}, one input image
14040: contains $bffffa50, and the other contains $bffffa40. Since these cells
14041: cannot be represented correctly in the output image, you should examine
14042: these places in the dictionary and verify that these cells are dead
14043: (i.e., not read before they are written).
14044:
14045: @cindex --application, @code{gforthmi} option
14046: If you insert the option @code{--application} in front of the image file
14047: name, you will get an image that uses the @code{--appl-image} option
14048: instead of the @code{--image-file} option (@pxref{Invoking
14049: Gforth}). When you execute such an image on Unix (by typing the image
14050: name as command), the Gforth engine will pass all options to the image
14051: instead of trying to interpret them as engine options.
14052:
14053: If you type @file{gforthmi} with no arguments, it prints some usage
14054: instructions.
14055:
14056: @cindex @code{savesystem} during @file{gforthmi}
14057: @cindex @code{bye} during @file{gforthmi}
14058: @cindex doubly indirect threaded code
14059: @cindex environment variables
14060: @cindex @code{GFORTHD} -- environment variable
14061: @cindex @code{GFORTH} -- environment variable
14062: @cindex @code{gforth-ditc}
14063: There are a few wrinkles: After processing the passed @i{options}, the
14064: words @code{savesystem} and @code{bye} must be visible. A special doubly
14065: indirect threaded version of the @file{gforth} executable is used for
14066: creating the non-relocatable images; you can pass the exact filename of
14067: this executable through the environment variable @code{GFORTHD}
14068: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14069: indirect threaded, you will not get a fully relocatable image, but a
14070: data-relocatable image (because there is no code address offset). The
14071: normal @file{gforth} executable is used for creating the relocatable
14072: image; you can pass the exact filename of this executable through the
14073: environment variable @code{GFORTH}.
14074:
14075: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14076: @subsection @file{cross.fs}
14077: @cindex @file{cross.fs}
14078: @cindex cross-compiler
14079: @cindex metacompiler
14080: @cindex target compiler
14081:
14082: You can also use @code{cross}, a batch compiler that accepts a Forth-like
14083: programming language (@pxref{Cross Compiler}).
14084:
14085: @code{cross} allows you to create image files for machines with
14086: different data sizes and data formats than the one used for generating
14087: the image file. You can also use it to create an application image that
14088: does not contain a Forth compiler. These features are bought with
14089: restrictions and inconveniences in programming. E.g., addresses have to
14090: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14091: order to make the code relocatable.
14092:
14093:
14094: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14095: @section Stack and Dictionary Sizes
14096: @cindex image file, stack and dictionary sizes
14097: @cindex dictionary size default
14098: @cindex stack size default
14099:
14100: If you invoke Gforth with a command line flag for the size
14101: (@pxref{Invoking Gforth}), the size you specify is stored in the
14102: dictionary. If you save the dictionary with @code{savesystem} or create
14103: an image with @file{gforthmi}, this size will become the default
14104: for the resulting image file. E.g., the following will create a
14105: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
14106:
14107: @example
14108: gforthmi gforth.fi -m 1M
14109: @end example
14110:
14111: In other words, if you want to set the default size for the dictionary
14112: and the stacks of an image, just invoke @file{gforthmi} with the
14113: appropriate options when creating the image.
14114:
14115: @cindex stack size, cache-friendly
14116: Note: For cache-friendly behaviour (i.e., good performance), you should
14117: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14118: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14119: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14120:
14121: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14122: @section Running Image Files
14123: @cindex running image files
14124: @cindex invoking image files
14125: @cindex image file invocation
14126:
14127: @cindex -i, invoke image file
14128: @cindex --image file, invoke image file
14129: You can invoke Gforth with an image file @i{image} instead of the
14130: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14131: @example
14132: gforth -i @i{image}
14133: @end example
14134:
14135: @cindex executable image file
14136: @cindex image file, executable
14137: If your operating system supports starting scripts with a line of the
14138: form @code{#! ...}, you just have to type the image file name to start
14139: Gforth with this image file (note that the file extension @code{.fi} is
14140: just a convention). I.e., to run Gforth with the image file @i{image},
14141: you can just type @i{image} instead of @code{gforth -i @i{image}}.
14142: This works because every @code{.fi} file starts with a line of this
14143: format:
14144:
14145: @example
14146: #! /usr/local/bin/gforth-0.4.0 -i
14147: @end example
14148:
14149: The file and pathname for the Gforth engine specified on this line is
14150: the specific Gforth executable that it was built against; i.e. the value
14151: of the environment variable @code{GFORTH} at the time that
14152: @file{gforthmi} was executed.
14153:
14154: You can make use of the same shell capability to make a Forth source
14155: file into an executable. For example, if you place this text in a file:
14156:
14157: @example
14158: #! /usr/local/bin/gforth
14159:
14160: ." Hello, world" CR
14161: bye
14162: @end example
14163:
14164: @noindent
14165: and then make the file executable (chmod +x in Unix), you can run it
14166: directly from the command line. The sequence @code{#!} is used in two
14167: ways; firstly, it is recognised as a ``magic sequence'' by the operating
14168: system@footnote{The Unix kernel actually recognises two types of files:
14169: executable files and files of data, where the data is processed by an
14170: interpreter that is specified on the ``interpreter line'' -- the first
14171: line of the file, starting with the sequence #!. There may be a small
14172: limit (e.g., 32) on the number of characters that may be specified on
14173: the interpreter line.} secondly it is treated as a comment character by
14174: Gforth. Because of the second usage, a space is required between
14175: @code{#!} and the path to the executable (moreover, some Unixes
14176: require the sequence @code{#! /}).
14177:
14178: The disadvantage of this latter technique, compared with using
14179: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14180: compiled on-the-fly, each time the program is invoked.
14181:
14182: doc-#!
14183:
14184:
14185: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14186: @section Modifying the Startup Sequence
14187: @cindex startup sequence for image file
14188: @cindex image file initialization sequence
14189: @cindex initialization sequence of image file
14190:
14191: You can add your own initialization to the startup sequence through the
14192: deferred word @code{'cold}. @code{'cold} is invoked just before the
14193: image-specific command line processing (i.e., loading files and
14194: evaluating (@code{-e}) strings) starts.
14195:
14196: A sequence for adding your initialization usually looks like this:
14197:
14198: @example
14199: :noname
14200: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14201: ... \ your stuff
14202: ; IS 'cold
14203: @end example
14204:
14205: @cindex turnkey image files
14206: @cindex image file, turnkey applications
14207: You can make a turnkey image by letting @code{'cold} execute a word
14208: (your turnkey application) that never returns; instead, it exits Gforth
14209: via @code{bye} or @code{throw}.
14210:
14211: @cindex command-line arguments, access
14212: @cindex arguments on the command line, access
14213: You can access the (image-specific) command-line arguments through the
14214: variables @code{argc} and @code{argv}. @code{arg} provides convenient
14215: access to @code{argv}.
14216:
14217: If @code{'cold} exits normally, Gforth processes the command-line
14218: arguments as files to be loaded and strings to be evaluated. Therefore,
14219: @code{'cold} should remove the arguments it has used in this case.
14220:
14221:
14222:
14223: doc-'cold
14224: doc-argc
14225: doc-argv
14226: doc-arg
14227:
14228:
14229:
14230: @c ******************************************************************
14231: @node Engine, Binding to System Library, Image Files, Top
14232: @chapter Engine
14233: @cindex engine
14234: @cindex virtual machine
14235:
14236: Reading this chapter is not necessary for programming with Gforth. It
14237: may be helpful for finding your way in the Gforth sources.
14238:
14239: The ideas in this section have also been published in Bernd Paysan,
14240: @cite{ANS fig/GNU/??? Forth} (in German), Forth-Tagung '93 and M. Anton
14241: Ertl, @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14242: Portable Forth Engine}}, EuroForth '93.
14243:
14244: @menu
14245: * Portability::
14246: * Threading::
14247: * Primitives::
14248: * Performance::
14249: @end menu
14250:
14251: @node Portability, Threading, Engine, Engine
14252: @section Portability
14253: @cindex engine portability
14254:
14255: An important goal of the Gforth Project is availability across a wide
14256: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14257: achieved this goal by manually coding the engine in assembly language
14258: for several then-popular processors. This approach is very
14259: labor-intensive and the results are short-lived due to progress in
14260: computer architecture.
14261:
14262: @cindex C, using C for the engine
14263: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14264: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14265: particularly popular for UNIX-based Forths due to the large variety of
14266: architectures of UNIX machines. Unfortunately an implementation in C
14267: does not mix well with the goals of efficiency and with using
14268: traditional techniques: Indirect or direct threading cannot be expressed
14269: in C, and switch threading, the fastest technique available in C, is
14270: significantly slower. Another problem with C is that it is very
14271: cumbersome to express double integer arithmetic.
14272:
14273: @cindex GNU C for the engine
14274: @cindex long long
14275: Fortunately, there is a portable language that does not have these
14276: limitations: GNU C, the version of C processed by the GNU C compiler
14277: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14278: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14279: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14280: threading possible, its @code{long long} type (@pxref{Long Long, ,
14281: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
14282: double numbers@footnote{Unfortunately, long longs are not implemented
14283: properly on all machines (e.g., on alpha-osf1, long longs are only 64
14284: bits, the same size as longs (and pointers), but they should be twice as
14285: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
14286: C Manual}). So, we had to implement doubles in C after all. Still, on
14287: most machines we can use long longs and achieve better performance than
14288: with the emulation package.}. GNU C is available for free on all
14289: important (and many unimportant) UNIX machines, VMS, 80386s running
14290: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14291: on all these machines.
14292:
14293: Writing in a portable language has the reputation of producing code that
14294: is slower than assembly. For our Forth engine we repeatedly looked at
14295: the code produced by the compiler and eliminated most compiler-induced
14296: inefficiencies by appropriate changes in the source code.
14297:
14298: @cindex explicit register declarations
14299: @cindex --enable-force-reg, configuration flag
14300: @cindex -DFORCE_REG
14301: However, register allocation cannot be portably influenced by the
14302: programmer, leading to some inefficiencies on register-starved
14303: machines. We use explicit register declarations (@pxref{Explicit Reg
14304: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14305: improve the speed on some machines. They are turned on by using the
14306: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14307: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14308: machine, but also on the compiler version: On some machines some
14309: compiler versions produce incorrect code when certain explicit register
14310: declarations are used. So by default @code{-DFORCE_REG} is not used.
14311:
14312: @node Threading, Primitives, Portability, Engine
14313: @section Threading
14314: @cindex inner interpreter implementation
14315: @cindex threaded code implementation
14316:
14317: @cindex labels as values
14318: GNU C's labels as values extension (available since @code{gcc-2.0},
14319: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
14320: makes it possible to take the address of @i{label} by writing
14321: @code{&&@i{label}}. This address can then be used in a statement like
14322: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
14323: @code{goto x}.
14324:
14325: @cindex @code{NEXT}, indirect threaded
14326: @cindex indirect threaded inner interpreter
14327: @cindex inner interpreter, indirect threaded
14328: With this feature an indirect threaded @code{NEXT} looks like:
14329: @example
14330: cfa = *ip++;
14331: ca = *cfa;
14332: goto *ca;
14333: @end example
14334: @cindex instruction pointer
14335: For those unfamiliar with the names: @code{ip} is the Forth instruction
14336: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14337: execution token and points to the code field of the next word to be
14338: executed; The @code{ca} (code address) fetched from there points to some
14339: executable code, e.g., a primitive or the colon definition handler
14340: @code{docol}.
14341:
14342: @cindex @code{NEXT}, direct threaded
14343: @cindex direct threaded inner interpreter
14344: @cindex inner interpreter, direct threaded
14345: Direct threading is even simpler:
14346: @example
14347: ca = *ip++;
14348: goto *ca;
14349: @end example
14350:
14351: Of course we have packaged the whole thing neatly in macros called
14352: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
14353:
14354: @menu
14355: * Scheduling::
14356: * Direct or Indirect Threaded?::
14357: * DOES>::
14358: @end menu
14359:
14360: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14361: @subsection Scheduling
14362: @cindex inner interpreter optimization
14363:
14364: There is a little complication: Pipelined and superscalar processors,
14365: i.e., RISC and some modern CISC machines can process independent
14366: instructions while waiting for the results of an instruction. The
14367: compiler usually reorders (schedules) the instructions in a way that
14368: achieves good usage of these delay slots. However, on our first tries
14369: the compiler did not do well on scheduling primitives. E.g., for
14370: @code{+} implemented as
14371: @example
14372: n=sp[0]+sp[1];
14373: sp++;
14374: sp[0]=n;
14375: NEXT;
14376: @end example
14377: the @code{NEXT} comes strictly after the other code, i.e., there is
14378: nearly no scheduling. After a little thought the problem becomes clear:
14379: The compiler cannot know that @code{sp} and @code{ip} point to different
14380: addresses (and the version of @code{gcc} we used would not know it even
14381: if it was possible), so it could not move the load of the cfa above the
14382: store to the TOS. Indeed the pointers could be the same, if code on or
14383: very near the top of stack were executed. In the interest of speed we
14384: chose to forbid this probably unused ``feature'' and helped the compiler
14385: in scheduling: @code{NEXT} is divided into several parts:
14386: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14387: like:
14388: @example
14389: NEXT_P0;
14390: n=sp[0]+sp[1];
14391: sp++;
14392: NEXT_P1;
14393: sp[0]=n;
14394: NEXT_P2;
14395: @end example
14396:
14397: There are various schemes that distribute the different operations of
14398: NEXT between these parts in several ways; in general, different schemes
14399: perform best on different processors. We use a scheme for most
14400: architectures that performs well for most processors of this
14401: architecture; in the furture we may switch to benchmarking and chosing
14402: the scheme on installation time.
14403:
14404:
14405: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
14406: @subsection Direct or Indirect Threaded?
14407: @cindex threading, direct or indirect?
14408:
14409: @cindex -DDIRECT_THREADED
14410: Both! After packaging the nasty details in macro definitions we
14411: realized that we could switch between direct and indirect threading by
14412: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
14413: defining a few machine-specific macros for the direct-threading case.
14414: On the Forth level we also offer access words that hide the
14415: differences between the threading methods (@pxref{Threading Words}).
14416:
14417: Indirect threading is implemented completely machine-independently.
14418: Direct threading needs routines for creating jumps to the executable
14419: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
14420: machine-dependent, but they do not amount to many source lines. Therefore,
14421: even porting direct threading to a new machine requires little effort.
14422:
14423: @cindex --enable-indirect-threaded, configuration flag
14424: @cindex --enable-direct-threaded, configuration flag
14425: The default threading method is machine-dependent. You can enforce a
14426: specific threading method when building Gforth with the configuration
14427: flag @code{--enable-direct-threaded} or
14428: @code{--enable-indirect-threaded}. Note that direct threading is not
14429: supported on all machines.
14430:
14431: @node DOES>, , Direct or Indirect Threaded?, Threading
14432: @subsection DOES>
14433: @cindex @code{DOES>} implementation
14434:
14435: @cindex @code{dodoes} routine
14436: @cindex @code{DOES>}-code
14437: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14438: the chunk of code executed by every word defined by a
14439: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
14440: the Forth code to be executed, i.e. the code after the
14441: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
14442:
14443: In fig-Forth the code field points directly to the @code{dodoes} and the
14444: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
14445: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
14446: the Forth-79 and all later standards, because in fig-Forth this address
14447: lies in the body (which is illegal in these standards). However, by
14448: making the code field larger for all words this solution becomes legal
14449: again. We use this approach for the indirect threaded version and for
14450: direct threading on some machines. Leaving a cell unused in most words
14451: is a bit wasteful, but on the machines we are targeting this is hardly a
14452: problem. The other reason for having a code field size of two cells is
14453: to avoid having different image files for direct and indirect threaded
14454: systems (direct threaded systems require two-cell code fields on many
14455: machines).
14456:
14457: @cindex @code{DOES>}-handler
14458: The other approach is that the code field points or jumps to the cell
14459: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
14460: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
14461: @code{DOES>}-code address by computing the code address, i.e., the address of
14462: the jump to @code{dodoes}, and add the length of that jump field. A variant of
14463: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
14464: return address (which can be found in the return register on RISCs) is
14465: the @code{DOES>}-code address. Since the two cells available in the code field
14466: are used up by the jump to the code address in direct threading on many
14467: architectures, we use this approach for direct threading on these
14468: architectures. We did not want to add another cell to the code field.
14469:
14470: @node Primitives, Performance, Threading, Engine
14471: @section Primitives
14472: @cindex primitives, implementation
14473: @cindex virtual machine instructions, implementation
14474:
14475: @menu
14476: * Automatic Generation::
14477: * TOS Optimization::
14478: * Produced code::
14479: @end menu
14480:
14481: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14482: @subsection Automatic Generation
14483: @cindex primitives, automatic generation
14484:
14485: @cindex @file{prims2x.fs}
14486: Since the primitives are implemented in a portable language, there is no
14487: longer any need to minimize the number of primitives. On the contrary,
14488: having many primitives has an advantage: speed. In order to reduce the
14489: number of errors in primitives and to make programming them easier, we
14490: provide a tool, the primitive generator (@file{prims2x.fs}), that
14491: automatically generates most (and sometimes all) of the C code for a
14492: primitive from the stack effect notation. The source for a primitive
14493: has the following form:
14494:
14495: @cindex primitive source format
14496: @format
14497: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
14498: [@code{""}@i{glossary entry}@code{""}]
14499: @i{C code}
14500: [@code{:}
14501: @i{Forth code}]
14502: @end format
14503:
14504: The items in brackets are optional. The category and glossary fields
14505: are there for generating the documentation, the Forth code is there
14506: for manual implementations on machines without GNU C. E.g., the source
14507: for the primitive @code{+} is:
14508: @example
14509: + ( n1 n2 -- n ) core plus
14510: n = n1+n2;
14511: @end example
14512:
14513: This looks like a specification, but in fact @code{n = n1+n2} is C
14514: code. Our primitive generation tool extracts a lot of information from
14515: the stack effect notations@footnote{We use a one-stack notation, even
14516: though we have separate data and floating-point stacks; The separate
14517: notation can be generated easily from the unified notation.}: The number
14518: of items popped from and pushed on the stack, their type, and by what
14519: name they are referred to in the C code. It then generates a C code
14520: prelude and postlude for each primitive. The final C code for @code{+}
14521: looks like this:
14522:
14523: @example
14524: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
14525: /* */ /* documentation */
14526: NAME("+") /* debugging output (with -DDEBUG) */
14527: @{
14528: DEF_CA /* definition of variable ca (indirect threading) */
14529: Cell n1; /* definitions of variables */
14530: Cell n2;
14531: Cell n;
14532: NEXT_P0; /* NEXT part 0 */
14533: n1 = (Cell) sp[1]; /* input */
14534: n2 = (Cell) TOS;
14535: sp += 1; /* stack adjustment */
14536: @{
14537: n = n1+n2; /* C code taken from the source */
14538: @}
14539: NEXT_P1; /* NEXT part 1 */
14540: TOS = (Cell)n; /* output */
14541: NEXT_P2; /* NEXT part 2 */
14542: @}
14543: @end example
14544:
14545: This looks long and inefficient, but the GNU C compiler optimizes quite
14546: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14547: HP RISC machines: Defining the @code{n}s does not produce any code, and
14548: using them as intermediate storage also adds no cost.
14549:
14550: There are also other optimizations that are not illustrated by this
14551: example: assignments between simple variables are usually for free (copy
14552: propagation). If one of the stack items is not used by the primitive
14553: (e.g. in @code{drop}), the compiler eliminates the load from the stack
14554: (dead code elimination). On the other hand, there are some things that
14555: the compiler does not do, therefore they are performed by
14556: @file{prims2x.fs}: The compiler does not optimize code away that stores
14557: a stack item to the place where it just came from (e.g., @code{over}).
14558:
14559: While programming a primitive is usually easy, there are a few cases
14560: where the programmer has to take the actions of the generator into
14561: account, most notably @code{?dup}, but also words that do not (always)
14562: fall through to @code{NEXT}.
14563:
14564: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14565: @subsection TOS Optimization
14566: @cindex TOS optimization for primitives
14567: @cindex primitives, keeping the TOS in a register
14568:
14569: An important optimization for stack machine emulators, e.g., Forth
14570: engines, is keeping one or more of the top stack items in
14571: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
14572: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
14573: @itemize @bullet
14574: @item
14575: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
14576: due to fewer loads from and stores to the stack.
14577: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14578: @i{y<n}, due to additional moves between registers.
14579: @end itemize
14580:
14581: @cindex -DUSE_TOS
14582: @cindex -DUSE_NO_TOS
14583: In particular, keeping one item in a register is never a disadvantage,
14584: if there are enough registers. Keeping two items in registers is a
14585: disadvantage for frequent words like @code{?branch}, constants,
14586: variables, literals and @code{i}. Therefore our generator only produces
14587: code that keeps zero or one items in registers. The generated C code
14588: covers both cases; the selection between these alternatives is made at
14589: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14590: code for @code{+} is just a simple variable name in the one-item case,
14591: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14592: GNU C compiler tries to keep simple variables like @code{TOS} in
14593: registers, and it usually succeeds, if there are enough registers.
14594:
14595: @cindex -DUSE_FTOS
14596: @cindex -DUSE_NO_FTOS
14597: The primitive generator performs the TOS optimization for the
14598: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14599: operations the benefit of this optimization is even larger:
14600: floating-point operations take quite long on most processors, but can be
14601: performed in parallel with other operations as long as their results are
14602: not used. If the FP-TOS is kept in a register, this works. If
14603: it is kept on the stack, i.e., in memory, the store into memory has to
14604: wait for the result of the floating-point operation, lengthening the
14605: execution time of the primitive considerably.
14606:
14607: The TOS optimization makes the automatic generation of primitives a
14608: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14609: @code{TOS} is not sufficient. There are some special cases to
14610: consider:
14611: @itemize @bullet
14612: @item In the case of @code{dup ( w -- w w )} the generator must not
14613: eliminate the store to the original location of the item on the stack,
14614: if the TOS optimization is turned on.
14615: @item Primitives with stack effects of the form @code{--}
14616: @i{out1}...@i{outy} must store the TOS to the stack at the start.
14617: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
14618: must load the TOS from the stack at the end. But for the null stack
14619: effect @code{--} no stores or loads should be generated.
14620: @end itemize
14621:
14622: @node Produced code, , TOS Optimization, Primitives
14623: @subsection Produced code
14624: @cindex primitives, assembly code listing
14625:
14626: @cindex @file{engine.s}
14627: To see what assembly code is produced for the primitives on your machine
14628: with your compiler and your flag settings, type @code{make engine.s} and
14629: look at the resulting file @file{engine.s}. Alternatively, you can also
14630: disassemble the code of primitives with @code{see} on some architectures.
14631:
14632: @node Performance, , Primitives, Engine
14633: @section Performance
14634: @cindex performance of some Forth interpreters
14635: @cindex engine performance
14636: @cindex benchmarking Forth systems
14637: @cindex Gforth performance
14638:
14639: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
14640: impossible to write a significantly faster engine.
14641:
14642: On register-starved machines like the 386 architecture processors
14643: improvements are possible, because @code{gcc} does not utilize the
14644: registers as well as a human, even with explicit register declarations;
14645: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
14646: and hand-tuned it for the 486; this system is 1.19 times faster on the
14647: Sieve benchmark on a 486DX2/66 than Gforth compiled with
14648: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
14649: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
14650: registers fit in real registers (and we can even afford to use the TOS
14651: optimization), resulting in a speedup of 1.14 on the sieve over the
14652: earlier results.
14653:
14654: @cindex Win32Forth performance
14655: @cindex NT Forth performance
14656: @cindex eforth performance
14657: @cindex ThisForth performance
14658: @cindex PFE performance
14659: @cindex TILE performance
14660: The potential advantage of assembly language implementations is not
14661: necessarily realized in complete Forth systems: We compared Gforth-0.4.9
14662: (direct threaded, compiled with @code{gcc-2.95.1} and
14663: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
14664: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
14665: (with and without peephole (aka pinhole) optimization of the threaded
14666: code); all these systems were written in assembly language. We also
14667: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
14668: with @code{gcc-2.6.3} with the default configuration for Linux:
14669: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
14670: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
14671: employs peephole optimization of the threaded code) and TILE (compiled
14672: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
14673: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
14674: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
14675: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
14676: then extended it to run the benchmarks, added the peephole optimizer,
14677: ran the benchmarks and reported the results.
14678:
14679: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
14680: matrix multiplication come from the Stanford integer benchmarks and have
14681: been translated into Forth by Martin Fraeman; we used the versions
14682: included in the TILE Forth package, but with bigger data set sizes; and
14683: a recursive Fibonacci number computation for benchmarking calling
14684: performance. The following table shows the time taken for the benchmarks
14685: scaled by the time taken by Gforth (in other words, it shows the speedup
14686: factor that Gforth achieved over the other systems).
14687:
14688: @example
14689: relative Win32- NT eforth This-
14690: time Gforth Forth Forth eforth +opt PFE Forth TILE
14691: sieve 1.00 1.60 1.32 1.60 0.98 1.82 3.67 9.91
14692: bubble 1.00 1.55 1.66 1.75 1.04 1.78 4.58
14693: matmul 1.00 1.71 1.57 1.69 0.86 1.83 4.74
14694: fib 1.00 1.76 1.54 1.41 1.00 2.01 3.45 4.96
14695: @end example
14696:
14697: You may be quite surprised by the good performance of Gforth when
14698: compared with systems written in assembly language. One important reason
14699: for the disappointing performance of these other systems is probably
14700: that they are not written optimally for the 486 (e.g., they use the
14701: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
14702: but costly method for relocating the Forth image: like @code{cforth}, it
14703: computes the actual addresses at run time, resulting in two address
14704: computations per @code{NEXT} (@pxref{Image File Background}).
14705:
14706: Only Eforth with the peephole optimizer performs comparable to
14707: Gforth. The speedups achieved with peephole optimization of threaded
14708: code are quite remarkable. Adding a peephole optimizer to Gforth should
14709: cause similar speedups.
14710:
14711: The speedup of Gforth over PFE, ThisForth and TILE can be easily
14712: explained with the self-imposed restriction of the latter systems to
14713: standard C, which makes efficient threading impossible (however, the
14714: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
14715: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
14716: Moreover, current C compilers have a hard time optimizing other aspects
14717: of the ThisForth and the TILE source.
14718:
14719: The performance of Gforth on 386 architecture processors varies widely
14720: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
14721: allocate any of the virtual machine registers into real machine
14722: registers by itself and would not work correctly with explicit register
14723: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
14724: the Sieve) than the one measured above.
14725:
14726: Note that there have been several releases of Win32Forth since the
14727: release presented here, so the results presented above may have little
14728: predictive value for the performance of Win32Forth today (results for
14729: the current release on an i486DX2/66 are welcome).
14730:
14731: @cindex @file{Benchres}
14732: In
14733: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
14734: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
14735: Maierhofer (presented at EuroForth '95), an indirect threaded version of
14736: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
14737: several native code systems; that version of Gforth is slower on a 486
14738: than the direct threaded version used here. You can find a newer version
14739: of these measurements at
14740: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
14741: find numbers for Gforth on various machines in @file{Benchres}.
14742:
14743: @c ******************************************************************
14744: @node Binding to System Library, Cross Compiler, Engine, Top
14745: @chapter Binding to System Library
14746:
14747: @node Cross Compiler, Bugs, Binding to System Library, Top
14748: @chapter Cross Compiler
14749: @cindex @file{cross.fs}
14750: @cindex cross-compiler
14751: @cindex metacompiler
14752: @cindex target compiler
14753:
14754: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
14755: mostly written in Forth, including crucial parts like the outer
14756: interpreter and compiler, it needs compiled Forth code to get
14757: started. The cross compiler allows to create new images for other
14758: architectures, even running under another Forth system.
14759:
14760: @menu
14761: * Using the Cross Compiler::
14762: * How the Cross Compiler Works::
14763: @end menu
14764:
14765: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
14766: @section Using the Cross Compiler
14767:
14768: The cross compiler uses a language that resembles Forth, but isn't. The
14769: main difference is that you can execute Forth code after definition,
14770: while you usually can't execute the code compiled by cross, because the
14771: code you are compiling is typically for a different computer than the
14772: one you are compiling on.
14773:
14774: @c anton: This chapter is somewhat different from waht I would expect: I
14775: @c would expect an explanation of the cross language and how to create an
14776: @c application image with it. The section explains some aspects of
14777: @c creating a Gforth kernel.
14778:
14779: The Makefile is already set up to allow you to create kernels for new
14780: architectures with a simple make command. The generic kernels using the
14781: GCC compiled virtual machine are created in the normal build process
14782: with @code{make}. To create a embedded Gforth executable for e.g. the
14783: 8086 processor (running on a DOS machine), type
14784:
14785: @example
14786: make kernl-8086.fi
14787: @end example
14788:
14789: This will use the machine description from the @file{arch/8086}
14790: directory to create a new kernel. A machine file may look like that:
14791:
14792: @example
14793: \ Parameter for target systems 06oct92py
14794:
14795: 4 Constant cell \ cell size in bytes
14796: 2 Constant cell<< \ cell shift to bytes
14797: 5 Constant cell>bit \ cell shift to bits
14798: 8 Constant bits/char \ bits per character
14799: 8 Constant bits/byte \ bits per byte [default: 8]
14800: 8 Constant float \ bytes per float
14801: 8 Constant /maxalign \ maximum alignment in bytes
14802: false Constant bigendian \ byte order
14803: ( true=big, false=little )
14804:
14805: include machpc.fs \ feature list
14806: @end example
14807:
14808: This part is obligatory for the cross compiler itself, the feature list
14809: is used by the kernel to conditionally compile some features in and out,
14810: depending on whether the target supports these features.
14811:
14812: There are some optional features, if you define your own primitives,
14813: have an assembler, or need special, nonstandard preparation to make the
14814: boot process work. @code{asm-include} includes an assembler,
14815: @code{prims-include} includes primitives, and @code{>boot} prepares for
14816: booting.
14817:
14818: @example
14819: : asm-include ." Include assembler" cr
14820: s" arch/8086/asm.fs" included ;
14821:
14822: : prims-include ." Include primitives" cr
14823: s" arch/8086/prim.fs" included ;
14824:
14825: : >boot ." Prepare booting" cr
14826: s" ' boot >body into-forth 1+ !" evaluate ;
14827: @end example
14828:
14829: These words are used as sort of macro during the cross compilation in
14830: the file @file{kernel/main.fs}. Instead of using these macros, it would
14831: be possible --- but more complicated --- to write a new kernel project
14832: file, too.
14833:
14834: @file{kernel/main.fs} expects the machine description file name on the
14835: stack; the cross compiler itself (@file{cross.fs}) assumes that either
14836: @code{mach-file} leaves a counted string on the stack, or
14837: @code{machine-file} leaves an address, count pair of the filename on the
14838: stack.
14839:
14840: The feature list is typically controlled using @code{SetValue}, generic
14841: files that are used by several projects can use @code{DefaultValue}
14842: instead. Both functions work like @code{Value}, when the value isn't
14843: defined, but @code{SetValue} works like @code{to} if the value is
14844: defined, and @code{DefaultValue} doesn't set anything, if the value is
14845: defined.
14846:
14847: @example
14848: \ generic mach file for pc gforth 03sep97jaw
14849:
14850: true DefaultValue NIL \ relocating
14851:
14852: >ENVIRON
14853:
14854: true DefaultValue file \ controls the presence of the
14855: \ file access wordset
14856: true DefaultValue OS \ flag to indicate a operating system
14857:
14858: true DefaultValue prims \ true: primitives are c-code
14859:
14860: true DefaultValue floating \ floating point wordset is present
14861:
14862: true DefaultValue glocals \ gforth locals are present
14863: \ will be loaded
14864: true DefaultValue dcomps \ double number comparisons
14865:
14866: true DefaultValue hash \ hashing primitives are loaded/present
14867:
14868: true DefaultValue xconds \ used together with glocals,
14869: \ special conditionals supporting gforths'
14870: \ local variables
14871: true DefaultValue header \ save a header information
14872:
14873: true DefaultValue backtrace \ enables backtrace code
14874:
14875: false DefaultValue ec
14876: false DefaultValue crlf
14877:
14878: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
14879:
14880: &16 KB DefaultValue stack-size
14881: &15 KB &512 + DefaultValue fstack-size
14882: &15 KB DefaultValue rstack-size
14883: &14 KB &512 + DefaultValue lstack-size
14884: @end example
14885:
14886: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
14887: @section How the Cross Compiler Works
14888:
14889: @node Bugs, Origin, Cross Compiler, Top
14890: @appendix Bugs
14891: @cindex bug reporting
14892:
14893: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
14894:
14895: If you find a bug, please send a bug report to
14896: @email{bug-gforth@@gnu.org}. A bug report should include this
14897: information:
14898:
14899: @itemize @bullet
14900: @item
14901: A program (or a sequence of keyboard commands) that reproduces the bug.
14902: @item
14903: A description of what you think constitutes the buggy behaviour.
14904: @item
14905: The Gforth version used (it is announced at the start of an
14906: interactive Gforth session).
14907: @item
14908: The machine and operating system (on Unix
14909: systems @code{uname -a} will report this information).
14910: @item
14911: The installation options (you can find the configure options at the
14912: start of @file{config.status}) and configuration (@code{configure}
14913: output or @file{config.cache}).
14914: @item
14915: A complete list of changes (if any) you (or your installer) have made to the
14916: Gforth sources.
14917: @end itemize
14918:
14919: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
14920: to Report Bugs, gcc.info, GNU C Manual}.
14921:
14922:
14923: @node Origin, Forth-related information, Bugs, Top
14924: @appendix Authors and Ancestors of Gforth
14925:
14926: @section Authors and Contributors
14927: @cindex authors of Gforth
14928: @cindex contributors to Gforth
14929:
14930: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
14931: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
14932: lot to the manual. Assemblers and disassemblers were contributed by
14933: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
14934: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
14935: inspired us with their continuous feedback. Lennart Benshop contributed
14936: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
14937: support for calling C libraries. Helpful comments also came from Paul
14938: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
14939: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and
14940: Robert Epprecht. Since the release of Gforth-0.2.1 there were also
14941: helpful comments from many others; thank you all, sorry for not listing
14942: you here (but digging through my mailbox to extract your names is on my
14943: to-do list).
14944:
14945: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
14946: and autoconf, among others), and to the creators of the Internet: Gforth
14947: was developed across the Internet, and its authors did not meet
14948: physically for the first 4 years of development.
14949:
14950: @section Pedigree
14951: @cindex pedigree of Gforth
14952:
14953: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
14954: significant part of the design of Gforth was prescribed by ANS Forth.
14955:
14956: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
14957: 32 bit native code version of VolksForth for the Atari ST, written
14958: mostly by Dietrich Weineck.
14959:
14960: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
14961: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
14962: the mid-80s and ported to the Atari ST in 1986. It descends from F83.
14963:
14964: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
14965: Forth-83 standard. !! Pedigree? When?
14966:
14967: A team led by Bill Ragsdale implemented fig-Forth on many processors in
14968: 1979. Robert Selzer and Bill Ragsdale developed the original
14969: implementation of fig-Forth for the 6502 based on microForth.
14970:
14971: The principal architect of microForth was Dean Sanderson. microForth was
14972: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
14973: the 1802, and subsequently implemented on the 8080, the 6800 and the
14974: Z80.
14975:
14976: All earlier Forth systems were custom-made, usually by Charles Moore,
14977: who discovered (as he puts it) Forth during the late 60s. The first full
14978: Forth existed in 1971.
14979:
14980: A part of the information in this section comes from
14981: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
14982: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
14983: Charles H. Moore, presented at the HOPL-II conference and preprinted in
14984: SIGPLAN Notices 28(3), 1993. You can find more historical and
14985: genealogical information about Forth there.
14986:
14987: @c ------------------------------------------------------------------
14988: @node Forth-related information, Word Index, Origin, Top
14989: @appendix Other Forth-related information
14990: @cindex Forth-related information
14991:
14992: @c anton: I threw most of this stuff out, because it can be found through
14993: @c the FAQ and the FAQ is more likely to be up-to-date.
14994:
14995: @cindex comp.lang.forth
14996: @cindex frequently asked questions
14997: There is an active news group (comp.lang.forth) discussing Forth
14998: (including Gforth) and Forth-related issues. Its
14999: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15000: (frequently asked questions and their answers) contains a lot of
15001: information on Forth. You should read it before posting to
15002: comp.lang.forth.
15003:
15004: The ANS Forth standard is most usable in its
15005: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
15006:
15007: @c ------------------------------------------------------------------
15008: @node Word Index, Concept Index, Forth-related information, Top
15009: @unnumbered Word Index
15010:
15011: This index is a list of Forth words that have ``glossary'' entries
15012: within this manual. Each word is listed with its stack effect and
15013: wordset.
15014:
15015: @printindex fn
15016:
15017: @c anton: the name index seems superfluous given the word and concept indices.
15018:
15019: @c @node Name Index, Concept Index, Word Index, Top
15020: @c @unnumbered Name Index
15021:
15022: @c This index is a list of Forth words that have ``glossary'' entries
15023: @c within this manual.
15024:
15025: @c @printindex ky
15026:
15027: @node Concept Index, , Word Index, Top
15028: @unnumbered Concept and Word Index
15029:
15030: Not all entries listed in this index are present verbatim in the
15031: text. This index also duplicates, in abbreviated form, all of the words
15032: listed in the Word Index (only the names are listed for the words here).
15033:
15034: @printindex cp
15035:
15036: @contents
15037: @bye
15038:
15039:
15040:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>