Annotation of gforth/doc/gforth.ds, revision 1.64
1.1 anton 1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28 crook 3:
1.21 crook 4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28 crook 5: @comment 1. x-ref all ambiguous or implementation-defined features?
6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
7: @comment 3. words in miscellaneous section need a home.
8: @comment 4. search for TODO for other minor and major works required.
9: @comment 5. [rats] change all @var to @i in Forth source so that info
10: @comment file looks decent.
1.36 anton 11: @c Not an improvement IMO - anton
12: @c and anyway, this should be taken up
13: @c with Karl Berry (the texinfo guy) - anton
1.29 crook 14: @comment .. would be useful to have a word that identified all deferred words
15: @comment should semantics stuff in intro be moved to another section
16:
1.28 crook 17:
1.1 anton 18: @comment %**start of header (This is for running Texinfo on a region.)
19: @setfilename gforth.info
20: @settitle Gforth Manual
21: @dircategory GNU programming tools
22: @direntry
23: * Gforth: (gforth). A fast interpreter for the Forth language.
24: @end direntry
1.49 anton 25: @c The Texinfo manual also recommends doing this, but for Gforth it may
26: @c not make much sense
27: @c @dircategory Individual utilities
28: @c @direntry
29: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
30: @c @end direntry
31:
1.1 anton 32: @comment @setchapternewpage odd
1.29 crook 33: @comment TODO this gets left in by HTML converter
1.12 anton 34: @macro progstyle {}
35: Programming style note:
1.3 anton 36: @end macro
1.48 anton 37:
38: @macro assignment {}
39: @table @i
40: @item Assignment:
41: @end macro
42: @macro endassignment {}
43: @end table
44: @end macro
45:
1.1 anton 46: @comment %**end of header (This is for running Texinfo on a region.)
47:
1.29 crook 48:
49: @comment ----------------------------------------------------------
50: @comment macros for beautifying glossary entries
51: @comment if these are used, need to strip them out for HTML converter
52: @comment else they get repeated verbatim in HTML output.
53: @comment .. not working yet.
54:
55: @macro GLOSS-START {}
56: @iftex
57: @ninerm
58: @end iftex
59: @end macro
60:
61: @macro GLOSS-END {}
62: @iftex
63: @rm
64: @end iftex
65: @end macro
66:
67: @comment ----------------------------------------------------------
68:
69:
1.10 anton 70: @include version.texi
71:
1.49 anton 72: @ifnottex
1.11 anton 73: This file documents Gforth @value{VERSION}
1.1 anton 74:
1.62 crook 75: Copyright @copyright{} 1995--2000 Free Software Foundation, Inc.
1.1 anton 76:
77: Permission is granted to make and distribute verbatim copies of
78: this manual provided the copyright notice and this permission notice
79: are preserved on all copies.
80:
81: @ignore
82: Permission is granted to process this file through TeX and print the
83: results, provided the printed document carries a copying permission
84: notice identical to this one except for the removal of this paragraph
85: (this paragraph not being relevant to the printed manual).
86:
87: @end ignore
88: Permission is granted to copy and distribute modified versions of this
89: manual under the conditions for verbatim copying, provided also that the
90: sections entitled "Distribution" and "General Public License" are
91: included exactly as in the original, and provided that the entire
92: resulting derived work is distributed under the terms of a permission
93: notice identical to this one.
94:
95: Permission is granted to copy and distribute translations of this manual
96: into another language, under the above conditions for modified versions,
97: except that the sections entitled "Distribution" and "General Public
98: License" may be included in a translation approved by the author instead
99: of in the original English.
1.49 anton 100: @end ifnottex
1.1 anton 101:
102: @finalout
103: @titlepage
104: @sp 10
105: @center @titlefont{Gforth Manual}
106: @sp 2
1.11 anton 107: @center for version @value{VERSION}
1.1 anton 108: @sp 2
1.34 anton 109: @center Neal Crook
1.1 anton 110: @center Anton Ertl
1.6 pazsan 111: @center Bernd Paysan
1.5 anton 112: @center Jens Wilke
1.1 anton 113: @sp 3
1.47 crook 114: @center This manual is permanently under construction and was last updated on 15-Mar-2000
1.1 anton 115:
116: @comment The following two commands start the copyright page.
117: @page
118: @vskip 0pt plus 1filll
1.62 crook 119: Copyright @copyright{} 1995--2000 Free Software Foundation, Inc.
1.1 anton 120:
121: @comment !! Published by ... or You can get a copy of this manual ...
122:
123: Permission is granted to make and distribute verbatim copies of
124: this manual provided the copyright notice and this permission notice
125: are preserved on all copies.
126:
127: Permission is granted to copy and distribute modified versions of this
128: manual under the conditions for verbatim copying, provided also that the
129: sections entitled "Distribution" and "General Public License" are
130: included exactly as in the original, and provided that the entire
131: resulting derived work is distributed under the terms of a permission
132: notice identical to this one.
133:
134: Permission is granted to copy and distribute translations of this manual
135: into another language, under the above conditions for modified versions,
136: except that the sections entitled "Distribution" and "General Public
137: License" may be included in a translation approved by the author instead
138: of in the original English.
139: @end titlepage
140:
141: @node Top, License, (dir), (dir)
1.49 anton 142: @ifnottex
1.1 anton 143: Gforth is a free implementation of ANS Forth available on many
1.11 anton 144: personal machines. This manual corresponds to version @value{VERSION}.
1.49 anton 145: @end ifnottex
1.1 anton 146:
147: @menu
1.21 crook 148: * License:: The GPL
1.26 crook 149: * Goals:: About the Gforth Project
1.29 crook 150: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 151: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 152: * Introduction:: An introduction to ANS Forth
1.1 anton 153: * Words:: Forth words available in Gforth
1.24 anton 154: * Error messages:: How to interpret them
1.1 anton 155: * Tools:: Programming tools
156: * ANS conformance:: Implementation-defined options etc.
157: * Model:: The abstract machine of Gforth
158: * Integrating Gforth:: Forth as scripting language for applications
159: * Emacs and Gforth:: The Gforth Mode
160: * Image Files:: @code{.fi} files contain compiled code
161: * Engine:: The inner interpreter and the primitives
1.24 anton 162: * Binding to System Library::
1.13 pazsan 163: * Cross Compiler:: The Cross Compiler
1.1 anton 164: * Bugs:: How to report them
165: * Origin:: Authors and ancestors of Gforth
1.21 crook 166: * Forth-related information:: Books and places to look on the WWW
1.1 anton 167: * Word Index:: An item for each Forth word
1.41 anton 168: * Name Index:: Forth words, only names listed
1.1 anton 169: * Concept Index:: A menu covering many topics
1.12 anton 170:
1.48 anton 171: @detailmenu --- The Detailed Node Listing ---
1.12 anton 172:
1.26 crook 173: Goals of Gforth
174:
175: * Gforth Extensions Sinful?::
176:
1.29 crook 177: Gforth Environment
178:
1.32 anton 179: * Invoking Gforth:: Getting in
180: * Leaving Gforth:: Getting out
181: * Command-line editing::
1.48 anton 182: * Upper and lower case::
183: * Environment variables:: that affect how Gforth starts up
1.32 anton 184: * Gforth Files:: What gets installed and where
1.48 anton 185: * Startup speed:: When 35ms is not fast enough ...
186:
187: Forth Tutorial
188:
189: * Starting Gforth Tutorial::
190: * Syntax Tutorial::
191: * Crash Course Tutorial::
192: * Stack Tutorial::
193: * Arithmetics Tutorial::
194: * Stack Manipulation Tutorial::
195: * Using files for Forth code Tutorial::
196: * Comments Tutorial::
197: * Colon Definitions Tutorial::
198: * Decompilation Tutorial::
199: * Stack-Effect Comments Tutorial::
200: * Types Tutorial::
201: * Factoring Tutorial::
202: * Designing the stack effect Tutorial::
203: * Local Variables Tutorial::
204: * Conditional execution Tutorial::
205: * Flags and Comparisons Tutorial::
206: * General Loops Tutorial::
207: * Counted loops Tutorial::
208: * Recursion Tutorial::
209: * Leaving definitions or loops Tutorial::
210: * Return Stack Tutorial::
211: * Memory Tutorial::
212: * Characters and Strings Tutorial::
213: * Alignment Tutorial::
214: * Interpretation and Compilation Semantics and Immediacy Tutorial::
215: * Execution Tokens Tutorial::
216: * Exceptions Tutorial::
217: * Defining Words Tutorial::
218: * Arrays and Records Tutorial::
219: * POSTPONE Tutorial::
220: * Literal Tutorial::
221: * Advanced macros Tutorial::
222: * Compilation Tokens Tutorial::
223: * Wordlists and Search Order Tutorial::
1.29 crook 224:
1.24 anton 225: An Introduction to ANS Forth
226:
227: * Introducing the Text Interpreter::
228: * Stacks and Postfix notation::
229: * Your first definition::
230: * How does that work?::
231: * Forth is written in Forth::
232: * Review - elements of a Forth system::
1.29 crook 233: * Where to go next::
1.24 anton 234: * Exercises::
235:
1.12 anton 236: Forth Words
237:
238: * Notation::
1.21 crook 239: * Comments::
240: * Boolean Flags::
1.12 anton 241: * Arithmetic::
242: * Stack Manipulation::
243: * Memory::
244: * Control Structures::
245: * Defining Words::
1.47 crook 246: * Interpretation and Compilation Semantics::
247: * Tokens for Words::
1.21 crook 248: * The Text Interpreter::
249: * Word Lists::
250: * Environmental Queries::
1.12 anton 251: * Files::
252: * Blocks::
253: * Other I/O::
254: * Programming Tools::
255: * Assembler and Code Words::
256: * Threading Words::
1.26 crook 257: * Locals::
258: * Structures::
259: * Object-oriented Forth::
1.21 crook 260: * Passing Commands to the OS::
1.47 crook 261: * Keeping track of Time::
1.21 crook 262: * Miscellaneous Words::
1.12 anton 263:
264: Arithmetic
265:
266: * Single precision::
267: * Bitwise operations::
1.21 crook 268: * Double precision:: Double-cell integer arithmetic
269: * Numeric comparison::
1.32 anton 270: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 271: * Floating Point::
272:
273: Stack Manipulation
274:
275: * Data stack::
276: * Floating point stack::
277: * Return stack::
278: * Locals stack::
279: * Stack pointer manipulation::
280:
281: Memory
282:
1.32 anton 283: * Memory model::
284: * Dictionary allocation::
285: * Heap Allocation::
286: * Memory Access::
287: * Address arithmetic::
288: * Memory Blocks::
1.12 anton 289:
290: Control Structures
291:
1.41 anton 292: * Selection:: IF ... ELSE ... ENDIF
293: * Simple Loops:: BEGIN ...
1.32 anton 294: * Counted Loops:: DO
295: * Arbitrary control structures::
296: * Calls and returns::
1.12 anton 297: * Exception Handling::
298:
299: Defining Words
300:
1.45 crook 301: * CREATE::
1.44 crook 302: * Variables:: Variables and user variables
303: * Constants::
304: * Values:: Initialised variables
1.32 anton 305: * Colon Definitions::
1.44 crook 306: * Anonymous Definitions:: Definitions without names
1.32 anton 307: * User-defined Defining Words::
1.44 crook 308: * Deferred words:: Allow forward references
309: * Aliases::
1.32 anton 310: * Supplying names::
1.47 crook 311:
1.63 anton 312: User-defined Defining Words
313:
314: * CREATE..DOES> applications::
315: * CREATE..DOES> details::
316: * Advanced does> usage example::
317:
1.47 crook 318: Interpretation and Compilation Semantics
319:
1.44 crook 320: * Combined words::
1.12 anton 321:
1.21 crook 322: The Text Interpreter
323:
1.29 crook 324: * Input Sources::
1.21 crook 325: * Number Conversion::
326: * Interpret/Compile states::
327: * Literals::
328: * Interpreter Directives::
329:
1.26 crook 330: Word Lists
331:
332: * Why use word lists?::
333: * Word list examples::
334:
335: Files
336:
1.48 anton 337: * Forth source files::
338: * General files::
339: * Search Paths::
340:
341: Search Paths
342:
343: * Forth Search Paths::
1.26 crook 344: * General Search Paths::
345:
346: Other I/O
347:
1.32 anton 348: * Simple numeric output:: Predefined formats
349: * Formatted numeric output:: Formatted (pictured) output
350: * String Formats:: How Forth stores strings in memory
351: * Displaying characters and strings:: Other stuff
352: * Input:: Input
1.26 crook 353:
354: Programming Tools
355:
356: * Debugging:: Simple and quick.
357: * Assertions:: Making your programs self-checking.
1.46 pazsan 358: * Singlestep Debugger:: Executing your program word by word.
1.26 crook 359:
1.63 anton 360: Assembler and Code Words
361:
362: * Code and ;code::
363: * Common Assembler:: Assembler Syntax
364: * Common Disassembler::
365: * 386 Assembler:: Deviations and special cases
366: * Alpha Assembler:: Deviations and special cases
367: * MIPS assembler:: Deviations and special cases
368: * Other assemblers:: How to write them
369:
1.26 crook 370: Locals
371:
372: * Gforth locals::
373: * ANS Forth locals::
374:
375: Gforth locals
376:
377: * Where are locals visible by name?::
378: * How long do locals live?::
379: * Programming Style::
380: * Implementation::
381:
1.12 anton 382: Structures
383:
384: * Why explicit structure support?::
385: * Structure Usage::
386: * Structure Naming Convention::
387: * Structure Implementation::
388: * Structure Glossary::
389:
390: Object-oriented Forth
391:
1.48 anton 392: * Why object-oriented programming?::
393: * Object-Oriented Terminology::
394: * Objects::
395: * OOF::
396: * Mini-OOF::
1.23 crook 397: * Comparison with other object models::
1.12 anton 398:
1.24 anton 399: The @file{objects.fs} model
1.12 anton 400:
401: * Properties of the Objects model::
402: * Basic Objects Usage::
1.41 anton 403: * The Objects base class::
1.12 anton 404: * Creating objects::
405: * Object-Oriented Programming Style::
406: * Class Binding::
407: * Method conveniences::
408: * Classes and Scoping::
1.41 anton 409: * Dividing classes::
1.12 anton 410: * Object Interfaces::
411: * Objects Implementation::
412: * Objects Glossary::
413:
1.24 anton 414: The @file{oof.fs} model
1.12 anton 415:
416: * Properties of the OOF model::
417: * Basic OOF Usage::
1.23 crook 418: * The OOF base class::
1.12 anton 419: * Class Declaration::
420: * Class Implementation::
421:
1.24 anton 422: The @file{mini-oof.fs} model
1.23 crook 423:
1.48 anton 424: * Basic Mini-OOF Usage::
425: * Mini-OOF Example::
426: * Mini-OOF Implementation::
427: * Comparison with other object models::
1.23 crook 428:
1.12 anton 429: Tools
430:
431: * ANS Report:: Report the words used, sorted by wordset.
432:
433: ANS conformance
434:
435: * The Core Words::
436: * The optional Block word set::
437: * The optional Double Number word set::
438: * The optional Exception word set::
439: * The optional Facility word set::
440: * The optional File-Access word set::
441: * The optional Floating-Point word set::
442: * The optional Locals word set::
443: * The optional Memory-Allocation word set::
444: * The optional Programming-Tools word set::
445: * The optional Search-Order word set::
446:
447: The Core Words
448:
449: * core-idef:: Implementation Defined Options
450: * core-ambcond:: Ambiguous Conditions
451: * core-other:: Other System Documentation
452:
453: The optional Block word set
454:
455: * block-idef:: Implementation Defined Options
456: * block-ambcond:: Ambiguous Conditions
457: * block-other:: Other System Documentation
458:
459: The optional Double Number word set
460:
461: * double-ambcond:: Ambiguous Conditions
462:
463: The optional Exception word set
464:
465: * exception-idef:: Implementation Defined Options
466:
467: The optional Facility word set
468:
469: * facility-idef:: Implementation Defined Options
470: * facility-ambcond:: Ambiguous Conditions
471:
472: The optional File-Access word set
473:
474: * file-idef:: Implementation Defined Options
475: * file-ambcond:: Ambiguous Conditions
476:
477: The optional Floating-Point word set
478:
479: * floating-idef:: Implementation Defined Options
480: * floating-ambcond:: Ambiguous Conditions
481:
482: The optional Locals word set
483:
484: * locals-idef:: Implementation Defined Options
485: * locals-ambcond:: Ambiguous Conditions
486:
487: The optional Memory-Allocation word set
488:
489: * memory-idef:: Implementation Defined Options
490:
491: The optional Programming-Tools word set
492:
493: * programming-idef:: Implementation Defined Options
494: * programming-ambcond:: Ambiguous Conditions
495:
496: The optional Search-Order word set
497:
498: * search-idef:: Implementation Defined Options
499: * search-ambcond:: Ambiguous Conditions
500:
501: Image Files
502:
1.24 anton 503: * Image Licensing Issues:: Distribution terms for images.
504: * Image File Background:: Why have image files?
1.32 anton 505: * Non-Relocatable Image Files:: don't always work.
1.24 anton 506: * Data-Relocatable Image Files:: are better.
1.32 anton 507: * Fully Relocatable Image Files:: better yet.
1.24 anton 508: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 509: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 510: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 511:
512: Fully Relocatable Image Files
513:
1.27 crook 514: * gforthmi:: The normal way
1.12 anton 515: * cross.fs:: The hard way
516:
517: Engine
518:
519: * Portability::
520: * Threading::
521: * Primitives::
522: * Performance::
523:
524: Threading
525:
526: * Scheduling::
527: * Direct or Indirect Threaded?::
528: * DOES>::
529:
530: Primitives
531:
532: * Automatic Generation::
533: * TOS Optimization::
534: * Produced code::
1.13 pazsan 535:
536: Cross Compiler
537:
538: * Using the Cross Compiler::
539: * How the Cross Compiler Works::
540:
1.24 anton 541: Other Forth-related information
1.21 crook 542:
543: * Internet resources::
544: * Books::
545: * The Forth Interest Group::
546: * Conferences::
547:
1.24 anton 548: @end detailmenu
1.1 anton 549: @end menu
550:
1.26 crook 551: @node License, Goals, Top, Top
1.1 anton 552: @unnumbered GNU GENERAL PUBLIC LICENSE
553: @center Version 2, June 1991
554:
555: @display
556: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
557: 675 Mass Ave, Cambridge, MA 02139, USA
558:
559: Everyone is permitted to copy and distribute verbatim copies
560: of this license document, but changing it is not allowed.
561: @end display
562:
563: @unnumberedsec Preamble
564:
565: The licenses for most software are designed to take away your
566: freedom to share and change it. By contrast, the GNU General Public
567: License is intended to guarantee your freedom to share and change free
568: software---to make sure the software is free for all its users. This
569: General Public License applies to most of the Free Software
570: Foundation's software and to any other program whose authors commit to
571: using it. (Some other Free Software Foundation software is covered by
572: the GNU Library General Public License instead.) You can apply it to
573: your programs, too.
574:
575: When we speak of free software, we are referring to freedom, not
576: price. Our General Public Licenses are designed to make sure that you
577: have the freedom to distribute copies of free software (and charge for
578: this service if you wish), that you receive source code or can get it
579: if you want it, that you can change the software or use pieces of it
580: in new free programs; and that you know you can do these things.
581:
582: To protect your rights, we need to make restrictions that forbid
583: anyone to deny you these rights or to ask you to surrender the rights.
584: These restrictions translate to certain responsibilities for you if you
585: distribute copies of the software, or if you modify it.
586:
587: For example, if you distribute copies of such a program, whether
588: gratis or for a fee, you must give the recipients all the rights that
589: you have. You must make sure that they, too, receive or can get the
590: source code. And you must show them these terms so they know their
591: rights.
592:
593: We protect your rights with two steps: (1) copyright the software, and
594: (2) offer you this license which gives you legal permission to copy,
595: distribute and/or modify the software.
596:
597: Also, for each author's protection and ours, we want to make certain
598: that everyone understands that there is no warranty for this free
599: software. If the software is modified by someone else and passed on, we
600: want its recipients to know that what they have is not the original, so
601: that any problems introduced by others will not reflect on the original
602: authors' reputations.
603:
604: Finally, any free program is threatened constantly by software
605: patents. We wish to avoid the danger that redistributors of a free
606: program will individually obtain patent licenses, in effect making the
607: program proprietary. To prevent this, we have made it clear that any
608: patent must be licensed for everyone's free use or not licensed at all.
609:
610: The precise terms and conditions for copying, distribution and
611: modification follow.
612:
613: @iftex
614: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
615: @end iftex
1.49 anton 616: @ifnottex
1.1 anton 617: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
1.49 anton 618: @end ifnottex
1.1 anton 619:
620: @enumerate 0
621: @item
622: This License applies to any program or other work which contains
623: a notice placed by the copyright holder saying it may be distributed
624: under the terms of this General Public License. The ``Program'', below,
625: refers to any such program or work, and a ``work based on the Program''
626: means either the Program or any derivative work under copyright law:
627: that is to say, a work containing the Program or a portion of it,
628: either verbatim or with modifications and/or translated into another
629: language. (Hereinafter, translation is included without limitation in
630: the term ``modification''.) Each licensee is addressed as ``you''.
631:
632: Activities other than copying, distribution and modification are not
633: covered by this License; they are outside its scope. The act of
634: running the Program is not restricted, and the output from the Program
635: is covered only if its contents constitute a work based on the
636: Program (independent of having been made by running the Program).
637: Whether that is true depends on what the Program does.
638:
639: @item
640: You may copy and distribute verbatim copies of the Program's
641: source code as you receive it, in any medium, provided that you
642: conspicuously and appropriately publish on each copy an appropriate
643: copyright notice and disclaimer of warranty; keep intact all the
644: notices that refer to this License and to the absence of any warranty;
645: and give any other recipients of the Program a copy of this License
646: along with the Program.
647:
648: You may charge a fee for the physical act of transferring a copy, and
649: you may at your option offer warranty protection in exchange for a fee.
650:
651: @item
652: You may modify your copy or copies of the Program or any portion
653: of it, thus forming a work based on the Program, and copy and
654: distribute such modifications or work under the terms of Section 1
655: above, provided that you also meet all of these conditions:
656:
657: @enumerate a
658: @item
659: You must cause the modified files to carry prominent notices
660: stating that you changed the files and the date of any change.
661:
662: @item
663: You must cause any work that you distribute or publish, that in
664: whole or in part contains or is derived from the Program or any
665: part thereof, to be licensed as a whole at no charge to all third
666: parties under the terms of this License.
667:
668: @item
669: If the modified program normally reads commands interactively
670: when run, you must cause it, when started running for such
671: interactive use in the most ordinary way, to print or display an
672: announcement including an appropriate copyright notice and a
673: notice that there is no warranty (or else, saying that you provide
674: a warranty) and that users may redistribute the program under
675: these conditions, and telling the user how to view a copy of this
676: License. (Exception: if the Program itself is interactive but
677: does not normally print such an announcement, your work based on
678: the Program is not required to print an announcement.)
679: @end enumerate
680:
681: These requirements apply to the modified work as a whole. If
682: identifiable sections of that work are not derived from the Program,
683: and can be reasonably considered independent and separate works in
684: themselves, then this License, and its terms, do not apply to those
685: sections when you distribute them as separate works. But when you
686: distribute the same sections as part of a whole which is a work based
687: on the Program, the distribution of the whole must be on the terms of
688: this License, whose permissions for other licensees extend to the
689: entire whole, and thus to each and every part regardless of who wrote it.
690:
691: Thus, it is not the intent of this section to claim rights or contest
692: your rights to work written entirely by you; rather, the intent is to
693: exercise the right to control the distribution of derivative or
694: collective works based on the Program.
695:
696: In addition, mere aggregation of another work not based on the Program
697: with the Program (or with a work based on the Program) on a volume of
698: a storage or distribution medium does not bring the other work under
699: the scope of this License.
700:
701: @item
702: You may copy and distribute the Program (or a work based on it,
703: under Section 2) in object code or executable form under the terms of
704: Sections 1 and 2 above provided that you also do one of the following:
705:
706: @enumerate a
707: @item
708: Accompany it with the complete corresponding machine-readable
709: source code, which must be distributed under the terms of Sections
710: 1 and 2 above on a medium customarily used for software interchange; or,
711:
712: @item
713: Accompany it with a written offer, valid for at least three
714: years, to give any third party, for a charge no more than your
715: cost of physically performing source distribution, a complete
716: machine-readable copy of the corresponding source code, to be
717: distributed under the terms of Sections 1 and 2 above on a medium
718: customarily used for software interchange; or,
719:
720: @item
721: Accompany it with the information you received as to the offer
722: to distribute corresponding source code. (This alternative is
723: allowed only for noncommercial distribution and only if you
724: received the program in object code or executable form with such
725: an offer, in accord with Subsection b above.)
726: @end enumerate
727:
728: The source code for a work means the preferred form of the work for
729: making modifications to it. For an executable work, complete source
730: code means all the source code for all modules it contains, plus any
731: associated interface definition files, plus the scripts used to
732: control compilation and installation of the executable. However, as a
733: special exception, the source code distributed need not include
734: anything that is normally distributed (in either source or binary
735: form) with the major components (compiler, kernel, and so on) of the
736: operating system on which the executable runs, unless that component
737: itself accompanies the executable.
738:
739: If distribution of executable or object code is made by offering
740: access to copy from a designated place, then offering equivalent
741: access to copy the source code from the same place counts as
742: distribution of the source code, even though third parties are not
743: compelled to copy the source along with the object code.
744:
745: @item
746: You may not copy, modify, sublicense, or distribute the Program
747: except as expressly provided under this License. Any attempt
748: otherwise to copy, modify, sublicense or distribute the Program is
749: void, and will automatically terminate your rights under this License.
750: However, parties who have received copies, or rights, from you under
751: this License will not have their licenses terminated so long as such
752: parties remain in full compliance.
753:
754: @item
755: You are not required to accept this License, since you have not
756: signed it. However, nothing else grants you permission to modify or
757: distribute the Program or its derivative works. These actions are
758: prohibited by law if you do not accept this License. Therefore, by
759: modifying or distributing the Program (or any work based on the
760: Program), you indicate your acceptance of this License to do so, and
761: all its terms and conditions for copying, distributing or modifying
762: the Program or works based on it.
763:
764: @item
765: Each time you redistribute the Program (or any work based on the
766: Program), the recipient automatically receives a license from the
767: original licensor to copy, distribute or modify the Program subject to
768: these terms and conditions. You may not impose any further
769: restrictions on the recipients' exercise of the rights granted herein.
770: You are not responsible for enforcing compliance by third parties to
771: this License.
772:
773: @item
774: If, as a consequence of a court judgment or allegation of patent
775: infringement or for any other reason (not limited to patent issues),
776: conditions are imposed on you (whether by court order, agreement or
777: otherwise) that contradict the conditions of this License, they do not
778: excuse you from the conditions of this License. If you cannot
779: distribute so as to satisfy simultaneously your obligations under this
780: License and any other pertinent obligations, then as a consequence you
781: may not distribute the Program at all. For example, if a patent
782: license would not permit royalty-free redistribution of the Program by
783: all those who receive copies directly or indirectly through you, then
784: the only way you could satisfy both it and this License would be to
785: refrain entirely from distribution of the Program.
786:
787: If any portion of this section is held invalid or unenforceable under
788: any particular circumstance, the balance of the section is intended to
789: apply and the section as a whole is intended to apply in other
790: circumstances.
791:
792: It is not the purpose of this section to induce you to infringe any
793: patents or other property right claims or to contest validity of any
794: such claims; this section has the sole purpose of protecting the
795: integrity of the free software distribution system, which is
796: implemented by public license practices. Many people have made
797: generous contributions to the wide range of software distributed
798: through that system in reliance on consistent application of that
799: system; it is up to the author/donor to decide if he or she is willing
800: to distribute software through any other system and a licensee cannot
801: impose that choice.
802:
803: This section is intended to make thoroughly clear what is believed to
804: be a consequence of the rest of this License.
805:
806: @item
807: If the distribution and/or use of the Program is restricted in
808: certain countries either by patents or by copyrighted interfaces, the
809: original copyright holder who places the Program under this License
810: may add an explicit geographical distribution limitation excluding
811: those countries, so that distribution is permitted only in or among
812: countries not thus excluded. In such case, this License incorporates
813: the limitation as if written in the body of this License.
814:
815: @item
816: The Free Software Foundation may publish revised and/or new versions
817: of the General Public License from time to time. Such new versions will
818: be similar in spirit to the present version, but may differ in detail to
819: address new problems or concerns.
820:
821: Each version is given a distinguishing version number. If the Program
822: specifies a version number of this License which applies to it and ``any
823: later version'', you have the option of following the terms and conditions
824: either of that version or of any later version published by the Free
825: Software Foundation. If the Program does not specify a version number of
826: this License, you may choose any version ever published by the Free Software
827: Foundation.
828:
829: @item
830: If you wish to incorporate parts of the Program into other free
831: programs whose distribution conditions are different, write to the author
832: to ask for permission. For software which is copyrighted by the Free
833: Software Foundation, write to the Free Software Foundation; we sometimes
834: make exceptions for this. Our decision will be guided by the two goals
835: of preserving the free status of all derivatives of our free software and
836: of promoting the sharing and reuse of software generally.
837:
838: @iftex
839: @heading NO WARRANTY
840: @end iftex
1.49 anton 841: @ifnottex
1.1 anton 842: @center NO WARRANTY
1.49 anton 843: @end ifnottex
1.1 anton 844:
845: @item
846: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
847: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
848: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
849: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
850: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
851: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
852: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
853: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
854: REPAIR OR CORRECTION.
855:
856: @item
857: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
858: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
859: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
860: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
861: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
862: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
863: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
864: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
865: POSSIBILITY OF SUCH DAMAGES.
866: @end enumerate
867:
868: @iftex
869: @heading END OF TERMS AND CONDITIONS
870: @end iftex
1.49 anton 871: @ifnottex
1.1 anton 872: @center END OF TERMS AND CONDITIONS
1.49 anton 873: @end ifnottex
1.1 anton 874:
875: @page
876: @unnumberedsec How to Apply These Terms to Your New Programs
877:
878: If you develop a new program, and you want it to be of the greatest
879: possible use to the public, the best way to achieve this is to make it
880: free software which everyone can redistribute and change under these terms.
881:
882: To do so, attach the following notices to the program. It is safest
883: to attach them to the start of each source file to most effectively
884: convey the exclusion of warranty; and each file should have at least
885: the ``copyright'' line and a pointer to where the full notice is found.
886:
887: @smallexample
888: @var{one line to give the program's name and a brief idea of what it does.}
889: Copyright (C) 19@var{yy} @var{name of author}
890:
891: This program is free software; you can redistribute it and/or modify
892: it under the terms of the GNU General Public License as published by
893: the Free Software Foundation; either version 2 of the License, or
894: (at your option) any later version.
895:
896: This program is distributed in the hope that it will be useful,
897: but WITHOUT ANY WARRANTY; without even the implied warranty of
898: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
899: GNU General Public License for more details.
900:
901: You should have received a copy of the GNU General Public License
902: along with this program; if not, write to the Free Software
903: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
904: @end smallexample
905:
906: Also add information on how to contact you by electronic and paper mail.
907:
908: If the program is interactive, make it output a short notice like this
909: when it starts in an interactive mode:
910:
911: @smallexample
912: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
913: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
914: type `show w'.
915: This is free software, and you are welcome to redistribute it
916: under certain conditions; type `show c' for details.
917: @end smallexample
918:
919: The hypothetical commands @samp{show w} and @samp{show c} should show
920: the appropriate parts of the General Public License. Of course, the
921: commands you use may be called something other than @samp{show w} and
922: @samp{show c}; they could even be mouse-clicks or menu items---whatever
923: suits your program.
924:
925: You should also get your employer (if you work as a programmer) or your
926: school, if any, to sign a ``copyright disclaimer'' for the program, if
927: necessary. Here is a sample; alter the names:
928:
929: @smallexample
930: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
931: `Gnomovision' (which makes passes at compilers) written by James Hacker.
932:
933: @var{signature of Ty Coon}, 1 April 1989
934: Ty Coon, President of Vice
935: @end smallexample
936:
937: This General Public License does not permit incorporating your program into
938: proprietary programs. If your program is a subroutine library, you may
939: consider it more useful to permit linking proprietary applications with the
940: library. If this is what you want to do, use the GNU Library General
941: Public License instead of this License.
942:
943: @iftex
944: @unnumbered Preface
945: @cindex Preface
1.21 crook 946: This manual documents Gforth. Some introductory material is provided for
947: readers who are unfamiliar with Forth or who are migrating to Gforth
948: from other Forth compilers. However, this manual is primarily a
949: reference manual.
1.1 anton 950: @end iftex
951:
1.28 crook 952: @comment TODO much more blurb here.
1.26 crook 953:
954: @c ******************************************************************
1.29 crook 955: @node Goals, Gforth Environment, License, Top
1.26 crook 956: @comment node-name, next, previous, up
957: @chapter Goals of Gforth
958: @cindex goals of the Gforth project
959: The goal of the Gforth Project is to develop a standard model for
960: ANS Forth. This can be split into several subgoals:
961:
962: @itemize @bullet
963: @item
964: Gforth should conform to the ANS Forth Standard.
965: @item
966: It should be a model, i.e. it should define all the
967: implementation-dependent things.
968: @item
969: It should become standard, i.e. widely accepted and used. This goal
970: is the most difficult one.
971: @end itemize
972:
973: To achieve these goals Gforth should be
974: @itemize @bullet
975: @item
976: Similar to previous models (fig-Forth, F83)
977: @item
978: Powerful. It should provide for all the things that are considered
979: necessary today and even some that are not yet considered necessary.
980: @item
981: Efficient. It should not get the reputation of being exceptionally
982: slow.
983: @item
984: Free.
985: @item
986: Available on many machines/easy to port.
987: @end itemize
988:
989: Have we achieved these goals? Gforth conforms to the ANS Forth
990: standard. It may be considered a model, but we have not yet documented
991: which parts of the model are stable and which parts we are likely to
992: change. It certainly has not yet become a de facto standard, but it
993: appears to be quite popular. It has some similarities to and some
994: differences from previous models. It has some powerful features, but not
995: yet everything that we envisioned. We certainly have achieved our
996: execution speed goals (@pxref{Performance}). It is free and available
997: on many machines.
998:
999: @menu
1000: * Gforth Extensions Sinful?::
1001: @end menu
1002:
1.48 anton 1003: @node Gforth Extensions Sinful?, , Goals, Goals
1.26 crook 1004: @comment node-name, next, previous, up
1005: @section Is it a Sin to use Gforth Extensions?
1006: @cindex Gforth extensions
1007:
1008: If you've been paying attention, you will have realised that there is an
1009: ANS (American National Standard) for Forth. As you read through the rest
1.29 crook 1010: of this manual, you will see documentation for @i{Standard} words, and
1011: documentation for some appealing Gforth @i{extensions}. You might ask
1012: yourself the question: @i{``Given that there is a standard, would I be
1.45 crook 1013: committing a sin if I use (non-Standard) Gforth extensions?''}
1.26 crook 1014:
1015: The answer to that question is somewhat pragmatic and somewhat
1016: philosophical. Consider these points:
1017:
1018: @itemize @bullet
1019: @item
1020: A number of the Gforth extensions can be implemented in ANS Forth using
1021: files provided in the @file{compat/} directory. These are mentioned in
1022: the text in passing.
1023: @item
1024: Forth has a rich historical precedent for programmers taking advantage
1025: of implementation-dependent features of their tools (for example,
1026: relying on a knowledge of the dictionary structure). Sometimes these
1027: techniques are necessary to extract every last bit of performance from
1028: the hardware, sometimes they are just a programming shorthand.
1029: @item
1030: The best way to break the rules is to know what the rules are. To learn
1031: the rules, there is no substitute for studying the text of the Standard
1032: itself. In particular, Appendix A of the Standard (@var{Rationale})
1033: provides a valuable insight into the thought processes of the technical
1034: committee.
1035: @item
1036: The best reason to break a rule is because you have to; because it's
1037: more productive to do that, because it makes your code run fast enough
1038: or because you can see no Standard way to achieve what you want to
1039: achieve.
1040: @end itemize
1041:
1042: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
1043: analyse your program and determine what non-Standard definitions it
1044: relies upon.
1045:
1.29 crook 1046:
1.26 crook 1047: @c ******************************************************************
1.48 anton 1048: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 1049: @chapter Gforth Environment
1050: @cindex Gforth environment
1.21 crook 1051:
1.45 crook 1052: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 1053: material in this chapter.
1.21 crook 1054:
1055: @menu
1.29 crook 1056: * Invoking Gforth:: Getting in
1057: * Leaving Gforth:: Getting out
1058: * Command-line editing::
1.48 anton 1059: * Upper and lower case::
1060: * Environment variables:: that affect how Gforth starts up
1.29 crook 1061: * Gforth Files:: What gets installed and where
1.48 anton 1062: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 1063: @end menu
1064:
1.49 anton 1065: For related information about the creation of images see @ref{Image Files}.
1.29 crook 1066:
1.21 crook 1067: @comment ----------------------------------------------
1.48 anton 1068: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 1069: @section Invoking Gforth
1070: @cindex invoking Gforth
1071: @cindex running Gforth
1072: @cindex command-line options
1073: @cindex options on the command line
1074: @cindex flags on the command line
1.21 crook 1075:
1.30 anton 1076: Gforth is made up of two parts; an executable ``engine'' (named
1077: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
1078: will usually just say @code{gforth} -- this automatically loads the
1079: default image file @file{gforth.fi}. In many other cases the default
1080: Gforth image will be invoked like this:
1.21 crook 1081: @example
1.30 anton 1082: gforth [file | -e forth-code] ...
1.21 crook 1083: @end example
1.29 crook 1084: @noindent
1085: This interprets the contents of the files and the Forth code in the order they
1086: are given.
1.21 crook 1087:
1.30 anton 1088: In addition to the @file{gforth} engine, there is also an engine called
1089: @file{gforth-fast}, which is faster, but gives less informative error
1090: messages (@pxref{Error messages}).
1091:
1.29 crook 1092: In general, the command line looks like this:
1.21 crook 1093:
1094: @example
1.30 anton 1095: gforth[-fast] [engine options] [image options]
1.21 crook 1096: @end example
1097:
1.30 anton 1098: The engine options must come before the rest of the command
1.29 crook 1099: line. They are:
1.26 crook 1100:
1.29 crook 1101: @table @code
1102: @cindex -i, command-line option
1103: @cindex --image-file, command-line option
1104: @item --image-file @i{file}
1105: @itemx -i @i{file}
1106: Loads the Forth image @i{file} instead of the default
1107: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 1108:
1.39 anton 1109: @cindex --appl-image, command-line option
1110: @item --appl-image @i{file}
1111: Loads the image @i{file} and leaves all further command-line arguments
1112: to the image (instead of processing them as options). This is useful
1113: for building executable application images on Unix, built with
1114: @code{gforthmi --application ...}.
1115:
1.29 crook 1116: @cindex --path, command-line option
1117: @cindex -p, command-line option
1118: @item --path @i{path}
1119: @itemx -p @i{path}
1120: Uses @i{path} for searching the image file and Forth source code files
1121: instead of the default in the environment variable @code{GFORTHPATH} or
1122: the path specified at installation time (e.g.,
1123: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
1124: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 1125:
1.29 crook 1126: @cindex --dictionary-size, command-line option
1127: @cindex -m, command-line option
1128: @cindex @i{size} parameters for command-line options
1129: @cindex size of the dictionary and the stacks
1130: @item --dictionary-size @i{size}
1131: @itemx -m @i{size}
1132: Allocate @i{size} space for the Forth dictionary space instead of
1133: using the default specified in the image (typically 256K). The
1134: @i{size} specification for this and subsequent options consists of
1135: an integer and a unit (e.g.,
1136: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
1137: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
1138: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
1139: @code{e} is used.
1.21 crook 1140:
1.29 crook 1141: @cindex --data-stack-size, command-line option
1142: @cindex -d, command-line option
1143: @item --data-stack-size @i{size}
1144: @itemx -d @i{size}
1145: Allocate @i{size} space for the data stack instead of using the
1146: default specified in the image (typically 16K).
1.21 crook 1147:
1.29 crook 1148: @cindex --return-stack-size, command-line option
1149: @cindex -r, command-line option
1150: @item --return-stack-size @i{size}
1151: @itemx -r @i{size}
1152: Allocate @i{size} space for the return stack instead of using the
1153: default specified in the image (typically 15K).
1.21 crook 1154:
1.29 crook 1155: @cindex --fp-stack-size, command-line option
1156: @cindex -f, command-line option
1157: @item --fp-stack-size @i{size}
1158: @itemx -f @i{size}
1159: Allocate @i{size} space for the floating point stack instead of
1160: using the default specified in the image (typically 15.5K). In this case
1161: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 1162:
1.48 anton 1163: @cindex --locals-stack-size, command-line option
1164: @cindex -l, command-line option
1165: @item --locals-stack-size @i{size}
1166: @itemx -l @i{size}
1167: Allocate @i{size} space for the locals stack instead of using the
1168: default specified in the image (typically 14.5K).
1169:
1170: @cindex -h, command-line option
1171: @cindex --help, command-line option
1172: @item --help
1173: @itemx -h
1174: Print a message about the command-line options
1175:
1176: @cindex -v, command-line option
1177: @cindex --version, command-line option
1178: @item --version
1179: @itemx -v
1180: Print version and exit
1181:
1182: @cindex --debug, command-line option
1183: @item --debug
1184: Print some information useful for debugging on startup.
1185:
1186: @cindex --offset-image, command-line option
1187: @item --offset-image
1188: Start the dictionary at a slightly different position than would be used
1189: otherwise (useful for creating data-relocatable images,
1190: @pxref{Data-Relocatable Image Files}).
1191:
1192: @cindex --no-offset-im, command-line option
1193: @item --no-offset-im
1194: Start the dictionary at the normal position.
1195:
1196: @cindex --clear-dictionary, command-line option
1197: @item --clear-dictionary
1198: Initialize all bytes in the dictionary to 0 before loading the image
1199: (@pxref{Data-Relocatable Image Files}).
1200:
1201: @cindex --die-on-signal, command-line-option
1202: @item --die-on-signal
1203: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
1204: or the segmentation violation SIGSEGV) by translating it into a Forth
1205: @code{THROW}. With this option, Gforth exits if it receives such a
1206: signal. This option is useful when the engine and/or the image might be
1207: severely broken (such that it causes another signal before recovering
1208: from the first); this option avoids endless loops in such cases.
1209: @end table
1210:
1211: @cindex loading files at startup
1212: @cindex executing code on startup
1213: @cindex batch processing with Gforth
1214: As explained above, the image-specific command-line arguments for the
1215: default image @file{gforth.fi} consist of a sequence of filenames and
1216: @code{-e @var{forth-code}} options that are interpreted in the sequence
1217: in which they are given. The @code{-e @var{forth-code}} or
1218: @code{--evaluate @var{forth-code}} option evaluates the Forth
1219: code. This option takes only one argument; if you want to evaluate more
1220: Forth words, you have to quote them or use @code{-e} several times. To exit
1221: after processing the command line (instead of entering interactive mode)
1222: append @code{-e bye} to the command line.
1223:
1224: @cindex versions, invoking other versions of Gforth
1225: If you have several versions of Gforth installed, @code{gforth} will
1226: invoke the version that was installed last. @code{gforth-@i{version}}
1227: invokes a specific version. If your environment contains the variable
1228: @code{GFORTHPATH}, you may want to override it by using the
1229: @code{--path} option.
1230:
1231: Not yet implemented:
1232: On startup the system first executes the system initialization file
1233: (unless the option @code{--no-init-file} is given; note that the system
1234: resulting from using this option may not be ANS Forth conformant). Then
1235: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 1236: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 1237: then in @file{~}, then in the normal path (see above).
1238:
1239:
1240:
1241: @comment ----------------------------------------------
1242: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
1243: @section Leaving Gforth
1244: @cindex Gforth - leaving
1245: @cindex leaving Gforth
1246:
1247: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
1248: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
1249: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 1250: data are discarded. For ways of saving the state of the system before
1251: leaving Gforth see @ref{Image Files}.
1.48 anton 1252:
1253: doc-bye
1254:
1255:
1256: @comment ----------------------------------------------
1257: @node Command-line editing, Upper and lower case, Leaving Gforth, Gforth Environment
1258: @section Command-line editing
1259: @cindex command-line editing
1260:
1261: Gforth maintains a history file that records every line that you type to
1262: the text interpreter. This file is preserved between sessions, and is
1263: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
1264: repeatedly you can recall successively older commands from this (or
1265: previous) session(s). The full list of command-line editing facilities is:
1266:
1267: @itemize @bullet
1268: @item
1269: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
1270: commands from the history buffer.
1271: @item
1272: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
1273: from the history buffer.
1274: @item
1275: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
1276: @item
1277: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
1278: @item
1279: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
1280: closing up the line.
1281: @item
1282: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
1283: @item
1284: @kbd{Ctrl-a} to move the cursor to the start of the line.
1285: @item
1286: @kbd{Ctrl-e} to move the cursor to the end of the line.
1287: @item
1288: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
1289: line.
1290: @item
1291: @key{TAB} to step through all possible full-word completions of the word
1292: currently being typed.
1293: @item
1294: @kbd{Ctrl-d} at the start of the line to terminate Gforth (gracefully,
1295: using @code{bye}).
1296: @end itemize
1297:
1298: When editing, displayable characters are inserted to the left of the
1299: cursor position; the line is always in ``insert'' (as opposed to
1300: ``overstrike'') mode.
1301:
1302: @cindex history file
1303: @cindex @file{.gforth-history}
1304: On Unix systems, the history file is @file{~/.gforth-history} by
1305: default@footnote{i.e. it is stored in the user's home directory.}. You
1306: can find out the name and location of your history file using:
1307:
1308: @example
1309: history-file type \ Unix-class systems
1310:
1311: history-file type \ Other systems
1312: history-dir type
1313: @end example
1314:
1315: If you enter long definitions by hand, you can use a text editor to
1316: paste them out of the history file into a Forth source file for reuse at
1317: a later time.
1318:
1319: Gforth never trims the size of the history file, so you should do this
1320: periodically, if necessary.
1321:
1322: @comment this is all defined in history.fs
1323: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
1324: @comment chosen?
1325:
1326:
1327:
1328: @comment ----------------------------------------------
1329: @node Upper and lower case, Environment variables, Command-line editing, Gforth Environment
1330: @section Upper and lower case
1331: @cindex case-sensitivity
1332: @cindex upper and lower case
1333:
1334: Gforth is case-insensitive; you can enter definitions and invoke
1335: Standard words using upper, lower or mixed case (however,
1336: @pxref{core-idef, Implementation-defined options, Implementation-defined
1337: options}).
1338:
1339: ANS Forth only @i{requires} implementations to recognise Standard words
1340: when they are typed entirely in upper case. Therefore, a Standard
1341: program must use upper case for all Standard words. You can use whatever
1.62 crook 1342: case you like for words that you define, but in a Standard program you
1.48 anton 1343: have to use the words in the same case that you defined them.
1344:
1345: Gforth supports case sensitivity through @code{table}s (case-sensitive
1346: wordlists, @pxref{Word Lists}).
1347:
1.62 crook 1348: Two people have asked how to convert Gforth to be case-sensitive; while
1.48 anton 1349: we think this is a bad idea, you can change all wordlists into tables
1350: like this:
1351:
1352: @example
1353: ' table-find forth-wordlist wordlist-map @ !
1354: @end example
1355:
1356: Note that you now have to type the predefined words in the same case
1357: that we defined them, which are varying. You may want to convert them
1358: to your favourite case before doing this operation (I won't explain how,
1.62 crook 1359: because if you are even contemplating doing this, you'd better have
1.48 anton 1360: enough knowledge of Forth systems to know this already).
1361:
1362: @comment ----------------------------------------------
1363: @node Environment variables, Gforth Files, Upper and lower case, Gforth Environment
1364: @section Environment variables
1365: @cindex environment variables
1366:
1367: Gforth uses these environment variables:
1368:
1369: @itemize @bullet
1370: @item
1371: @cindex @code{GFORTHHIST} -- environment variable
1372: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
1373: open/create the history file, @file{.gforth-history}. Default:
1374: @code{$HOME}.
1375:
1376: @item
1377: @cindex @code{GFORTHPATH} -- environment variable
1378: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
1379: for Forth source-code files.
1380:
1381: @item
1382: @cindex @code{GFORTH} -- environment variable
1.49 anton 1383: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1384:
1385: @item
1386: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1387: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1388:
1389: @item
1390: @cindex @code{TMP}, @code{TEMP} - environment variable
1391: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1392: location for the history file.
1393: @end itemize
1394:
1395: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1396: @comment mentioning these.
1397:
1398: All the Gforth environment variables default to sensible values if they
1399: are not set.
1400:
1401:
1402: @comment ----------------------------------------------
1403: @node Gforth Files, Startup speed, Environment variables, Gforth Environment
1404: @section Gforth files
1405: @cindex Gforth files
1406:
1407: When you install Gforth on a Unix system, it installs files in these
1408: locations by default:
1409:
1410: @itemize @bullet
1411: @item
1412: @file{/usr/local/bin/gforth}
1413: @item
1414: @file{/usr/local/bin/gforthmi}
1415: @item
1416: @file{/usr/local/man/man1/gforth.1} - man page.
1417: @item
1418: @file{/usr/local/info} - the Info version of this manual.
1419: @item
1420: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1421: @item
1422: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1423: @item
1424: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1425: @item
1426: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1427: @end itemize
1428:
1429: You can select different places for installation by using
1430: @code{configure} options (listed with @code{configure --help}).
1431:
1432: @comment ----------------------------------------------
1433: @node Startup speed, , Gforth Files, Gforth Environment
1434: @section Startup speed
1435: @cindex Startup speed
1436: @cindex speed, startup
1437:
1438: If Gforth is used for CGI scripts or in shell scripts, its startup
1439: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1440: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1441: system time.
1442:
1443: If startup speed is a problem, you may consider the following ways to
1444: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1445: (for example, by using Fast-CGI).
1.48 anton 1446:
1447: The first step to improve startup speed is to statically link Gforth, by
1448: building it with @code{XLDFLAGS=-static}. This requires more memory for
1449: the code and will therefore slow down the first invocation, but
1450: subsequent invocations avoid the dynamic linking overhead. Another
1451: disadvantage is that Gforth won't profit from library upgrades. As a
1452: result, @code{gforth-static -e bye} takes about 17.1ms user and
1453: 8.2ms system time.
1454:
1455: The next step to improve startup speed is to use a non-relocatable image
1.62 crook 1456: (@xref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1457: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1458: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1459: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1460: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1461: address for the dictionary, for whatever reason; so you better provide a
1462: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1463: bye} takes about 15.3ms user and 7.5ms system time.
1464:
1465: The final step is to disable dictionary hashing in Gforth. Gforth
1466: builds the hash table on startup, which takes much of the startup
1467: overhead. You can do this by commenting out the @code{include hash.fs}
1468: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1469: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1470: The disadvantages are that functionality like @code{table} and
1471: @code{ekey} is missing and that text interpretation (e.g., compiling)
1472: now takes much longer. So, you should only use this method if there is
1473: no significant text interpretation to perform (the script should be
1.62 crook 1474: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1475: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1476:
1477: @c ******************************************************************
1478: @node Tutorial, Introduction, Gforth Environment, Top
1479: @chapter Forth Tutorial
1480: @cindex Tutorial
1481: @cindex Forth Tutorial
1482:
1.62 crook 1483: This tutorial can be used with any ANS-compliant Forth; any
1484: Gforth-specific features are marked as such and you can skip them if you
1485: work with another Forth. This tutorial does not explain all features of
1486: Forth, just enough to get you started and give you some ideas about the
1487: facilities available in Forth. Read the rest of the manual and the
1488: standard when you are through this.
1.48 anton 1489:
1490: The intended way to use this tutorial is that you work through it while
1491: sitting in front of the console, take a look at the examples and predict
1492: what they will do, then try them out; if the outcome is not as expected,
1493: find out why (e.g., by trying out variations of the example), so you
1494: understand what's going on. There are also some assignments that you
1495: should solve.
1496:
1497: This tutorial assumes that you have programmed before and know what,
1498: e.g., a loop is.
1499:
1500: @c !! explain compat library
1501:
1502: @menu
1503: * Starting Gforth Tutorial::
1504: * Syntax Tutorial::
1505: * Crash Course Tutorial::
1506: * Stack Tutorial::
1507: * Arithmetics Tutorial::
1508: * Stack Manipulation Tutorial::
1509: * Using files for Forth code Tutorial::
1510: * Comments Tutorial::
1511: * Colon Definitions Tutorial::
1512: * Decompilation Tutorial::
1513: * Stack-Effect Comments Tutorial::
1514: * Types Tutorial::
1515: * Factoring Tutorial::
1516: * Designing the stack effect Tutorial::
1517: * Local Variables Tutorial::
1518: * Conditional execution Tutorial::
1519: * Flags and Comparisons Tutorial::
1520: * General Loops Tutorial::
1521: * Counted loops Tutorial::
1522: * Recursion Tutorial::
1523: * Leaving definitions or loops Tutorial::
1524: * Return Stack Tutorial::
1525: * Memory Tutorial::
1526: * Characters and Strings Tutorial::
1527: * Alignment Tutorial::
1528: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1529: * Execution Tokens Tutorial::
1530: * Exceptions Tutorial::
1531: * Defining Words Tutorial::
1532: * Arrays and Records Tutorial::
1533: * POSTPONE Tutorial::
1534: * Literal Tutorial::
1535: * Advanced macros Tutorial::
1536: * Compilation Tokens Tutorial::
1537: * Wordlists and Search Order Tutorial::
1538: @end menu
1539:
1540: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1541: @section Starting Gforth
1542:
1543: You can start Gforth by typing its name:
1544:
1545: @example
1546: gforth
1547: @end example
1548:
1549: That puts you into interactive mode; you can leave Gforth by typing
1550: @code{bye}. While in Gforth, you can edit the command line and access
1551: the command line history with cursor keys, similar to bash.
1552:
1553:
1554: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1555: @section Syntax
1556:
1557: A @dfn{word} is a sequence of arbitrary characters (expcept white
1558: space). Words are separated by white space. E.g., each of the
1559: following lines contains exactly one word:
1560:
1561: @example
1562: word
1563: !@@#$%^&*()
1564: 1234567890
1565: 5!a
1566: @end example
1567:
1568: A frequent beginner's error is to leave away necessary white space,
1569: resulting in an error like @samp{Undefined word}; so if you see such an
1570: error, check if you have put spaces wherever necessary.
1571:
1572: @example
1573: ." hello, world" \ correct
1574: ."hello, world" \ gives an "Undefined word" error
1575: @end example
1576:
1577: Gforth and most other Forth systems ignores differences in case (it is
1578: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1579: your system is case-sensitive, you may have to type all the examples
1580: given here in upper case.
1581:
1582:
1583: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1584: @section Crash Course
1585:
1586: Type
1587:
1588: @example
1589: 0 0 !
1590: here execute
1591: ' catch >body 20 erase abort
1592: ' (quit) >body 20 erase
1593: @end example
1594:
1595: The last two examples are guaranteed to destroy parts of Gforth (and
1596: most other systems), so you better leave Gforth afterwards (if it has
1597: not finished by itself). On some systems you may have to kill gforth
1598: from outside (e.g., in Unix with @code{kill}).
1599:
1600: Now that you know how to produce crashes (and that there's not much to
1601: them), let's learn how to produce meaningful programs.
1602:
1603:
1604: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1605: @section Stack
1606:
1607: The most obvious feature of Forth is the stack. When you type in a
1608: number, it is pushed on the stack. You can display the content of the
1609: stack with @code{.s}.
1610:
1611: @example
1612: 1 2 .s
1613: 3 .s
1614: @end example
1615:
1616: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1617: appear in @code{.s} output as they appeared in the input.
1618:
1619: You can print the top of stack element with @code{.}.
1620:
1621: @example
1622: 1 2 3 . . .
1623: @end example
1624:
1625: In general, words consume their stack arguments (@code{.s} is an
1626: exception).
1627:
1628: @assignment
1629: What does the stack contain after @code{5 6 7 .}?
1630: @endassignment
1631:
1632:
1633: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1634: @section Arithmetics
1635:
1636: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1637: operate on the top two stack items:
1638:
1639: @example
1640: 2 2 + .
1641: 2 1 - .
1642: 7 3 mod .
1643: @end example
1644:
1645: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1646: as in the corresponding infix expression (this is generally the case in
1647: Forth).
1648:
1649: Parentheses are superfluous (and not available), because the order of
1650: the words unambiguously determines the order of evaluation and the
1651: operands:
1652:
1653: @example
1654: 3 4 + 5 * .
1655: 3 4 5 * + .
1656: @end example
1657:
1658: @assignment
1659: What are the infix expressions corresponding to the Forth code above?
1660: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1661: known as Postfix or RPN (Reverse Polish Notation).}.
1662: @endassignment
1663:
1664: To change the sign, use @code{negate}:
1665:
1666: @example
1667: 2 negate .
1668: @end example
1669:
1670: @assignment
1671: Convert -(-3)*4-5 to Forth.
1672: @endassignment
1673:
1674: @code{/mod} performs both @code{/} and @code{mod}.
1675:
1676: @example
1677: 7 3 /mod . .
1678: @end example
1679:
1680: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1681: @section Stack Manipulation
1682:
1683: Stack manipulation words rearrange the data on the stack.
1684:
1685: @example
1686: 1 .s drop .s
1687: 1 .s dup .s drop drop .s
1688: 1 2 .s over .s drop drop drop
1689: 1 2 .s swap .s drop drop
1690: 1 2 3 .s rot .s drop drop drop
1691: @end example
1692:
1693: These are the most important stack manipulation words. There are also
1694: variants that manipulate twice as many stack items:
1695:
1696: @example
1697: 1 2 3 4 .s 2swap .s 2drop 2drop
1698: @end example
1699:
1700: Two more stack manipulation words are:
1701:
1702: @example
1703: 1 2 .s nip .s drop
1704: 1 2 .s tuck .s 2drop drop
1705: @end example
1706:
1707: @assignment
1708: Replace @code{nip} and @code{tuck} with combinations of other stack
1709: manipulation words.
1710:
1711: @example
1712: Given: How do you get:
1713: 1 2 3 3 2 1
1714: 1 2 3 1 2 3 2
1715: 1 2 3 1 2 3 3
1716: 1 2 3 1 3 3
1717: 1 2 3 2 1 3
1718: 1 2 3 4 4 3 2 1
1719: 1 2 3 1 2 3 1 2 3
1720: 1 2 3 4 1 2 3 4 1 2
1721: 1 2 3
1722: 1 2 3 1 2 3 4
1723: 1 2 3 1 3
1724: @end example
1725: @endassignment
1726:
1727: @example
1728: 5 dup * .
1729: @end example
1730:
1731: @assignment
1732: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1733: Write a piece of Forth code that expects two numbers on the stack
1734: (@var{a} and @var{b}, with @var{b} on top) and computes
1735: @code{(a-b)(a+1)}.
1736: @endassignment
1737:
1738: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1739: @section Using files for Forth code
1740:
1741: While working at the Forth command line is convenient for one-line
1742: examples and short one-off code, you probably want to store your source
1743: code in files for convenient editing and persistence. You can use your
1744: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1745: Gforth}) to create @var{file} and use
1746:
1747: @example
1748: s" @var{file}" included
1749: @end example
1750:
1751: to load it into your Forth system. The file name extension I use for
1752: Forth files is @samp{.fs}.
1753:
1754: You can easily start Gforth with some files loaded like this:
1755:
1756: @example
1757: gforth @var{file1} @var{file2}
1758: @end example
1759:
1760: If an error occurs during loading these files, Gforth terminates,
1761: whereas an error during @code{INCLUDED} within Gforth usually gives you
1762: a Gforth command line. Starting the Forth system every time gives you a
1763: clean start every time, without interference from the results of earlier
1764: tries.
1765:
1766: I often put all the tests in a file, then load the code and run the
1767: tests with
1768:
1769: @example
1770: gforth @var{code} @var{tests} -e bye
1771: @end example
1772:
1773: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1774: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1775: restart this command without ado.
1776:
1777: The advantage of this approach is that the tests can be repeated easily
1778: every time the program ist changed, making it easy to catch bugs
1779: introduced by the change.
1780:
1781:
1782: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1783: @section Comments
1784:
1785: @example
1786: \ That's a comment; it ends at the end of the line
1787: ( Another comment; it ends here: ) .s
1788: @end example
1789:
1790: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1791: separated with white space from the following text.
1792:
1793: @example
1794: \This gives an "Undefined word" error
1795: @end example
1796:
1797: The first @code{)} ends a comment started with @code{(}, so you cannot
1798: nest @code{(}-comments; and you cannot comment out text containing a
1799: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1800: avoid @code{)} in word names.}.
1801:
1802: I use @code{\}-comments for descriptive text and for commenting out code
1803: of one or more line; I use @code{(}-comments for describing the stack
1804: effect, the stack contents, or for commenting out sub-line pieces of
1805: code.
1806:
1807: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1808: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1809: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1810: with @kbd{M-q}.
1811:
1812:
1813: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1814: @section Colon Definitions
1815:
1816: are similar to procedures and functions in other programming languages.
1817:
1818: @example
1819: : squared ( n -- n^2 )
1820: dup * ;
1821: 5 squared .
1822: 7 squared .
1823: @end example
1824:
1825: @code{:} starts the colon definition; its name is @code{squared}. The
1826: following comment describes its stack effect. The words @code{dup *}
1827: are not executed, but compiled into the definition. @code{;} ends the
1828: colon definition.
1829:
1830: The newly-defined word can be used like any other word, including using
1831: it in other definitions:
1832:
1833: @example
1834: : cubed ( n -- n^3 )
1835: dup squared * ;
1836: -5 cubed .
1837: : fourth-power ( n -- n^4 )
1838: squared squared ;
1839: 3 fourth-power .
1840: @end example
1841:
1842: @assignment
1843: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1844: @code{/mod} in terms of other Forth words, and check if they work (hint:
1845: test your tests on the originals first). Don't let the
1846: @samp{redefined}-Messages spook you, they are just warnings.
1847: @endassignment
1848:
1849:
1850: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1851: @section Decompilation
1852:
1853: You can decompile colon definitions with @code{see}:
1854:
1855: @example
1856: see squared
1857: see cubed
1858: @end example
1859:
1860: In Gforth @code{see} shows you a reconstruction of the source code from
1861: the executable code. Informations that were present in the source, but
1862: not in the executable code, are lost (e.g., comments).
1863:
1864: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1865: @section Stack-Effect Comments
1866:
1867: By convention the comment after the name of a definition describes the
1868: stack effect: The part in from of the @samp{--} describes the state of
1869: the stack before the execution of the definition, i.e., the parameters
1870: that are passed into the colon definition; the part behind the @samp{--}
1871: is the state of the stack after the execution of the definition, i.e.,
1872: the results of the definition. The stack comment only shows the top
1873: stack items that the definition accesses and/or changes.
1874:
1875: You should put a correct stack effect on every definition, even if it is
1876: just @code{( -- )}. You should also add some descriptive comment to
1877: more complicated words (I usually do this in the lines following
1878: @code{:}). If you don't do this, your code becomes unreadable (because
1879: you have to work through every definition before you can undertsand
1880: any).
1881:
1882: @assignment
1883: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1884: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1885: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1886: are done, you can compare your stack effects to this in this manual
1887: (@pxref{Word Index}).
1888: @endassignment
1889:
1890: Sometimes programmers put comments at various places in colon
1891: definitions that describe the contents of the stack at that place (stack
1892: comments); i.e., they are like the first part of a stack-effect
1893: comment. E.g.,
1894:
1895: @example
1896: : cubed ( n -- n^3 )
1897: dup squared ( n n^2 ) * ;
1898: @end example
1899:
1900: In this case the stack comment is pretty superfluous, because the word
1901: is simple enough. If you think it would be a good idea to add such a
1902: comment to increase readability, you should also consider factoring the
1903: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1904: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1905: however, if you decide not to refactor it, then having such a comment is
1906: better than not having it.
1907:
1908: The names of the stack items in stack-effect and stack comments in the
1909: standard, in this manual, and in many programs specify the type through
1910: a type prefix, similar to Fortran and Hungarian notation. The most
1911: frequent prefixes are:
1912:
1913: @table @code
1914: @item n
1915: signed integer
1916: @item u
1917: unsigned integer
1918: @item c
1919: character
1920: @item f
1921: Boolean flags, i.e. @code{false} or @code{true}.
1922: @item a-addr,a-
1923: Cell-aligned address
1924: @item c-addr,c-
1925: Char-aligned address (note that a Char may have two bytes in Windows NT)
1926: @item xt
1927: Execution token, same size as Cell
1928: @item w,x
1929: Cell, can contain an integer or an address. It usually takes 32, 64 or
1930: 16 bits (depending on your platform and Forth system). A cell is more
1931: commonly known as machine word, but the term @emph{word} already means
1932: something different in Forth.
1933: @item d
1934: signed double-cell integer
1935: @item ud
1936: unsigned double-cell integer
1937: @item r
1938: Float (on the FP stack)
1939: @end table
1940:
1941: You can find a more complete list in @ref{Notation}.
1942:
1943: @assignment
1944: Write stack-effect comments for all definitions you have written up to
1945: now.
1946: @endassignment
1947:
1948:
1949: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1950: @section Types
1951:
1952: In Forth the names of the operations are not overloaded; so similar
1953: operations on different types need different names; e.g., @code{+} adds
1954: integers, and you have to use @code{f+} to add floating-point numbers.
1955: The following prefixes are often used for related operations on
1956: different types:
1957:
1958: @table @code
1959: @item (none)
1960: signed integer
1961: @item u
1962: unsigned integer
1963: @item c
1964: character
1965: @item d
1966: signed double-cell integer
1967: @item ud, du
1968: unsigned double-cell integer
1969: @item 2
1970: two cells (not-necessarily double-cell numbers)
1971: @item m, um
1972: mixed single-cell and double-cell operations
1973: @item f
1974: floating-point (note that in stack comments @samp{f} represents flags,
1975: and @samp{r} represents FP number).
1976: @end table
1977:
1978: If there are no differences between the signed and the unsigned variant
1979: (e.g., for @code{+}), there is only the prefix-less variant.
1980:
1981: Forth does not perform type checking, neither at compile time, nor at
1982: run time. If you use the wrong oeration, the data are interpreted
1983: incorrectly:
1984:
1985: @example
1986: -1 u.
1987: @end example
1988:
1989: If you have only experience with type-checked languages until now, and
1990: have heard how important type-checking is, don't panic! In my
1991: experience (and that of other Forthers), type errors in Forth code are
1992: usually easy to find (once you get used to it), the increased vigilance
1993: of the programmer tends to catch some harder errors in addition to most
1994: type errors, and you never have to work around the type system, so in
1995: most situations the lack of type-checking seems to be a win (projects to
1996: add type checking to Forth have not caught on).
1997:
1998:
1999: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
2000: @section Factoring
2001:
2002: If you try to write longer definitions, you will soon find it hard to
2003: keep track of the stack contents. Therefore, good Forth programmers
2004: tend to write only short definitions (e.g., three lines). The art of
2005: finding meaningful short definitions is known as factoring (as in
2006: factoring polynomials).
2007:
2008: Well-factored programs offer additional advantages: smaller, more
2009: general words, are easier to test and debug and can be reused more and
2010: better than larger, specialized words.
2011:
2012: So, if you run into difficulties with stack management, when writing
2013: code, try to define meaningful factors for the word, and define the word
2014: in terms of those. Even if a factor contains only two words, it is
2015: often helpful.
2016:
2017: Good factoring is not easy, and even experienced Forth programmers often
2018: don't find the right solution right away, but only when rewriting the
2019: program. So, if you don't come up with a good solution immediately,
2020: keep trying, don't despair.
2021:
2022: @c example !!
2023:
2024:
2025: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
2026: @section Designing the stack effect
2027:
2028: In other languages you can use an arbitrary order of parameters for a
2029: function; and since ther is only one result, you don't have to deal with
2030: the order of results, either.
2031:
2032: In Forth (and other stack-based languages, e.g., Postscript) the
2033: parameter and result order of a definition is important and should be
2034: designed well. The general guideline is to design the stack effect such
2035: that the word is simple to use in most cases, even if that complicates
2036: the implementation of the word. Some concrete rules are:
2037:
2038: @itemize @bullet
2039:
2040: @item
2041: Words consume all of their parameters (e.g., @code{.}).
2042:
2043: @item
2044: If there is a convention on the order of parameters (e.g., from
2045: mathematics or another programming language), stick with it (e.g.,
2046: @code{-}).
2047:
2048: @item
2049: If one parameter usually requires only a short computation (e.g., it is
2050: a constant), pass it on the top of the stack. Conversely, parameters
2051: that usually require a long sequence of code to compute should be passed
2052: as the bottom (i.e., first) parameter. This makes the code easier to
2053: read, because reader does not need to keep track of the bottom item
2054: through a long sequence of code (or, alternatively, through stack
1.49 anton 2055: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 2056: address on top of the stack because it is usually simpler to compute
2057: than the stored value (often the address is just a variable).
2058:
2059: @item
2060: Similarly, results that are usually consumed quickly should be returned
2061: on the top of stack, whereas a result that is often used in long
2062: computations should be passed as bottom result. E.g., the file words
2063: like @code{open-file} return the error code on the top of stack, because
2064: it is usually consumed quickly by @code{throw}; moreover, the error code
2065: has to be checked before doing anything with the other results.
2066:
2067: @end itemize
2068:
2069: These rules are just general guidelines, don't lose sight of the overall
2070: goal to make the words easy to use. E.g., if the convention rule
2071: conflicts with the computation-length rule, you might decide in favour
2072: of the convention if the word will be used rarely, and in favour of the
2073: computation-length rule if the word will be used frequently (because
2074: with frequent use the cost of breaking the computation-length rule would
2075: be quite high, and frequent use makes it easier to remember an
2076: unconventional order).
2077:
2078: @c example !! structure package
2079:
2080: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
2081: @section Local Variables
2082:
2083: You can define local variables (@emph{locals}) in a colon definition:
2084:
2085: @example
2086: : swap @{ a b -- b a @}
2087: b a ;
2088: 1 2 swap .s 2drop
2089: @end example
2090:
2091: (If your Forth system does not support this syntax, include
2092: @file{compat/anslocals.fs} first).
2093:
2094: In this example @code{@{ a b -- b a @}} is the locals definition; it
2095: takes two cells from the stack, puts the top of stack in @code{b} and
2096: the next stack element in @code{a}. @code{--} starts a comment ending
2097: with @code{@}}. After the locals definition, using the name of the
2098: local will push its value on the stack. You can leave the comment
2099: part (@code{-- b a}) away:
2100:
2101: @example
2102: : swap ( x1 x2 -- x2 x1 )
2103: @{ a b @} b a ;
2104: @end example
2105:
2106: In Gforth you can have several locals definitions, anywhere in a colon
2107: definition; in contrast, in a standard program you can have only one
2108: locals definition per colon definition, and that locals definition must
2109: be outside any controll structure.
2110:
2111: With locals you can write slightly longer definitions without running
2112: into stack trouble. However, I recommend trying to write colon
2113: definitions without locals for exercise purposes to help you gain the
2114: essential factoring skills.
2115:
2116: @assignment
2117: Rewrite your definitions until now with locals
2118: @endassignment
2119:
2120:
2121: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
2122: @section Conditional execution
2123:
2124: In Forth you can use control structures only inside colon definitions.
2125: An @code{if}-structure looks like this:
2126:
2127: @example
2128: : abs ( n1 -- +n2 )
2129: dup 0 < if
2130: negate
2131: endif ;
2132: 5 abs .
2133: -5 abs .
2134: @end example
2135:
2136: @code{if} takes a flag from the stack. If the flag is non-zero (true),
2137: the following code is performed, otherwise execution continues after the
1.51 pazsan 2138: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 2139: elements and prioduces a flag:
2140:
2141: @example
2142: 1 2 < .
2143: 2 1 < .
2144: 1 1 < .
2145: @end example
2146:
2147: Actually the standard name for @code{endif} is @code{then}. This
2148: tutorial presents the examples using @code{endif}, because this is often
2149: less confusing for people familiar with other programming languages
2150: where @code{then} has a different meaning. If your system does not have
2151: @code{endif}, define it with
2152:
2153: @example
2154: : endif postpone then ; immediate
2155: @end example
2156:
2157: You can optionally use an @code{else}-part:
2158:
2159: @example
2160: : min ( n1 n2 -- n )
2161: 2dup < if
2162: drop
2163: else
2164: nip
2165: endif ;
2166: 2 3 min .
2167: 3 2 min .
2168: @end example
2169:
2170: @assignment
2171: Write @code{min} without @code{else}-part (hint: what's the definition
2172: of @code{nip}?).
2173: @endassignment
2174:
2175:
2176: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
2177: @section Flags and Comparisons
2178:
2179: In a false-flag all bits are clear (0 when interpreted as integer). In
2180: a canonical true-flag all bits are set (-1 as a twos-complement signed
2181: integer); in many contexts (e.g., @code{if}) any non-zero value is
2182: treated as true flag.
2183:
2184: @example
2185: false .
2186: true .
2187: true hex u. decimal
2188: @end example
2189:
2190: Comparison words produce canonical flags:
2191:
2192: @example
2193: 1 1 = .
2194: 1 0= .
2195: 0 1 < .
2196: 0 0 < .
2197: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
2198: -1 1 < .
2199: @end example
2200:
2201: Gforth supports all combinations of the prefixes @code{0 u d d0 du} (or
2202: none) and the comparisons @code{= <> < > <= >=}. Only a part of these
1.60 anton 2203: combinations are standard (for details see the standard or @ref{Word
1.61 anton 2204: Index}).
1.48 anton 2205:
2206: You can use @code{and or xor invert} can be used as operations on
2207: canonical flags. Actually they are bitwise operations:
2208:
2209: @example
2210: 1 2 and .
2211: 1 2 or .
2212: 1 3 xor .
2213: 1 invert .
2214: @end example
2215:
2216: You can convert a zero/non-zero flag into a canonical flag with
2217: @code{0<>} (and complement it on the way with @code{0=}).
2218:
2219: @example
2220: 1 0= .
2221: 1 0<> .
2222: @end example
2223:
2224: You can use the all-bits-set feature of canonicasl flags and the bitwise
2225: operation of the Boolean operations to avoid @code{if}s:
2226:
2227: @example
2228: : foo ( n1 -- n2 )
2229: 0= if
2230: 14
2231: else
2232: 0
2233: endif ;
2234: 0 foo .
2235: 1 foo .
2236:
2237: : foo ( n1 -- n2 )
2238: 0= 14 and ;
2239: 0 foo .
2240: 1 foo .
2241: @end example
2242:
2243: @assignment
2244: Write @code{min} without @code{if}.
2245: @endassignment
2246:
2247:
2248: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2249: @section General Loops
2250:
2251: The endless loop is the most simple one:
2252:
2253: @example
2254: : endless ( -- )
2255: 0 begin
2256: dup . 1+
2257: again ;
2258: endless
2259: @end example
2260:
2261: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2262: does nothing at run-time, @code{again} jumps back to @code{begin}.
2263:
2264: A loop with one exit at any place looks like this:
2265:
2266: @example
2267: : log2 ( +n1 -- n2 )
2268: \ logarithmus dualis of n1>0, rounded down to the next integer
2269: assert( dup 0> )
2270: 2/ 0 begin
2271: over 0> while
2272: 1+ swap 2/ swap
2273: repeat
2274: nip ;
2275: 7 log2 .
2276: 8 log2 .
2277: @end example
2278:
2279: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2280: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2281: continues behind the @code{while}. @code{Repeat} jumps back to
2282: @code{begin}, just like @code{again}.
2283:
2284: In Forth there are many combinations/abbreviations, like @code{1+}.
2285: However, @code{2/} is not one of them; it shifts it's argument right by
2286: one bit (arithmetic shift right):
2287:
2288: @example
2289: -5 2 / .
2290: -5 2/ .
2291: @end example
2292:
2293: @code{assert(} is no standard word, but you can get it on systems other
2294: then Gforth by including @file{compat/assert.fs}. You can see what it
2295: does by trying
2296:
2297: @example
2298: 0 log2 .
2299: @end example
2300:
2301: Here's a loop with an exit at the end:
2302:
2303: @example
2304: : log2 ( +n1 -- n2 )
2305: \ logarithmus dualis of n1>0, rounded down to the next integer
2306: assert( dup 0 > )
2307: -1 begin
2308: 1+ swap 2/ swap
2309: over 0 <=
2310: until
2311: nip ;
2312: @end example
2313:
2314: @code{Until} consumes a flag; if it is non-zero, execution continues at
2315: the @code{begin}, otherwise after the @code{until}.
2316:
2317: @assignment
2318: Write a definition for computing the greatest common divisor.
2319: @endassignment
2320:
2321:
2322: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2323: @section Counted loops
2324:
2325: @example
2326: : ^ ( n1 u -- n )
2327: \ n = the uth power of u1
2328: 1 swap 0 u+do
2329: over *
2330: loop
2331: nip ;
2332: 3 2 ^ .
2333: 4 3 ^ .
2334: @end example
2335:
2336: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2337: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2338: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2339: times (or not at all, if @code{u3-u4<0}).
2340:
2341: You can see the stack effect design rules at work in the stack effect of
2342: the loop start words: Since the start value of the loop is more
2343: frequently constant than the end value, the start value is passed on
2344: the top-of-stack.
2345:
2346: You can access the counter of a counted loop with @code{i}:
2347:
2348: @example
2349: : fac ( u -- u! )
2350: 1 swap 1+ 1 u+do
2351: i *
2352: loop ;
2353: 5 fac .
2354: 7 fac .
2355: @end example
2356:
2357: There is also @code{+do}, which expects signed numbers (important for
2358: deciding whether to enter the loop).
2359:
2360: @assignment
2361: Write a definition for computing the nth Fibonacci number.
2362: @endassignment
2363:
2364: !! +DO...+LOOP
2365: !! -DO...-LOOP
2366:
2367:
2368: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2369: @section Recursion
2370:
2371: Usually the name of a definition is not visible in the definition; but
2372: earlier definitions are usually visible:
2373:
2374: @example
2375: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2376: : / ( n1 n2 -- n )
2377: dup 0= if
2378: -10 throw \ report division by zero
2379: endif
2380: / \ old version
2381: ;
2382: 1 0 /
2383: @end example
2384:
2385: For recursive definitions you can use @code{recursive} (non-standard) or
2386: @code{recurse}:
2387:
2388: @example
2389: : fac1 ( n -- n! ) recursive
2390: dup 0> if
2391: dup 1- fac1 *
2392: else
2393: drop 1
2394: endif ;
2395: 7 fac1 .
2396:
2397: : fac2 ( n -- n! )
2398: dup 0> if
2399: dup 1- recurse *
2400: else
2401: drop 1
2402: endif ;
2403: 8 fac2 .
2404: @end example
2405:
2406: @assignment
2407: Write a recursive definition for computing the nth Fibonacci number.
2408: @endassignment
2409:
2410:
2411: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2412: @section Leaving definitions or loops
2413:
2414: @code{EXIT} exits the current definition right away. For every counted
2415: loop that is left in this way, an @code{UNLOOP} has to be performed
2416: before the @code{EXIT}:
2417:
2418: @c !! real examples
2419: @example
2420: : ...
2421: ... u+do
2422: ... if
2423: ... unloop exit
2424: endif
2425: ...
2426: loop
2427: ... ;
2428: @end example
2429:
2430: @code{LEAVE} leaves the innermost counted loop right away:
2431:
2432: @example
2433: : ...
2434: ... u+do
2435: ... if
2436: ... leave
2437: endif
2438: ...
2439: loop
2440: ... ;
2441: @end example
2442:
2443:
2444: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2445: @section Return Stack
2446:
2447: In addition to the data stack Forth also has a second stack, the return
2448: stack; most Forth systems store the return addresses of procedure calls
2449: there (thus its name). Programmers can also use this stack:
2450:
2451: @example
2452: : foo ( n1 n2 -- )
2453: .s
2454: >r .s
1.50 anton 2455: r@@ .
1.48 anton 2456: >r .s
1.50 anton 2457: r@@ .
1.48 anton 2458: r> .
1.50 anton 2459: r@@ .
1.48 anton 2460: r> . ;
2461: 1 2 foo
2462: @end example
2463:
2464: @code{>r} takes an element from the data stack and pushes it onto the
2465: return stack; conversely, @code{r>} moves an elementm from the return to
2466: the data stack; @code{r@@} pushes a copy of the top of the return stack
2467: on the return stack.
2468:
2469: Forth programmers usually use the return stack for storing data
2470: temporarily, if using the data stack alone would be too complex, and
2471: factoring and locals are not an option:
2472:
2473: @example
2474: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2475: rot >r rot r> ;
2476: @end example
2477:
2478: The return address of the definition and the loop control parameters of
2479: counted loops usually reside on the return stack, so you have to take
2480: all items, that you have pushed on the return stack in a colon
2481: definition or counted loop, from the return stack before the definition
2482: or loop ends. You cannot access items that you pushed on the return
2483: stack outside some definition or loop within the definition of loop.
2484:
2485: If you miscount the return stack items, this usually ends in a crash:
2486:
2487: @example
2488: : crash ( n -- )
2489: >r ;
2490: 5 crash
2491: @end example
2492:
2493: You cannot mix using locals and using the return stack (according to the
2494: standard; Gforth has no problem). However, they solve the same
2495: problems, so this shouldn't be an issue.
2496:
2497: @assignment
2498: Can you rewrite any of the definitions you wrote until now in a better
2499: way using the return stack?
2500: @endassignment
2501:
2502:
2503: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2504: @section Memory
2505:
2506: You can create a global variable @code{v} with
2507:
2508: @example
2509: variable v ( -- addr )
2510: @end example
2511:
2512: @code{v} pushes the address of a cell in memory on the stack. This cell
2513: was reserved by @code{variable}. You can use @code{!} (store) to store
2514: values into this cell and @code{@@} (fetch) to load the value from the
2515: stack into memory:
2516:
2517: @example
2518: v .
2519: 5 v ! .s
1.50 anton 2520: v @@ .
1.48 anton 2521: @end example
2522:
2523: You can also reserve more memory:
2524:
2525: @example
2526: create v2 20 cells allot
2527: @end example
2528:
2529: creates a word @code{v2} and reserves 20 cells; the address pushed by
2530: @code{v2} points to the start of these 20 cells. You can use address
2531: arithmetic to access these cells:
2532:
2533: @example
2534: 3 v2 5 cells + !
2535: @end example
2536:
2537: You can reserve and initialize memory with @code{,}:
2538:
2539: @example
2540: create v3
2541: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2542: v3 @@ .
2543: v3 cell+ @@ .
2544: v3 2 cells + @@ .
1.48 anton 2545: @end example
2546:
2547: @assignment
2548: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2549: @code{u} cells, with the first of these cells at @code{addr}, the next
2550: one at @code{addr cell+} etc.
2551: @endassignment
2552:
2553: You can also reserve memory without creating a new word:
2554:
2555: @example
1.60 anton 2556: here 10 cells allot .
2557: here .
1.48 anton 2558: @end example
2559:
2560: @code{Here} pushes the start address of the memory area. You should
2561: store it somewhere, or you will have a hard time finding the memory area
2562: again.
2563:
2564: @code{Allot} manages dictionary memory. The dictionary memory contains
2565: the system's data structures for words etc. on Gforth and most other
2566: Forth systems. It is managed like a stack: You can free the memory that
2567: you have just @code{allot}ed with
2568:
2569: @example
2570: -10 cells allot
1.60 anton 2571: here .
1.48 anton 2572: @end example
2573:
2574: Note that you cannot do this if you have created a new word in the
2575: meantime (because then your @code{allot}ed memory is no longer on the
2576: top of the dictionary ``stack'').
2577:
2578: Alternatively, you can use @code{allocate} and @code{free} which allow
2579: freeing memory in any order:
2580:
2581: @example
2582: 10 cells allocate throw .s
2583: 20 cells allocate throw .s
2584: swap
2585: free throw
2586: free throw
2587: @end example
2588:
2589: The @code{throw}s deal with errors (e.g., out of memory).
2590:
1.60 anton 2591: And there is also a garbage collector
2592: @url{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip},
2593: which eliminates the need to @code{free} memory explicitly.
1.48 anton 2594:
2595:
2596: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2597: @section Characters and Strings
2598:
2599: On the stack characters take up a cell, like numbers. In memory they
2600: have their own size (one 8-bit byte on most systems), and therefore
2601: require their own words for memory access:
2602:
2603: @example
2604: create v4
2605: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2606: v4 4 chars + c@@ .
1.48 anton 2607: @end example
2608:
2609: The preferred representation of strings on the stack is @code{addr
2610: u-count}, where @code{addr} is the address of the first character and
2611: @code{u-count} is the number of characters in the string.
2612:
2613: @example
2614: v4 5 type
2615: @end example
2616:
2617: You get a string constant with
2618:
2619: @example
2620: s" hello, world" .s
2621: type
2622: @end example
2623:
2624: Make sure you have a space between @code{s"} and the string; @code{s"}
2625: is a normal Forth word and must be delimited with white space (try what
2626: happens when you remove the space).
2627:
2628: However, this interpretive use of @code{s"} is quite restricted: the
2629: string exists only until the next call of @code{s"} (some Forth systems
2630: keep more than one of these strings, but usually they still have a
1.62 crook 2631: limited lifetime).
1.48 anton 2632:
2633: @example
2634: s" hello," s" world" .s
2635: type
2636: type
2637: @end example
2638:
1.62 crook 2639: You can also use @code{s"} in a definition, and the resulting
2640: strings then live forever (well, for as long as the definition):
1.48 anton 2641:
2642: @example
2643: : foo s" hello," s" world" ;
2644: foo .s
2645: type
2646: type
2647: @end example
2648:
2649: @assignment
2650: @code{Emit ( c -- )} types @code{c} as character (not a number).
2651: Implement @code{type ( addr u -- )}.
2652: @endassignment
2653:
2654: @node Alignment Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Characters and Strings Tutorial, Tutorial
2655: @section Alignment
2656:
2657: On many processors cells have to be aligned in memory, if you want to
2658: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2659: not require alignment, access to aligned cells is faster).
1.48 anton 2660:
2661: @code{Create} aligns @code{here} (i.e., the place where the next
2662: allocation will occur, and that the @code{create}d word points to).
2663: Likewise, the memory produced by @code{allocate} starts at an aligned
2664: address. Adding a number of @code{cells} to an aligned address produces
2665: another aligned address.
2666:
2667: However, address arithmetic involving @code{char+} and @code{chars} can
2668: create an address that is not cell-aligned. @code{Aligned ( addr --
2669: a-addr )} produces the next aligned address:
2670:
2671: @example
1.50 anton 2672: v3 char+ aligned .s @@ .
2673: v3 char+ .s @@ .
1.48 anton 2674: @end example
2675:
2676: Similarly, @code{align} advances @code{here} to the next aligned
2677: address:
2678:
2679: @example
2680: create v5 97 c,
2681: here .
2682: align here .
2683: 1000 ,
2684: @end example
2685:
2686: Note that you should use aligned addresses even if your processor does
2687: not require them, if you want your program to be portable.
2688:
2689:
2690: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Alignment Tutorial, Tutorial
2691: @section Interpretation and Compilation Semantics and Immediacy
2692:
2693: When a word is compiled, it behaves differently from being interpreted.
2694: E.g., consider @code{+}:
2695:
2696: @example
2697: 1 2 + .
2698: : foo + ;
2699: @end example
2700:
2701: These two behaviours are known as compilation and interpretation
2702: semantics. For normal words (e.g., @code{+}), the compilation semantics
2703: is to append the interpretation semantics to the currently defined word
2704: (@code{foo} in the example above). I.e., when @code{foo} is executed
2705: later, the interpretation semantics of @code{+} (i.e., adding two
2706: numbers) will be performed.
2707:
2708: However, there are words with non-default compilation semantics, e.g.,
2709: the control-flow words like @code{if}. You can use @code{immediate} to
2710: change the compilation semantics of the last defined word to be equal to
2711: the interpretation semantics:
2712:
2713: @example
2714: : [FOO] ( -- )
2715: 5 . ; immediate
2716:
2717: [FOO]
2718: : bar ( -- )
2719: [FOO] ;
2720: bar
2721: see bar
2722: @end example
2723:
2724: Two conventions to mark words with non-default compilation semnatics are
2725: names with brackets (more frequently used) and to write them all in
2726: upper case (less frequently used).
2727:
2728: In Gforth (and many other systems) you can also remove the
2729: interpretation semantics with @code{compile-only} (the compilation
2730: semantics is derived from the original interpretation semantics):
2731:
2732: @example
2733: : flip ( -- )
2734: 6 . ; compile-only \ but not immediate
2735: flip
2736:
2737: : flop ( -- )
2738: flip ;
2739: flop
2740: @end example
2741:
2742: In this example the interpretation semantics of @code{flop} is equal to
2743: the original interpretation semantics of @code{flip}.
2744:
2745: The text interpreter has two states: in interpret state, it performs the
2746: interpretation semantics of words it encounters; in compile state, it
2747: performs the compilation semantics of these words.
2748:
2749: Among other things, @code{:} switches into compile state, and @code{;}
2750: switches back to interpret state. They contain the factors @code{]}
2751: (switch to compile state) and @code{[} (switch to interpret state), that
2752: do nothing but switch the state.
2753:
2754: @example
2755: : xxx ( -- )
2756: [ 5 . ]
2757: ;
2758:
2759: xxx
2760: see xxx
2761: @end example
2762:
2763: These brackets are also the source of the naming convention mentioned
2764: above.
2765:
2766:
2767: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2768: @section Execution Tokens
2769:
2770: @code{' word} gives you the execution token (XT) of a word. The XT is a
2771: cell representing the interpretation semantics of a word. You can
2772: execute this semantics with @code{execute}:
2773:
2774: @example
2775: ' + .s
2776: 1 2 rot execute .
2777: @end example
2778:
2779: The XT is similar to a function pointer in C. However, parameter
2780: passing through the stack makes it a little more flexible:
2781:
2782: @example
2783: : map-array ( ... addr u xt -- ... )
1.50 anton 2784: \ executes xt ( ... x -- ... ) for every element of the array starting
2785: \ at addr and containing u elements
1.48 anton 2786: @{ xt @}
2787: cells over + swap ?do
1.50 anton 2788: i @@ xt execute
1.48 anton 2789: 1 cells +loop ;
2790:
2791: create a 3 , 4 , 2 , -1 , 4 ,
2792: a 5 ' . map-array .s
2793: 0 a 5 ' + map-array .
2794: s" max-n" environment? drop .s
2795: a 5 ' min map-array .
2796: @end example
2797:
2798: You can use map-array with the XTs of words that consume one element
2799: more than they produce. In theory you can also use it with other XTs,
2800: but the stack effect then depends on the size of the array, which is
2801: hard to understand.
2802:
1.51 pazsan 2803: Since XTs are cell-sized, you can store them in memory and manipulate
2804: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2805: word with @code{compile,}:
2806:
2807: @example
2808: : foo1 ( n1 n2 -- n )
2809: [ ' + compile, ] ;
2810: see foo
2811: @end example
2812:
2813: This is non-standard, because @code{compile,} has no compilation
2814: semantics in the standard, but it works in good Forth systems. For the
2815: broken ones, use
2816:
2817: @example
2818: : [compile,] compile, ; immediate
2819:
2820: : foo1 ( n1 n2 -- n )
2821: [ ' + ] [compile,] ;
2822: see foo
2823: @end example
2824:
2825: @code{'} is a word with default compilation semantics; it parses the
2826: next word when its interpretation semantics are executed, not during
2827: compilation:
2828:
2829: @example
2830: : foo ( -- xt )
2831: ' ;
2832: see foo
2833: : bar ( ... "word" -- ... )
2834: ' execute ;
2835: see bar
1.60 anton 2836: 1 2 bar + .
1.48 anton 2837: @end example
2838:
2839: You often want to parse a word during compilation and compile its XT so
2840: it will be pushed on the stack at run-time. @code{[']} does this:
2841:
2842: @example
2843: : xt-+ ( -- xt )
2844: ['] + ;
2845: see xt-+
2846: 1 2 xt-+ execute .
2847: @end example
2848:
2849: Many programmers tend to see @code{'} and the word it parses as one
2850: unit, and expect it to behave like @code{[']} when compiled, and are
2851: confused by the actual behaviour. If you are, just remember that the
2852: Forth system just takes @code{'} as one unit and has no idea that it is
2853: a parsing word (attempts to convenience programmers in this issue have
2854: usually resulted in even worse pitfalls, see
2855: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz}).
2856:
2857: Note that the state of the interpreter does not come into play when
1.51 pazsan 2858: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2859: compile state, it still gives you the interpretation semantics. And
2860: whatever that state is, @code{execute} performs the semantics
1.51 pazsan 2861: represented by the XT (i.e., the interpretation semantics).
1.48 anton 2862:
2863:
2864: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2865: @section Exceptions
2866:
2867: @code{throw ( n -- )} causes an exception unless n is zero.
2868:
2869: @example
2870: 100 throw .s
2871: 0 throw .s
2872: @end example
2873:
2874: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2875: it catches exceptions and pushes the number of the exception on the
2876: stack (or 0, if the xt executed without exception). If there was an
2877: exception, the stacks have the same depth as when entering @code{catch}:
2878:
2879: @example
2880: .s
2881: 3 0 ' / catch .s
2882: 3 2 ' / catch .s
2883: @end example
2884:
2885: @assignment
2886: Try the same with @code{execute} instead of @code{catch}.
2887: @endassignment
2888:
2889: @code{Throw} always jumps to the dynamically next enclosing
2890: @code{catch}, even if it has to leave several call levels to achieve
2891: this:
2892:
2893: @example
2894: : foo 100 throw ;
2895: : foo1 foo ." after foo" ;
1.51 pazsan 2896: : bar ['] foo1 catch ;
1.60 anton 2897: bar .
1.48 anton 2898: @end example
2899:
2900: It is often important to restore a value upon leaving a definition, even
2901: if the definition is left through an exception. You can ensure this
2902: like this:
2903:
2904: @example
2905: : ...
2906: save-x
1.51 pazsan 2907: ['] word-changing-x catch ( ... n )
1.48 anton 2908: restore-x
2909: ( ... n ) throw ;
2910: @end example
2911:
1.55 anton 2912: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 2913: @code{try ... recover ... endtry}. If the code between @code{try} and
2914: @code{recover} has an exception, the stack depths are restored, the
2915: exception number is pushed on the stack, and the code between
2916: @code{recover} and @code{endtry} is performed. E.g., the definition for
2917: @code{catch} is
2918:
2919: @example
2920: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
2921: try
2922: execute 0
2923: recover
2924: nip
2925: endtry ;
2926: @end example
2927:
2928: The equivalent to the restoration code above is
2929:
2930: @example
2931: : ...
2932: save-x
2933: try
2934: word-changing-x
2935: end-try
2936: restore-x
2937: throw ;
2938: @end example
2939:
2940: As you can see, the @code{recover} part is optional.
2941:
2942:
2943: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2944: @section Defining Words
2945:
2946: @code{:}, @code{create}, and @code{variable} are definition words: They
2947: define other words. @code{Constant} is another definition word:
2948:
2949: @example
2950: 5 constant foo
2951: foo .
2952: @end example
2953:
2954: You can also use the prefixes @code{2} (double-cell) and @code{f}
2955: (floating point) with @code{variable} and @code{constant}.
2956:
2957: You can also define your own defining words. E.g.:
2958:
2959: @example
2960: : variable ( "name" -- )
2961: create 0 , ;
2962: @end example
2963:
2964: You can also define defining words that create words that do something
2965: other than just producing their address:
2966:
2967: @example
2968: : constant ( n "name" -- )
2969: create ,
2970: does> ( -- n )
1.50 anton 2971: ( addr ) @@ ;
1.48 anton 2972:
2973: 5 constant foo
2974: foo .
2975: @end example
2976:
2977: The definition of @code{constant} above ends at the @code{does>}; i.e.,
2978: @code{does>} replaces @code{;}, but it also does something else: It
2979: changes the last defined word such that it pushes the address of the
2980: body of the word and then performs the code after the @code{does>}
2981: whenever it is called.
2982:
2983: In the example above, @code{constant} uses @code{,} to store 5 into the
2984: body of @code{foo}. When @code{foo} executes, it pushes the address of
2985: the body onto the stack, then (in the code after the @code{does>})
2986: fetches the 5 from there.
2987:
2988: The stack comment near the @code{does>} reflects the stack effect of the
2989: defined word, not the stack effect of the code after the @code{does>}
2990: (the difference is that the code expects the address of the body that
2991: the stack comment does not show).
2992:
2993: You can use these definition words to do factoring in cases that involve
2994: (other) definition words. E.g., a field offset is always added to an
2995: address. Instead of defining
2996:
2997: @example
2998: 2 cells constant offset-field1
2999: @end example
3000:
3001: and using this like
3002:
3003: @example
3004: ( addr ) offset-field1 +
3005: @end example
3006:
3007: you can define a definition word
3008:
3009: @example
3010: : simple-field ( n "name" -- )
3011: create ,
3012: does> ( n1 -- n1+n )
1.50 anton 3013: ( addr ) @@ + ;
1.48 anton 3014: @end example
1.21 crook 3015:
1.48 anton 3016: Definition and use of field offsets now look like this:
1.21 crook 3017:
1.48 anton 3018: @example
3019: 2 cells simple-field field1
1.60 anton 3020: create mystruct 4 cells allot
3021: mystruct .s field1 .s drop
1.48 anton 3022: @end example
1.21 crook 3023:
1.48 anton 3024: If you want to do something with the word without performing the code
3025: after the @code{does>}, you can access the body of a @code{create}d word
3026: with @code{>body ( xt -- addr )}:
1.21 crook 3027:
1.48 anton 3028: @example
3029: : value ( n "name" -- )
3030: create ,
3031: does> ( -- n1 )
1.50 anton 3032: @@ ;
1.48 anton 3033: : to ( n "name" -- )
3034: ' >body ! ;
1.21 crook 3035:
1.48 anton 3036: 5 value foo
3037: foo .
3038: 7 to foo
3039: foo .
3040: @end example
1.21 crook 3041:
1.48 anton 3042: @assignment
3043: Define @code{defer ( "name" -- )}, which creates a word that stores an
3044: XT (at the start the XT of @code{abort}), and upon execution
3045: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3046: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3047: recursion is one application of @code{defer}.
3048: @endassignment
1.29 crook 3049:
1.48 anton 3050: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3051: @section Arrays and Records
1.29 crook 3052:
1.48 anton 3053: Forth has no standard words for defining data structures such as arrays
3054: and records (structs in C terminology), but you can build them yourself
3055: based on address arithmetic. You can also define words for defining
3056: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3057:
1.48 anton 3058: One of the first projects a Forth newcomer sets out upon when learning
3059: about defining words is an array defining word (possibly for
3060: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3061: learn something from it. However, don't be disappointed when you later
3062: learn that you have little use for these words (inappropriate use would
3063: be even worse). I have not yet found a set of useful array words yet;
3064: the needs are just too diverse, and named, global arrays (the result of
3065: naive use of defining words) are often not flexible enough (e.g.,
3066: consider how to pass them as parameters).
1.29 crook 3067:
1.48 anton 3068: On the other hand, there is a useful set of record words, and it has
3069: been defined in @file{compat/struct.fs}; these words are predefined in
3070: Gforth. They are explained in depth elsewhere in this manual (see
3071: @pxref{Structures}). The @code{simple-field} example above is
3072: simplified variant of fields in this package.
1.21 crook 3073:
3074:
1.48 anton 3075: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3076: @section @code{POSTPONE}
1.21 crook 3077:
1.48 anton 3078: You can compile the compilation semantics (instead of compiling the
3079: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3080:
1.48 anton 3081: @example
3082: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3083: POSTPONE + ; immediate
1.48 anton 3084: : foo ( n1 n2 -- n )
3085: MY-+ ;
3086: 1 2 foo .
3087: see foo
3088: @end example
1.21 crook 3089:
1.48 anton 3090: During the definition of @code{foo} the text interpreter performs the
3091: compilation semantics of @code{MY-+}, which performs the compilation
3092: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3093:
3094: This example also displays separate stack comments for the compilation
3095: semantics and for the stack effect of the compiled code. For words with
3096: default compilation semantics these stack effects are usually not
3097: displayed; the stack effect of the compilation semantics is always
3098: @code{( -- )} for these words, the stack effect for the compiled code is
3099: the stack effect of the interpretation semantics.
3100:
3101: Note that the state of the interpreter does not come into play when
3102: performing the compilation semantics in this way. You can also perform
3103: it interpretively, e.g.:
3104:
3105: @example
3106: : foo2 ( n1 n2 -- n )
3107: [ MY-+ ] ;
3108: 1 2 foo .
3109: see foo
3110: @end example
1.21 crook 3111:
1.48 anton 3112: However, there are some broken Forth systems where this does not always
1.62 crook 3113: work, and therefore this practice was been declared non-standard in
1.48 anton 3114: 1999.
3115: @c !! repair.fs
3116:
3117: Here is another example for using @code{POSTPONE}:
1.44 crook 3118:
1.48 anton 3119: @example
3120: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3121: POSTPONE negate POSTPONE + ; immediate compile-only
3122: : bar ( n1 n2 -- n )
3123: MY-- ;
3124: 2 1 bar .
3125: see bar
3126: @end example
1.21 crook 3127:
1.48 anton 3128: You can define @code{ENDIF} in this way:
1.21 crook 3129:
1.48 anton 3130: @example
3131: : ENDIF ( Compilation: orig -- )
3132: POSTPONE then ; immediate
3133: @end example
1.21 crook 3134:
1.48 anton 3135: @assignment
3136: Write @code{MY-2DUP} that has compilation semantics equivalent to
3137: @code{2dup}, but compiles @code{over over}.
3138: @endassignment
1.29 crook 3139:
1.48 anton 3140: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3141: @section @code{Literal}
1.29 crook 3142:
1.48 anton 3143: You cannot @code{POSTPONE} numbers:
1.21 crook 3144:
1.48 anton 3145: @example
3146: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3147: @end example
3148:
1.48 anton 3149: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3150:
1.48 anton 3151: @example
3152: : [FOO] ( compilation: --; run-time: -- n )
3153: 500 POSTPONE literal ; immediate
1.29 crook 3154:
1.60 anton 3155: : flip [FOO] ;
1.48 anton 3156: flip .
3157: see flip
3158: @end example
1.29 crook 3159:
1.48 anton 3160: @code{LITERAL} consumes a number at compile-time (when it's compilation
3161: semantics are executed) and pushes it at run-time (when the code it
3162: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3163: number computed at compile time into the current word:
1.29 crook 3164:
1.48 anton 3165: @example
3166: : bar ( -- n )
3167: [ 2 2 + ] literal ;
3168: see bar
3169: @end example
1.29 crook 3170:
1.48 anton 3171: @assignment
3172: Write @code{]L} which allows writing the example above as @code{: bar (
3173: -- n ) [ 2 2 + ]L ;}
3174: @endassignment
3175:
3176:
3177: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3178: @section Advanced macros
3179:
3180: Reconsider @code{map-array} from @ref{Execution Tokens
3181: Tutorial,, Execution Tokens}. It frequently performs @code{execute}, a
3182: relatively expensive operation in some implementations. You can use
3183: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3184: and produce a word that contains the word to be performed directly:
3185:
3186: @c use ]] ... [[
3187: @example
3188: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3189: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3190: \ array beginning at addr and containing u elements
3191: @{ xt @}
3192: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3193: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3194: 1 cells POSTPONE literal POSTPONE +loop ;
3195:
3196: : sum-array ( addr u -- n )
3197: 0 rot rot [ ' + compile-map-array ] ;
3198: see sum-array
3199: a 5 sum-array .
3200: @end example
3201:
3202: You can use the full power of Forth for generating the code; here's an
3203: example where the code is generated in a loop:
3204:
3205: @example
3206: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3207: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3208: POSTPONE tuck POSTPONE @@
1.48 anton 3209: POSTPONE literal POSTPONE * POSTPONE +
3210: POSTPONE swap POSTPONE cell+ ;
3211:
3212: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3213: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3214: 0 postpone literal postpone swap
3215: [ ' compile-vmul-step compile-map-array ]
3216: postpone drop ;
3217: see compile-vmul
3218:
3219: : a-vmul ( addr -- n )
1.51 pazsan 3220: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3221: [ a 5 compile-vmul ] ;
3222: see a-vmul
3223: a a-vmul .
3224: @end example
3225:
3226: This example uses @code{compile-map-array} to show off, but you could
3227: also use @code{map-array} instead (try it now).
3228:
3229: You can use this technique for efficient multiplication of large
3230: matrices. In matrix multiplication, you multiply every line of one
3231: matrix with every column of the other matrix. You can generate the code
3232: for one line once, and use it for every column. The only downside of
3233: this technique is that it is cumbersome to recover the memory consumed
3234: by the generated code when you are done (and in more complicated cases
3235: it is not possible portably).
3236:
3237: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3238: @section Compilation Tokens
3239:
3240: This section is Gforth-specific. You can skip it.
3241:
3242: @code{' word compile,} compiles the interpretation semantics. For words
3243: with default compilation semantics this is the same as performing the
3244: compilation semantics. To represent the compilation semantics of other
3245: words (e.g., words like @code{if} that have no interpretation
3246: semantics), Gforth has the concept of a compilation token (CT,
3247: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3248: You can perform the compilation semantics represented by a CT with
3249: @code{execute}:
1.29 crook 3250:
1.48 anton 3251: @example
3252: : foo2 ( n1 n2 -- n )
3253: [ comp' + execute ] ;
3254: see foo
3255: @end example
1.29 crook 3256:
1.48 anton 3257: You can compile the compilation semantics represented by a CT with
3258: @code{postpone,}:
1.30 anton 3259:
1.48 anton 3260: @example
3261: : foo3 ( -- )
3262: [ comp' + postpone, ] ;
3263: see foo3
3264: @end example
1.30 anton 3265:
1.51 pazsan 3266: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3267: @code{comp'} is particularly useful for words that have no
3268: interpretation semantics:
1.29 crook 3269:
1.30 anton 3270: @example
1.48 anton 3271: ' if
1.60 anton 3272: comp' if .s 2drop
1.30 anton 3273: @end example
3274:
1.29 crook 3275:
1.48 anton 3276: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3277: @section Wordlists and Search Order
3278:
3279: The dictionary is not just a memory area that allows you to allocate
3280: memory with @code{allot}, it also contains the Forth words, arranged in
3281: several wordlists. When searching for a word in a wordlist,
3282: conceptually you start searching at the youngest and proceed towards
3283: older words (in reality most systems nowadays use hash-tables); i.e., if
3284: you define a word with the same name as an older word, the new word
3285: shadows the older word.
3286:
3287: Which wordlists are searched in which order is determined by the search
3288: order. You can display the search order with @code{order}. It displays
3289: first the search order, starting with the wordlist searched first, then
3290: it displays the wordlist that will contain newly defined words.
1.21 crook 3291:
1.48 anton 3292: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3293:
1.48 anton 3294: @example
3295: wordlist constant mywords
3296: @end example
1.21 crook 3297:
1.48 anton 3298: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3299: defined words (the @emph{current} wordlist):
1.21 crook 3300:
1.48 anton 3301: @example
3302: mywords set-current
3303: order
3304: @end example
1.26 crook 3305:
1.48 anton 3306: Gforth does not display a name for the wordlist in @code{mywords}
3307: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3308:
1.48 anton 3309: You can get the current wordlist with @code{get-current ( -- wid)}. If
3310: you want to put something into a specific wordlist without overall
3311: effect on the current wordlist, this typically looks like this:
1.21 crook 3312:
1.48 anton 3313: @example
3314: get-current mywords set-current ( wid )
3315: create someword
3316: ( wid ) set-current
3317: @end example
1.21 crook 3318:
1.48 anton 3319: You can write the search order with @code{set-order ( wid1 .. widn n --
3320: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3321: searched wordlist is topmost.
1.21 crook 3322:
1.48 anton 3323: @example
3324: get-order mywords swap 1+ set-order
3325: order
3326: @end example
1.21 crook 3327:
1.48 anton 3328: Yes, the order of wordlists in the output of @code{order} is reversed
3329: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3330:
1.48 anton 3331: @assignment
3332: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3333: wordlist to the search order. Define @code{previous ( -- )}, which
3334: removes the first searched wordlist from the search order. Experiment
3335: with boundary conditions (you will see some crashes or situations that
3336: are hard or impossible to leave).
3337: @endassignment
1.21 crook 3338:
1.48 anton 3339: The search order is a powerful foundation for providing features similar
3340: to Modula-2 modules and C++ namespaces. However, trying to modularize
3341: programs in this way has disadvantages for debugging and reuse/factoring
3342: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3343: though). These disadvantages are not so clear in other
1.48 anton 3344: languages/programming environments, because these langauges are not so
3345: strong in debugging and reuse.
1.21 crook 3346:
3347:
1.29 crook 3348: @c ******************************************************************
1.48 anton 3349: @node Introduction, Words, Tutorial, Top
1.29 crook 3350: @comment node-name, next, previous, up
3351: @chapter An Introduction to ANS Forth
3352: @cindex Forth - an introduction
1.21 crook 3353:
1.29 crook 3354: The primary purpose of this manual is to document Gforth. However, since
3355: Forth is not a widely-known language and there is a lack of up-to-date
3356: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3357: material. For other sources of Forth-related
3358: information, see @ref{Forth-related information}.
1.21 crook 3359:
1.29 crook 3360: The examples in this section should work on any ANS Forth; the
3361: output shown was produced using Gforth. Each example attempts to
3362: reproduce the exact output that Gforth produces. If you try out the
3363: examples (and you should), what you should type is shown @kbd{like this}
3364: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3365: that, where the example shows @key{RET} it means that you should
1.29 crook 3366: press the ``carriage return'' key. Unfortunately, some output formats for
3367: this manual cannot show the difference between @kbd{this} and
3368: @code{this} which will make trying out the examples harder (but not
3369: impossible).
1.21 crook 3370:
1.29 crook 3371: Forth is an unusual language. It provides an interactive development
3372: environment which includes both an interpreter and compiler. Forth
3373: programming style encourages you to break a problem down into many
3374: @cindex factoring
3375: small fragments (@dfn{factoring}), and then to develop and test each
3376: fragment interactively. Forth advocates assert that breaking the
3377: edit-compile-test cycle used by conventional programming languages can
3378: lead to great productivity improvements.
1.21 crook 3379:
1.29 crook 3380: @menu
3381: * Introducing the Text Interpreter::
3382: * Stacks and Postfix notation::
3383: * Your first definition::
3384: * How does that work?::
3385: * Forth is written in Forth::
3386: * Review - elements of a Forth system::
3387: * Where to go next::
3388: * Exercises::
3389: @end menu
1.21 crook 3390:
1.29 crook 3391: @comment ----------------------------------------------
3392: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3393: @section Introducing the Text Interpreter
3394: @cindex text interpreter
3395: @cindex outer interpreter
1.21 crook 3396:
1.30 anton 3397: @c IMO this is too detailed and the pace is too slow for
3398: @c an introduction. If you know German, take a look at
3399: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3400: @c to see how I do it - anton
3401:
1.44 crook 3402: @c nac-> Where I have accepted your comments 100% and modified the text
3403: @c accordingly, I have deleted your comments. Elsewhere I have added a
3404: @c response like this to attempt to rationalise what I have done. Of
3405: @c course, this is a very clumsy mechanism for something that would be
3406: @c done far more efficiently over a beer. Please delete any dialogue
3407: @c you consider closed.
3408:
1.29 crook 3409: When you invoke the Forth image, you will see a startup banner printed
3410: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3411: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3412: its command line interpreter, which is called the @dfn{Text Interpreter}
3413: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3414: about the text interpreter as you read through this chapter, for more
3415: detail @pxref{The Text Interpreter}).
1.21 crook 3416:
1.29 crook 3417: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3418: input. Type a number and press the @key{RET} key:
1.21 crook 3419:
1.26 crook 3420: @example
1.30 anton 3421: @kbd{45@key{RET}} ok
1.26 crook 3422: @end example
1.21 crook 3423:
1.29 crook 3424: Rather than give you a prompt to invite you to input something, the text
3425: interpreter prints a status message @i{after} it has processed a line
3426: of input. The status message in this case (``@code{ ok}'' followed by
3427: carriage-return) indicates that the text interpreter was able to process
3428: all of your input successfully. Now type something illegal:
3429:
3430: @example
1.30 anton 3431: @kbd{qwer341@key{RET}}
1.29 crook 3432: :1: Undefined word
3433: qwer341
3434: ^^^^^^^
3435: $400D2BA8 Bounce
3436: $400DBDA8 no.extensions
3437: @end example
1.23 crook 3438:
1.29 crook 3439: The exact text, other than the ``Undefined word'' may differ slightly on
3440: your system, but the effect is the same; when the text interpreter
3441: detects an error, it discards any remaining text on a line, resets
1.49 anton 3442: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
3443: messages}.
1.23 crook 3444:
1.29 crook 3445: The text interpreter waits for you to press carriage-return, and then
3446: processes your input line. Starting at the beginning of the line, it
3447: breaks the line into groups of characters separated by spaces. For each
3448: group of characters in turn, it makes two attempts to do something:
1.23 crook 3449:
1.29 crook 3450: @itemize @bullet
3451: @item
1.44 crook 3452: @cindex name dictionary
1.29 crook 3453: It tries to treat it as a command. It does this by searching a @dfn{name
3454: dictionary}. If the group of characters matches an entry in the name
3455: dictionary, the name dictionary provides the text interpreter with
3456: information that allows the text interpreter perform some actions. In
3457: Forth jargon, we say that the group
3458: @cindex word
3459: @cindex definition
3460: @cindex execution token
3461: @cindex xt
3462: of characters names a @dfn{word}, that the dictionary search returns an
3463: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3464: word, and that the text interpreter executes the xt. Often, the terms
3465: @dfn{word} and @dfn{definition} are used interchangeably.
3466: @item
3467: If the text interpreter fails to find a match in the name dictionary, it
3468: tries to treat the group of characters as a number in the current number
3469: base (when you start up Forth, the current number base is base 10). If
3470: the group of characters legitimately represents a number, the text
3471: interpreter pushes the number onto a stack (we'll learn more about that
3472: in the next section).
3473: @end itemize
1.23 crook 3474:
1.29 crook 3475: If the text interpreter is unable to do either of these things with any
3476: group of characters, it discards the group of characters and the rest of
3477: the line, then prints an error message. If the text interpreter reaches
3478: the end of the line without error, it prints the status message ``@code{ ok}''
3479: followed by carriage-return.
1.21 crook 3480:
1.29 crook 3481: This is the simplest command we can give to the text interpreter:
1.23 crook 3482:
3483: @example
1.30 anton 3484: @key{RET} ok
1.23 crook 3485: @end example
1.21 crook 3486:
1.29 crook 3487: The text interpreter did everything we asked it to do (nothing) without
3488: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3489: command:
1.21 crook 3490:
1.23 crook 3491: @example
1.30 anton 3492: @kbd{12 dup fred dup@key{RET}}
1.29 crook 3493: :1: Undefined word
3494: 12 dup fred dup
3495: ^^^^
3496: $400D2BA8 Bounce
3497: $400DBDA8 no.extensions
1.23 crook 3498: @end example
1.21 crook 3499:
1.29 crook 3500: When you press the carriage-return key, the text interpreter starts to
3501: work its way along the line:
1.21 crook 3502:
1.29 crook 3503: @itemize @bullet
3504: @item
3505: When it gets to the space after the @code{2}, it takes the group of
3506: characters @code{12} and looks them up in the name
3507: dictionary@footnote{We can't tell if it found them or not, but assume
3508: for now that it did not}. There is no match for this group of characters
3509: in the name dictionary, so it tries to treat them as a number. It is
3510: able to do this successfully, so it puts the number, 12, ``on the stack''
3511: (whatever that means).
3512: @item
3513: The text interpreter resumes scanning the line and gets the next group
3514: of characters, @code{dup}. It looks it up in the name dictionary and
3515: (you'll have to take my word for this) finds it, and executes the word
3516: @code{dup} (whatever that means).
3517: @item
3518: Once again, the text interpreter resumes scanning the line and gets the
3519: group of characters @code{fred}. It looks them up in the name
3520: dictionary, but can't find them. It tries to treat them as a number, but
3521: they don't represent any legal number.
3522: @end itemize
1.21 crook 3523:
1.29 crook 3524: At this point, the text interpreter gives up and prints an error
3525: message. The error message shows exactly how far the text interpreter
3526: got in processing the line. In particular, it shows that the text
3527: interpreter made no attempt to do anything with the final character
3528: group, @code{dup}, even though we have good reason to believe that the
3529: text interpreter would have no problem looking that word up and
3530: executing it a second time.
1.21 crook 3531:
3532:
1.29 crook 3533: @comment ----------------------------------------------
3534: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3535: @section Stacks, postfix notation and parameter passing
3536: @cindex text interpreter
3537: @cindex outer interpreter
1.21 crook 3538:
1.29 crook 3539: In procedural programming languages (like C and Pascal), the
3540: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3541: functions or procedures are called with @dfn{explicit parameters}. For
3542: example, in C we might write:
1.21 crook 3543:
1.23 crook 3544: @example
1.29 crook 3545: total = total + new_volume(length,height,depth);
1.23 crook 3546: @end example
1.21 crook 3547:
1.23 crook 3548: @noindent
1.29 crook 3549: where new_volume is a function-call to another piece of code, and total,
3550: length, height and depth are all variables. length, height and depth are
3551: parameters to the function-call.
1.21 crook 3552:
1.29 crook 3553: In Forth, the equivalent of the function or procedure is the
3554: @dfn{definition} and parameters are implicitly passed between
3555: definitions using a shared stack that is visible to the
3556: programmer. Although Forth does support variables, the existence of the
3557: stack means that they are used far less often than in most other
3558: programming languages. When the text interpreter encounters a number, it
3559: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3560: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3561: used for any operation is implied unambiguously by the operation being
3562: performed. The stack used for all integer operations is called the @dfn{data
3563: stack} and, since this is the stack used most commonly, references to
3564: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3565:
1.29 crook 3566: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3567:
1.23 crook 3568: @example
1.30 anton 3569: @kbd{1 2 3@key{RET}} ok
1.23 crook 3570: @end example
1.21 crook 3571:
1.29 crook 3572: Then this instructs the text interpreter to placed three numbers on the
3573: (data) stack. An analogy for the behaviour of the stack is to take a
3574: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3575: the table. The 3 was the last card onto the pile (``last-in'') and if
3576: you take a card off the pile then, unless you're prepared to fiddle a
3577: bit, the card that you take off will be the 3 (``first-out''). The
3578: number that will be first-out of the stack is called the @dfn{top of
3579: stack}, which
3580: @cindex TOS definition
3581: is often abbreviated to @dfn{TOS}.
1.21 crook 3582:
1.29 crook 3583: To understand how parameters are passed in Forth, consider the
3584: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3585: be surprised to learn that this definition performs addition. More
3586: precisely, it adds two number together and produces a result. Where does
3587: it get the two numbers from? It takes the top two numbers off the
3588: stack. Where does it place the result? On the stack. You can act-out the
3589: behaviour of @code{+} with your playing cards like this:
1.21 crook 3590:
3591: @itemize @bullet
3592: @item
1.29 crook 3593: Pick up two cards from the stack on the table
1.21 crook 3594: @item
1.29 crook 3595: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3596: numbers''
1.21 crook 3597: @item
1.29 crook 3598: Decide that the answer is 5
1.21 crook 3599: @item
1.29 crook 3600: Shuffle the two cards back into the pack and find a 5
1.21 crook 3601: @item
1.29 crook 3602: Put a 5 on the remaining ace that's on the table.
1.21 crook 3603: @end itemize
3604:
1.29 crook 3605: If you don't have a pack of cards handy but you do have Forth running,
3606: you can use the definition @code{.s} to show the current state of the stack,
3607: without affecting the stack. Type:
1.21 crook 3608:
3609: @example
1.30 anton 3610: @kbd{clearstack 1 2 3@key{RET}} ok
3611: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3612: @end example
3613:
1.29 crook 3614: The text interpreter looks up the word @code{clearstack} and executes
3615: it; it tidies up the stack and removes any entries that may have been
3616: left on it by earlier examples. The text interpreter pushes each of the
3617: three numbers in turn onto the stack. Finally, the text interpreter
3618: looks up the word @code{.s} and executes it. The effect of executing
3619: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3620: followed by a list of all the items on the stack; the item on the far
3621: right-hand side is the TOS.
1.21 crook 3622:
1.29 crook 3623: You can now type:
1.21 crook 3624:
1.29 crook 3625: @example
1.30 anton 3626: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3627: @end example
1.21 crook 3628:
1.29 crook 3629: @noindent
3630: which is correct; there are now 2 items on the stack and the result of
3631: the addition is 5.
1.23 crook 3632:
1.29 crook 3633: If you're playing with cards, try doing a second addition: pick up the
3634: two cards, work out that their sum is 6, shuffle them into the pack,
3635: look for a 6 and place that on the table. You now have just one item on
3636: the stack. What happens if you try to do a third addition? Pick up the
3637: first card, pick up the second card -- ah! There is no second card. This
3638: is called a @dfn{stack underflow} and consitutes an error. If you try to
3639: do the same thing with Forth it will report an error (probably a Stack
3640: Underflow or an Invalid Memory Address error).
1.23 crook 3641:
1.29 crook 3642: The opposite situation to a stack underflow is a @dfn{stack overflow},
3643: which simply accepts that there is a finite amount of storage space
3644: reserved for the stack. To stretch the playing card analogy, if you had
3645: enough packs of cards and you piled the cards up on the table, you would
3646: eventually be unable to add another card; you'd hit the ceiling. Gforth
3647: allows you to set the maximum size of the stacks. In general, the only
3648: time that you will get a stack overflow is because a definition has a
3649: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3650:
1.29 crook 3651: There's one final use for the playing card analogy. If you model your
3652: stack using a pack of playing cards, the maximum number of items on
3653: your stack will be 52 (I assume you didn't use the Joker). The maximum
3654: @i{value} of any item on the stack is 13 (the King). In fact, the only
3655: possible numbers are positive integer numbers 1 through 13; you can't
3656: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3657: think about some of the cards, you can accommodate different
3658: numbers. For example, you could think of the Jack as representing 0,
3659: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3660: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3661: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3662:
1.29 crook 3663: In that analogy, the limit was the amount of information that a single
3664: stack entry could hold, and Forth has a similar limit. In Forth, the
3665: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3666: implementation dependent and affects the maximum value that a stack
3667: entry can hold. A Standard Forth provides a cell size of at least
3668: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3669:
1.29 crook 3670: Forth does not do any type checking for you, so you are free to
3671: manipulate and combine stack items in any way you wish. A convenient way
3672: of treating stack items is as 2's complement signed integers, and that
3673: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3674:
1.29 crook 3675: @example
1.30 anton 3676: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3677: @end example
1.21 crook 3678:
1.29 crook 3679: If you use numbers and definitions like @code{+} in order to turn Forth
3680: into a great big pocket calculator, you will realise that it's rather
3681: different from a normal calculator. Rather than typing 2 + 3 = you had
3682: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3683: result). The terminology used to describe this difference is to say that
3684: your calculator uses @dfn{Infix Notation} (parameters and operators are
3685: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3686: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3687:
1.29 crook 3688: Whilst postfix notation might look confusing to begin with, it has
3689: several important advantages:
1.21 crook 3690:
1.23 crook 3691: @itemize @bullet
3692: @item
1.29 crook 3693: it is unambiguous
1.23 crook 3694: @item
1.29 crook 3695: it is more concise
1.23 crook 3696: @item
1.29 crook 3697: it fits naturally with a stack-based system
1.23 crook 3698: @end itemize
1.21 crook 3699:
1.29 crook 3700: To examine these claims in more detail, consider these sums:
1.21 crook 3701:
1.29 crook 3702: @example
3703: 6 + 5 * 4 =
3704: 4 * 5 + 6 =
3705: @end example
1.21 crook 3706:
1.29 crook 3707: If you're just learning maths or your maths is very rusty, you will
3708: probably come up with the answer 44 for the first and 26 for the
3709: second. If you are a bit of a whizz at maths you will remember the
3710: @i{convention} that multiplication takes precendence over addition, and
3711: you'd come up with the answer 26 both times. To explain the answer 26
3712: to someone who got the answer 44, you'd probably rewrite the first sum
3713: like this:
1.21 crook 3714:
1.29 crook 3715: @example
3716: 6 + (5 * 4) =
3717: @end example
1.21 crook 3718:
1.29 crook 3719: If what you really wanted was to perform the addition before the
3720: multiplication, you would have to use parentheses to force it.
1.21 crook 3721:
1.29 crook 3722: If you did the first two sums on a pocket calculator you would probably
3723: get the right answers, unless you were very cautious and entered them using
3724: these keystroke sequences:
1.21 crook 3725:
1.29 crook 3726: 6 + 5 = * 4 =
3727: 4 * 5 = + 6 =
1.21 crook 3728:
1.29 crook 3729: Postfix notation is unambiguous because the order that the operators
3730: are applied is always explicit; that also means that parentheses are
3731: never required. The operators are @i{active} (the act of quoting the
3732: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3733:
1.29 crook 3734: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3735: equivalent ways:
1.26 crook 3736:
3737: @example
1.29 crook 3738: 6 5 4 * + or:
3739: 5 4 * 6 +
1.26 crook 3740: @end example
1.23 crook 3741:
1.29 crook 3742: An important thing that you should notice about this notation is that
3743: the @i{order} of the numbers does not change; if you want to subtract
3744: 2 from 10 you type @code{10 2 -}.
1.1 anton 3745:
1.29 crook 3746: The reason that Forth uses postfix notation is very simple to explain: it
3747: makes the implementation extremely simple, and it follows naturally from
3748: using the stack as a mechanism for passing parameters. Another way of
3749: thinking about this is to realise that all Forth definitions are
3750: @i{active}; they execute as they are encountered by the text
3751: interpreter. The result of this is that the syntax of Forth is trivially
3752: simple.
1.1 anton 3753:
3754:
3755:
1.29 crook 3756: @comment ----------------------------------------------
3757: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3758: @section Your first Forth definition
3759: @cindex first definition
1.1 anton 3760:
1.29 crook 3761: Until now, the examples we've seen have been trivial; we've just been
3762: using Forth as a bigger-than-pocket calculator. Also, each calculation
3763: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3764: again@footnote{That's not quite true. If you press the up-arrow key on
3765: your keyboard you should be able to scroll back to any earlier command,
3766: edit it and re-enter it.} In this section we'll see how to add new
3767: words to Forth's vocabulary.
1.1 anton 3768:
1.29 crook 3769: The easiest way to create a new word is to use a @dfn{colon
3770: definition}. We'll define a few and try them out before worrying too
3771: much about how they work. Try typing in these examples; be careful to
3772: copy the spaces accurately:
1.1 anton 3773:
1.29 crook 3774: @example
3775: : add-two 2 + . ;
3776: : greet ." Hello and welcome" ;
3777: : demo 5 add-two ;
3778: @end example
1.1 anton 3779:
1.29 crook 3780: @noindent
3781: Now try them out:
1.1 anton 3782:
1.29 crook 3783: @example
1.30 anton 3784: @kbd{greet@key{RET}} Hello and welcome ok
3785: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3786: @kbd{4 add-two@key{RET}} 6 ok
3787: @kbd{demo@key{RET}} 7 ok
3788: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3789: @end example
1.1 anton 3790:
1.29 crook 3791: The first new thing that we've introduced here is the pair of words
3792: @code{:} and @code{;}. These are used to start and terminate a new
3793: definition, respectively. The first word after the @code{:} is the name
3794: for the new definition.
1.1 anton 3795:
1.29 crook 3796: As you can see from the examples, a definition is built up of words that
3797: have already been defined; Forth makes no distinction between
3798: definitions that existed when you started the system up, and those that
3799: you define yourself.
1.1 anton 3800:
1.29 crook 3801: The examples also introduce the words @code{.} (dot), @code{."}
3802: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3803: the stack and displays it. It's like @code{.s} except that it only
3804: displays the top item of the stack and it is destructive; after it has
3805: executed, the number is no longer on the stack. There is always one
3806: space printed after the number, and no spaces before it. Dot-quote
3807: defines a string (a sequence of characters) that will be printed when
3808: the word is executed. The string can contain any printable characters
3809: except @code{"}. A @code{"} has a special function; it is not a Forth
3810: word but it acts as a delimiter (the way that delimiters work is
3811: described in the next section). Finally, @code{dup} duplicates the value
3812: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3813:
1.29 crook 3814: We already know that the text interpreter searches through the
3815: dictionary to locate names. If you've followed the examples earlier, you
3816: will already have a definition called @code{add-two}. Lets try modifying
3817: it by typing in a new definition:
1.1 anton 3818:
1.29 crook 3819: @example
1.30 anton 3820: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3821: @end example
1.5 anton 3822:
1.29 crook 3823: Forth recognised that we were defining a word that already exists, and
3824: printed a message to warn us of that fact. Let's try out the new
3825: definition:
1.5 anton 3826:
1.29 crook 3827: @example
1.30 anton 3828: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3829: @end example
1.1 anton 3830:
1.29 crook 3831: @noindent
3832: All that we've actually done here, though, is to create a new
3833: definition, with a particular name. The fact that there was already a
3834: definition with the same name did not make any difference to the way
3835: that the new definition was created (except that Forth printed a warning
3836: message). The old definition of add-two still exists (try @code{demo}
3837: again to see that this is true). Any new definition will use the new
3838: definition of @code{add-two}, but old definitions continue to use the
3839: version that already existed at the time that they were @code{compiled}.
1.1 anton 3840:
1.29 crook 3841: Before you go on to the next section, try defining and redefining some
3842: words of your own.
1.1 anton 3843:
1.29 crook 3844: @comment ----------------------------------------------
3845: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3846: @section How does that work?
3847: @cindex parsing words
1.1 anton 3848:
1.30 anton 3849: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3850:
3851: @c Is it a good idea to talk about the interpretation semantics of a
3852: @c number? We don't have an xt to go along with it. - anton
3853:
3854: @c Now that I have eliminated execution semantics, I wonder if it would not
3855: @c be better to keep them (or add run-time semantics), to make it easier to
3856: @c explain what compilation semantics usually does. - anton
3857:
1.44 crook 3858: @c nac-> I removed the term ``default compilation sematics'' from the
3859: @c introductory chapter. Removing ``execution semantics'' was making
3860: @c everything simpler to explain, then I think the use of this term made
3861: @c everything more complex again. I replaced it with ``default
3862: @c semantics'' (which is used elsewhere in the manual) by which I mean
3863: @c ``a definition that has neither the immediate nor the compile-only
3864: @c flag set''. I reworded big chunks of the ``how does that work''
3865: @c section (and, unusually for me, I think I even made it shorter!). See
3866: @c what you think -- I know I have not addressed your primary concern
3867: @c that it is too heavy-going for an introduction. From what I understood
3868: @c of your course notes it looks as though they might be a good framework.
3869: @c Things that I've tried to capture here are some things that came as a
3870: @c great revelation here when I first understood them. Also, I like the
3871: @c fact that a very simple code example shows up almost all of the issues
3872: @c that you need to understand to see how Forth works. That's unique and
3873: @c worthwhile to emphasise.
3874:
1.29 crook 3875: Now we're going to take another look at the definition of @code{add-two}
3876: from the previous section. From our knowledge of the way that the text
3877: interpreter works, we would have expected this result when we tried to
3878: define @code{add-two}:
1.21 crook 3879:
1.29 crook 3880: @example
1.44 crook 3881: @kbd{: add-two 2 + . ;@key{RET}}
1.29 crook 3882: ^^^^^^^
3883: Error: Undefined word
3884: @end example
1.28 crook 3885:
1.29 crook 3886: The reason that this didn't happen is bound up in the way that @code{:}
3887: works. The word @code{:} does two special things. The first special
3888: thing that it does prevents the text interpreter from ever seeing the
3889: characters @code{add-two}. The text interpreter uses a variable called
3890: @cindex modifying >IN
1.44 crook 3891: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3892: input line. When it encounters the word @code{:} it behaves in exactly
3893: the same way as it does for any other word; it looks it up in the name
3894: dictionary, finds its xt and executes it. When @code{:} executes, it
3895: looks at the input buffer, finds the word @code{add-two} and advances the
3896: value of @code{>IN} to point past it. It then does some other stuff
3897: associated with creating the new definition (including creating an entry
3898: for @code{add-two} in the name dictionary). When the execution of @code{:}
3899: completes, control returns to the text interpreter, which is oblivious
3900: to the fact that it has been tricked into ignoring part of the input
3901: line.
1.21 crook 3902:
1.29 crook 3903: @cindex parsing words
3904: Words like @code{:} -- words that advance the value of @code{>IN} and so
3905: prevent the text interpreter from acting on the whole of the input line
3906: -- are called @dfn{parsing words}.
1.21 crook 3907:
1.29 crook 3908: @cindex @code{state} - effect on the text interpreter
3909: @cindex text interpreter - effect of state
3910: The second special thing that @code{:} does is change the value of a
3911: variable called @code{state}, which affects the way that the text
3912: interpreter behaves. When Gforth starts up, @code{state} has the value
3913: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3914: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 3915: the text interpreter is said to be @dfn{compiling}.
3916:
3917: In this example, the text interpreter is compiling when it processes the
3918: string ``@code{2 + . ;}''. It still breaks the string down into
3919: character sequences in the same way. However, instead of pushing the
3920: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
3921: into the definition of @code{add-two} that will make the number @code{2} get
3922: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
3923: the behaviours of @code{+} and @code{.} are also compiled into the
3924: definition.
3925:
3926: One category of words don't get compiled. These so-called @dfn{immediate
3927: words} get executed (performed @i{now}) regardless of whether the text
3928: interpreter is interpreting or compiling. The word @code{;} is an
3929: immediate word. Rather than being compiled into the definition, it
3930: executes. Its effect is to terminate the current definition, which
3931: includes changing the value of @code{state} back to 0.
3932:
3933: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
3934: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
3935: definition.
1.28 crook 3936:
1.30 anton 3937: In Forth, every word or number can be described in terms of two
1.29 crook 3938: properties:
1.28 crook 3939:
3940: @itemize @bullet
3941: @item
1.29 crook 3942: @cindex interpretation semantics
1.44 crook 3943: Its @dfn{interpretation semantics} describe how it will behave when the
3944: text interpreter encounters it in @dfn{interpret} state. The
3945: interpretation semantics of a word are represented by an @dfn{execution
3946: token}.
1.28 crook 3947: @item
1.29 crook 3948: @cindex compilation semantics
1.44 crook 3949: Its @dfn{compilation semantics} describe how it will behave when the
3950: text interpreter encounters it in @dfn{compile} state. The compilation
3951: semantics of a word are represented in an implementation-dependent way;
3952: Gforth uses a @dfn{compilation token}.
1.29 crook 3953: @end itemize
3954:
3955: @noindent
3956: Numbers are always treated in a fixed way:
3957:
3958: @itemize @bullet
1.28 crook 3959: @item
1.44 crook 3960: When the number is @dfn{interpreted}, its behaviour is to push the
3961: number onto the stack.
1.28 crook 3962: @item
1.30 anton 3963: When the number is @dfn{compiled}, a piece of code is appended to the
3964: current definition that pushes the number when it runs. (In other words,
3965: the compilation semantics of a number are to postpone its interpretation
3966: semantics until the run-time of the definition that it is being compiled
3967: into.)
1.29 crook 3968: @end itemize
3969:
1.44 crook 3970: Words don't behave in such a regular way, but most have @i{default
3971: semantics} which means that they behave like this:
1.29 crook 3972:
3973: @itemize @bullet
1.28 crook 3974: @item
1.30 anton 3975: The @dfn{interpretation semantics} of the word are to do something useful.
3976: @item
1.29 crook 3977: The @dfn{compilation semantics} of the word are to append its
1.30 anton 3978: @dfn{interpretation semantics} to the current definition (so that its
3979: run-time behaviour is to do something useful).
1.28 crook 3980: @end itemize
3981:
1.30 anton 3982: @cindex immediate words
1.44 crook 3983: The actual behaviour of any particular word can be controlled by using
3984: the words @code{immediate} and @code{compile-only} when the word is
3985: defined. These words set flags in the name dictionary entry of the most
3986: recently defined word, and these flags are retrieved by the text
3987: interpreter when it finds the word in the name dictionary.
3988:
3989: A word that is marked as @dfn{immediate} has compilation semantics that
3990: are identical to its interpretation semantics. In other words, it
3991: behaves like this:
1.29 crook 3992:
3993: @itemize @bullet
3994: @item
1.30 anton 3995: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 3996: @item
1.30 anton 3997: The @dfn{compilation semantics} of the word are to do something useful
3998: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 3999: @end itemize
1.28 crook 4000:
1.44 crook 4001: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4002: performing the interpretation semantics of the word directly; an attempt
4003: to do so will generate an error. It is never necessary to use
4004: @code{compile-only} (and it is not even part of ANS Forth, though it is
4005: provided by many implementations) but it is good etiquette to apply it
4006: to a word that will not behave correctly (and might have unexpected
4007: side-effects) in interpret state. For example, it is only legal to use
4008: the conditional word @code{IF} within a definition. If you forget this
4009: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4010: @code{compile-only} allows the text interpreter to generate a helpful
4011: error message rather than subjecting you to the consequences of your
4012: folly.
4013:
1.29 crook 4014: This example shows the difference between an immediate and a
4015: non-immediate word:
1.28 crook 4016:
1.29 crook 4017: @example
4018: : show-state state @@ . ;
4019: : show-state-now show-state ; immediate
4020: : word1 show-state ;
4021: : word2 show-state-now ;
1.28 crook 4022: @end example
1.23 crook 4023:
1.29 crook 4024: The word @code{immediate} after the definition of @code{show-state-now}
4025: makes that word an immediate word. These definitions introduce a new
4026: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4027: variable, and leaves it on the stack. Therefore, the behaviour of
4028: @code{show-state} is to print a number that represents the current value
4029: of @code{state}.
1.28 crook 4030:
1.29 crook 4031: When you execute @code{word1}, it prints the number 0, indicating that
4032: the system is interpreting. When the text interpreter compiled the
4033: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4034: compilation semantics are to append its interpretation semantics to the
1.29 crook 4035: current definition. When you execute @code{word1}, it performs the
1.30 anton 4036: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4037: (and therefore @code{show-state}) are executed, the system is
4038: interpreting.
1.28 crook 4039:
1.30 anton 4040: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4041: you should have seen the number -1 printed, followed by ``@code{
4042: ok}''. When the text interpreter compiled the definition of
4043: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4044: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4045: semantics. It is executed straight away (even before the text
4046: interpreter has moved on to process another group of characters; the
4047: @code{;} in this example). The effect of executing it are to display the
4048: value of @code{state} @i{at the time that the definition of}
4049: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4050: system is compiling at this time. If you execute @code{word2} it does
4051: nothing at all.
1.28 crook 4052:
1.29 crook 4053: @cindex @code{."}, how it works
4054: Before leaving the subject of immediate words, consider the behaviour of
4055: @code{."} in the definition of @code{greet}, in the previous
4056: section. This word is both a parsing word and an immediate word. Notice
4057: that there is a space between @code{."} and the start of the text
4058: @code{Hello and welcome}, but that there is no space between the last
4059: letter of @code{welcome} and the @code{"} character. The reason for this
4060: is that @code{."} is a Forth word; it must have a space after it so that
4061: the text interpreter can identify it. The @code{"} is not a Forth word;
4062: it is a @dfn{delimiter}. The examples earlier show that, when the string
4063: is displayed, there is neither a space before the @code{H} nor after the
4064: @code{e}. Since @code{."} is an immediate word, it executes at the time
4065: that @code{greet} is defined. When it executes, its behaviour is to
4066: search forward in the input line looking for the delimiter. When it
4067: finds the delimiter, it updates @code{>IN} to point past the
4068: delimiter. It also compiles some magic code into the definition of
4069: @code{greet}; the xt of a run-time routine that prints a text string. It
4070: compiles the string @code{Hello and welcome} into memory so that it is
4071: available to be printed later. When the text interpreter gains control,
4072: the next word it finds in the input stream is @code{;} and so it
4073: terminates the definition of @code{greet}.
1.28 crook 4074:
4075:
4076: @comment ----------------------------------------------
1.29 crook 4077: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4078: @section Forth is written in Forth
4079: @cindex structure of Forth programs
4080:
4081: When you start up a Forth compiler, a large number of definitions
4082: already exist. In Forth, you develop a new application using bottom-up
4083: programming techniques to create new definitions that are defined in
4084: terms of existing definitions. As you create each definition you can
4085: test and debug it interactively.
4086:
4087: If you have tried out the examples in this section, you will probably
4088: have typed them in by hand; when you leave Gforth, your definitions will
4089: be lost. You can avoid this by using a text editor to enter Forth source
4090: code into a file, and then loading code from the file using
1.49 anton 4091: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4092: processed by the text interpreter, just as though you had typed it in by
4093: hand@footnote{Actually, there are some subtle differences -- see
4094: @ref{The Text Interpreter}.}.
4095:
4096: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4097: files for program entry (@pxref{Blocks}).
1.28 crook 4098:
1.29 crook 4099: In common with many, if not most, Forth compilers, most of Gforth is
4100: actually written in Forth. All of the @file{.fs} files in the
4101: installation directory@footnote{For example,
1.30 anton 4102: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4103: study to see examples of Forth programming.
1.28 crook 4104:
1.29 crook 4105: Gforth maintains a history file that records every line that you type to
4106: the text interpreter. This file is preserved between sessions, and is
4107: used to provide a command-line recall facility. If you enter long
4108: definitions by hand, you can use a text editor to paste them out of the
4109: history file into a Forth source file for reuse at a later time
1.49 anton 4110: (for more information @pxref{Command-line editing}).
1.28 crook 4111:
4112:
4113: @comment ----------------------------------------------
1.29 crook 4114: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4115: @section Review - elements of a Forth system
4116: @cindex elements of a Forth system
1.28 crook 4117:
1.29 crook 4118: To summarise this chapter:
1.28 crook 4119:
4120: @itemize @bullet
4121: @item
1.29 crook 4122: Forth programs use @dfn{factoring} to break a problem down into small
4123: fragments called @dfn{words} or @dfn{definitions}.
4124: @item
4125: Forth program development is an interactive process.
4126: @item
4127: The main command loop that accepts input, and controls both
4128: interpretation and compilation, is called the @dfn{text interpreter}
4129: (also known as the @dfn{outer interpreter}).
4130: @item
4131: Forth has a very simple syntax, consisting of words and numbers
4132: separated by spaces or carriage-return characters. Any additional syntax
4133: is imposed by @dfn{parsing words}.
4134: @item
4135: Forth uses a stack to pass parameters between words. As a result, it
4136: uses postfix notation.
4137: @item
4138: To use a word that has previously been defined, the text interpreter
4139: searches for the word in the @dfn{name dictionary}.
4140: @item
1.30 anton 4141: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4142: @item
1.29 crook 4143: The text interpreter uses the value of @code{state} to select between
4144: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4145: semantics} of a word that it encounters.
1.28 crook 4146: @item
1.30 anton 4147: The relationship between the @dfn{interpretation semantics} and
4148: @dfn{compilation semantics} for a word
1.29 crook 4149: depend upon the way in which the word was defined (for example, whether
4150: it is an @dfn{immediate} word).
1.28 crook 4151: @item
1.29 crook 4152: Forth definitions can be implemented in Forth (called @dfn{high-level
4153: definitions}) or in some other way (usually a lower-level language and
4154: as a result often called @dfn{low-level definitions}, @dfn{code
4155: definitions} or @dfn{primitives}).
1.28 crook 4156: @item
1.29 crook 4157: Many Forth systems are implemented mainly in Forth.
1.28 crook 4158: @end itemize
4159:
4160:
1.29 crook 4161: @comment ----------------------------------------------
1.48 anton 4162: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4163: @section Where To Go Next
4164: @cindex where to go next
1.28 crook 4165:
1.29 crook 4166: Amazing as it may seem, if you have read (and understood) this far, you
4167: know almost all the fundamentals about the inner workings of a Forth
4168: system. You certainly know enough to be able to read and understand the
4169: rest of this manual and the ANS Forth document, to learn more about the
4170: facilities that Forth in general and Gforth in particular provide. Even
4171: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4172: However, that's not a good idea just yet... better to try writing some
1.29 crook 4173: programs in Gforth.
1.28 crook 4174:
1.29 crook 4175: Forth has such a rich vocabulary that it can be hard to know where to
4176: start in learning it. This section suggests a few sets of words that are
4177: enough to write small but useful programs. Use the word index in this
4178: document to learn more about each word, then try it out and try to write
4179: small definitions using it. Start by experimenting with these words:
1.28 crook 4180:
4181: @itemize @bullet
4182: @item
1.29 crook 4183: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4184: @item
4185: Comparison: @code{MIN MAX =}
4186: @item
4187: Logic: @code{AND OR XOR NOT}
4188: @item
4189: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4190: @item
1.29 crook 4191: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4192: @item
1.29 crook 4193: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4194: @item
1.29 crook 4195: Defining words: @code{: ; CREATE}
1.28 crook 4196: @item
1.29 crook 4197: Memory allocation words: @code{ALLOT ,}
1.28 crook 4198: @item
1.29 crook 4199: Tools: @code{SEE WORDS .S MARKER}
4200: @end itemize
4201:
4202: When you have mastered those, go on to:
4203:
4204: @itemize @bullet
1.28 crook 4205: @item
1.29 crook 4206: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4207: @item
1.29 crook 4208: Memory access: @code{@@ !}
1.28 crook 4209: @end itemize
1.23 crook 4210:
1.29 crook 4211: When you have mastered these, there's nothing for it but to read through
4212: the whole of this manual and find out what you've missed.
4213:
4214: @comment ----------------------------------------------
1.48 anton 4215: @node Exercises, , Where to go next, Introduction
1.29 crook 4216: @section Exercises
4217: @cindex exercises
4218:
4219: TODO: provide a set of programming excercises linked into the stuff done
4220: already and into other sections of the manual. Provide solutions to all
4221: the exercises in a .fs file in the distribution.
4222:
4223: @c Get some inspiration from Starting Forth and Kelly&Spies.
4224:
4225: @c excercises:
4226: @c 1. take inches and convert to feet and inches.
4227: @c 2. take temperature and convert from fahrenheight to celcius;
4228: @c may need to care about symmetric vs floored??
4229: @c 3. take input line and do character substitution
4230: @c to encipher or decipher
4231: @c 4. as above but work on a file for in and out
4232: @c 5. take input line and convert to pig-latin
4233: @c
4234: @c thing of sets of things to exercise then come up with
4235: @c problems that need those things.
4236:
4237:
1.26 crook 4238: @c ******************************************************************
1.29 crook 4239: @node Words, Error messages, Introduction, Top
1.1 anton 4240: @chapter Forth Words
1.26 crook 4241: @cindex words
1.1 anton 4242:
4243: @menu
4244: * Notation::
1.21 crook 4245: * Comments::
4246: * Boolean Flags::
1.1 anton 4247: * Arithmetic::
4248: * Stack Manipulation::
1.5 anton 4249: * Memory::
1.1 anton 4250: * Control Structures::
4251: * Defining Words::
1.47 crook 4252: * Interpretation and Compilation Semantics::
4253: * Tokens for Words::
1.21 crook 4254: * The Text Interpreter::
4255: * Word Lists::
4256: * Environmental Queries::
1.12 anton 4257: * Files::
4258: * Blocks::
4259: * Other I/O::
4260: * Programming Tools::
4261: * Assembler and Code Words::
4262: * Threading Words::
1.26 crook 4263: * Locals::
4264: * Structures::
4265: * Object-oriented Forth::
1.21 crook 4266: * Passing Commands to the OS::
1.47 crook 4267: * Keeping track of Time::
1.21 crook 4268: * Miscellaneous Words::
1.1 anton 4269: @end menu
4270:
1.21 crook 4271: @node Notation, Comments, Words, Words
1.1 anton 4272: @section Notation
4273: @cindex notation of glossary entries
4274: @cindex format of glossary entries
4275: @cindex glossary notation format
4276: @cindex word glossary entry format
4277:
4278: The Forth words are described in this section in the glossary notation
4279: that has become a de-facto standard for Forth texts, i.e.,
4280:
4281: @format
1.29 crook 4282: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4283: @end format
1.29 crook 4284: @i{Description}
1.1 anton 4285:
4286: @table @var
4287: @item word
1.28 crook 4288: The name of the word.
1.1 anton 4289:
4290: @item Stack effect
4291: @cindex stack effect
1.29 crook 4292: The stack effect is written in the notation @code{@i{before} --
4293: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4294: stack entries before and after the execution of the word. The rest of
4295: the stack is not touched by the word. The top of stack is rightmost,
4296: i.e., a stack sequence is written as it is typed in. Note that Gforth
4297: uses a separate floating point stack, but a unified stack
1.29 crook 4298: notation. Also, return stack effects are not shown in @i{stack
4299: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4300: the type and/or the function of the item. See below for a discussion of
4301: the types.
4302:
4303: All words have two stack effects: A compile-time stack effect and a
4304: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4305: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4306: this standard behaviour, or the word does other unusual things at
4307: compile time, both stack effects are shown; otherwise only the run-time
4308: stack effect is shown.
4309:
4310: @cindex pronounciation of words
4311: @item pronunciation
4312: How the word is pronounced.
4313:
4314: @cindex wordset
4315: @item wordset
1.21 crook 4316: The ANS Forth standard is divided into several word sets. A standard
4317: system need not support all of them. Therefore, in theory, the fewer
4318: word sets your program uses the more portable it will be. However, we
4319: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4320: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4321: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4322: describes words that will work in future releases of Gforth;
4323: @code{gforth-internal} words are more volatile. Environmental query
4324: strings are also displayed like words; you can recognize them by the
1.21 crook 4325: @code{environment} in the word set field.
1.1 anton 4326:
4327: @item Description
4328: A description of the behaviour of the word.
4329: @end table
4330:
4331: @cindex types of stack items
4332: @cindex stack item types
4333: The type of a stack item is specified by the character(s) the name
4334: starts with:
4335:
4336: @table @code
4337: @item f
4338: @cindex @code{f}, stack item type
4339: Boolean flags, i.e. @code{false} or @code{true}.
4340: @item c
4341: @cindex @code{c}, stack item type
4342: Char
4343: @item w
4344: @cindex @code{w}, stack item type
4345: Cell, can contain an integer or an address
4346: @item n
4347: @cindex @code{n}, stack item type
4348: signed integer
4349: @item u
4350: @cindex @code{u}, stack item type
4351: unsigned integer
4352: @item d
4353: @cindex @code{d}, stack item type
4354: double sized signed integer
4355: @item ud
4356: @cindex @code{ud}, stack item type
4357: double sized unsigned integer
4358: @item r
4359: @cindex @code{r}, stack item type
4360: Float (on the FP stack)
1.21 crook 4361: @item a-
1.1 anton 4362: @cindex @code{a_}, stack item type
4363: Cell-aligned address
1.21 crook 4364: @item c-
1.1 anton 4365: @cindex @code{c_}, stack item type
4366: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4367: @item f-
1.1 anton 4368: @cindex @code{f_}, stack item type
4369: Float-aligned address
1.21 crook 4370: @item df-
1.1 anton 4371: @cindex @code{df_}, stack item type
4372: Address aligned for IEEE double precision float
1.21 crook 4373: @item sf-
1.1 anton 4374: @cindex @code{sf_}, stack item type
4375: Address aligned for IEEE single precision float
4376: @item xt
4377: @cindex @code{xt}, stack item type
4378: Execution token, same size as Cell
4379: @item wid
4380: @cindex @code{wid}, stack item type
1.21 crook 4381: Word list ID, same size as Cell
1.1 anton 4382: @item f83name
4383: @cindex @code{f83name}, stack item type
4384: Pointer to a name structure
4385: @item "
4386: @cindex @code{"}, stack item type
1.12 anton 4387: string in the input stream (not on the stack). The terminating character
4388: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4389: quotes.
4390: @end table
4391:
1.21 crook 4392: @node Comments, Boolean Flags, Notation, Words
4393: @section Comments
1.26 crook 4394: @cindex comments
1.21 crook 4395:
1.29 crook 4396: Forth supports two styles of comment; the traditional @i{in-line} comment,
4397: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4398:
1.44 crook 4399:
1.23 crook 4400: doc-(
1.21 crook 4401: doc-\
1.23 crook 4402: doc-\G
1.21 crook 4403:
1.44 crook 4404:
1.21 crook 4405: @node Boolean Flags, Arithmetic, Comments, Words
4406: @section Boolean Flags
1.26 crook 4407: @cindex Boolean flags
1.21 crook 4408:
4409: A Boolean flag is cell-sized. A cell with all bits clear represents the
4410: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4411: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4412: a cell that has @i{any} bit set as @code{true}.
1.21 crook 4413:
1.44 crook 4414:
1.21 crook 4415: doc-true
4416: doc-false
1.29 crook 4417: doc-on
4418: doc-off
1.21 crook 4419:
1.44 crook 4420:
1.21 crook 4421: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4422: @section Arithmetic
4423: @cindex arithmetic words
4424:
4425: @cindex division with potentially negative operands
4426: Forth arithmetic is not checked, i.e., you will not hear about integer
4427: overflow on addition or multiplication, you may hear about division by
4428: zero if you are lucky. The operator is written after the operands, but
4429: the operands are still in the original order. I.e., the infix @code{2-1}
4430: corresponds to @code{2 1 -}. Forth offers a variety of division
4431: operators. If you perform division with potentially negative operands,
4432: you do not want to use @code{/} or @code{/mod} with its undefined
4433: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4434: former, @pxref{Mixed precision}).
1.26 crook 4435: @comment TODO discuss the different division forms and the std approach
1.1 anton 4436:
4437: @menu
4438: * Single precision::
4439: * Bitwise operations::
1.21 crook 4440: * Double precision:: Double-cell integer arithmetic
4441: * Numeric comparison::
1.29 crook 4442: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4443: * Floating Point::
4444: @end menu
4445:
4446: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
4447: @subsection Single precision
4448: @cindex single precision arithmetic words
4449:
1.21 crook 4450: By default, numbers in Forth are single-precision integers that are 1
1.26 crook 4451: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4452: treat them. For the rules used by the text interpreter for recognising
4453: single-precision integers see @ref{Number Conversion}.
1.21 crook 4454:
1.44 crook 4455:
1.1 anton 4456: doc-+
1.21 crook 4457: doc-1+
1.1 anton 4458: doc--
1.21 crook 4459: doc-1-
1.1 anton 4460: doc-*
4461: doc-/
4462: doc-mod
4463: doc-/mod
4464: doc-negate
4465: doc-abs
4466: doc-min
4467: doc-max
1.21 crook 4468: doc-d>s
1.27 crook 4469: doc-floored
1.1 anton 4470:
1.44 crook 4471:
1.21 crook 4472: @node Bitwise operations, Double precision, Single precision, Arithmetic
1.1 anton 4473: @subsection Bitwise operations
4474: @cindex bitwise operation words
4475:
1.44 crook 4476:
1.1 anton 4477: doc-and
4478: doc-or
4479: doc-xor
4480: doc-invert
1.21 crook 4481: doc-lshift
4482: doc-rshift
1.1 anton 4483: doc-2*
1.21 crook 4484: doc-d2*
1.1 anton 4485: doc-2/
1.21 crook 4486: doc-d2/
4487:
1.44 crook 4488:
1.21 crook 4489: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
4490: @subsection Double precision
4491: @cindex double precision arithmetic words
4492:
1.49 anton 4493: For the rules used by the text interpreter for
4494: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4495:
4496: A double precision number is represented by a cell pair, with the most
1.31 anton 4497: significant cell at the TOS. It is trivial to convert an unsigned
1.26 crook 4498: single to an (unsigned) double; simply push a @code{0} onto the
4499: TOS. Since numbers are represented by Gforth using 2's complement
4500: arithmetic, converting a signed single to a (signed) double requires
1.31 anton 4501: sign-extension across the most significant cell. This can be achieved
1.26 crook 4502: using @code{s>d}. The moral of the story is that you cannot convert a
4503: number without knowing whether it represents an unsigned or a
4504: signed number.
1.21 crook 4505:
1.44 crook 4506:
1.21 crook 4507: doc-s>d
4508: doc-d+
4509: doc-d-
4510: doc-dnegate
4511: doc-dabs
4512: doc-dmin
4513: doc-dmax
4514:
1.44 crook 4515:
1.21 crook 4516: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
4517: @subsection Numeric comparison
4518: @cindex numeric comparison words
4519:
1.44 crook 4520:
1.28 crook 4521: doc-<
4522: doc-<=
4523: doc-<>
4524: doc-=
4525: doc->
4526: doc->=
4527:
1.21 crook 4528: doc-0<
1.23 crook 4529: doc-0<=
1.21 crook 4530: doc-0<>
4531: doc-0=
1.23 crook 4532: doc-0>
4533: doc-0>=
1.28 crook 4534:
4535: doc-u<
4536: doc-u<=
1.44 crook 4537: @c u<> and u= exist but are the same as <> and =
1.31 anton 4538: @c doc-u<>
4539: @c doc-u=
1.28 crook 4540: doc-u>
4541: doc-u>=
4542:
4543: doc-within
4544:
4545: doc-d<
4546: doc-d<=
4547: doc-d<>
4548: doc-d=
4549: doc-d>
4550: doc-d>=
1.23 crook 4551:
1.21 crook 4552: doc-d0<
1.23 crook 4553: doc-d0<=
4554: doc-d0<>
1.21 crook 4555: doc-d0=
1.23 crook 4556: doc-d0>
4557: doc-d0>=
4558:
1.21 crook 4559: doc-du<
1.28 crook 4560: doc-du<=
1.44 crook 4561: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4562: @c doc-du<>
4563: @c doc-du=
1.28 crook 4564: doc-du>
4565: doc-du>=
1.1 anton 4566:
1.44 crook 4567:
1.21 crook 4568: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4569: @subsection Mixed precision
4570: @cindex mixed precision arithmetic words
4571:
1.44 crook 4572:
1.1 anton 4573: doc-m+
4574: doc-*/
4575: doc-*/mod
4576: doc-m*
4577: doc-um*
4578: doc-m*/
4579: doc-um/mod
4580: doc-fm/mod
4581: doc-sm/rem
4582:
1.44 crook 4583:
1.21 crook 4584: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4585: @subsection Floating Point
4586: @cindex floating point arithmetic words
4587:
1.49 anton 4588: For the rules used by the text interpreter for
4589: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4590:
1.32 anton 4591: Gforth has a separate floating point
1.26 crook 4592: stack, but the documentation uses the unified notation.
1.1 anton 4593:
4594: @cindex floating-point arithmetic, pitfalls
4595: Floating point numbers have a number of unpleasant surprises for the
4596: unwary (e.g., floating point addition is not associative) and even a few
4597: for the wary. You should not use them unless you know what you are doing
4598: or you don't care that the results you get are totally bogus. If you
4599: want to learn about the problems of floating point numbers (and how to
4600: avoid them), you might start with @cite{David Goldberg, What Every
4601: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
1.17 anton 4602: Computing Surveys 23(1):5@minus{}48, March 1991}
1.47 crook 4603: (@uref{http://www.validgh.com/goldberg/paper.ps}).
1.1 anton 4604:
1.44 crook 4605:
1.21 crook 4606: doc-d>f
4607: doc-f>d
1.1 anton 4608: doc-f+
4609: doc-f-
4610: doc-f*
4611: doc-f/
4612: doc-fnegate
4613: doc-fabs
4614: doc-fmax
4615: doc-fmin
4616: doc-floor
4617: doc-fround
4618: doc-f**
4619: doc-fsqrt
4620: doc-fexp
4621: doc-fexpm1
4622: doc-fln
4623: doc-flnp1
4624: doc-flog
4625: doc-falog
1.32 anton 4626: doc-f2*
4627: doc-f2/
4628: doc-1/f
4629: doc-precision
4630: doc-set-precision
4631:
4632: @cindex angles in trigonometric operations
4633: @cindex trigonometric operations
4634: Angles in floating point operations are given in radians (a full circle
4635: has 2 pi radians).
4636:
1.1 anton 4637: doc-fsin
4638: doc-fcos
4639: doc-fsincos
4640: doc-ftan
4641: doc-fasin
4642: doc-facos
4643: doc-fatan
4644: doc-fatan2
4645: doc-fsinh
4646: doc-fcosh
4647: doc-ftanh
4648: doc-fasinh
4649: doc-facosh
4650: doc-fatanh
1.21 crook 4651: doc-pi
1.28 crook 4652:
1.32 anton 4653: @cindex equality of floats
4654: @cindex floating-point comparisons
1.31 anton 4655: One particular problem with floating-point arithmetic is that comparison
4656: for equality often fails when you would expect it to succeed. For this
4657: reason approximate equality is often preferred (but you still have to
4658: know what you are doing). The comparison words are:
4659:
4660: doc-f~rel
4661: doc-f~abs
4662: doc-f=
4663: doc-f~
4664: doc-f<>
4665:
4666: doc-f<
4667: doc-f<=
4668: doc-f>
4669: doc-f>=
4670:
1.21 crook 4671: doc-f0<
1.28 crook 4672: doc-f0<=
4673: doc-f0<>
1.21 crook 4674: doc-f0=
1.28 crook 4675: doc-f0>
4676: doc-f0>=
4677:
1.1 anton 4678:
4679: @node Stack Manipulation, Memory, Arithmetic, Words
4680: @section Stack Manipulation
4681: @cindex stack manipulation words
4682:
4683: @cindex floating-point stack in the standard
1.21 crook 4684: Gforth maintains a number of separate stacks:
4685:
1.29 crook 4686: @cindex data stack
4687: @cindex parameter stack
1.21 crook 4688: @itemize @bullet
4689: @item
1.29 crook 4690: A data stack (also known as the @dfn{parameter stack}) -- for
4691: characters, cells, addresses, and double cells.
1.21 crook 4692:
1.29 crook 4693: @cindex floating-point stack
1.21 crook 4694: @item
1.44 crook 4695: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4696:
1.29 crook 4697: @cindex return stack
1.21 crook 4698: @item
1.44 crook 4699: A return stack -- for holding the return addresses of colon
1.32 anton 4700: definitions and other (non-FP) data.
1.21 crook 4701:
1.29 crook 4702: @cindex locals stack
1.21 crook 4703: @item
1.44 crook 4704: A locals stack -- for holding local variables.
1.21 crook 4705: @end itemize
4706:
1.1 anton 4707: @menu
4708: * Data stack::
4709: * Floating point stack::
4710: * Return stack::
4711: * Locals stack::
4712: * Stack pointer manipulation::
4713: @end menu
4714:
4715: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4716: @subsection Data stack
4717: @cindex data stack manipulation words
4718: @cindex stack manipulations words, data stack
4719:
1.44 crook 4720:
1.1 anton 4721: doc-drop
4722: doc-nip
4723: doc-dup
4724: doc-over
4725: doc-tuck
4726: doc-swap
1.21 crook 4727: doc-pick
1.1 anton 4728: doc-rot
4729: doc--rot
4730: doc-?dup
4731: doc-roll
4732: doc-2drop
4733: doc-2nip
4734: doc-2dup
4735: doc-2over
4736: doc-2tuck
4737: doc-2swap
4738: doc-2rot
4739:
1.44 crook 4740:
1.1 anton 4741: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4742: @subsection Floating point stack
4743: @cindex floating-point stack manipulation words
4744: @cindex stack manipulation words, floating-point stack
4745:
1.32 anton 4746: Whilst every sane Forth has a separate floating-point stack, it is not
4747: strictly required; an ANS Forth system could theoretically keep
4748: floating-point numbers on the data stack. As an additional difficulty,
4749: you don't know how many cells a floating-point number takes. It is
4750: reportedly possible to write words in a way that they work also for a
4751: unified stack model, but we do not recommend trying it. Instead, just
4752: say that your program has an environmental dependency on a separate
4753: floating-point stack.
4754:
4755: doc-floating-stack
4756:
1.1 anton 4757: doc-fdrop
4758: doc-fnip
4759: doc-fdup
4760: doc-fover
4761: doc-ftuck
4762: doc-fswap
1.21 crook 4763: doc-fpick
1.1 anton 4764: doc-frot
4765:
1.44 crook 4766:
1.1 anton 4767: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4768: @subsection Return stack
4769: @cindex return stack manipulation words
4770: @cindex stack manipulation words, return stack
4771:
1.32 anton 4772: @cindex return stack and locals
4773: @cindex locals and return stack
4774: A Forth system is allowed to keep local variables on the
4775: return stack. This is reasonable, as local variables usually eliminate
4776: the need to use the return stack explicitly. So, if you want to produce
4777: a standard compliant program and you are using local variables in a
4778: word, forget about return stack manipulations in that word (refer to the
4779: standard document for the exact rules).
4780:
1.1 anton 4781: doc->r
4782: doc-r>
4783: doc-r@
4784: doc-rdrop
4785: doc-2>r
4786: doc-2r>
4787: doc-2r@
4788: doc-2rdrop
4789:
1.44 crook 4790:
1.1 anton 4791: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4792: @subsection Locals stack
4793:
1.47 crook 4794: Gforth uses an extra locals stack. It is described, along with the
4795: reasons for its existence, in @ref{Implementation,Implementation of locals}.
1.21 crook 4796:
1.1 anton 4797: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4798: @subsection Stack pointer manipulation
4799: @cindex stack pointer manipulation words
4800:
1.44 crook 4801: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4802: doc-sp0
1.1 anton 4803: doc-sp@
4804: doc-sp!
1.21 crook 4805: doc-fp0
1.1 anton 4806: doc-fp@
4807: doc-fp!
1.21 crook 4808: doc-rp0
1.1 anton 4809: doc-rp@
4810: doc-rp!
1.21 crook 4811: doc-lp0
1.1 anton 4812: doc-lp@
4813: doc-lp!
4814:
1.44 crook 4815:
1.1 anton 4816: @node Memory, Control Structures, Stack Manipulation, Words
4817: @section Memory
1.26 crook 4818: @cindex memory words
1.1 anton 4819:
1.32 anton 4820: @menu
4821: * Memory model::
4822: * Dictionary allocation::
4823: * Heap Allocation::
4824: * Memory Access::
4825: * Address arithmetic::
4826: * Memory Blocks::
4827: @end menu
4828:
4829: @node Memory model, Dictionary allocation, Memory, Memory
4830: @subsection ANS Forth and Gforth memory models
4831:
4832: @c The ANS Forth description is a mess (e.g., is the heap part of
4833: @c the dictionary?), so let's not stick to closely with it.
4834:
4835: ANS Forth considers a Forth system as consisting of several memories, of
4836: which only @dfn{data space} is managed and accessible with the memory
4837: words. Memory not necessarily in data space includes the stacks, the
4838: code (called code space) and the headers (called name space). In Gforth
4839: everything is in data space, but the code for the primitives is usually
4840: read-only.
4841:
4842: Data space is divided into a number of areas: The (data space portion of
4843: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4844: refer to the search data structure embodied in word lists and headers,
4845: because it is used for looking up names, just as you would in a
4846: conventional dictionary.}, the heap, and a number of system-allocated
4847: buffers.
4848:
4849: In ANS Forth data space is also divided into contiguous regions. You
4850: can only use address arithmetic within a contiguous region, not between
4851: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 4852: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 4853: allocation}).
4854:
4855: Gforth provides one big address space, and address arithmetic can be
4856: performed between any addresses. However, in the dictionary headers or
4857: code are interleaved with data, so almost the only contiguous data space
4858: regions there are those described by ANS Forth as contiguous; but you
4859: can be sure that the dictionary is allocated towards increasing
4860: addresses even between contiguous regions. The memory order of
4861: allocations in the heap is platform-dependent (and possibly different
4862: from one run to the next).
4863:
4864: @subsubsection ANS Forth dictionary details
4865:
4866: This section is just informative, you can skip it if you are in a hurry.
1.27 crook 4867:
1.29 crook 4868: When you create a colon definition, the text interpreter compiles the
1.32 anton 4869: code for the definition into the code space and compiles the name
4870: of the definition into the header space, together with other
1.27 crook 4871: information about the definition (such as its execution token).
4872:
1.44 crook 4873: When you create a variable, the execution of @code{Variable} will
1.32 anton 4874: compile some code, assign one cell in data space, and compile the name
4875: of the variable into the header space.
1.27 crook 4876:
4877: @cindex memory regions - relationship between them
4878: ANS Forth does not specify the relationship between the three memory
4879: regions, and specifies that a Standard program must not access code or
4880: data space directly -- it may only access data space directly. In
4881: addition, the Standard defines what relationships you may and may not
4882: rely on when allocating regions in data space. These constraints are
4883: simply a reflection of the many diverse techniques that are used to
4884: implement Forth systems; understanding and following the requirements of
4885: the Standard allows you to write portable programs -- programs that run
4886: in the same way on any of these diverse systems. Another way of looking
4887: at this is to say that ANS Forth was designed to permit compliant Forth
4888: systems to be implemented in many diverse ways.
4889:
4890: @cindex memory regions - how they are assigned
1.29 crook 4891: Here are some examples of ways in which name, code and data spaces
4892: might be assigned in different Forth implementations:
1.27 crook 4893:
4894: @itemize @bullet
4895: @item
4896: For a Forth system that runs from RAM under a general-purpose operating
4897: system, it can be convenient to interleave name, code and data spaces in
4898: a single contiguous memory region. This organisation can be
4899: memory-efficient (for example, because the relationship between the name
1.32 anton 4900: dictionary entry and the associated code space entry can be
1.27 crook 4901: implicit, rather than requiring an explicit memory pointer to reference
1.32 anton 4902: from the header space and the code space). This is the
1.27 crook 4903: organisation used by Gforth, as this example@footnote{The addresses
4904: in the example have been truncated to fit it onto the page, and the
4905: addresses and data shown will not match the output from your system} shows:
4906: @example
4907: hex
4908: variable fred 123456 fred !
4909: variable jim abcd jim !
4910: : foo + / - ;
4911: ' fred 10 - 50 dump
4912: ..80: 5C 46 0E 40 84 66 72 65 - 64 20 20 20 20 20 20 20 \F.@.fred
1.50 anton 4913: ..90: D0 9B 04 08 00 00 00 00 - 56 34 12 00 80 46 0E 40 ........V4...F.@@
1.27 crook 4914: ..A0: 83 6A 69 6D 20 20 20 20 - D0 9B 04 08 00 00 00 00 .jim ........
4915: ..B0: CD AB 00 00 9C 46 0E 40 - 83 66 6F 6F 20 20 20 20 .....F.@.foo
4916: ..C0: 80 9B 04 08 00 00 00 00 - E4 2E 05 08 0C 2F 05 08 ............./..
4917: @end example
4918:
4919: @item
4920: For a high-performance system running on a modern RISC processor with a
4921: modified Harvard architecture (one that has a unified main memory but
4922: separate instruction and data caches), it is desirable to separate
4923: processor instructions from processor data. This encourages a high cache
1.32 anton 4924: density and therefore a high cache hit rate. The Forth code space
1.27 crook 4925: is not necessarily made up entirely of processor instructions; its
4926: nature is dependent upon the Forth implementation.
4927:
4928: @item
4929: A Forth compiler that runs on a segmented 8086 processor could be
4930: designed to interleave the name, code and data spaces within a single
4931: 64Kbyte segment. A more common implementation choice is to use a
4932: separate 64Kbyte segment for each region, which provides more memory
4933: overall but provides an address map in which only the data space is
4934: accessible.
4935:
4936: @item
4937: Microprocessors exist that run Forth (or many of the primitives required
4938: to implement the Forth virtual machine efficiently) directly. On these
4939: processors, the relationship between name, code and data spaces may be
1.32 anton 4940: imposed as a side-effect of the architecture of the processor.
1.27 crook 4941:
4942: @item
4943: A Forth compiler that executes from ROM on an embedded system needs its
4944: data space separated from the name and code spaces so that the data
4945: space can be mapped to a RAM area.
4946:
4947: @item
4948: A Forth compiler that runs on an embedded system may have a requirement
4949: for a small memory footprint. On such a system it can be useful to
1.32 anton 4950: separate the header space from the data and code spaces; once the
4951: application has been compiled, the header space is no longer
1.27 crook 4952: required@footnote{more strictly speaking, most applications can be
1.32 anton 4953: designed so that this is the case}. The header space can be deleted
1.29 crook 4954: entirely, or could be stored in memory on a remote @i{host} system for
1.27 crook 4955: debug and development purposes. In the latter case, the compiler running
1.29 crook 4956: on the @i{target} system could implement a protocol across a
1.32 anton 4957: communication link that would allow it to interrogate the header space.
1.27 crook 4958: @end itemize
4959:
1.32 anton 4960: @node Dictionary allocation, Heap Allocation, Memory model, Memory
4961: @subsection Dictionary allocation
1.27 crook 4962: @cindex reserving data space
4963: @cindex data space - reserving some
4964:
1.32 anton 4965: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
4966: you want to deallocate X, you also deallocate everything
4967: allocated after X.
4968:
4969: The allocations using the words below are contiguous and grow the region
4970: towards increasing addresses. Other words that allocate dictionary
4971: memory of any kind (i.e., defining words including @code{:noname}) end
4972: the contiguous region and start a new one.
4973:
4974: In ANS Forth only @code{create}d words are guaranteed to produce an
4975: address that is the start of the following contiguous region. In
4976: particular, the cell allocated by @code{variable} is not guaranteed to
4977: be contiguous with following @code{allot}ed memory.
4978:
4979: You can deallocate memory by using @code{allot} with a negative argument
4980: (with some restrictions, see @code{allot}). For larger deallocations use
4981: @code{marker}.
1.27 crook 4982:
1.29 crook 4983:
1.27 crook 4984: doc-here
4985: doc-unused
4986: doc-allot
4987: doc-c,
1.29 crook 4988: doc-f,
1.27 crook 4989: doc-,
4990: doc-2,
1.29 crook 4991: @cindex user space
4992: doc-udp
4993: doc-uallot
1.27 crook 4994:
1.32 anton 4995: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
4996: course you should allocate memory in an aligned way, too. I.e., before
4997: allocating allocating a cell, @code{here} must be cell-aligned, etc.
4998: The words below align @code{here} if it is not already. Basically it is
4999: only already aligned for a type, if the last allocation was a multiple
5000: of the size of this type and if @code{here} was aligned for this type
5001: before.
5002:
5003: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5004: ANS Forth (@code{maxalign}ed in Gforth).
5005:
5006: doc-align
5007: doc-falign
5008: doc-sfalign
5009: doc-dfalign
5010: doc-maxalign
5011: doc-cfalign
5012:
5013:
5014: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5015: @subsection Heap allocation
5016: @cindex heap allocation
5017: @cindex dynamic allocation of memory
5018: @cindex memory-allocation word set
5019:
5020: Heap allocation supports deallocation of allocated memory in any
5021: order. Dictionary allocation is not affected by it (i.e., it does not
5022: end a contiguous region). In Gforth, these words are implemented using
5023: the standard C library calls malloc(), free() and resize().
5024:
5025: doc-allocate
5026: doc-free
5027: doc-resize
5028:
1.27 crook 5029:
1.32 anton 5030: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5031: @subsection Memory Access
5032: @cindex memory access words
5033:
1.44 crook 5034:
1.1 anton 5035: doc-@
5036: doc-!
5037: doc-+!
5038: doc-c@
5039: doc-c!
5040: doc-2@
5041: doc-2!
5042: doc-f@
5043: doc-f!
5044: doc-sf@
5045: doc-sf!
5046: doc-df@
5047: doc-df!
5048:
1.32 anton 5049: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5050: @subsection Address arithmetic
1.1 anton 5051: @cindex address arithmetic words
5052:
1.32 anton 5053: Address arithmetic is the foundation on which data structures like
5054: arrays, records (@pxref{Structures}) and objects (@pxref{Object-oriented
5055: Forth}) are built.
5056:
1.1 anton 5057: ANS Forth does not specify the sizes of the data types. Instead, it
5058: offers a number of words for computing sizes and doing address
1.29 crook 5059: arithmetic. Address arithmetic is performed in terms of address units
5060: (aus); on most systems the address unit is one byte. Note that a
5061: character may have more than one au, so @code{chars} is no noop (on
5062: systems where it is a noop, it compiles to nothing).
1.1 anton 5063:
5064: @cindex alignment of addresses for types
5065: ANS Forth also defines words for aligning addresses for specific
5066: types. Many computers require that accesses to specific data types
5067: must only occur at specific addresses; e.g., that cells may only be
5068: accessed at addresses divisible by 4. Even if a machine allows unaligned
5069: accesses, it can usually perform aligned accesses faster.
5070:
5071: For the performance-conscious: alignment operations are usually only
5072: necessary during the definition of a data structure, not during the
5073: (more frequent) accesses to it.
5074:
5075: ANS Forth defines no words for character-aligning addresses. This is not
5076: an oversight, but reflects the fact that addresses that are not
5077: char-aligned have no use in the standard and therefore will not be
5078: created.
5079:
5080: @cindex @code{CREATE} and alignment
1.29 crook 5081: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5082: are cell-aligned; in addition, Gforth guarantees that these addresses
5083: are aligned for all purposes.
5084:
1.26 crook 5085: Note that the ANS Forth word @code{char} has nothing to do with address
5086: arithmetic.
1.1 anton 5087:
1.44 crook 5088:
1.1 anton 5089: doc-chars
5090: doc-char+
5091: doc-cells
5092: doc-cell+
5093: doc-cell
5094: doc-aligned
5095: doc-floats
5096: doc-float+
5097: doc-float
5098: doc-faligned
5099: doc-sfloats
5100: doc-sfloat+
5101: doc-sfaligned
5102: doc-dfloats
5103: doc-dfloat+
5104: doc-dfaligned
5105: doc-maxaligned
5106: doc-cfaligned
5107: doc-address-unit-bits
5108:
1.44 crook 5109:
1.32 anton 5110: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5111: @subsection Memory Blocks
5112: @cindex memory block words
1.27 crook 5113: @cindex character strings - moving and copying
5114:
1.49 anton 5115: Memory blocks often represent character strings; For ways of storing
5116: character strings in memory see @ref{String Formats}. For other
5117: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5118:
1.32 anton 5119: Some of these words work on address units. Others work on character
5120: units (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
5121: address. Choose the correct operation depending upon your data type.
1.21 crook 5122:
5123: When copying characters between overlapping memory regions, choose
5124: carefully between @code{cmove} and @code{cmove>}.
5125:
1.29 crook 5126: You can only use any of these words @i{portably} to access data space.
1.21 crook 5127:
1.27 crook 5128: @comment TODO - think the naming of the arguments is wrong for move
1.29 crook 5129: @comment well, really it seems to be the Standard that's wrong; it
5130: @comment describes MOVE as a word that requires a CELL-aligned source
5131: @comment and destination address but a xtranfer count that need not
5132: @comment be a multiple of CELL.
1.44 crook 5133:
1.1 anton 5134: doc-move
5135: doc-erase
5136: doc-cmove
5137: doc-cmove>
5138: doc-fill
5139: doc-blank
1.21 crook 5140: doc-compare
5141: doc-search
1.27 crook 5142: doc--trailing
5143: doc-/string
5144:
1.44 crook 5145:
1.27 crook 5146: @comment TODO examples
5147:
1.1 anton 5148:
1.26 crook 5149: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5150: @section Control Structures
5151: @cindex control structures
5152:
1.33 anton 5153: Control structures in Forth cannot be used interpretively, only in a
5154: colon definition@footnote{To be precise, they have no interpretation
5155: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5156: not like this limitation, but have not seen a satisfying way around it
5157: yet, although many schemes have been proposed.
1.1 anton 5158:
5159: @menu
1.33 anton 5160: * Selection:: IF ... ELSE ... ENDIF
5161: * Simple Loops:: BEGIN ...
1.29 crook 5162: * Counted Loops:: DO
5163: * Arbitrary control structures::
5164: * Calls and returns::
1.1 anton 5165: * Exception Handling::
5166: @end menu
5167:
5168: @node Selection, Simple Loops, Control Structures, Control Structures
5169: @subsection Selection
5170: @cindex selection control structures
5171: @cindex control structures for selection
5172:
1.33 anton 5173: @c what's the purpose of all these @i? Maybe we should define a macro
5174: @c so we can produce logical markup. - anton
5175:
1.44 crook 5176: @c nac-> When I started working on the manual, a mixture of @i and @var
5177: @c were used inconsistently in code examples and \Glossary entries. These
5178: @c two behave differently in info format so I decided to standardize on @i.
5179: @c Logical markup would be better but texi isn't really upto it, and
5180: @c texi2html just ignores macros.
1.47 crook 5181: @c nac02dec1999-> update: the latest texinfo release can spit out html
5182: @c and it handles macros, so we could do some logical markup. Unfortunately
5183: @c texinfo will not split html output, which would be a big pain if you
5184: @c wanted to put the document on the web, which would be nice.
1.44 crook 5185:
1.1 anton 5186: @cindex @code{IF} control structure
5187: @example
1.29 crook 5188: @i{flag}
1.1 anton 5189: IF
1.29 crook 5190: @i{code}
1.1 anton 5191: ENDIF
5192: @end example
1.21 crook 5193: @noindent
1.33 anton 5194:
1.44 crook 5195: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5196: with any bit set represents truth) @i{code} is executed.
1.33 anton 5197:
1.1 anton 5198: @example
1.29 crook 5199: @i{flag}
1.1 anton 5200: IF
1.29 crook 5201: @i{code1}
1.1 anton 5202: ELSE
1.29 crook 5203: @i{code2}
1.1 anton 5204: ENDIF
5205: @end example
5206:
1.44 crook 5207: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5208: executed.
1.33 anton 5209:
1.1 anton 5210: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5211: standard, and @code{ENDIF} is not, although it is quite popular. We
5212: recommend using @code{ENDIF}, because it is less confusing for people
5213: who also know other languages (and is not prone to reinforcing negative
5214: prejudices against Forth in these people). Adding @code{ENDIF} to a
5215: system that only supplies @code{THEN} is simple:
5216: @example
1.21 crook 5217: : ENDIF POSTPONE THEN ; immediate
1.1 anton 5218: @end example
5219:
5220: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5221: (adv.)} has the following meanings:
5222: @quotation
5223: ... 2b: following next after in order ... 3d: as a necessary consequence
5224: (if you were there, then you saw them).
5225: @end quotation
5226: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5227: and many other programming languages has the meaning 3d.]
5228:
1.21 crook 5229: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5230: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5231: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5232: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5233: @file{compat/control.fs}.
5234:
5235: @cindex @code{CASE} control structure
5236: @example
1.29 crook 5237: @i{n}
1.1 anton 5238: CASE
1.29 crook 5239: @i{n1} OF @i{code1} ENDOF
5240: @i{n2} OF @i{code2} ENDOF
1.1 anton 5241: @dots{}
5242: ENDCASE
5243: @end example
5244:
1.29 crook 5245: Executes the first @i{codei}, where the @i{ni} is equal to
5246: @i{n}. A default case can be added by simply writing the code after
5247: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
1.1 anton 5248: but must not consume it.
5249:
5250: @node Simple Loops, Counted Loops, Selection, Control Structures
5251: @subsection Simple Loops
5252: @cindex simple loops
5253: @cindex loops without count
5254:
5255: @cindex @code{WHILE} loop
5256: @example
5257: BEGIN
1.29 crook 5258: @i{code1}
5259: @i{flag}
1.1 anton 5260: WHILE
1.29 crook 5261: @i{code2}
1.1 anton 5262: REPEAT
5263: @end example
5264:
1.29 crook 5265: @i{code1} is executed and @i{flag} is computed. If it is true,
5266: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5267: false, execution continues after the @code{REPEAT}.
5268:
5269: @cindex @code{UNTIL} loop
5270: @example
5271: BEGIN
1.29 crook 5272: @i{code}
5273: @i{flag}
1.1 anton 5274: UNTIL
5275: @end example
5276:
1.29 crook 5277: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5278:
5279: @cindex endless loop
5280: @cindex loops, endless
5281: @example
5282: BEGIN
1.29 crook 5283: @i{code}
1.1 anton 5284: AGAIN
5285: @end example
5286:
5287: This is an endless loop.
5288:
5289: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5290: @subsection Counted Loops
5291: @cindex counted loops
5292: @cindex loops, counted
5293: @cindex @code{DO} loops
5294:
5295: The basic counted loop is:
5296: @example
1.29 crook 5297: @i{limit} @i{start}
1.1 anton 5298: ?DO
1.29 crook 5299: @i{body}
1.1 anton 5300: LOOP
5301: @end example
5302:
1.29 crook 5303: This performs one iteration for every integer, starting from @i{start}
5304: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5305: accessed with @code{i}. For example, the loop:
1.1 anton 5306: @example
5307: 10 0 ?DO
5308: i .
5309: LOOP
5310: @end example
1.21 crook 5311: @noindent
5312: prints @code{0 1 2 3 4 5 6 7 8 9}
5313:
1.1 anton 5314: The index of the innermost loop can be accessed with @code{i}, the index
5315: of the next loop with @code{j}, and the index of the third loop with
5316: @code{k}.
5317:
1.44 crook 5318:
1.1 anton 5319: doc-i
5320: doc-j
5321: doc-k
5322:
1.44 crook 5323:
1.1 anton 5324: The loop control data are kept on the return stack, so there are some
1.21 crook 5325: restrictions on mixing return stack accesses and counted loop words. In
5326: particuler, if you put values on the return stack outside the loop, you
5327: cannot read them inside the loop@footnote{well, not in a way that is
5328: portable.}. If you put values on the return stack within a loop, you
5329: have to remove them before the end of the loop and before accessing the
5330: index of the loop.
1.1 anton 5331:
5332: There are several variations on the counted loop:
5333:
1.21 crook 5334: @itemize @bullet
5335: @item
5336: @code{LEAVE} leaves the innermost counted loop immediately; execution
5337: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5338:
5339: @example
5340: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5341: @end example
5342: prints @code{0 1 2 3}
5343:
1.1 anton 5344:
1.21 crook 5345: @item
5346: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5347: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5348: return stack so @code{EXIT} can get to its return address. For example:
5349:
5350: @example
5351: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5352: @end example
5353: prints @code{0 1 2 3}
5354:
5355:
5356: @item
1.29 crook 5357: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5358: (and @code{LOOP} iterates until they become equal by wrap-around
5359: arithmetic). This behaviour is usually not what you want. Therefore,
5360: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5361: @code{?DO}), which do not enter the loop if @i{start} is greater than
5362: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5363: unsigned loop parameters.
5364:
1.21 crook 5365: @item
5366: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5367: the loop, independent of the loop parameters. Do not use @code{DO}, even
5368: if you know that the loop is entered in any case. Such knowledge tends
5369: to become invalid during maintenance of a program, and then the
5370: @code{DO} will make trouble.
5371:
5372: @item
1.29 crook 5373: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5374: index by @i{n} instead of by 1. The loop is terminated when the border
5375: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5376:
1.21 crook 5377: @example
5378: 4 0 +DO i . 2 +LOOP
5379: @end example
5380: @noindent
5381: prints @code{0 2}
5382:
5383: @example
5384: 4 1 +DO i . 2 +LOOP
5385: @end example
5386: @noindent
5387: prints @code{1 3}
1.1 anton 5388:
5389:
5390: @cindex negative increment for counted loops
5391: @cindex counted loops with negative increment
1.29 crook 5392: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5393:
1.21 crook 5394: @example
5395: -1 0 ?DO i . -1 +LOOP
5396: @end example
5397: @noindent
5398: prints @code{0 -1}
1.1 anton 5399:
1.21 crook 5400: @example
5401: 0 0 ?DO i . -1 +LOOP
5402: @end example
5403: prints nothing.
1.1 anton 5404:
1.29 crook 5405: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5406: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5407: index by @i{u} each iteration. The loop is terminated when the border
5408: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5409: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5410:
1.21 crook 5411: @example
5412: -2 0 -DO i . 1 -LOOP
5413: @end example
5414: @noindent
5415: prints @code{0 -1}
1.1 anton 5416:
1.21 crook 5417: @example
5418: -1 0 -DO i . 1 -LOOP
5419: @end example
5420: @noindent
5421: prints @code{0}
5422:
5423: @example
5424: 0 0 -DO i . 1 -LOOP
5425: @end example
5426: @noindent
5427: prints nothing.
1.1 anton 5428:
1.21 crook 5429: @end itemize
1.1 anton 5430:
5431: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5432: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5433: for these words that uses only standard words is provided in
5434: @file{compat/loops.fs}.
1.1 anton 5435:
5436:
5437: @cindex @code{FOR} loops
1.26 crook 5438: Another counted loop is:
1.1 anton 5439: @example
1.29 crook 5440: @i{n}
1.1 anton 5441: FOR
1.29 crook 5442: @i{body}
1.1 anton 5443: NEXT
5444: @end example
5445: This is the preferred loop of native code compiler writers who are too
1.26 crook 5446: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5447: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5448: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5449: Forth systems may behave differently, even if they support @code{FOR}
5450: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5451:
5452: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5453: @subsection Arbitrary control structures
5454: @cindex control structures, user-defined
5455:
5456: @cindex control-flow stack
5457: ANS Forth permits and supports using control structures in a non-nested
5458: way. Information about incomplete control structures is stored on the
5459: control-flow stack. This stack may be implemented on the Forth data
5460: stack, and this is what we have done in Gforth.
5461:
5462: @cindex @code{orig}, control-flow stack item
5463: @cindex @code{dest}, control-flow stack item
5464: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5465: entry represents a backward branch target. A few words are the basis for
5466: building any control structure possible (except control structures that
5467: need storage, like calls, coroutines, and backtracking).
5468:
1.44 crook 5469:
1.1 anton 5470: doc-if
5471: doc-ahead
5472: doc-then
5473: doc-begin
5474: doc-until
5475: doc-again
5476: doc-cs-pick
5477: doc-cs-roll
5478:
1.44 crook 5479:
1.21 crook 5480: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5481: manipulate the control-flow stack in a portable way. Without them, you
5482: would need to know how many stack items are occupied by a control-flow
5483: entry (many systems use one cell. In Gforth they currently take three,
5484: but this may change in the future).
5485:
1.1 anton 5486: Some standard control structure words are built from these words:
5487:
1.44 crook 5488:
1.1 anton 5489: doc-else
5490: doc-while
5491: doc-repeat
5492:
1.44 crook 5493:
5494: @noindent
1.1 anton 5495: Gforth adds some more control-structure words:
5496:
1.44 crook 5497:
1.1 anton 5498: doc-endif
5499: doc-?dup-if
5500: doc-?dup-0=-if
5501:
1.44 crook 5502:
5503: @noindent
1.1 anton 5504: Counted loop words constitute a separate group of words:
5505:
1.44 crook 5506:
1.1 anton 5507: doc-?do
5508: doc-+do
5509: doc-u+do
5510: doc--do
5511: doc-u-do
5512: doc-do
5513: doc-for
5514: doc-loop
5515: doc-+loop
5516: doc--loop
5517: doc-next
5518: doc-leave
5519: doc-?leave
5520: doc-unloop
5521: doc-done
5522:
1.44 crook 5523:
1.21 crook 5524: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5525: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5526: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5527: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5528: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5529: resolved (by using one of the loop-ending words or @code{DONE}).
5530:
1.44 crook 5531: @noindent
1.26 crook 5532: Another group of control structure words are:
1.1 anton 5533:
1.44 crook 5534:
1.1 anton 5535: doc-case
5536: doc-endcase
5537: doc-of
5538: doc-endof
5539:
1.44 crook 5540:
1.21 crook 5541: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5542: @code{CS-ROLL}.
1.1 anton 5543:
5544: @subsubsection Programming Style
1.47 crook 5545: @cindex control structures programming style
5546: @cindex programming style, arbitrary control structures
1.1 anton 5547:
5548: In order to ensure readability we recommend that you do not create
5549: arbitrary control structures directly, but define new control structure
5550: words for the control structure you want and use these words in your
1.26 crook 5551: program. For example, instead of writing:
1.1 anton 5552:
5553: @example
1.26 crook 5554: BEGIN
1.1 anton 5555: ...
1.26 crook 5556: IF [ 1 CS-ROLL ]
1.1 anton 5557: ...
1.26 crook 5558: AGAIN THEN
1.1 anton 5559: @end example
5560:
1.21 crook 5561: @noindent
1.1 anton 5562: we recommend defining control structure words, e.g.,
5563:
5564: @example
1.26 crook 5565: : WHILE ( DEST -- ORIG DEST )
5566: POSTPONE IF
5567: 1 CS-ROLL ; immediate
5568:
5569: : REPEAT ( orig dest -- )
5570: POSTPONE AGAIN
5571: POSTPONE THEN ; immediate
1.1 anton 5572: @end example
5573:
1.21 crook 5574: @noindent
1.1 anton 5575: and then using these to create the control structure:
5576:
5577: @example
1.26 crook 5578: BEGIN
1.1 anton 5579: ...
1.26 crook 5580: WHILE
1.1 anton 5581: ...
1.26 crook 5582: REPEAT
1.1 anton 5583: @end example
5584:
5585: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5586: @code{WHILE} are predefined, so in this example it would not be
5587: necessary to define them.
5588:
5589: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5590: @subsection Calls and returns
5591: @cindex calling a definition
5592: @cindex returning from a definition
5593:
1.3 anton 5594: @cindex recursive definitions
5595: A definition can be called simply be writing the name of the definition
1.26 crook 5596: to be called. Normally a definition is invisible during its own
1.3 anton 5597: definition. If you want to write a directly recursive definition, you
1.26 crook 5598: can use @code{recursive} to make the current definition visible, or
5599: @code{recurse} to call the current definition directly.
1.3 anton 5600:
1.44 crook 5601:
1.3 anton 5602: doc-recursive
5603: doc-recurse
5604:
1.44 crook 5605:
1.21 crook 5606: @comment TODO add example of the two recursion methods
1.12 anton 5607: @quotation
5608: @progstyle
5609: I prefer using @code{recursive} to @code{recurse}, because calling the
5610: definition by name is more descriptive (if the name is well-chosen) than
5611: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5612: implementation, it is much better to read (and think) ``now sort the
5613: partitions'' than to read ``now do a recursive call''.
5614: @end quotation
1.3 anton 5615:
1.29 crook 5616: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5617:
5618: @example
1.28 crook 5619: Defer foo
1.3 anton 5620:
5621: : bar ( ... -- ... )
5622: ... foo ... ;
5623:
5624: :noname ( ... -- ... )
5625: ... bar ... ;
5626: IS foo
5627: @end example
5628:
1.44 crook 5629: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5630:
1.26 crook 5631: The current definition returns control to the calling definition when
1.33 anton 5632: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5633:
5634: doc-exit
5635: doc-;s
5636:
1.44 crook 5637:
1.1 anton 5638: @node Exception Handling, , Calls and returns, Control Structures
5639: @subsection Exception Handling
1.26 crook 5640: @cindex exceptions
1.1 anton 5641:
1.26 crook 5642: If your program detects a fatal error condition, the simplest action
5643: that it can take is to @code{quit}. This resets the return stack and
5644: restarts the text interpreter, but does not print any error message.
1.21 crook 5645:
1.26 crook 5646: The next stage in severity is to execute @code{abort}, which has the
5647: same effect as @code{quit}, with the addition that it resets the data
5648: stack.
1.1 anton 5649:
1.26 crook 5650: A slightly more sophisticated approach is use use @code{abort"}, which
5651: compiles a string to be used as an error message and does a conditional
5652: @code{abort} at run-time. For example:
1.1 anton 5653:
1.26 crook 5654: @example
1.30 anton 5655: @kbd{: checker abort" That flag was true" ." A false flag" ;@key{RET}} ok
5656: @kbd{0 checker@key{RET}} A false flag ok
5657: @kbd{1 checker@key{RET}}
1.26 crook 5658: :1: That flag was true
5659: 1 checker
5660: ^^^^^^^
5661: $400D1648 throw
5662: $400E4660
5663: @end example
1.1 anton 5664:
1.26 crook 5665: These simple techniques allow a program to react to a fatal error
5666: condition, but they are not exactly user-friendly. The ANS Forth
5667: Exception word set provides the pair of words @code{throw} and
5668: @code{catch}, which can be used to provide sophisticated error-handling.
1.1 anton 5669:
1.26 crook 5670: @code{catch} has a similar behaviour to @code{execute}, in that it takes
1.29 crook 5671: an @i{xt} as a parameter and starts execution of the xt. However,
1.26 crook 5672: before passing control to the xt, @code{catch} pushes an
1.29 crook 5673: @dfn{exception frame} onto the @dfn{exception stack}. This exception
1.26 crook 5674: frame is used to restore the system to a known state if a detected error
5675: occurs during the execution of the xt. A typical way to use @code{catch}
5676: would be:
1.1 anton 5677:
1.26 crook 5678: @example
5679: ... ['] foo catch IF ...
5680: @end example
1.1 anton 5681:
1.33 anton 5682: @c TOS is undefined. - anton
1.44 crook 5683:
5684: @c nac-> TODO -- I need to look at this example again.
5685:
1.26 crook 5686: Whilst @code{foo} executes, it can call other words to any level of
5687: nesting, as usual. If @code{foo} (and all the words that it calls)
1.33 anton 5688: execute successfully, control will ultimately pass to the word following
5689: the @code{catch}, and there will be a 0 at TOS. However, if any word
5690: detects an error, it can terminate the execution of @code{foo} by
5691: pushing a non-zero error code onto the stack and then performing a
5692: @code{throw}. The execution of @code{throw} will pass control to the
5693: word following the @code{catch}, but this time the TOS will hold the
5694: error code. Therefore, the @code{IF} in the example can be used to
5695: determine whether @code{foo} executed successfully.
1.1 anton 5696:
1.26 crook 5697: This simple example shows how you can use @code{throw} and @code{catch}
5698: to ``take over'' exception handling from the system:
1.1 anton 5699: @example
1.26 crook 5700: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
1.1 anton 5701: @end example
5702:
1.26 crook 5703: The next example is more sophisticated and shows a multi-level
5704: @code{throw} and @code{catch}. To understand this example, start at the
5705: definition of @code{top-level} and work backwards:
5706:
1.1 anton 5707: @example
1.26 crook 5708: : lowest-level ( -- c )
5709: key dup 27 = if
1.44 crook 5710: 1 throw \ ESCAPE key pressed
1.26 crook 5711: else
1.44 crook 5712: ." lowest-level successful" CR
1.26 crook 5713: then
5714: ;
5715:
5716: : lower-level ( -- c )
5717: lowest-level
5718: \ at this level consider a CTRL-U to be a fatal error
5719: dup 21 = if \ CTRL-U
1.44 crook 5720: 2 throw
1.26 crook 5721: else
1.44 crook 5722: ." lower-level successful" CR
1.26 crook 5723: then
5724: ;
5725:
5726: : low-level ( -- c )
5727: ['] lower-level catch
5728: ?dup if
1.44 crook 5729: \ error occurred - do we recognise it?
5730: dup 1 = if
5731: \ ESCAPE key pressed.. pretend it was an E
5732: [char] E
5733: else throw \ propogate the error upwards
5734: then
1.26 crook 5735: then
5736: ." low-level successfull" CR
5737: ;
5738:
5739: : top-level ( -- )
5740: CR ['] low-level catch \ CATCH is used like EXECUTE
5741: ?dup if \ error occurred..
1.44 crook 5742: ." Error " . ." occurred - contact your supplier"
1.26 crook 5743: else
1.44 crook 5744: ." The '" emit ." ' key was pressed" CR
1.26 crook 5745: then
5746: ;
1.1 anton 5747: @end example
5748:
1.26 crook 5749: The ANS Forth document assigns @code{throw} codes thus:
1.1 anton 5750:
1.26 crook 5751: @itemize @bullet
5752: @item
5753: codes in the range -1 -- -255 are reserved to be assigned by the
5754: Standard. Assignments for codes in the range -1 -- -58 are currently
5755: documented in the Standard. In particular, @code{-1 throw} is equivalent
5756: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
5757: @item
5758: codes in the range -256 -- -4095 are reserved to be assigned by the system.
5759: @item
5760: all other codes may be assigned by programs.
5761: @end itemize
1.1 anton 5762:
1.26 crook 5763: Gforth provides the word @code{exception} as a mechanism for assigning
5764: system throw codes to applications. This allows multiple applications to
5765: co-exist in memory without any clash of @code{throw} codes. A definition
5766: of @code{exception} in ANS Forth is provided in
5767: @file{compat/exception.fs}.
1.1 anton 5768:
1.44 crook 5769:
1.26 crook 5770: doc-quit
5771: doc-abort
5772: doc-abort"
1.1 anton 5773:
1.26 crook 5774: doc-catch
1.29 crook 5775: doc-throw
5776: doc---exception-exception
5777:
5778:
1.44 crook 5779:
1.29 crook 5780: @c -------------------------------------------------------------
1.47 crook 5781: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5782: @section Defining Words
5783: @cindex defining words
5784:
1.47 crook 5785: Defining words are used to extend Forth by creating new entries in the dictionary.
5786:
1.29 crook 5787: @menu
1.44 crook 5788: * CREATE::
5789: * Variables:: Variables and user variables
5790: * Constants::
5791: * Values:: Initialised variables
1.29 crook 5792: * Colon Definitions::
1.44 crook 5793: * Anonymous Definitions:: Definitions without names
1.29 crook 5794: * User-defined Defining Words::
1.44 crook 5795: * Deferred words:: Allow forward references
5796: * Aliases::
1.29 crook 5797: * Supplying names::
5798: @end menu
5799:
1.44 crook 5800: @node CREATE, Variables, Defining Words, Defining Words
5801: @subsection @code{CREATE}
1.29 crook 5802: @cindex simple defining words
5803: @cindex defining words, simple
5804:
5805: Defining words are used to create new entries in the dictionary. The
5806: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5807: this:
5808:
5809: @example
5810: CREATE new-word1
5811: @end example
5812:
5813: @code{CREATE} is a parsing word that generates a dictionary entry for
5814: @code{new-word1}. When @code{new-word1} is executed, all that it does is
5815: leave an address on the stack. The address represents the value of
5816: the data space pointer (@code{HERE}) at the time that @code{new-word1}
5817: was defined. Therefore, @code{CREATE} is a way of associating a name
5818: with the address of a region of memory.
5819:
1.34 anton 5820: doc-create
5821:
1.29 crook 5822: By extending this example to reserve some memory in data space, we end
5823: up with a @i{variable}. Here are two different ways to do it:
5824:
5825: @example
5826: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5827: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5828: @end example
5829:
5830: The variable can be examined and modified using @code{@@} (``fetch'') and
5831: @code{!} (``store'') like this:
5832:
5833: @example
5834: new-word2 @@ . \ get address, fetch from it and display
5835: 1234 new-word2 ! \ new value, get address, store to it
5836: @end example
5837:
1.44 crook 5838: @cindex arrays
5839: A similar mechanism can be used to create arrays. For example, an
5840: 80-character text input buffer:
1.29 crook 5841:
5842: @example
1.44 crook 5843: CREATE text-buf 80 chars allot
5844:
5845: text-buf 0 chars c@@ \ the 1st character (offset 0)
5846: text-buf 3 chars c@@ \ the 4th character (offset 3)
5847: @end example
1.29 crook 5848:
1.44 crook 5849: You can build arbitrarily complex data structures by allocating
1.49 anton 5850: appropriate areas of memory. For further discussions of this, and to
5851: learn about some Gforth tools that make it easier, see
5852: @xref{Structures}.
1.44 crook 5853:
5854:
5855: @node Variables, Constants, CREATE, Defining Words
5856: @subsection Variables
5857: @cindex variables
5858:
5859: The previous section showed how a sequence of commands could be used to
5860: generate a variable. As a final refinement, the whole code sequence can
5861: be wrapped up in a defining word (pre-empting the subject of the next
5862: section), making it easier to create new variables:
5863:
5864: @example
5865: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5866: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5867:
5868: myvariableX foo \ variable foo starts off with an unknown value
5869: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5870:
5871: 45 3 * foo ! \ set foo to 135
5872: 1234 joe ! \ set joe to 1234
5873: 3 joe +! \ increment joe by 3.. to 1237
5874: @end example
5875:
5876: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5877: Forth already has a definition @code{Variable}. ANS Forth does not
5878: require a @code{Variable} to be initialised when it is created (i.e., it
5879: behaves like @code{myvariableX}). In contrast, Gforth's @code{Variable}
5880: initialises the variable to 0 (i.e., it behaves exactly like
5881: @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5882: @code{fvariable} for double and floating-point variables, respectively
5883: -- both are initialised to 0 in Gforth. If you use a @code{Variable} to
5884: store a boolean, you can use @code{on} and @code{off} to toggle its
5885: state.
1.29 crook 5886:
1.34 anton 5887: doc-variable
5888: doc-2variable
5889: doc-fvariable
5890:
1.29 crook 5891: @cindex user variables
5892: @cindex user space
5893: The defining word @code{User} behaves in the same way as @code{Variable}.
5894: The difference is that it reserves space in @i{user (data) space} rather
5895: than normal data space. In a Forth system that has a multi-tasker, each
5896: task has its own set of user variables.
5897:
1.34 anton 5898: doc-user
5899:
1.29 crook 5900: @comment TODO is that stuff about user variables strictly correct? Is it
5901: @comment just terminal tasks that have user variables?
5902: @comment should document tasker.fs (with some examples) elsewhere
5903: @comment in this manual, then expand on user space and user variables.
5904:
1.44 crook 5905:
5906: @node Constants, Values, Variables, Defining Words
5907: @subsection Constants
5908: @cindex constants
5909:
5910: @code{Constant} allows you to declare a fixed value and refer to it by
5911: name. For example:
1.29 crook 5912:
5913: @example
5914: 12 Constant INCHES-PER-FOOT
5915: 3E+08 fconstant SPEED-O-LIGHT
5916: @end example
5917:
5918: A @code{Variable} can be both read and written, so its run-time
5919: behaviour is to supply an address through which its current value can be
5920: manipulated. In contrast, the value of a @code{Constant} cannot be
5921: changed once it has been declared@footnote{Well, often it can be -- but
5922: not in a Standard, portable way. It's safer to use a @code{Value} (read
5923: on).} so it's not necessary to supply the address -- it is more
5924: efficient to return the value of the constant directly. That's exactly
5925: what happens; the run-time effect of a constant is to put its value on
1.49 anton 5926: the top of the stack (You can find one
5927: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 5928:
5929: Gforth also provides @code{2Constant} and @code{fconstant} for defining
5930: double and floating-point constants, respectively.
5931:
1.34 anton 5932: doc-constant
5933: doc-2constant
5934: doc-fconstant
5935:
5936: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 5937: @c nac-> How could that not be true in an ANS Forth? You can't define a
5938: @c constant, use it and then delete the definition of the constant..
5939: @c I agree that it's rather deep, but IMO it is an important difference
5940: @c relative to other programming languages.. often it's annoying: it
5941: @c certainly changes my programming style relative to C.
5942:
1.29 crook 5943: Constants in Forth behave differently from their equivalents in other
5944: programming languages. In other languages, a constant (such as an EQU in
5945: assembler or a #define in C) only exists at compile-time; in the
5946: executable program the constant has been translated into an absolute
5947: number and, unless you are using a symbolic debugger, it's impossible to
5948: know what abstract thing that number represents. In Forth a constant has
1.44 crook 5949: an entry in the header space and remains there after the code that uses
5950: it has been defined. In fact, it must remain in the dictionary since it
5951: has run-time duties to perform. For example:
1.29 crook 5952:
5953: @example
5954: 12 Constant INCHES-PER-FOOT
5955: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
5956: @end example
5957:
5958: @cindex in-lining of constants
5959: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
5960: associated with the constant @code{INCHES-PER-FOOT}. If you use
5961: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
5962: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
5963: attempt to optimise constants by in-lining them where they are used. You
5964: can force Gforth to in-line a constant like this:
5965:
5966: @example
5967: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
5968: @end example
5969:
5970: If you use @code{see} to decompile @i{this} version of
5971: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 5972: longer present. To understand how this works, read
5973: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 5974:
5975: In-lining constants in this way might improve execution time
5976: fractionally, and can ensure that a constant is now only referenced at
5977: compile-time. However, the definition of the constant still remains in
5978: the dictionary. Some Forth compilers provide a mechanism for controlling
5979: a second dictionary for holding transient words such that this second
5980: dictionary can be deleted later in order to recover memory
5981: space. However, there is no standard way of doing this.
5982:
5983:
1.44 crook 5984: @node Values, Colon Definitions, Constants, Defining Words
5985: @subsection Values
5986: @cindex values
1.34 anton 5987:
1.44 crook 5988: A @code{Value} is like a @code{Variable} but with two important
5989: differences:
1.29 crook 5990:
5991: @itemize @bullet
5992: @item
1.44 crook 5993: A @code{Value} is initialised when it is declared; like a
5994: @code{Constant} but unlike a @code{Variable}.
1.29 crook 5995: @item
1.44 crook 5996: A @code{Value} returns its value rather than its address when it is
5997: executed; i.e., it has the same run-time behaviour as @code{Constant}.
1.29 crook 5998: @end itemize
5999:
1.44 crook 6000: A @code{Value} needs an additional word, @code{TO} to allow its value to
6001: be changed. Here are some examples:
1.29 crook 6002:
6003: @example
1.44 crook 6004: 12 Value APPLES \ Define APPLES with an initial value of 12
6005: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6006: APPLES \ puts 34 on the top of the stack.
1.29 crook 6007: @end example
6008:
1.44 crook 6009: doc-value
6010: doc-to
1.29 crook 6011:
1.35 anton 6012:
1.44 crook 6013: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6014: @subsection Colon Definitions
6015: @cindex colon definitions
1.35 anton 6016:
6017: @example
1.44 crook 6018: : name ( ... -- ... )
6019: word1 word2 word3 ;
1.29 crook 6020: @end example
6021:
1.44 crook 6022: @noindent
6023: Creates a word called @code{name} that, upon execution, executes
6024: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6025:
1.49 anton 6026: The explanation above is somewhat superficial. For simple examples of
6027: colon definitions see @ref{Your first definition}. For an in-depth
6028: discussion of some of the issues involved, see @xref{Interpretation and
6029: Compilation Semantics}.
1.29 crook 6030:
1.44 crook 6031: doc-:
6032: doc-;
1.1 anton 6033:
1.34 anton 6034:
1.44 crook 6035: @node Anonymous Definitions, User-defined Defining Words, Colon Definitions, Defining Words
6036: @subsection Anonymous Definitions
6037: @cindex colon definitions
6038: @cindex defining words without name
1.34 anton 6039:
1.44 crook 6040: Sometimes you want to define an @dfn{anonymous word}; a word without a
6041: name. You can do this with:
1.1 anton 6042:
1.44 crook 6043: doc-:noname
1.1 anton 6044:
1.44 crook 6045: This leaves the execution token for the word on the stack after the
6046: closing @code{;}. Here's an example in which a deferred word is
6047: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6048:
1.29 crook 6049: @example
1.44 crook 6050: Defer deferred
6051: :noname ( ... -- ... )
6052: ... ;
6053: IS deferred
1.29 crook 6054: @end example
1.26 crook 6055:
1.44 crook 6056: @noindent
6057: Gforth provides an alternative way of doing this, using two separate
6058: words:
1.27 crook 6059:
1.44 crook 6060: doc-noname
6061: @cindex execution token of last defined word
6062: doc-lastxt
1.1 anton 6063:
1.44 crook 6064: @noindent
6065: The previous example can be rewritten using @code{noname} and
6066: @code{lastxt}:
1.1 anton 6067:
1.26 crook 6068: @example
1.44 crook 6069: Defer deferred
6070: noname : ( ... -- ... )
6071: ... ;
6072: lastxt IS deferred
1.26 crook 6073: @end example
1.1 anton 6074:
1.29 crook 6075: @noindent
1.44 crook 6076: @code{noname} works with any defining word, not just @code{:}.
6077:
6078: @code{lastxt} also works when the last word was not defined as
6079: @code{noname}. It also has the useful property that is is valid as soon
6080: as the header for a definition has been built. Thus:
6081:
6082: @example
6083: lastxt . : foo [ lastxt . ] ; ' foo .
6084: @end example
1.1 anton 6085:
1.44 crook 6086: @noindent
6087: prints 3 numbers; the last two are the same.
1.26 crook 6088:
1.1 anton 6089:
1.44 crook 6090: @node User-defined Defining Words, Deferred words, Anonymous Definitions, Defining Words
1.26 crook 6091: @subsection User-defined Defining Words
6092: @cindex user-defined defining words
6093: @cindex defining words, user-defined
1.1 anton 6094:
1.29 crook 6095: You can create a new defining word by wrapping defining-time code around
6096: an existing defining word and putting the sequence in a colon
6097: definition. For example, suppose that you have a word @code{stats} that
6098: gathers statistics about colon definitions given the @i{xt} of the
6099: definition, and you want every colon definition in your application to
6100: make a call to @code{stats}. You can define and use a new version of
6101: @code{:} like this:
6102:
6103: @example
6104: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6105: ... ; \ other code
6106:
6107: : my: : lastxt postpone literal ['] stats compile, ;
6108:
6109: my: foo + - ;
6110: @end example
6111:
6112: When @code{foo} is defined using @code{my:} these steps occur:
6113:
6114: @itemize @bullet
6115: @item
6116: @code{my:} is executed.
6117: @item
6118: The @code{:} within the definition (the one between @code{my:} and
6119: @code{lastxt}) is executed, and does just what it always does; it parses
6120: the input stream for a name, builds a dictionary header for the name
6121: @code{foo} and switches @code{state} from interpret to compile.
6122: @item
6123: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
6124: being defined -- @code{foo} -- onto the stack.
6125: @item
6126: The code that was produced by @code{postpone literal} is executed; this
6127: causes the value on the stack to be compiled as a literal in the code
6128: area of @code{foo}.
6129: @item
6130: The code @code{['] stats} compiles a literal into the definition of
6131: @code{my:}. When @code{compile,} is executed, that literal -- the
6132: execution token for @code{stats} -- is layed down in the code area of
6133: @code{foo} , following the literal@footnote{Strictly speaking, the
6134: mechanism that @code{compile,} uses to convert an @i{xt} into something
6135: in the code area is implementation-dependent. A threaded implementation
6136: might spit out the execution token directly whilst another
6137: implementation might spit out a native code sequence.}.
6138: @item
6139: At this point, the execution of @code{my:} is complete, and control
6140: returns to the text interpreter. The text interpreter is in compile
6141: state, so subsequent text @code{+ -} is compiled into the definition of
6142: @code{foo} and the @code{;} terminates the definition as always.
6143: @end itemize
6144:
6145: You can use @code{see} to decompile a word that was defined using
6146: @code{my:} and see how it is different from a normal @code{:}
6147: definition. For example:
6148:
6149: @example
6150: : bar + - ; \ like foo but using : rather than my:
6151: see bar
6152: : bar
6153: + - ;
6154: see foo
6155: : foo
6156: 107645672 stats + - ;
6157:
6158: \ use ' stats . to show that 107645672 is the xt for stats
6159: @end example
6160:
6161: You can use techniques like this to make new defining words in terms of
6162: @i{any} existing defining word.
1.1 anton 6163:
6164:
1.29 crook 6165: @cindex defining defining words
1.26 crook 6166: @cindex @code{CREATE} ... @code{DOES>}
6167: If you want the words defined with your defining words to behave
6168: differently from words defined with standard defining words, you can
6169: write your defining word like this:
1.1 anton 6170:
6171: @example
1.26 crook 6172: : def-word ( "name" -- )
1.29 crook 6173: CREATE @i{code1}
1.26 crook 6174: DOES> ( ... -- ... )
1.29 crook 6175: @i{code2} ;
1.26 crook 6176:
6177: def-word name
1.1 anton 6178: @end example
6179:
1.29 crook 6180: @cindex child words
6181: This fragment defines a @dfn{defining word} @code{def-word} and then
6182: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6183: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6184: is not executed at this time. The word @code{name} is sometimes called a
6185: @dfn{child} of @code{def-word}.
6186:
6187: When you execute @code{name}, the address of the body of @code{name} is
6188: put on the data stack and @i{code2} is executed (the address of the body
6189: of @code{name} is the address @code{HERE} returns immediately after the
6190: @code{CREATE}).
6191:
6192: @cindex atavism in child words
1.33 anton 6193: You can use @code{def-word} to define a set of child words that behave
1.29 crook 6194: differently, though atavistically; they all have a common run-time
6195: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
6196: builds a data area in the body of the child word. The structure of the
6197: data is common to all children of @code{def-word}, but the data values
6198: are specific -- and private -- to each child word. When a child word is
6199: executed, the address of its private data area is passed as a parameter
6200: on TOS to be used and manipulated@footnote{It is legitimate both to read
6201: and write to this data area.} by @i{code2}.
6202:
6203: The two fragments of code that make up the defining words act (are
6204: executed) at two completely separate times:
1.1 anton 6205:
1.29 crook 6206: @itemize @bullet
6207: @item
6208: At @i{define time}, the defining word executes @i{code1} to generate a
6209: child word
6210: @item
6211: At @i{child execution time}, when a child word is invoked, @i{code2}
6212: is executed, using parameters (data) that are private and specific to
6213: the child word.
6214: @end itemize
6215:
1.44 crook 6216: Another way of understanding the behaviour of @code{def-word} and
6217: @code{name} is to say that, if you make the following definitions:
1.33 anton 6218: @example
6219: : def-word1 ( "name" -- )
6220: CREATE @i{code1} ;
6221:
6222: : action1 ( ... -- ... )
6223: @i{code2} ;
6224:
6225: def-word1 name1
6226: @end example
6227:
1.44 crook 6228: @noindent
6229: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6230:
1.29 crook 6231: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6232:
1.1 anton 6233: @example
1.29 crook 6234: : CONSTANT ( w "name" -- )
6235: CREATE ,
1.26 crook 6236: DOES> ( -- w )
6237: @@ ;
1.1 anton 6238: @end example
6239:
1.29 crook 6240: @comment There is a beautiful description of how this works and what
6241: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6242: @comment commentary on the Counting Fruits problem.
6243:
6244: When you create a constant with @code{5 CONSTANT five}, a set of
6245: define-time actions take place; first a new word @code{five} is created,
6246: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6247: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6248: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6249: no code of its own; it simply contains a data field and a pointer to the
6250: code that follows @code{DOES>} in its defining word. That makes words
6251: created in this way very compact.
6252:
6253: The final example in this section is intended to remind you that space
6254: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6255: both read and written by a Standard program@footnote{Exercise: use this
6256: example as a starting point for your own implementation of @code{Value}
6257: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6258: @code{[']}.}:
6259:
6260: @example
6261: : foo ( "name" -- )
6262: CREATE -1 ,
6263: DOES> ( -- )
1.33 anton 6264: @@ . ;
1.29 crook 6265:
6266: foo first-word
6267: foo second-word
6268:
6269: 123 ' first-word >BODY !
6270: @end example
6271:
6272: If @code{first-word} had been a @code{CREATE}d word, we could simply
6273: have executed it to get the address of its data field. However, since it
6274: was defined to have @code{DOES>} actions, its execution semantics are to
6275: perform those @code{DOES>} actions. To get the address of its data field
6276: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6277: translate the xt into the address of the data field. When you execute
6278: @code{first-word}, it will display @code{123}. When you execute
6279: @code{second-word} it will display @code{-1}.
1.26 crook 6280:
6281: @cindex stack effect of @code{DOES>}-parts
6282: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6283: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6284: the stack effect of the defined words, not the stack effect of the
6285: following code (the following code expects the address of the body on
6286: the top of stack, which is not reflected in the stack comment). This is
6287: the convention that I use and recommend (it clashes a bit with using
6288: locals declarations for stack effect specification, though).
1.1 anton 6289:
1.53 anton 6290: @menu
6291: * CREATE..DOES> applications::
6292: * CREATE..DOES> details::
1.63 anton 6293: * Advanced does> usage example::
1.53 anton 6294: @end menu
6295:
6296: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6297: @subsubsection Applications of @code{CREATE..DOES>}
6298: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6299:
1.26 crook 6300: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6301:
1.26 crook 6302: @cindex factoring similar colon definitions
6303: When you see a sequence of code occurring several times, and you can
6304: identify a meaning, you will factor it out as a colon definition. When
6305: you see similar colon definitions, you can factor them using
6306: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6307: that look very similar:
1.1 anton 6308: @example
1.26 crook 6309: : ori, ( reg-target reg-source n -- )
6310: 0 asm-reg-reg-imm ;
6311: : andi, ( reg-target reg-source n -- )
6312: 1 asm-reg-reg-imm ;
1.1 anton 6313: @end example
6314:
1.26 crook 6315: @noindent
6316: This could be factored with:
6317: @example
6318: : reg-reg-imm ( op-code -- )
6319: CREATE ,
6320: DOES> ( reg-target reg-source n -- )
6321: @@ asm-reg-reg-imm ;
6322:
6323: 0 reg-reg-imm ori,
6324: 1 reg-reg-imm andi,
6325: @end example
1.1 anton 6326:
1.26 crook 6327: @cindex currying
6328: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6329: supply a part of the parameters for a word (known as @dfn{currying} in
6330: the functional language community). E.g., @code{+} needs two
6331: parameters. Creating versions of @code{+} with one parameter fixed can
6332: be done like this:
1.1 anton 6333: @example
1.26 crook 6334: : curry+ ( n1 -- )
6335: CREATE ,
6336: DOES> ( n2 -- n1+n2 )
6337: @@ + ;
6338:
6339: 3 curry+ 3+
6340: -2 curry+ 2-
1.1 anton 6341: @end example
6342:
1.63 anton 6343: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6344: @subsubsection The gory details of @code{CREATE..DOES>}
6345: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6346:
1.26 crook 6347: doc-does>
1.1 anton 6348:
1.26 crook 6349: @cindex @code{DOES>} in a separate definition
6350: This means that you need not use @code{CREATE} and @code{DOES>} in the
6351: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6352: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6353: @example
6354: : does1
6355: DOES> ( ... -- ... )
1.44 crook 6356: ... ;
6357:
6358: : does2
6359: DOES> ( ... -- ... )
6360: ... ;
6361:
6362: : def-word ( ... -- ... )
6363: create ...
6364: IF
6365: does1
6366: ELSE
6367: does2
6368: ENDIF ;
6369: @end example
6370:
6371: In this example, the selection of whether to use @code{does1} or
6372: @code{does2} is made at compile-time; at the time that the child word is
6373: @code{CREATE}d.
6374:
6375: @cindex @code{DOES>} in interpretation state
6376: In a standard program you can apply a @code{DOES>}-part only if the last
6377: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6378: will override the behaviour of the last word defined in any case. In a
6379: standard program, you can use @code{DOES>} only in a colon
6380: definition. In Gforth, you can also use it in interpretation state, in a
6381: kind of one-shot mode; for example:
6382: @example
6383: CREATE name ( ... -- ... )
6384: @i{initialization}
6385: DOES>
6386: @i{code} ;
6387: @end example
6388:
6389: @noindent
6390: is equivalent to the standard:
6391: @example
6392: :noname
6393: DOES>
6394: @i{code} ;
6395: CREATE name EXECUTE ( ... -- ... )
6396: @i{initialization}
6397: @end example
6398:
1.53 anton 6399: doc->body
6400:
1.63 anton 6401: @node Advanced does> usage example, , CREATE..DOES> details, User-defined Defining Words
6402: @subsubsection Advanced does> usage example
6403:
6404: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6405: for disassembling instructions, that follow a very repetetive scheme:
6406:
6407: @example
6408: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6409: @var{entry-num} cells @var{table} + !
6410: @end example
6411:
6412: Of course, this inspires the idea to factor out the commonalities to
6413: allow a definition like
6414:
6415: @example
6416: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6417: @end example
6418:
6419: The parameters @var{disasm-operands} and @var{table} are usually
6420: correlated. Moreover, there existed code defining instructions like
6421: this:
6422:
6423: @example
6424: @var{entry-num} @var{inst-format} @var{inst-name}
6425: @end example
6426:
6427: This code comes from the assembler and resides in
6428: @file{arch/mips/insts.fs}.
6429:
6430: So I had to define the @var{inst-format} words that performed the scheme
6431: above when executed. At first I chose to use run-time code-generation:
6432:
6433: @example
6434: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6435: :noname Postpone @var{disasm-operands}
6436: name Postpone sliteral Postpone type Postpone ;
6437: swap cells @var{table} + ! ;
6438: @end example
6439:
6440: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6441:
1.63 anton 6442: An alternative would have been to write this using
6443: @code{create}/@code{does>}:
6444:
6445: @example
6446: : @var{inst-format} ( entry-num "name" -- )
6447: here name string, ( entry-num c-addr ) \ parse and save "name"
6448: noname create , ( entry-num )
6449: lastxt swap cells @var{table} + !
6450: does> ( addr w -- )
6451: \ disassemble instruction w at addr
6452: @@ >r
6453: @var{disasm-operands}
6454: r> count type ;
6455: @end example
6456:
6457: Somehow the first solution is simpler, mainly because it's simpler to
6458: shift a string from definition-time to use-time with @code{sliteral}
6459: than with @code{string,} and friends.
6460:
6461: I wrote a lot of words following this scheme and soon thought about
6462: factoring out the commonalities among them. Note that this uses a
6463: two-level defining word, i.e., a word that defines ordinary defining
6464: words.
6465:
6466: This time a solution involving @code{postpone} and friends seemed more
6467: difficult (try it as an exercise), so I decided to use a
6468: @code{create}/@code{does>} word; since I was already at it, I also used
6469: @code{create}/@code{does>} for the lower level (try using
6470: @code{postpone} etc. as an exercise), resulting in the following
6471: definition:
6472:
6473: @example
6474: : define-format ( disasm-xt table-xt -- )
6475: \ define an instruction format that uses disasm-xt for
6476: \ disassembling and enters the defined instructions into table
6477: \ table-xt
6478: create 2,
6479: does> ( u "inst" -- )
6480: \ defines an anonymous word for disassembling instruction inst,
6481: \ and enters it as u-th entry into table-xt
6482: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6483: noname create 2, \ define anonymous word
6484: execute lastxt swap ! \ enter xt of defined word into table-xt
6485: does> ( addr w -- )
6486: \ disassemble instruction w at addr
6487: 2@@ >r ( addr w disasm-xt R: c-addr )
6488: execute ( R: c-addr ) \ disassemble operands
6489: r> count type ; \ print name
6490: @end example
6491:
6492: Note that the tables here (in contrast to above) do the @code{cells +}
6493: by themselves (that's why you have to pass an xt). This word is used in
6494: the following way:
6495:
6496: @example
6497: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6498: @end example
6499:
6500: In terms of currying, this kind of two-level defining word provides the
6501: parameters in three stages: first @var{disasm-operands} and @var{table},
6502: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6503: the instruction to be disassembled.
6504:
6505: Of course this did not quite fit all the instruction format names used
6506: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6507: the parameters into the right form.
6508:
6509: If you have trouble following this section, don't worry. First, this is
6510: involved and takes time (and probably some playing around) to
6511: understand; second, this is the first two-level
6512: @code{create}/@code{does>} word I have written in seventeen years of
6513: Forth; and if I did not have @file{insts.fs} to start with, I may well
6514: have elected to use just a one-level defining word (with some repeating
6515: of parameters when using the defining word). So it is not necessary to
6516: understand this, but it may improve your understanding of Forth.
1.44 crook 6517:
6518:
6519: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6520: @subsection Deferred words
6521: @cindex deferred words
6522:
6523: The defining word @code{Defer} allows you to define a word by name
6524: without defining its behaviour; the definition of its behaviour is
6525: deferred. Here are two situation where this can be useful:
6526:
6527: @itemize @bullet
6528: @item
6529: Where you want to allow the behaviour of a word to be altered later, and
6530: for all precompiled references to the word to change when its behaviour
6531: is changed.
6532: @item
6533: For mutual recursion; @xref{Calls and returns}.
6534: @end itemize
6535:
6536: In the following example, @code{foo} always invokes the version of
6537: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6538: always invokes the version that prints ``@code{Hello}''. There is no way
6539: of getting @code{foo} to use the later version without re-ordering the
6540: source code and recompiling it.
6541:
6542: @example
6543: : greet ." Good morning" ;
6544: : foo ... greet ... ;
6545: : greet ." Hello" ;
6546: : bar ... greet ... ;
6547: @end example
6548:
6549: This problem can be solved by defining @code{greet} as a @code{Defer}red
6550: word. The behaviour of a @code{Defer}red word can be defined and
6551: redefined at any time by using @code{IS} to associate the xt of a
6552: previously-defined word with it. The previous example becomes:
6553:
6554: @example
6555: Defer greet
6556: : foo ... greet ... ;
6557: : bar ... greet ... ;
6558: : greet1 ." Good morning" ;
6559: : greet2 ." Hello" ;
6560: ' greet2 <IS> greet \ make greet behave like greet2
6561: @end example
6562:
6563: A deferred word can be used to improve the statistics-gathering example
6564: from @ref{User-defined Defining Words}; rather than edit the
6565: application's source code to change every @code{:} to a @code{my:}, do
6566: this:
6567:
6568: @example
6569: : real: : ; \ retain access to the original
6570: defer : \ redefine as a deferred word
6571: ' my: IS : \ use special version of :
6572: \
6573: \ load application here
6574: \
6575: ' real: IS : \ go back to the original
6576: @end example
6577:
6578:
6579: One thing to note is that @code{<IS>} consumes its name when it is
6580: executed. If you want to specify the name at compile time, use
6581: @code{[IS]}:
6582:
6583: @example
6584: : set-greet ( xt -- )
6585: [IS] greet ;
6586:
6587: ' greet1 set-greet
6588: @end example
6589:
6590: A deferred word can only inherit default semantics from the xt (because
1.49 anton 6591: that is all that an xt can represent -- for more discussion of this
6592: @pxref{Tokens for Words}). However, the semantics of the deferred word
1.44 crook 6593: itself can be modified at the time that it is defined. For example:
6594:
6595: @example
6596: : bar .... ; compile-only
6597: Defer fred immediate
6598: Defer jim
6599:
6600: ' bar <IS> jim \ jim has default semantics
6601: ' bar <IS> fred \ fred is immediate
6602: @end example
6603:
6604: doc-defer
6605: doc-<is>
6606: doc-[is]
6607: doc-is
6608: @comment TODO document these: what's defers [is]
6609: doc-what's
6610: doc-defers
6611:
6612: @c Use @code{words-deferred} to see a list of deferred words.
6613:
6614: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
6615: are provided in @file{compat/defer.fs}.
6616:
6617:
6618: @node Aliases, Supplying names, Deferred words, Defining Words
6619: @subsection Aliases
6620: @cindex aliases
1.1 anton 6621:
1.44 crook 6622: The defining word @code{Alias} allows you to define a word by name that
6623: has the same behaviour as some other word. Here are two situation where
6624: this can be useful:
1.1 anton 6625:
1.44 crook 6626: @itemize @bullet
6627: @item
6628: When you want access to a word's definition from a different word list
6629: (for an example of this, see the definition of the @code{Root} word list
6630: in the Gforth source).
6631: @item
6632: When you want to create a synonym; a definition that can be known by
6633: either of two names (for example, @code{THEN} and @code{ENDIF} are
6634: aliases).
6635: @end itemize
1.1 anton 6636:
1.44 crook 6637: The word whose behaviour the alias is to inherit is represented by an
6638: xt. Therefore, the alias only inherits default semantics from its
6639: ancestor. The semantics of the alias itself can be modified at the time
6640: that it is defined. For example:
1.1 anton 6641:
6642: @example
1.44 crook 6643: : foo ... ; immediate
6644:
6645: ' foo Alias bar \ bar is not an immediate word
6646: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6647: @end example
6648:
1.44 crook 6649: Words that are aliases have the same xt, different headers in the
6650: dictionary, and consequently different name tokens (@pxref{Tokens for
6651: Words}) and possibly different immediate flags. An alias can only have
6652: default or immediate compilation semantics; you can define aliases for
6653: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6654:
1.44 crook 6655: doc-alias
1.26 crook 6656:
1.1 anton 6657:
1.52 anton 6658: @node Supplying names, , Aliases, Defining Words
1.29 crook 6659: @subsection Supplying the name of a defined word
1.26 crook 6660: @cindex names for defined words
1.44 crook 6661: @cindex defining words, name given in a string
1.1 anton 6662:
1.29 crook 6663: By default, a defining word takes the name for the defined word from the
1.26 crook 6664: input stream. Sometimes you want to supply the name from a string. You
6665: can do this with:
1.1 anton 6666:
1.26 crook 6667: doc-nextname
1.1 anton 6668:
1.26 crook 6669: For example:
1.1 anton 6670:
1.26 crook 6671: @example
6672: s" foo" nextname create
6673: @end example
1.44 crook 6674:
1.26 crook 6675: @noindent
6676: is equivalent to:
1.44 crook 6677:
1.26 crook 6678: @example
6679: create foo
6680: @end example
1.1 anton 6681:
1.29 crook 6682: @noindent
1.44 crook 6683: @code{nextname} works with any defining word, not just @code{:}.
1.1 anton 6684:
6685:
1.47 crook 6686: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6687: @section Interpretation and Compilation Semantics
1.26 crook 6688: @cindex semantics, interpretation and compilation
1.1 anton 6689:
1.26 crook 6690: @cindex interpretation semantics
6691: The @dfn{interpretation semantics} of a word are what the text
6692: interpreter does when it encounters the word in interpret state. It also
6693: appears in some other contexts, e.g., the execution token returned by
1.29 crook 6694: @code{' @i{word}} identifies the interpretation semantics of
6695: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
6696: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6697:
1.26 crook 6698: @cindex compilation semantics
6699: The @dfn{compilation semantics} of a word are what the text interpreter
6700: does when it encounters the word in compile state. It also appears in
1.29 crook 6701: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
1.26 crook 6702: standard terminology, ``appends to the current definition''.} the
1.29 crook 6703: compilation semantics of @i{word}.
1.1 anton 6704:
1.26 crook 6705: @cindex execution semantics
6706: The standard also talks about @dfn{execution semantics}. They are used
6707: only for defining the interpretation and compilation semantics of many
6708: words. By default, the interpretation semantics of a word are to
6709: @code{execute} its execution semantics, and the compilation semantics of
6710: a word are to @code{compile,} its execution semantics.@footnote{In
6711: standard terminology: The default interpretation semantics are its
6712: execution semantics; the default compilation semantics are to append its
6713: execution semantics to the execution semantics of the current
6714: definition.}
6715:
6716: @comment TODO expand, make it co-operate with new sections on text interpreter.
6717:
6718: @cindex immediate words
6719: @cindex compile-only words
6720: You can change the semantics of the most-recently defined word:
6721:
1.44 crook 6722:
1.26 crook 6723: doc-immediate
6724: doc-compile-only
6725: doc-restrict
6726:
1.44 crook 6727:
1.26 crook 6728: Note that ticking (@code{'}) a compile-only word gives an error
6729: (``Interpreting a compile-only word'').
1.1 anton 6730:
1.47 crook 6731: @menu
6732: * Combined words::
6733: @end menu
1.44 crook 6734:
1.48 anton 6735: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6736: @subsection Combined Words
6737: @cindex combined words
6738:
6739: Gforth allows you to define @dfn{combined words} -- words that have an
6740: arbitrary combination of interpretation and compilation semantics.
6741:
1.1 anton 6742:
1.26 crook 6743: doc-interpret/compile:
1.1 anton 6744:
1.44 crook 6745:
1.26 crook 6746: This feature was introduced for implementing @code{TO} and @code{S"}. I
6747: recommend that you do not define such words, as cute as they may be:
6748: they make it hard to get at both parts of the word in some contexts.
6749: E.g., assume you want to get an execution token for the compilation
6750: part. Instead, define two words, one that embodies the interpretation
6751: part, and one that embodies the compilation part. Once you have done
6752: that, you can define a combined word with @code{interpret/compile:} for
6753: the convenience of your users.
1.1 anton 6754:
1.26 crook 6755: You might try to use this feature to provide an optimizing
6756: implementation of the default compilation semantics of a word. For
6757: example, by defining:
1.1 anton 6758: @example
1.26 crook 6759: :noname
6760: foo bar ;
6761: :noname
6762: POSTPONE foo POSTPONE bar ;
1.29 crook 6763: interpret/compile: opti-foobar
1.1 anton 6764: @end example
1.26 crook 6765:
1.23 crook 6766: @noindent
1.26 crook 6767: as an optimizing version of:
6768:
1.1 anton 6769: @example
1.26 crook 6770: : foobar
6771: foo bar ;
1.1 anton 6772: @end example
6773:
1.26 crook 6774: Unfortunately, this does not work correctly with @code{[compile]},
6775: because @code{[compile]} assumes that the compilation semantics of all
6776: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6777: opti-foobar} would compile compilation semantics, whereas
6778: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6779:
1.26 crook 6780: @cindex state-smart words (are a bad idea)
1.29 crook 6781: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6782: by @code{interpret/compile:} (words are state-smart if they check
6783: @code{STATE} during execution). E.g., they would try to code
6784: @code{foobar} like this:
1.1 anton 6785:
1.26 crook 6786: @example
6787: : foobar
6788: STATE @@
6789: IF ( compilation state )
6790: POSTPONE foo POSTPONE bar
6791: ELSE
6792: foo bar
6793: ENDIF ; immediate
6794: @end example
1.1 anton 6795:
1.26 crook 6796: Although this works if @code{foobar} is only processed by the text
6797: interpreter, it does not work in other contexts (like @code{'} or
6798: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6799: for a state-smart word, not for the interpretation semantics of the
6800: original @code{foobar}; when you execute this execution token (directly
6801: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6802: state, the result will not be what you expected (i.e., it will not
6803: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6804: write them@footnote{For a more detailed discussion of this topic, see
6805: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
6806: Ertl; presented at EuroForth '98 and available from
1.47 crook 6807: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz}}!
1.1 anton 6808:
1.26 crook 6809: @cindex defining words with arbitrary semantics combinations
6810: It is also possible to write defining words that define words with
6811: arbitrary combinations of interpretation and compilation semantics. In
6812: general, they look like this:
1.1 anton 6813:
1.26 crook 6814: @example
6815: : def-word
6816: create-interpret/compile
1.29 crook 6817: @i{code1}
1.26 crook 6818: interpretation>
1.29 crook 6819: @i{code2}
1.26 crook 6820: <interpretation
6821: compilation>
1.29 crook 6822: @i{code3}
1.26 crook 6823: <compilation ;
6824: @end example
1.1 anton 6825:
1.29 crook 6826: For a @i{word} defined with @code{def-word}, the interpretation
6827: semantics are to push the address of the body of @i{word} and perform
6828: @i{code2}, and the compilation semantics are to push the address of
6829: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 6830: can also be defined like this (except that the defined constants don't
6831: behave correctly when @code{[compile]}d):
1.1 anton 6832:
1.26 crook 6833: @example
6834: : constant ( n "name" -- )
6835: create-interpret/compile
6836: ,
6837: interpretation> ( -- n )
6838: @@
6839: <interpretation
6840: compilation> ( compilation. -- ; run-time. -- n )
6841: @@ postpone literal
6842: <compilation ;
6843: @end example
1.1 anton 6844:
1.44 crook 6845:
1.26 crook 6846: doc-create-interpret/compile
6847: doc-interpretation>
6848: doc-<interpretation
6849: doc-compilation>
6850: doc-<compilation
1.1 anton 6851:
1.44 crook 6852:
1.29 crook 6853: Words defined with @code{interpret/compile:} and
1.26 crook 6854: @code{create-interpret/compile} have an extended header structure that
6855: differs from other words; however, unless you try to access them with
6856: plain address arithmetic, you should not notice this. Words for
6857: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 6858: @code{'} @i{word} @code{>body} also gives you the body of a word created
6859: with @code{create-interpret/compile}.
1.1 anton 6860:
1.44 crook 6861:
1.27 crook 6862: doc-postpone
1.44 crook 6863:
1.29 crook 6864: @comment TODO -- expand glossary text for POSTPONE
1.27 crook 6865:
1.47 crook 6866:
6867: @c -------------------------------------------------------------
6868: @node Tokens for Words, The Text Interpreter, Interpretation and Compilation Semantics, Words
6869: @section Tokens for Words
6870: @cindex tokens for words
6871:
6872: This section describes the creation and use of tokens that represent
6873: words.
6874:
6875: Named words have information stored in their header space entries to
6876: indicate any non-default semantics (@pxref{Interpretation and
6877: Compilation Semantics}). The semantics can be modified, using
6878: @code{immediate} and/or @code{compile-only}, at the time that the words
6879: are defined. Unnamed words have (by definition) no header space
6880: entry, and therefore must have default semantics.
6881:
6882: Named words have interpretation and compilation semantics. Unnamed words
6883: just have execution semantics.
6884:
6885: @cindex xt
6886: @cindex execution token
6887: The execution semantics of an unnamed word are represented by an
6888: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
6889: the execution token of the last word defined can be produced with
6890: @code{lastxt}.
6891:
6892: The interpretation semantics of a named word are also represented by an
6893: execution token. You can produce the execution token using @code{'} or
6894: @code{[']}. A simple example shows the difference between the two:
6895:
6896: @example
6897: : greet ( -- ) ." Hello" ;
6898: : foo ( -- xt ) ['] greet execute ; \ ['] parses greet at compile-time
6899: : bar ( -- ) ' execute ; \ ' parses at run-time
6900:
6901: \ the next four lines all do the same thing
6902: foo
6903: bar greet
6904: greet
6905: ' greet EXECUTE
6906: @end example
6907:
6908: An execution token occupies one cell.
6909: @cindex code field address
6910: @cindex CFA
6911: In Gforth, the abstract data type @i{execution token} is implemented
6912: as a code field address (CFA).
6913: @comment TODO note that the standard does not say what it represents..
6914: @comment and you cannot necessarily compile it in all Forths (eg native
6915: @comment compilers?).
6916:
6917: For literals, use @code{'} in interpreted code and @code{[']} in
6918: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
6919: unusually by complaining about compile-only words. To get the execution
6920: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
6921: or @code{[COMP'] @i{name} DROP}.
6922:
6923: @cindex compilation token
6924: The compilation semantics of a named word are represented by a
6925: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
6926: @i{xt} is an execution token. The compilation semantics represented by
6927: the compilation token can be performed with @code{execute}, which
6928: consumes the whole compilation token, with an additional stack effect
6929: determined by the represented compilation semantics.
6930:
6931: At present, the @i{w} part of a compilation token is an execution token,
6932: and the @i{xt} part represents either @code{execute} or
6933: @code{compile,}@footnote{Depending upon the compilation semantics of the
6934: word. If the word has default compilation semantics, the @i{xt} will
6935: represent @code{compile,}. Otherwise (e.g., for immediate words), the
6936: @i{xt} will represent @code{execute}.}. However, don't rely on that
6937: knowledge, unless necessary; future versions of Gforth may introduce
6938: unusual compilation tokens (e.g., a compilation token that represents
6939: the compilation semantics of a literal).
6940:
6941: You can compile the compilation semantics with @code{postpone,}. I.e.,
6942: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
6943: @i{word}}.
6944:
6945: @cindex name token
6946: @cindex name field address
6947: @cindex NFA
6948: Named words are also represented by the @dfn{name token}, (@i{nt}). In
6949: Gforth, the abstract data type @emph{name token} is implemented as a
6950: name field address (NFA).
6951:
6952:
6953: doc-execute
6954: doc-perform
6955: doc-compile,
6956: doc-[']
6957: doc-'
6958: doc-[comp']
6959: doc-comp'
6960: doc-postpone,
6961:
6962: doc-find-name
6963: doc-name>int
6964: doc-name?int
6965: doc-name>comp
6966: doc-name>string
6967:
6968:
1.26 crook 6969: @c ----------------------------------------------------------
1.47 crook 6970: @node The Text Interpreter, Word Lists, Tokens for Words, Words
1.26 crook 6971: @section The Text Interpreter
6972: @cindex interpreter - outer
6973: @cindex text interpreter
6974: @cindex outer interpreter
1.1 anton 6975:
1.34 anton 6976: @c Should we really describe all these ugly details? IMO the text
6977: @c interpreter should be much cleaner, but that may not be possible within
6978: @c ANS Forth. - anton
1.44 crook 6979: @c nac-> I wanted to explain how it works to show how you can exploit
6980: @c it in your own programs. When I was writing a cross-compiler, figuring out
6981: @c some of these gory details was very helpful to me. None of the textbooks
6982: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
6983: @c seems to positively avoid going into too much detail for some of
6984: @c the internals.
1.34 anton 6985:
1.29 crook 6986: The text interpreter@footnote{This is an expanded version of the
6987: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 6988: that processes input from the current input device. It is also called
6989: the outer interpreter, in contrast to the inner interpreter
6990: (@pxref{Engine}) which executes the compiled Forth code on interpretive
6991: implementations.
1.27 crook 6992:
1.29 crook 6993: @cindex interpret state
6994: @cindex compile state
6995: The text interpreter operates in one of two states: @dfn{interpret
6996: state} and @dfn{compile state}. The current state is defined by the
6997: aptly-named variable, @code{state}.
6998:
6999: This section starts by describing how the text interpreter behaves when
7000: it is in interpret state, processing input from the user input device --
7001: the keyboard. This is the mode that a Forth system is in after it starts
7002: up.
7003:
7004: @cindex input buffer
7005: @cindex terminal input buffer
7006: The text interpreter works from an area of memory called the @dfn{input
7007: buffer}@footnote{When the text interpreter is processing input from the
7008: keyboard, this area of memory is called the @dfn{terminal input buffer}
7009: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7010: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7011: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7012: leading spaces (called @dfn{delimiters}) then parses a string (a
7013: sequence of non-space characters) until it reaches either a space
7014: character or the end of the buffer. Having parsed a string, it makes two
7015: attempts to process it:
1.27 crook 7016:
1.29 crook 7017: @cindex dictionary
1.27 crook 7018: @itemize @bullet
7019: @item
1.29 crook 7020: It looks for the string in a @dfn{dictionary} of definitions. If the
7021: string is found, the string names a @dfn{definition} (also known as a
7022: @dfn{word}) and the dictionary search returns information that allows
7023: the text interpreter to perform the word's @dfn{interpretation
7024: semantics}. In most cases, this simply means that the word will be
7025: executed.
1.27 crook 7026: @item
7027: If the string is not found in the dictionary, the text interpreter
1.29 crook 7028: attempts to treat it as a number, using the rules described in
7029: @ref{Number Conversion}. If the string represents a legal number in the
7030: current radix, the number is pushed onto a parameter stack (the data
7031: stack for integers, the floating-point stack for floating-point
7032: numbers).
7033: @end itemize
7034:
7035: If both attempts fail, or if the word is found in the dictionary but has
7036: no interpretation semantics@footnote{This happens if the word was
7037: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7038: remainder of the input buffer, issues an error message and waits for
7039: more input. If one of the attempts succeeds, the text interpreter
7040: repeats the parsing process until the whole of the input buffer has been
7041: processed, at which point it prints the status message ``@code{ ok}''
7042: and waits for more input.
7043:
7044: @cindex parse area
7045: The text interpreter keeps track of its position in the input buffer by
7046: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7047: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7048: of the input buffer. The region from offset @code{>IN @@} to the end of
7049: the input buffer is called the @dfn{parse area}@footnote{In other words,
7050: the text interpreter processes the contents of the input buffer by
7051: parsing strings from the parse area until the parse area is empty.}.
7052: This example shows how @code{>IN} changes as the text interpreter parses
7053: the input buffer:
7054:
7055: @example
7056: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7057: CR ." ->" TYPE ." <-" ; IMMEDIATE
7058:
7059: 1 2 3 remaining + remaining .
7060:
7061: : foo 1 2 3 remaining SWAP remaining ;
7062: @end example
7063:
7064: @noindent
7065: The result is:
7066:
7067: @example
7068: ->+ remaining .<-
7069: ->.<-5 ok
7070:
7071: ->SWAP remaining ;-<
7072: ->;<- ok
7073: @end example
7074:
7075: @cindex parsing words
7076: The value of @code{>IN} can also be modified by a word in the input
7077: buffer that is executed by the text interpreter. This means that a word
7078: can ``trick'' the text interpreter into either skipping a section of the
7079: input buffer@footnote{This is how parsing words work.} or into parsing a
7080: section twice. For example:
1.27 crook 7081:
1.29 crook 7082: @example
7083: : lat ." <<lat>>" ;
7084: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
7085: @end example
7086:
7087: @noindent
7088: When @code{flat} is executed, this output is produced@footnote{Exercise
7089: for the reader: what would happen if the @code{3} were replaced with
7090: @code{4}?}:
7091:
7092: @example
7093: <<flat>><<lat>>
7094: @end example
7095:
7096: @noindent
7097: Two important notes about the behaviour of the text interpreter:
1.27 crook 7098:
7099: @itemize @bullet
7100: @item
7101: It processes each input string to completion before parsing additional
1.29 crook 7102: characters from the input buffer.
7103: @item
7104: It treats the input buffer as a read-only region (and so must your code).
7105: @end itemize
7106:
7107: @noindent
7108: When the text interpreter is in compile state, its behaviour changes in
7109: these ways:
7110:
7111: @itemize @bullet
7112: @item
7113: If a parsed string is found in the dictionary, the text interpreter will
7114: perform the word's @dfn{compilation semantics}. In most cases, this
7115: simply means that the execution semantics of the word will be appended
7116: to the current definition.
1.27 crook 7117: @item
1.29 crook 7118: When a number is encountered, it is compiled into the current definition
7119: (as a literal) rather than being pushed onto a parameter stack.
7120: @item
7121: If an error occurs, @code{state} is modified to put the text interpreter
7122: back into interpret state.
7123: @item
7124: Each time a line is entered from the keyboard, Gforth prints
7125: ``@code{ compiled}'' rather than `` @code{ok}''.
7126: @end itemize
7127:
7128: @cindex text interpreter - input sources
7129: When the text interpreter is using an input device other than the
7130: keyboard, its behaviour changes in these ways:
7131:
7132: @itemize @bullet
7133: @item
7134: When the parse area is empty, the text interpreter attempts to refill
7135: the input buffer from the input source. When the input source is
7136: exhausted, the input source is set back to the user input device.
7137: @item
7138: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7139: time the parse area is emptied.
7140: @item
7141: If an error occurs, the input source is set back to the user input
7142: device.
1.27 crook 7143: @end itemize
1.21 crook 7144:
1.49 anton 7145: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7146:
1.26 crook 7147: doc->in
1.27 crook 7148: doc-source
7149:
1.26 crook 7150: doc-tib
7151: doc-#tib
1.1 anton 7152:
1.44 crook 7153:
1.26 crook 7154: @menu
1.29 crook 7155: * Input Sources::
1.26 crook 7156: * Number Conversion::
7157: * Interpret/Compile states::
7158: * Literals::
7159: * Interpreter Directives::
7160: @end menu
1.1 anton 7161:
1.29 crook 7162: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7163: @subsection Input Sources
7164: @cindex input sources
7165: @cindex text interpreter - input sources
7166:
1.44 crook 7167: By default, the text interpreter processes input from the user input
1.29 crook 7168: device (the keyboard) when Forth starts up. The text interpreter can
7169: process input from any of these sources:
7170:
7171: @itemize @bullet
7172: @item
7173: The user input device -- the keyboard.
7174: @item
7175: A file, using the words described in @ref{Forth source files}.
7176: @item
7177: A block, using the words described in @ref{Blocks}.
7178: @item
7179: A text string, using @code{evaluate}.
7180: @end itemize
7181:
7182: A program can identify the current input device from the values of
7183: @code{source-id} and @code{blk}.
7184:
1.44 crook 7185:
1.29 crook 7186: doc-source-id
7187: doc-blk
7188:
7189: doc-save-input
7190: doc-restore-input
7191:
7192: doc-evaluate
1.1 anton 7193:
1.29 crook 7194:
1.44 crook 7195:
1.29 crook 7196: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7197: @subsection Number Conversion
7198: @cindex number conversion
7199: @cindex double-cell numbers, input format
7200: @cindex input format for double-cell numbers
7201: @cindex single-cell numbers, input format
7202: @cindex input format for single-cell numbers
7203: @cindex floating-point numbers, input format
7204: @cindex input format for floating-point numbers
1.1 anton 7205:
1.29 crook 7206: This section describes the rules that the text interpreter uses when it
7207: tries to convert a string into a number.
1.1 anton 7208:
1.26 crook 7209: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7210: number base@footnote{For example, 0-9 when the number base is decimal or
7211: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7212:
1.26 crook 7213: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7214:
1.29 crook 7215: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7216: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7217:
1.26 crook 7218: Let * represent any number of instances of the previous character
7219: (including none).
1.1 anton 7220:
1.26 crook 7221: Let any other character represent itself.
1.1 anton 7222:
1.29 crook 7223: @noindent
1.26 crook 7224: Now, the conversion rules are:
1.21 crook 7225:
1.26 crook 7226: @itemize @bullet
7227: @item
7228: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7229: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7230: @item
7231: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7232: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7233: arithmetic. Examples are -45 -5681 -0
7234: @item
7235: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7236: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7237: (all three of these represent the same number).
1.26 crook 7238: @item
7239: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7240: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7241: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7242: -34.65 (all three of these represent the same number).
1.26 crook 7243: @item
1.29 crook 7244: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7245: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7246: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7247: number) +12.E-4
1.26 crook 7248: @end itemize
1.1 anton 7249:
1.26 crook 7250: By default, the number base used for integer number conversion is given
1.35 anton 7251: by the contents of the variable @code{base}. Note that a lot of
7252: confusion can result from unexpected values of @code{base}. If you
7253: change @code{base} anywhere, make sure to save the old value and restore
7254: it afterwards. In general I recommend keeping @code{base} decimal, and
7255: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7256:
1.29 crook 7257: doc-dpl
1.26 crook 7258: doc-base
7259: doc-hex
7260: doc-decimal
1.1 anton 7261:
1.44 crook 7262:
1.26 crook 7263: @cindex '-prefix for character strings
7264: @cindex &-prefix for decimal numbers
7265: @cindex %-prefix for binary numbers
7266: @cindex $-prefix for hexadecimal numbers
1.35 anton 7267: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7268: prefix@footnote{Some Forth implementations provide a similar scheme by
7269: implementing @code{$} etc. as parsing words that process the subsequent
7270: number in the input stream and push it onto the stack. For example, see
7271: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7272: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7273: is required between the prefix and the number.} before the first digit
7274: of an (integer) number. Four prefixes are supported:
1.1 anton 7275:
1.26 crook 7276: @itemize @bullet
7277: @item
1.35 anton 7278: @code{&} -- decimal
1.26 crook 7279: @item
1.35 anton 7280: @code{%} -- binary
1.26 crook 7281: @item
1.35 anton 7282: @code{$} -- hexadecimal
1.26 crook 7283: @item
1.35 anton 7284: @code{'} -- base @code{max-char+1}
1.26 crook 7285: @end itemize
1.1 anton 7286:
1.26 crook 7287: Here are some examples, with the equivalent decimal number shown after
7288: in braces:
1.1 anton 7289:
1.26 crook 7290: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
7291: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
7292: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
7293: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7294:
1.26 crook 7295: @cindex number conversion - traps for the unwary
1.29 crook 7296: @noindent
1.26 crook 7297: Number conversion has a number of traps for the unwary:
1.1 anton 7298:
1.26 crook 7299: @itemize @bullet
7300: @item
7301: You cannot determine the current number base using the code sequence
1.35 anton 7302: @code{base @@ .} -- the number base is always 10 in the current number
7303: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7304: @item
7305: If the number base is set to a value greater than 14 (for example,
7306: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7307: it to be intepreted as either a single-precision integer or a
7308: floating-point number (Gforth treats it as an integer). The ambiguity
7309: can be resolved by explicitly stating the sign of the mantissa and/or
7310: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7311: ambiguity arises; either representation will be treated as a
7312: floating-point number.
7313: @item
1.29 crook 7314: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7315: It is used to specify file types.
7316: @item
7317: ANS Forth requires the @code{.} of a double-precision number to
7318: be the final character in the string. Allowing the @code{.} to be
7319: anywhere after the first digit is a Gforth extension.
7320: @item
7321: The number conversion process does not check for overflow.
7322: @item
7323: In Gforth, number conversion to floating-point numbers always use base
1.35 anton 7324: 10, irrespective of the value of @code{base}. In ANS Forth,
1.26 crook 7325: conversion to floating-point numbers whilst the value of
1.35 anton 7326: @code{base} is not 10 is an ambiguous condition.
1.26 crook 7327: @end itemize
1.1 anton 7328:
1.49 anton 7329: You can read numbers into your programs with the words described in
7330: @ref{Input}.
1.1 anton 7331:
1.26 crook 7332: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
7333: @subsection Interpret/Compile states
7334: @cindex Interpret/Compile states
1.1 anton 7335:
1.29 crook 7336: A standard program is not permitted to change @code{state}
7337: explicitly. However, it can change @code{state} implicitly, using the
7338: words @code{[} and @code{]}. When @code{[} is executed it switches
7339: @code{state} to interpret state, and therefore the text interpreter
7340: starts interpreting. When @code{]} is executed it switches @code{state}
7341: to compile state and therefore the text interpreter starts
1.44 crook 7342: compiling. The most common usage for these words is for switching into
7343: interpret state and back from within a colon definition; this technique
1.49 anton 7344: can be used to compile a literal (for an example, @pxref{Literals}) or
7345: for conditional compilation (for an example, @pxref{Interpreter
7346: Directives}).
1.44 crook 7347:
1.35 anton 7348:
7349: @c This is a bad example: It's non-standard, and it's not necessary.
7350: @c However, I can't think of a good example for switching into compile
7351: @c state when there is no current word (@code{state}-smart words are not a
7352: @c good reason). So maybe we should use an example for switching into
7353: @c interpret @code{state} in a colon def. - anton
1.44 crook 7354: @c nac-> I agree. I started out by putting in the example, then realised
7355: @c that it was non-ANS, so wrote more words around it. I hope this
7356: @c re-written version is acceptable to you. I do want to keep the example
7357: @c as it is helpful for showing what is and what is not portable, particularly
7358: @c where it outlaws a style in common use.
7359:
1.35 anton 7360:
1.44 crook 7361: @code{[} and @code{]} also give you the ability to switch into compile
7362: state and back, but we cannot think of any useful Standard application
7363: for this ability. Pre-ANS Forth textbooks have examples like this:
1.29 crook 7364:
7365: @example
7366: : AA ." this is A" ;
7367: : BB ." this is B" ;
7368: : CC ." this is C" ;
7369:
1.44 crook 7370: create table ] aa bb cc [
7371:
1.29 crook 7372: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7373: cells table + @ execute ;
7374: @end example
7375:
1.44 crook 7376: This example builds a jump table; @code{0 go} will display ``@code{this
7377: is A}''. Using @code{[} and @code{]} in this example is equivalent to
7378: defining @code{table} like this:
1.29 crook 7379:
7380: @example
1.44 crook 7381: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
1.29 crook 7382: @end example
7383:
1.44 crook 7384: The problem with this code is that the definition of @code{table} is not
7385: portable -- it @i{compile}s execution tokens into code space. Whilst it
7386: @i{may} work on systems where code space and data space co-incide, the
1.29 crook 7387: Standard only allows data space to be assigned for a @code{CREATE}d
7388: word. In addition, the Standard only allows @code{@@} to access data
7389: space, whilst this example is using it to access code space. The only
7390: portable, Standard way to build this table is to build it in data space,
7391: like this:
7392:
7393: @example
7394: create table ' aa , ' bb , ' cc ,
7395: @end example
7396:
1.26 crook 7397: doc-state
7398: doc-[
7399: doc-]
1.1 anton 7400:
1.44 crook 7401:
1.26 crook 7402: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
7403: @subsection Literals
7404: @cindex Literals
1.21 crook 7405:
1.29 crook 7406: Often, you want to use a number within a colon definition. When you do
7407: this, the text interpreter automatically compiles the number as a
7408: @i{literal}. A literal is a number whose run-time effect is to be pushed
7409: onto the stack. If you had to do some maths to generate the number, you
7410: might write it like this:
7411:
7412: @example
7413: : HOUR-TO-SEC ( n1 -- n2 )
7414: 60 * \ to minutes
7415: 60 * ; \ to seconds
7416: @end example
7417:
7418: It is very clear what this definition is doing, but it's inefficient
7419: since it is performing 2 multiples at run-time. An alternative would be
7420: to write:
7421:
7422: @example
7423: : HOUR-TO-SEC ( n1 -- n2 )
7424: 3600 * ; \ to seconds
7425: @end example
7426:
7427: Which does the same thing, and has the advantage of using a single
7428: multiply. Ideally, we'd like the efficiency of the second with the
7429: readability of the first.
7430:
7431: @code{Literal} allows us to achieve that. It takes a number from the
7432: stack and lays it down in the current definition just as though the
7433: number had been typed directly into the definition. Our first attempt
7434: might look like this:
7435:
7436: @example
7437: 60 \ mins per hour
7438: 60 * \ seconds per minute
7439: : HOUR-TO-SEC ( n1 -- n2 )
7440: Literal * ; \ to seconds
7441: @end example
7442:
7443: But this produces the error message @code{unstructured}. What happened?
7444: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
7445: @i{colon-sys} is implementation-defined. In other words, once we start a
7446: colon definition we can't portably access anything that was on the stack
7447: before the definition began@footnote{@cite{Two Problems in ANS Forth},
7448: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
7449: some situations where you might want to access stack items above
7450: colon-sys, and provides a solution to the problem.}. The correct way of
7451: solving this problem in this instance is to use @code{[ ]} like this:
7452:
7453: @example
7454: : HOUR-TO-SEC ( n1 -- n2 )
7455: [ 60 \ minutes per hour
7456: 60 * ] \ seconds per minute
7457: LITERAL * ; \ to seconds
7458: @end example
1.23 crook 7459:
1.44 crook 7460:
1.26 crook 7461: doc-literal
7462: doc-]L
7463: doc-2literal
7464: doc-fliteral
1.1 anton 7465:
1.44 crook 7466:
1.48 anton 7467: @node Interpreter Directives, , Literals, The Text Interpreter
1.26 crook 7468: @subsection Interpreter Directives
7469: @cindex interpreter directives
1.1 anton 7470:
1.29 crook 7471: These words are usually used in interpret state; typically to control
7472: which parts of a source file are processed by the text
1.26 crook 7473: interpreter. There are only a few ANS Forth Standard words, but Gforth
7474: supplements these with a rich set of immediate control structure words
7475: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7476: used in compile state (@pxref{Control Structures}). Typical usages:
7477:
7478: @example
7479: FALSE Constant ASSEMBLER
7480: .
7481: .
7482: ASSEMBLER [IF]
7483: : ASSEMBLER-FEATURE
7484: ...
7485: ;
7486: [ENDIF]
7487: .
7488: .
7489: : SEE
7490: ... \ general-purpose SEE code
7491: [ ASSEMBLER [IF] ]
7492: ... \ assembler-specific SEE code
7493: [ [ENDIF] ]
7494: ;
7495: @end example
1.1 anton 7496:
1.44 crook 7497:
1.26 crook 7498: doc-[IF]
7499: doc-[ELSE]
7500: doc-[THEN]
7501: doc-[ENDIF]
1.1 anton 7502:
1.26 crook 7503: doc-[IFDEF]
7504: doc-[IFUNDEF]
1.1 anton 7505:
1.26 crook 7506: doc-[?DO]
7507: doc-[DO]
7508: doc-[FOR]
7509: doc-[LOOP]
7510: doc-[+LOOP]
7511: doc-[NEXT]
1.1 anton 7512:
1.26 crook 7513: doc-[BEGIN]
7514: doc-[UNTIL]
7515: doc-[AGAIN]
7516: doc-[WHILE]
7517: doc-[REPEAT]
1.1 anton 7518:
1.27 crook 7519:
1.26 crook 7520: @c -------------------------------------------------------------
1.47 crook 7521: @node Word Lists, Environmental Queries, The Text Interpreter, Words
1.26 crook 7522: @section Word Lists
7523: @cindex word lists
1.32 anton 7524: @cindex header space
1.1 anton 7525:
1.36 anton 7526: A wordlist is a list of named words; you can add new words and look up
7527: words by name (and you can remove words in a restricted way with
7528: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7529:
7530: @cindex search order stack
7531: The text interpreter searches the wordlists present in the search order
7532: (a stack of wordlists), from the top to the bottom. Within each
7533: wordlist, the search starts conceptually at the newest word; i.e., if
7534: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7535:
1.26 crook 7536: @cindex compilation word list
1.36 anton 7537: New words are added to the @dfn{compilation wordlist} (aka current
7538: wordlist).
1.1 anton 7539:
1.36 anton 7540: @cindex wid
7541: A word list is identified by a cell-sized word list identifier (@i{wid})
7542: in much the same way as a file is identified by a file handle. The
7543: numerical value of the wid has no (portable) meaning, and might change
7544: from session to session.
1.1 anton 7545:
1.29 crook 7546: The ANS Forth ``Search order'' word set is intended to provide a set of
7547: low-level tools that allow various different schemes to be
1.26 crook 7548: implemented. Gforth provides @code{vocabulary}, a traditional Forth
7549: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 7550: Forth.
1.1 anton 7551:
1.27 crook 7552: @comment TODO: locals section refers to here, saying that every word list (aka
7553: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.1 anton 7554:
1.45 crook 7555: @comment TODO: document markers, reveal, tables, mappedwordlist
7556:
7557: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 7558: @comment word from the source files, rather than some alias.
1.44 crook 7559:
1.26 crook 7560: doc-forth-wordlist
7561: doc-definitions
7562: doc-get-current
7563: doc-set-current
7564: doc-get-order
1.45 crook 7565: doc---gforthman-set-order
1.26 crook 7566: doc-wordlist
1.30 anton 7567: doc-table
1.36 anton 7568: doc-push-order
7569: doc-previous
1.26 crook 7570: doc-also
1.45 crook 7571: doc---gforthman-forth
1.26 crook 7572: doc-only
1.45 crook 7573: doc---gforthman-order
1.15 anton 7574:
1.26 crook 7575: doc-find
7576: doc-search-wordlist
1.15 anton 7577:
1.26 crook 7578: doc-words
7579: doc-vlist
1.44 crook 7580: @c doc-words-deferred
1.1 anton 7581:
1.26 crook 7582: doc-mappedwordlist
7583: doc-root
7584: doc-vocabulary
7585: doc-seal
7586: doc-vocs
7587: doc-current
7588: doc-context
1.1 anton 7589:
1.44 crook 7590:
1.26 crook 7591: @menu
7592: * Why use word lists?::
7593: * Word list examples::
7594: @end menu
7595:
7596: @node Why use word lists?, Word list examples, Word Lists, Word Lists
7597: @subsection Why use word lists?
7598: @cindex word lists - why use them?
7599:
1.29 crook 7600: Here are some reasons for using multiple word lists:
1.26 crook 7601:
7602: @itemize @bullet
7603: @item
1.32 anton 7604: To improve compilation speed by reducing the number of header space
1.26 crook 7605: entries that must be searched. This is achieved by creating a new
7606: word list that contains all of the definitions that are used in the
7607: definition of a Forth system but which would not usually be used by
7608: programs running on that system. That word list would be on the search
7609: list when the Forth system was compiled but would be removed from the
7610: search list for normal operation. This can be a useful technique for
7611: low-performance systems (for example, 8-bit processors in embedded
7612: systems) but is unlikely to be necessary in high-performance desktop
7613: systems.
7614: @item
7615: To prevent a set of words from being used outside the context in which
7616: they are valid. Two classic examples of this are an integrated editor
7617: (all of the edit commands are defined in a separate word list; the
7618: search order is set to the editor word list when the editor is invoked;
7619: the old search order is restored when the editor is terminated) and an
7620: integrated assembler (the op-codes for the machine are defined in a
7621: separate word list which is used when a @code{CODE} word is defined).
7622: @item
7623: To prevent a name-space clash between multiple definitions with the same
7624: name. For example, when building a cross-compiler you might have a word
7625: @code{IF} that generates conditional code for your target system. By
7626: placing this definition in a different word list you can control whether
7627: the host system's @code{IF} or the target system's @code{IF} get used in
7628: any particular context by controlling the order of the word lists on the
7629: search order stack.
7630: @end itemize
1.1 anton 7631:
1.48 anton 7632: @node Word list examples, , Why use word lists?, Word Lists
1.26 crook 7633: @subsection Word list examples
7634: @cindex word lists - examples
1.1 anton 7635:
1.26 crook 7636: Here is an example of creating and using a new wordlist using ANS
7637: Forth Standard words:
1.1 anton 7638:
7639: @example
1.26 crook 7640: wordlist constant my-new-words-wordlist
7641: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
1.21 crook 7642:
1.26 crook 7643: \ add it to the search order
7644: also my-new-words
1.21 crook 7645:
1.26 crook 7646: \ alternatively, add it to the search order and make it
7647: \ the compilation word list
7648: also my-new-words definitions
7649: \ type "order" to see the problem
1.21 crook 7650: @end example
7651:
1.26 crook 7652: The problem with this example is that @code{order} has no way to
7653: associate the name @code{my-new-words} with the wid of the word list (in
7654: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7655: that has no associated name). There is no Standard way of associating a
7656: name with a wid.
7657:
7658: In Gforth, this example can be re-coded using @code{vocabulary}, which
7659: associates a name with a wid:
1.21 crook 7660:
1.26 crook 7661: @example
7662: vocabulary my-new-words
1.21 crook 7663:
1.26 crook 7664: \ add it to the search order
1.45 crook 7665: also my-new-words
1.21 crook 7666:
1.26 crook 7667: \ alternatively, add it to the search order and make it
7668: \ the compilation word list
7669: my-new-words definitions
7670: \ type "order" to see that the problem is solved
7671: @end example
1.23 crook 7672:
1.26 crook 7673: @c -------------------------------------------------------------
7674: @node Environmental Queries, Files, Word Lists, Words
7675: @section Environmental Queries
7676: @cindex environmental queries
1.21 crook 7677:
1.26 crook 7678: ANS Forth introduced the idea of ``environmental queries'' as a way
7679: for a program running on a system to determine certain characteristics of the system.
7680: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 7681:
1.32 anton 7682: The Standard requires that the header space used for environmental queries
7683: be distinct from the header space used for definitions.
1.21 crook 7684:
1.26 crook 7685: Typically, environmental queries are supported by creating a set of
1.29 crook 7686: definitions in a word list that is @i{only} used during environmental
1.26 crook 7687: queries; that is what Gforth does. There is no Standard way of adding
7688: definitions to the set of recognised environmental queries, but any
7689: implementation that supports the loading of optional word sets must have
7690: some mechanism for doing this (after loading the word set, the
7691: associated environmental query string must return @code{true}). In
7692: Gforth, the word list used to honour environmental queries can be
7693: manipulated just like any other word list.
1.21 crook 7694:
1.44 crook 7695:
1.26 crook 7696: doc-environment?
7697: doc-environment-wordlist
1.21 crook 7698:
1.26 crook 7699: doc-gforth
7700: doc-os-class
1.21 crook 7701:
1.44 crook 7702:
1.26 crook 7703: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
7704: returning two items on the stack, querying it using @code{environment?}
7705: will return an additional item; the @code{true} flag that shows that the
7706: string was recognised.
1.21 crook 7707:
1.26 crook 7708: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 7709:
1.26 crook 7710: Here are some examples of using environmental queries:
1.21 crook 7711:
1.26 crook 7712: @example
7713: s" address-unit-bits" environment? 0=
7714: [IF]
7715: cr .( environmental attribute address-units-bits unknown... ) cr
7716: [THEN]
1.21 crook 7717:
1.26 crook 7718: s" block" environment? [IF] DROP include block.fs [THEN]
1.21 crook 7719:
1.26 crook 7720: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
1.21 crook 7721:
1.26 crook 7722: s" gforth" environment? [IF] .( Gforth version ) TYPE
7723: [ELSE] .( Not Gforth..) [THEN]
7724: @end example
1.21 crook 7725:
7726:
1.26 crook 7727: Here is an example of adding a definition to the environment word list:
1.21 crook 7728:
1.26 crook 7729: @example
7730: get-current environment-wordlist set-current
7731: true constant block
7732: true constant block-ext
7733: set-current
7734: @end example
1.21 crook 7735:
1.26 crook 7736: You can see what definitions are in the environment word list like this:
1.21 crook 7737:
1.26 crook 7738: @example
7739: get-order 1+ environment-wordlist swap set-order words previous
7740: @end example
1.21 crook 7741:
7742:
1.26 crook 7743: @c -------------------------------------------------------------
7744: @node Files, Blocks, Environmental Queries, Words
7745: @section Files
1.28 crook 7746: @cindex files
7747: @cindex I/O - file-handling
1.21 crook 7748:
1.26 crook 7749: Gforth provides facilities for accessing files that are stored in the
7750: host operating system's file-system. Files that are processed by Gforth
7751: can be divided into two categories:
1.21 crook 7752:
1.23 crook 7753: @itemize @bullet
7754: @item
1.29 crook 7755: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 7756: @item
1.29 crook 7757: Files that are processed by some other program (@dfn{general files}).
1.26 crook 7758: @end itemize
7759:
1.45 crook 7760: doc-loadfilename
7761: doc-sourcefilename
7762: doc-sourceline#
7763:
1.26 crook 7764: @menu
1.48 anton 7765: * Forth source files::
7766: * General files::
7767: * Search Paths::
1.26 crook 7768: @end menu
7769:
1.21 crook 7770:
1.26 crook 7771: @c -------------------------------------------------------------
7772: @node Forth source files, General files, Files, Files
7773: @subsection Forth source files
7774: @cindex including files
7775: @cindex Forth source files
1.21 crook 7776:
1.26 crook 7777: The simplest way to interpret the contents of a file is to use one of
7778: these two formats:
1.21 crook 7779:
1.26 crook 7780: @example
7781: include mysource.fs
7782: s" mysource.fs" included
7783: @end example
1.21 crook 7784:
1.26 crook 7785: Sometimes you want to include a file only if it is not included already
7786: (by, say, another source file). In that case, you can use one of these
1.45 crook 7787: three formats:
1.21 crook 7788:
1.26 crook 7789: @example
7790: require mysource.fs
7791: needs mysource.fs
7792: s" mysource.fs" required
7793: @end example
1.21 crook 7794:
1.26 crook 7795: @cindex stack effect of included files
7796: @cindex including files, stack effect
1.45 crook 7797: It is good practice to write your source files such that interpreting them
7798: does not change the stack. Source files designed in this way can be used with
1.26 crook 7799: @code{required} and friends without complications. For example:
1.21 crook 7800:
1.26 crook 7801: @example
7802: 1 require foo.fs drop
7803: @end example
1.21 crook 7804:
1.44 crook 7805:
1.26 crook 7806: doc-include-file
7807: doc-included
1.28 crook 7808: doc-included?
1.26 crook 7809: doc-include
7810: doc-required
7811: doc-require
7812: doc-needs
1.28 crook 7813: doc-init-included-files
1.21 crook 7814:
1.44 crook 7815:
1.26 crook 7816: A definition in ANS Forth for @code{required} is provided in
7817: @file{compat/required.fs}.
1.21 crook 7818:
1.26 crook 7819: @c -------------------------------------------------------------
7820: @node General files, Search Paths, Forth source files, Files
7821: @subsection General files
7822: @cindex general files
7823: @cindex file-handling
1.21 crook 7824:
1.26 crook 7825: Files are opened/created by name and type. The following types are
7826: recognised:
1.1 anton 7827:
1.44 crook 7828:
1.26 crook 7829: doc-r/o
7830: doc-r/w
7831: doc-w/o
7832: doc-bin
1.1 anton 7833:
1.44 crook 7834:
1.26 crook 7835: When a file is opened/created, it returns a file identifier,
1.29 crook 7836: @i{wfileid} that is used for all other file commands. All file
7837: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 7838: successful operation and an implementation-defined non-zero value in the
7839: case of an error.
1.21 crook 7840:
1.44 crook 7841:
1.26 crook 7842: doc-open-file
7843: doc-create-file
1.21 crook 7844:
1.26 crook 7845: doc-close-file
7846: doc-delete-file
7847: doc-rename-file
7848: doc-read-file
7849: doc-read-line
7850: doc-write-file
7851: doc-write-line
7852: doc-emit-file
7853: doc-flush-file
1.21 crook 7854:
1.26 crook 7855: doc-file-status
7856: doc-file-position
7857: doc-reposition-file
7858: doc-file-size
7859: doc-resize-file
1.21 crook 7860:
1.44 crook 7861:
1.26 crook 7862: @c ---------------------------------------------------------
1.48 anton 7863: @node Search Paths, , General files, Files
1.26 crook 7864: @subsection Search Paths
7865: @cindex path for @code{included}
7866: @cindex file search path
7867: @cindex @code{include} search path
7868: @cindex search path for files
1.21 crook 7869:
1.26 crook 7870: If you specify an absolute filename (i.e., a filename starting with
7871: @file{/} or @file{~}, or with @file{:} in the second position (as in
7872: @samp{C:...})) for @code{included} and friends, that file is included
7873: just as you would expect.
1.21 crook 7874:
1.26 crook 7875: For relative filenames, Gforth uses a search path similar to Forth's
7876: search order (@pxref{Word Lists}). It tries to find the given filename
7877: in the directories present in the path, and includes the first one it
7878: finds. There are separate search paths for Forth source files and
7879: general files.
1.21 crook 7880:
1.26 crook 7881: If the search path contains the directory @file{.} (as it should), this
7882: refers to the directory that the present file was @code{included}
7883: from. This allows files to include other files relative to their own
7884: position (irrespective of the current working directory or the absolute
7885: position). This feature is essential for libraries consisting of
7886: several files, where a file may include other files from the library.
7887: It corresponds to @code{#include "..."} in C. If the current input
7888: source is not a file, @file{.} refers to the directory of the innermost
7889: file being included, or, if there is no file being included, to the
7890: current working directory.
1.21 crook 7891:
1.26 crook 7892: Use @file{~+} to refer to the current working directory (as in the
7893: @code{bash}).
1.1 anton 7894:
1.26 crook 7895: If the filename starts with @file{./}, the search path is not searched
7896: (just as with absolute filenames), and the @file{.} has the same meaning
7897: as described above.
1.1 anton 7898:
1.48 anton 7899: @menu
7900: * Forth Search Paths::
7901: * General Search Paths::
7902: @end menu
7903:
1.26 crook 7904: @c ---------------------------------------------------------
1.48 anton 7905: @node Forth Search Paths, General Search Paths, Search Paths, Search Paths
1.26 crook 7906: @subsubsection Forth Search Paths
1.28 crook 7907: @cindex search path control - Forth
1.5 anton 7908:
1.26 crook 7909: The search path is initialized when you start Gforth (@pxref{Invoking
7910: Gforth}). You can display it and change it using these words:
1.5 anton 7911:
1.44 crook 7912:
1.26 crook 7913: doc-.fpath
7914: doc-fpath+
7915: doc-fpath=
7916: doc-open-fpath-file
1.5 anton 7917:
1.44 crook 7918:
7919: @noindent
1.26 crook 7920: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 7921:
1.26 crook 7922: @example
7923: fpath= /usr/lib/forth/|./
7924: require timer.fs
7925: @end example
1.5 anton 7926:
1.26 crook 7927: @c ---------------------------------------------------------
1.48 anton 7928: @node General Search Paths, , Forth Search Paths, Search Paths
1.26 crook 7929: @subsubsection General Search Paths
7930: @cindex search path control - for user applications
1.5 anton 7931:
1.26 crook 7932: Your application may need to search files in several directories, like
7933: @code{included} does. To facilitate this, Gforth allows you to define
7934: and use your own search paths, by providing generic equivalents of the
7935: Forth search path words:
1.5 anton 7936:
1.44 crook 7937:
1.26 crook 7938: doc-.path
7939: doc-path+
7940: doc-path=
7941: doc-open-path-file
1.5 anton 7942:
1.44 crook 7943:
1.26 crook 7944: Here's an example of creating a search path:
1.5 anton 7945:
1.26 crook 7946: @example
7947: \ Make a buffer for the path:
7948: create mypath 100 chars , \ maximum length (is checked)
7949: 0 , \ real len
7950: 100 chars allot \ space for path
7951: @end example
1.5 anton 7952:
1.26 crook 7953: @c -------------------------------------------------------------
7954: @node Blocks, Other I/O, Files, Words
7955: @section Blocks
1.28 crook 7956: @cindex I/O - blocks
7957: @cindex blocks
7958:
7959: When you run Gforth on a modern desk-top computer, it runs under the
7960: control of an operating system which provides certain services. One of
7961: these services is @var{file services}, which allows Forth source code
7962: and data to be stored in files and read into Gforth (@pxref{Files}).
7963:
7964: Traditionally, Forth has been an important programming language on
7965: systems where it has interfaced directly to the underlying hardware with
7966: no intervening operating system. Forth provides a mechanism, called
1.29 crook 7967: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 7968:
7969: A block is a 1024-byte data area, which can be used to hold data or
7970: Forth source code. No structure is imposed on the contents of the
7971: block. A block is identified by its number; blocks are numbered
7972: contiguously from 1 to an implementation-defined maximum.
7973:
7974: A typical system that used blocks but no operating system might use a
7975: single floppy-disk drive for mass storage, with the disks formatted to
7976: provide 256-byte sectors. Blocks would be implemented by assigning the
7977: first four sectors of the disk to block 1, the second four sectors to
7978: block 2 and so on, up to the limit of the capacity of the disk. The disk
7979: would not contain any file system information, just the set of blocks.
7980:
1.29 crook 7981: @cindex blocks file
1.28 crook 7982: On systems that do provide file services, blocks are typically
1.29 crook 7983: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 7984: file}. The size of the blocks file will be an exact multiple of 1024
7985: bytes, corresponding to the number of blocks it contains. This is the
7986: mechanism that Gforth uses.
7987:
1.29 crook 7988: @cindex @file{blocks.fb}
1.28 crook 7989: Only 1 blocks file can be open at a time. If you use block words without
7990: having specified a blocks file, Gforth defaults to the blocks file
7991: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
7992: locate a blocks file (@pxref{Forth Search Paths}).
7993:
1.29 crook 7994: @cindex block buffers
1.28 crook 7995: When you read and write blocks under program control, Gforth uses a
1.29 crook 7996: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 7997: not used when you use @code{load} to interpret the contents of a block.
7998:
7999: The behaviour of the block buffers is directly analagous to that of a
8000: cache. Each block buffer has three states:
8001:
8002: @itemize @bullet
8003: @item
8004: Unassigned
8005: @item
8006: Assigned-clean
8007: @item
8008: Assigned-dirty
8009: @end itemize
8010:
1.29 crook 8011: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8012: block, the block (specified by its block number) must be assigned to a
8013: block buffer.
8014:
8015: The assignment of a block to a block buffer is performed by @code{block}
8016: or @code{buffer}. Use @code{block} when you wish to modify the existing
8017: contents of a block. Use @code{buffer} when you don't care about the
8018: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8019: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8020: with the particular block is already stored in a block buffer due to an
8021: earlier @code{block} command, @code{buffer} will return that block
8022: buffer and the existing contents of the block will be
8023: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8024: block buffer for the block.}.
1.28 crook 8025:
1.47 crook 8026: Once a block has been assigned to a block buffer using @code{block} or
8027: @code{buffer}, that block buffer becomes the @i{current block buffer}
8028: and its state changes to @i{assigned-clean}. Data may only be
8029: manipulated (read or written) within the current block buffer.
8030:
8031: When the contents of the current block buffer has been modified it is
1.48 anton 8032: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
8033: either abandon the changes (by doing nothing) or commit the changes,
8034: using @code{update}. Using @code{update} does not change the blocks
8035: file; it simply changes a block buffer's state to @i{assigned-dirty}.
1.28 crook 8036:
1.29 crook 8037: The word @code{flush} causes all @i{assigned-dirty} blocks to be
1.28 crook 8038: written back to the blocks file on disk. Leaving Gforth using @code{bye}
8039: also causes a @code{flush} to be performed.
8040:
1.29 crook 8041: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8042: algorithm to assign a block buffer to a block. That means that any
8043: particular block can only be assigned to one specific block buffer,
1.29 crook 8044: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8045: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8046: the new block immediately. If it is @i{assigned-dirty} its current
8047: contents are written back to the blocks file on disk before it is
1.28 crook 8048: allocated to the new block.
8049:
8050: Although no structure is imposed on the contents of a block, it is
8051: traditional to display the contents as 16 lines each of 64 characters. A
8052: block provides a single, continuous stream of input (for example, it
8053: acts as a single parse area) -- there are no end-of-line characters
8054: within a block, and no end-of-file character at the end of a
8055: block. There are two consequences of this:
1.26 crook 8056:
1.28 crook 8057: @itemize @bullet
8058: @item
8059: The last character of one line wraps straight into the first character
8060: of the following line
8061: @item
8062: The word @code{\} -- comment to end of line -- requires special
8063: treatment; in the context of a block it causes all characters until the
8064: end of the current 64-character ``line'' to be ignored.
8065: @end itemize
8066:
8067: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8068: the current blocks file will be extended to the appropriate size and the
1.28 crook 8069: block buffer will be initialised with spaces.
8070:
1.47 crook 8071: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8072: for details) but doesn't encourage the use of blocks; the mechanism is
8073: only provided for backward compatibility -- ANS Forth requires blocks to
8074: be available when files are.
1.28 crook 8075:
8076: Common techniques that are used when working with blocks include:
8077:
8078: @itemize @bullet
8079: @item
8080: A screen editor that allows you to edit blocks without leaving the Forth
8081: environment.
8082: @item
8083: Shadow screens; where every code block has an associated block
8084: containing comments (for example: code in odd block numbers, comments in
8085: even block numbers). Typically, the block editor provides a convenient
8086: mechanism to toggle between code and comments.
8087: @item
8088: Load blocks; a single block (typically block 1) contains a number of
8089: @code{thru} commands which @code{load} the whole of the application.
8090: @end itemize
1.26 crook 8091:
1.29 crook 8092: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8093: integrated into a Forth programming environment.
1.26 crook 8094:
8095: @comment TODO what about errors on open-blocks?
1.44 crook 8096:
1.26 crook 8097: doc-open-blocks
8098: doc-use
8099: doc-get-block-fid
8100: doc-block-position
1.28 crook 8101:
8102: doc-scr
8103: doc-list
8104:
1.45 crook 8105: doc---gforthman-block
1.28 crook 8106: doc-buffer
8107:
1.26 crook 8108: doc-update
1.28 crook 8109: doc-updated?
1.26 crook 8110: doc-save-buffers
8111: doc-empty-buffers
8112: doc-empty-buffer
8113: doc-flush
1.28 crook 8114:
1.26 crook 8115: doc-load
8116: doc-thru
8117: doc-+load
8118: doc-+thru
1.45 crook 8119: doc---gforthman--->
1.26 crook 8120: doc-block-included
8121:
1.44 crook 8122:
1.26 crook 8123: @c -------------------------------------------------------------
8124: @node Other I/O, Programming Tools, Blocks, Words
8125: @section Other I/O
1.28 crook 8126: @cindex I/O - keyboard and display
1.26 crook 8127:
8128: @menu
8129: * Simple numeric output:: Predefined formats
8130: * Formatted numeric output:: Formatted (pictured) output
8131: * String Formats:: How Forth stores strings in memory
8132: * Displaying characters and strings:: Other stuff
8133: * Input:: Input
8134: @end menu
8135:
8136: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8137: @subsection Simple numeric output
1.28 crook 8138: @cindex numeric output - simple/free-format
1.5 anton 8139:
1.26 crook 8140: The simplest output functions are those that display numbers from the
8141: data or floating-point stacks. Floating-point output is always displayed
8142: using base 10. Numbers displayed from the data stack use the value stored
8143: in @code{base}.
1.5 anton 8144:
1.44 crook 8145:
1.26 crook 8146: doc-.
8147: doc-dec.
8148: doc-hex.
8149: doc-u.
8150: doc-.r
8151: doc-u.r
8152: doc-d.
8153: doc-ud.
8154: doc-d.r
8155: doc-ud.r
8156: doc-f.
8157: doc-fe.
8158: doc-fs.
1.5 anton 8159:
1.44 crook 8160:
1.26 crook 8161: Examples of printing the number 1234.5678E23 in the different floating-point output
8162: formats are shown below:
1.5 anton 8163:
8164: @example
1.26 crook 8165: f. 123456779999999000000000000.
8166: fe. 123.456779999999E24
8167: fs. 1.23456779999999E26
1.5 anton 8168: @end example
8169:
8170:
1.26 crook 8171: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8172: @subsection Formatted numeric output
1.28 crook 8173: @cindex formatted numeric output
1.26 crook 8174: @cindex pictured numeric output
1.28 crook 8175: @cindex numeric output - formatted
1.26 crook 8176:
1.29 crook 8177: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8178: output} for formatted printing of integers. In this technique, digits
8179: are extracted from the number (using the current output radix defined by
8180: @code{base}), converted to ASCII codes and appended to a string that is
8181: built in a scratch-pad area of memory (@pxref{core-idef,
8182: Implementation-defined options, Implementation-defined
8183: options}). Arbitrary characters can be appended to the string during the
8184: extraction process. The completed string is specified by an address
8185: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8186: under program control.
1.5 anton 8187:
1.26 crook 8188: All of the words described in the previous section for simple numeric
8189: output are implemented in Gforth using pictured numeric output.
1.5 anton 8190:
1.47 crook 8191: Three important things to remember about pictured numeric output:
1.5 anton 8192:
1.26 crook 8193: @itemize @bullet
8194: @item
1.28 crook 8195: It always operates on double-precision numbers; to display a
1.49 anton 8196: single-precision number, convert it first (for ways of doing this
8197: @pxref{Double precision}).
1.26 crook 8198: @item
1.28 crook 8199: It always treats the double-precision number as though it were
8200: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8201: @item
8202: The string is built up from right to left; least significant digit first.
8203: @end itemize
1.5 anton 8204:
1.44 crook 8205:
1.26 crook 8206: doc-<#
1.47 crook 8207: doc-<<#
1.26 crook 8208: doc-#
8209: doc-#s
8210: doc-hold
8211: doc-sign
8212: doc-#>
1.47 crook 8213: doc-#>>
1.5 anton 8214:
1.26 crook 8215: doc-represent
1.5 anton 8216:
1.44 crook 8217:
8218: @noindent
1.26 crook 8219: Here are some examples of using pictured numeric output:
1.5 anton 8220:
8221: @example
1.26 crook 8222: : my-u. ( u -- )
8223: \ Simplest use of pns.. behaves like Standard u.
8224: 0 \ convert to unsigned double
8225: <# \ start conversion
8226: #s \ convert all digits
8227: #> \ complete conversion
8228: TYPE SPACE ; \ display, with trailing space
1.5 anton 8229:
1.26 crook 8230: : cents-only ( u -- )
8231: 0 \ convert to unsigned double
8232: <# \ start conversion
8233: # # \ convert two least-significant digits
8234: #> \ complete conversion, discard other digits
8235: TYPE SPACE ; \ display, with trailing space
1.5 anton 8236:
1.26 crook 8237: : dollars-and-cents ( u -- )
8238: 0 \ convert to unsigned double
8239: <# \ start conversion
8240: # # \ convert two least-significant digits
8241: [char] . hold \ insert decimal point
8242: #s \ convert remaining digits
8243: [char] $ hold \ append currency symbol
8244: #> \ complete conversion
8245: TYPE SPACE ; \ display, with trailing space
1.5 anton 8246:
1.26 crook 8247: : my-. ( n -- )
8248: \ handling negatives.. behaves like Standard .
8249: s>d \ convert to signed double
8250: swap over dabs \ leave sign byte followed by unsigned double
8251: <# \ start conversion
8252: #s \ convert all digits
8253: rot sign \ get at sign byte, append "-" if needed
8254: #> \ complete conversion
8255: TYPE SPACE ; \ display, with trailing space
1.5 anton 8256:
1.26 crook 8257: : account. ( n -- )
8258: \ accountants don't like minus signs, they use braces
8259: \ for negative numbers
8260: s>d \ convert to signed double
8261: swap over dabs \ leave sign byte followed by unsigned double
8262: <# \ start conversion
8263: 2 pick \ get copy of sign byte
8264: 0< IF [char] ) hold THEN \ right-most character of output
8265: #s \ convert all digits
8266: rot \ get at sign byte
8267: 0< IF [char] ( hold THEN
8268: #> \ complete conversion
8269: TYPE SPACE ; \ display, with trailing space
1.5 anton 8270: @end example
8271:
1.26 crook 8272: Here are some examples of using these words:
1.5 anton 8273:
8274: @example
1.26 crook 8275: 1 my-u. 1
8276: hex -1 my-u. decimal FFFFFFFF
8277: 1 cents-only 01
8278: 1234 cents-only 34
8279: 2 dollars-and-cents $0.02
8280: 1234 dollars-and-cents $12.34
8281: 123 my-. 123
8282: -123 my. -123
8283: 123 account. 123
8284: -456 account. (456)
1.5 anton 8285: @end example
8286:
8287:
1.26 crook 8288: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8289: @subsection String Formats
1.27 crook 8290: @cindex strings - see character strings
8291: @cindex character strings - formats
1.28 crook 8292: @cindex I/O - see character strings
1.26 crook 8293:
1.27 crook 8294: Forth commonly uses two different methods for representing character
8295: strings:
1.26 crook 8296:
8297: @itemize @bullet
8298: @item
8299: @cindex address of counted string
1.45 crook 8300: @cindex counted string
1.29 crook 8301: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8302: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8303: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8304: memory.
8305: @item
1.29 crook 8306: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8307: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8308: first byte of the string.
8309: @end itemize
8310:
8311: ANS Forth encourages the use of the second format when representing
8312: strings on the stack, whilst conceeding that the counted string format
8313: remains useful as a way of storing strings in memory.
8314:
1.44 crook 8315:
1.26 crook 8316: doc-count
8317:
1.44 crook 8318:
1.49 anton 8319: For words that move, copy and search for strings see @ref{Memory
8320: Blocks}. For words that display characters and strings see
8321: @ref{Displaying characters and strings}.
1.26 crook 8322:
8323: @node Displaying characters and strings, Input, String Formats, Other I/O
8324: @subsection Displaying characters and strings
1.27 crook 8325: @cindex characters - compiling and displaying
8326: @cindex character strings - compiling and displaying
1.26 crook 8327:
8328: This section starts with a glossary of Forth words and ends with a set
8329: of examples.
8330:
1.44 crook 8331:
1.26 crook 8332: doc-bl
8333: doc-space
8334: doc-spaces
8335: doc-emit
8336: doc-toupper
8337: doc-."
8338: doc-.(
8339: doc-type
1.44 crook 8340: doc-typewhite
1.26 crook 8341: doc-cr
1.27 crook 8342: @cindex cursor control
1.26 crook 8343: doc-at-xy
8344: doc-page
8345: doc-s"
8346: doc-c"
8347: doc-char
8348: doc-[char]
8349: doc-sliteral
8350:
1.44 crook 8351:
8352: @noindent
1.26 crook 8353: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8354:
8355: @example
1.26 crook 8356: .( text-1)
8357: : my-word
8358: ." text-2" cr
8359: .( text-3)
8360: ;
8361:
8362: ." text-4"
8363:
8364: : my-char
8365: [char] ALPHABET emit
8366: char emit
8367: ;
1.5 anton 8368: @end example
8369:
1.26 crook 8370: When you load this code into Gforth, the following output is generated:
1.5 anton 8371:
1.26 crook 8372: @example
1.30 anton 8373: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8374: @end example
1.5 anton 8375:
1.26 crook 8376: @itemize @bullet
8377: @item
8378: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8379: is an immediate word; it behaves in the same way whether it is used inside
8380: or outside a colon definition.
8381: @item
8382: Message @code{text-4} is displayed because of Gforth's added interpretation
8383: semantics for @code{."}.
8384: @item
1.29 crook 8385: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8386: performs the compilation semantics for @code{."} within the definition of
8387: @code{my-word}.
8388: @end itemize
1.5 anton 8389:
1.26 crook 8390: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8391:
1.26 crook 8392: @example
1.30 anton 8393: @kbd{my-word @key{RET}} text-2
1.26 crook 8394: ok
1.30 anton 8395: @kbd{my-char fred @key{RET}} Af ok
8396: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 8397: @end example
1.5 anton 8398:
8399: @itemize @bullet
8400: @item
1.26 crook 8401: Message @code{text-2} is displayed because of the run-time behaviour of
8402: @code{."}.
8403: @item
8404: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8405: on the stack at run-time. @code{emit} always displays the character
8406: when @code{my-char} is executed.
8407: @item
8408: @code{char} parses a string at run-time and the second @code{emit} displays
8409: the first character of the string.
1.5 anton 8410: @item
1.26 crook 8411: If you type @code{see my-char} you can see that @code{[char]} discarded
8412: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8413: definition of @code{my-char}.
1.5 anton 8414: @end itemize
8415:
8416:
8417:
1.48 anton 8418: @node Input, , Displaying characters and strings, Other I/O
1.26 crook 8419: @subsection Input
8420: @cindex input
1.28 crook 8421: @cindex I/O - see input
8422: @cindex parsing a string
1.5 anton 8423:
1.49 anton 8424: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 8425:
1.27 crook 8426: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 8427: @comment then index them
1.27 crook 8428:
1.44 crook 8429:
1.27 crook 8430: doc-key
8431: doc-key?
1.45 crook 8432: doc-ekey
8433: doc-ekey?
8434: doc-ekey>char
1.26 crook 8435: doc->number
8436: doc->float
8437: doc-accept
1.27 crook 8438: doc-pad
8439: doc-parse
8440: doc-word
8441: doc-sword
1.44 crook 8442: doc-(name)
1.27 crook 8443: doc-refill
8444: @comment obsolescent words..
8445: doc-convert
1.26 crook 8446: doc-query
8447: doc-expect
1.27 crook 8448: doc-span
1.5 anton 8449:
8450:
1.44 crook 8451:
1.5 anton 8452: @c -------------------------------------------------------------
1.26 crook 8453: @node Programming Tools, Assembler and Code Words, Other I/O, Words
8454: @section Programming Tools
8455: @cindex programming tools
1.12 anton 8456:
8457: @menu
1.26 crook 8458: * Debugging:: Simple and quick.
8459: * Assertions:: Making your programs self-checking.
1.46 pazsan 8460: * Singlestep Debugger:: Executing your program word by word.
1.5 anton 8461: @end menu
8462:
1.26 crook 8463: @node Debugging, Assertions, Programming Tools, Programming Tools
8464: @subsection Debugging
8465: @cindex debugging
1.5 anton 8466:
1.26 crook 8467: Languages with a slow edit/compile/link/test development loop tend to
8468: require sophisticated tracing/stepping debuggers to facilate
8469: productive debugging.
1.5 anton 8470:
1.26 crook 8471: A much better (faster) way in fast-compiling languages is to add
8472: printing code at well-selected places, let the program run, look at
8473: the output, see where things went wrong, add more printing code, etc.,
8474: until the bug is found.
1.5 anton 8475:
1.26 crook 8476: The simple debugging aids provided in @file{debugs.fs}
8477: are meant to support this style of debugging. In addition, there are
8478: words for non-destructively inspecting the stack and memory:
1.5 anton 8479:
1.44 crook 8480:
1.26 crook 8481: doc-.s
8482: doc-f.s
1.5 anton 8483:
1.44 crook 8484:
1.29 crook 8485: There is a word @code{.r} but it does @i{not} display the return
1.26 crook 8486: stack! It is used for formatted numeric output.
1.5 anton 8487:
1.44 crook 8488:
1.26 crook 8489: doc-depth
8490: doc-fdepth
8491: doc-clearstack
8492: doc-?
8493: doc-dump
1.5 anton 8494:
1.44 crook 8495:
1.26 crook 8496: The word @code{~~} prints debugging information (by default the source
8497: location and the stack contents). It is easy to insert. If you use Emacs
8498: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
8499: query-replace them with nothing). The deferred words
8500: @code{printdebugdata} and @code{printdebugline} control the output of
8501: @code{~~}. The default source location output format works well with
8502: Emacs' compilation mode, so you can step through the program at the
8503: source level using @kbd{C-x `} (the advantage over a stepping debugger
8504: is that you can step in any direction and you know where the crash has
8505: happened or where the strange data has occurred).
1.5 anton 8506:
1.26 crook 8507: The default actions of @code{~~} clobber the contents of the pictured
8508: numeric output string, so you should not use @code{~~}, e.g., between
8509: @code{<#} and @code{#>}.
1.5 anton 8510:
1.44 crook 8511:
1.26 crook 8512: doc-~~
8513: doc-printdebugdata
8514: doc-printdebugline
1.5 anton 8515:
1.26 crook 8516: doc-see
8517: doc-marker
1.5 anton 8518:
1.44 crook 8519:
1.26 crook 8520: Here's an example of using @code{marker} at the start of a source file
8521: that you are debugging; it ensures that you only ever have one copy of
8522: the file's definitions compiled at any time:
1.5 anton 8523:
1.26 crook 8524: @example
8525: [IFDEF] my-code
8526: my-code
8527: [ENDIF]
1.5 anton 8528:
1.26 crook 8529: marker my-code
1.28 crook 8530: init-included-files
1.5 anton 8531:
1.26 crook 8532: \ .. definitions start here
8533: \ .
8534: \ .
8535: \ end
8536: @end example
1.5 anton 8537:
8538:
8539:
1.26 crook 8540: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
8541: @subsection Assertions
8542: @cindex assertions
1.5 anton 8543:
1.26 crook 8544: It is a good idea to make your programs self-checking, especially if you
8545: make an assumption that may become invalid during maintenance (for
8546: example, that a certain field of a data structure is never zero). Gforth
1.29 crook 8547: supports @dfn{assertions} for this purpose. They are used like this:
1.23 crook 8548:
1.26 crook 8549: @example
1.29 crook 8550: assert( @i{flag} )
1.26 crook 8551: @end example
1.23 crook 8552:
1.26 crook 8553: The code between @code{assert(} and @code{)} should compute a flag, that
8554: should be true if everything is alright and false otherwise. It should
8555: not change anything else on the stack. The overall stack effect of the
8556: assertion is @code{( -- )}. E.g.
1.23 crook 8557:
1.26 crook 8558: @example
8559: assert( 1 1 + 2 = ) \ what we learn in school
8560: assert( dup 0<> ) \ assert that the top of stack is not zero
8561: assert( false ) \ this code should not be reached
8562: @end example
1.23 crook 8563:
1.26 crook 8564: The need for assertions is different at different times. During
8565: debugging, we want more checking, in production we sometimes care more
8566: for speed. Therefore, assertions can be turned off, i.e., the assertion
8567: becomes a comment. Depending on the importance of an assertion and the
8568: time it takes to check it, you may want to turn off some assertions and
8569: keep others turned on. Gforth provides several levels of assertions for
8570: this purpose:
1.23 crook 8571:
1.44 crook 8572:
1.26 crook 8573: doc-assert0(
8574: doc-assert1(
8575: doc-assert2(
8576: doc-assert3(
8577: doc-assert(
8578: doc-)
1.23 crook 8579:
1.44 crook 8580:
1.26 crook 8581: The variable @code{assert-level} specifies the highest assertions that
8582: are turned on. I.e., at the default @code{assert-level} of one,
8583: @code{assert0(} and @code{assert1(} assertions perform checking, while
8584: @code{assert2(} and @code{assert3(} assertions are treated as comments.
8585:
8586: The value of @code{assert-level} is evaluated at compile-time, not at
8587: run-time. Therefore you cannot turn assertions on or off at run-time;
8588: you have to set the @code{assert-level} appropriately before compiling a
8589: piece of code. You can compile different pieces of code at different
8590: @code{assert-level}s (e.g., a trusted library at level 1 and
8591: newly-written code at level 3).
1.23 crook 8592:
1.44 crook 8593:
1.26 crook 8594: doc-assert-level
1.23 crook 8595:
1.44 crook 8596:
1.26 crook 8597: If an assertion fails, a message compatible with Emacs' compilation mode
8598: is produced and the execution is aborted (currently with @code{ABORT"}.
8599: If there is interest, we will introduce a special throw code. But if you
8600: intend to @code{catch} a specific condition, using @code{throw} is
8601: probably more appropriate than an assertion).
1.23 crook 8602:
1.26 crook 8603: Definitions in ANS Forth for these assertion words are provided
8604: in @file{compat/assert.fs}.
1.23 crook 8605:
8606:
1.48 anton 8607: @node Singlestep Debugger, , Assertions, Programming Tools
1.26 crook 8608: @subsection Singlestep Debugger
8609: @cindex singlestep Debugger
8610: @cindex debugging Singlestep
1.23 crook 8611:
1.26 crook 8612: When you create a new word there's often the need to check whether it
8613: behaves correctly or not. You can do this by typing @code{dbg
8614: badword}. A debug session might look like this:
1.23 crook 8615:
1.26 crook 8616: @example
8617: : badword 0 DO i . LOOP ; ok
8618: 2 dbg badword
8619: : badword
8620: Scanning code...
1.23 crook 8621:
1.26 crook 8622: Nesting debugger ready!
1.23 crook 8623:
1.26 crook 8624: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
8625: 400D4740 8049F68 DO -> [ 0 ]
8626: 400D4744 804A0C8 i -> [ 1 ] 00000
8627: 400D4748 400C5E60 . -> 0 [ 0 ]
8628: 400D474C 8049D0C LOOP -> [ 0 ]
8629: 400D4744 804A0C8 i -> [ 1 ] 00001
8630: 400D4748 400C5E60 . -> 1 [ 0 ]
8631: 400D474C 8049D0C LOOP -> [ 0 ]
8632: 400D4758 804B384 ; -> ok
8633: @end example
1.23 crook 8634:
1.26 crook 8635: Each line displayed is one step. You always have to hit return to
8636: execute the next word that is displayed. If you don't want to execute
8637: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
8638: an overview what keys are available:
1.23 crook 8639:
1.26 crook 8640: @table @i
1.23 crook 8641:
1.30 anton 8642: @item @key{RET}
1.26 crook 8643: Next; Execute the next word.
1.23 crook 8644:
1.26 crook 8645: @item n
8646: Nest; Single step through next word.
1.5 anton 8647:
1.26 crook 8648: @item u
8649: Unnest; Stop debugging and execute rest of word. If we got to this word
8650: with nest, continue debugging with the calling word.
1.5 anton 8651:
1.26 crook 8652: @item d
8653: Done; Stop debugging and execute rest.
1.5 anton 8654:
1.26 crook 8655: @item s
8656: Stop; Abort immediately.
1.5 anton 8657:
1.26 crook 8658: @end table
1.5 anton 8659:
1.26 crook 8660: Debugging large application with this mechanism is very difficult, because
8661: you have to nest very deeply into the program before the interesting part
8662: begins. This takes a lot of time.
1.5 anton 8663:
1.26 crook 8664: To do it more directly put a @code{BREAK:} command into your source code.
8665: When program execution reaches @code{BREAK:} the single step debugger is
8666: invoked and you have all the features described above.
1.23 crook 8667:
1.26 crook 8668: If you have more than one part to debug it is useful to know where the
8669: program has stopped at the moment. You can do this by the
8670: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
8671: string is typed out when the ``breakpoint'' is reached.
8672:
1.44 crook 8673:
1.26 crook 8674: doc-dbg
1.45 crook 8675: doc-break:
8676: doc-break"
1.26 crook 8677:
8678:
1.44 crook 8679:
1.26 crook 8680: @c -------------------------------------------------------------
8681: @node Assembler and Code Words, Threading Words, Programming Tools, Words
8682: @section Assembler and Code Words
8683: @cindex assembler
8684: @cindex code words
1.5 anton 8685:
1.52 anton 8686: @menu
1.53 anton 8687: * Code and ;code::
8688: * Common Assembler:: Assembler Syntax
1.52 anton 8689: * Common Disassembler::
8690: * 386 Assembler:: Deviations and special cases
8691: * Alpha Assembler:: Deviations and special cases
8692: * MIPS assembler:: Deviations and special cases
1.53 anton 8693: * Other assemblers:: How to write them
1.52 anton 8694: @end menu
8695:
1.53 anton 8696: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
8697: @subsection @code{Code} and @code{;code}
1.52 anton 8698:
1.26 crook 8699: Gforth provides some words for defining primitives (words written in
1.29 crook 8700: machine code), and for defining the machine-code equivalent of
1.26 crook 8701: @code{DOES>}-based defining words. However, the machine-independent
8702: nature of Gforth poses a few problems: First of all, Gforth runs on
8703: several architectures, so it can provide no standard assembler. What's
8704: worse is that the register allocation not only depends on the processor,
8705: but also on the @code{gcc} version and options used.
1.5 anton 8706:
1.29 crook 8707: The words that Gforth offers encapsulate some system dependences (e.g.,
8708: the header structure), so a system-independent assembler may be used in
1.26 crook 8709: Gforth. If you do not have an assembler, you can compile machine code
1.29 crook 8710: directly with @code{,} and @code{c,}@footnote{This isn't portable,
8711: because these words emit stuff in @i{data} space; it works because
8712: Gforth has unified code/data spaces. Assembler isn't likely to be
8713: portable anyway.}.
1.5 anton 8714:
1.44 crook 8715:
1.26 crook 8716: doc-assembler
1.45 crook 8717: doc-init-asm
1.26 crook 8718: doc-code
8719: doc-end-code
8720: doc-;code
8721: doc-flush-icache
1.5 anton 8722:
1.44 crook 8723:
1.26 crook 8724: If @code{flush-icache} does not work correctly, @code{code} words
8725: etc. will not work (reliably), either.
1.5 anton 8726:
1.29 crook 8727: The typical usage of these @code{code} words can be shown most easily by
8728: analogy to the equivalent high-level defining words:
8729:
8730: @example
1.53 anton 8731: : foo code foo
8732: <high-level Forth words> <assembler>
8733: ; end-code
8734:
8735: : bar : bar
8736: <high-level Forth words> <high-level Forth words>
8737: CREATE CREATE
8738: <high-level Forth words> <high-level Forth words>
8739: DOES> ;code
8740: <high-level Forth words> <assembler>
8741: ; end-code
1.29 crook 8742: @end example
8743:
1.26 crook 8744: @code{flush-icache} is always present. The other words are rarely used
8745: and reside in @code{code.fs}, which is usually not loaded. You can load
8746: it with @code{require code.fs}.
1.5 anton 8747:
1.26 crook 8748: @cindex registers of the inner interpreter
8749: In the assembly code you will want to refer to the inner interpreter's
8750: registers (e.g., the data stack pointer) and you may want to use other
8751: registers for temporary storage. Unfortunately, the register allocation
8752: is installation-dependent.
1.5 anton 8753:
1.26 crook 8754: The easiest solution is to use explicit register declarations
8755: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
8756: GNU C Manual}) for all of the inner interpreter's registers: You have to
8757: compile Gforth with @code{-DFORCE_REG} (configure option
8758: @code{--enable-force-reg}) and the appropriate declarations must be
8759: present in the @code{machine.h} file (see @code{mips.h} for an example;
8760: you can find a full list of all declarable register symbols with
8761: @code{grep register engine.c}). If you give explicit registers to all
8762: variables that are declared at the beginning of @code{engine()}, you
8763: should be able to use the other caller-saved registers for temporary
8764: storage. Alternatively, you can use the @code{gcc} option
8765: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
8766: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
8767: (however, this restriction on register allocation may slow Gforth
8768: significantly).
1.5 anton 8769:
1.26 crook 8770: If this solution is not viable (e.g., because @code{gcc} does not allow
8771: you to explicitly declare all the registers you need), you have to find
8772: out by looking at the code where the inner interpreter's registers
8773: reside and which registers can be used for temporary storage. You can
8774: get an assembly listing of the engine's code with @code{make engine.s}.
1.5 anton 8775:
1.26 crook 8776: In any case, it is good practice to abstract your assembly code from the
8777: actual register allocation. E.g., if the data stack pointer resides in
8778: register @code{$17}, create an alias for this register called @code{sp},
8779: and use that in your assembly code.
1.5 anton 8780:
1.26 crook 8781: @cindex code words, portable
8782: Another option for implementing normal and defining words efficiently
8783: is to add the desired functionality to the source of Gforth. For normal
8784: words you just have to edit @file{primitives} (@pxref{Automatic
8785: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
8786: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
8787: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5 anton 8788:
1.53 anton 8789: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
8790: @subsection Common Assembler
8791:
8792: The assemblers in Gforth generally use a postfix syntax, i.e., the
8793: instruction name follows the operands.
8794:
8795: The operands are passed in the usual order (the same that is used in the
8796: manual of the architecture). Since they all are Forth words, they have
8797: to be separated by spaces; you can also use Forth words to compute the
8798: operands.
8799:
8800: The instruction names usually end with a @code{,}. This makes it easier
8801: to visually separate instructions if you put several of them on one
8802: line; it also avoids shadowing other Forth words (e.g., @code{and}).
8803:
1.55 anton 8804: Registers are usually specified by number; e.g., (decimal) @code{11}
8805: specifies registers R11 and F11 on the Alpha architecture (which one,
8806: depends on the instruction). The usual names are also available, e.g.,
8807: @code{s2} for R11 on Alpha.
8808:
1.53 anton 8809: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
8810: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
8811: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
8812: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
8813: conditions are specified in a way specific to each assembler.
8814:
1.57 anton 8815: Note that the register assignments of the Gforth engine can change
8816: between Gforth versions, or even between different compilations of the
8817: same Gforth version (e.g., if you use a different GCC version). So if
8818: you want to refer to Gforth's registers (e.g., the stack pointer or
8819: TOS), I recommend defining your own words for refering to these
8820: registers, and using them later on; then you can easily adapt to a
8821: changed register assignment. The stability of the register assignment
8822: is usually better if you build Gforth with @code{--enable-force-reg}.
8823:
8824: In particular, the resturn stack pointer and the instruction pointer are
8825: in memory in @code{gforth}, and usually in registers in
8826: @code{gforth-fast}. The most common use of these registers is to
8827: dispatch to the next word (the @code{next} routine). A portable way to
8828: do this is to jump to @code{' noop >code-address} (of course, this is
8829: less efficient than integrating the @code{next} code and scheduling it
8830: well).
8831:
1.52 anton 8832: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
8833: @subsection Common Disassembler
8834:
8835: You can disassemble a @code{code} word with @code{see}
8836: (@pxref{Debugging}). You can disassemble a section of memory with
8837:
8838: doc-disasm
8839:
8840: The disassembler generally produces output that can be fed into the
8841: assembler (i.e., same syntax, etc.). It also includes additional
1.53 anton 8842: information in comments. In particular, the address of the instruction
8843: is given in a comment before the instruction.
8844:
8845: @code{See} may display more or less than the actual code of the word,
8846: because the recognition of the end of the code is unreliable. You can
8847: use @code{disasm} if it did not display enough. It may display more, if
8848: the code word is not immediately followed by a named word. If you have
8849: something else there, you can follow the word with @code{align last @ ,}
8850: to ensure that the end is recognized.
1.52 anton 8851:
8852: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
8853: @subsection 386 Assembler
8854:
1.64 ! pazsan 8855: The 386 assembler included in Gforth was written by Bernd Paysan, it's
! 8856: available under GPL, and originally part of bigFORTH.
! 8857:
! 8858: The 386 disassembler included in Gforth was written by Andrew McKewan
! 8859: and is in the public domain.
1.57 anton 8860:
8861: The disassembler displays code in prefix Intel syntax.
8862:
1.64 ! pazsan 8863: The assembler uses a postfix syntax with reversed parameters.
! 8864:
! 8865: The assembler includes all instruction of the Athlon, i.e. 486 core
! 8866: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
! 8867: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
! 8868: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
! 8869:
! 8870: There are several prefixes to switch between different operation sizes,
! 8871: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
! 8872: double-word accesses. Addressing modes can be switched with @code{.wa}
! 8873: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
! 8874: need a prefix for byte register names (@code{AL} et al).
! 8875:
! 8876: For floating point operations, the prefixes are @code{.fs} (IEEE
! 8877: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
! 8878: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
! 8879:
! 8880: The MMX opcodes don't have size prefixes, they are spelled out like in
! 8881: the Intel assembler. Instead of move from and to memory, there are
! 8882: PLDQ/PLDD and PSTQ/PSTD.
! 8883:
! 8884: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
! 8885: ax. Immediate values are indicated by postfixing them with @code{#},
! 8886: e.g., @code{3 #}. Here are some examples of addressing modes:
1.57 anton 8887:
8888: @example
8889: 3 #
1.64 ! pazsan 8890: ax
! 8891: 100 di d)
! 8892: 4 bx cx di)
! 8893: di ax *4 i)
! 8894: 20 ax *4 i#)
1.57 anton 8895: @end example
8896:
8897: Some example of instructions are:
8898:
8899: @example
1.64 ! pazsan 8900: ax bx mov \ move ebx,eax
! 8901: 3 # ax mov \ mov eax,3
! 8902: 100 di ) ax mov \ mov eax,100[edi]
! 8903: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
! 8904: .w ax bx mov \ mov bx,ax
1.57 anton 8905: @end example
8906:
1.64 ! pazsan 8907: The following forms are supported for binary instructions:
1.57 anton 8908:
8909: @example
8910: <reg> <reg> <inst>
8911: <n> # <reg> <inst>
8912: <mem> <reg> <inst>
8913: <reg> <mem> <inst>
8914: @end example
8915:
8916: Immediate to memory is not supported. The shift/rotate syntax is:
8917:
8918: @example
1.64 ! pazsan 8919: <reg/mem> 1 # shl \ shortens to shift without immediate
! 8920: <reg/mem> 4 # shl
! 8921: <reg/mem> cl shl
1.57 anton 8922: @end example
8923:
1.64 ! pazsan 8924: Precede string instructions (@code{movs} etc.) with @code{.b} to get
1.57 anton 8925: the byte version.
8926:
1.64 ! pazsan 8927: The control structure words @code{IF} @code{UNTIL} etc. must be
! 8928: preceded by one of these conditions:
! 8929: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps pc < >= <= >}. (Note that most
! 8930: of these words shadow some Forth words when @code{assembler} is before
1.57 anton 8931: @code{forth} in the search path, e.g., in code words). Currently the
8932: control structure words use one stack item, so you have to use
8933: @code{roll} instead of @code{cs-roll} to shuffle them (you can also use
8934: @code{swap} etc.).
1.52 anton 8935:
8936: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
8937: @subsection Alpha Assembler
8938:
1.55 anton 8939: The Alpha assembler and disassembler were originally written by Bernd
8940: Thallner.
8941:
8942: The register names @code{a0}--@code{a5} are not available to avoid
8943: shadowing hex numbers.
8944:
8945: Immediate forms of arithmetic instructions are distinguished by a
8946: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
8947: does not count as arithmetic instruction).
8948:
8949: You have to specify all operands to an instruction, even those that
8950: other assemblers consider optional, e.g., the destination register for
8951: @code{br,}, or the destination register and hint for @code{jmp,}.
8952:
8953: You can specify conditions for @code{if,} by removing the first @code{b}
8954: and the trailing @code{,} from a branch with a corresponding name; e.g.,
8955:
8956: @example
8957: 11 fgt if, \ if F11>0e
8958: ...
8959: endif,
1.56 anton 8960: @end example
1.55 anton 8961:
8962: @code{fbgt,} gives @code{fgt}.
1.52 anton 8963:
1.53 anton 8964: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
1.52 anton 8965: @subsection MIPS assembler
8966:
8967: The MIPS assembler was originally written by Christian Pirker.
8968:
8969: Currently the assembler and disassembler only cover the MIPS-I
8970: architecture (R3000), and don't support FP instructions.
8971:
1.55 anton 8972: The register names @code{$a0}--@code{$a3} are not available to avoid
8973: shadowing hex numbers.
1.52 anton 8974:
8975: Because there is no way to distinguish registers from immediate values,
8976: you have to explicitly use the immediate forms of instructions, i.e.,
8977: @code{addiu,}, not just @code{addu,} (@command{as} does this
8978: implicitly).
8979:
8980: If the architecture manual specifies several formats for the instruction
8981: (e.g., for @code{jalr,}), you usually have to use the one with more
8982: arguments (i.e., two for @code{jalr,}). When in doubt, see
8983: @code{arch/mips/testasm.fs} for an example of correct use.
8984:
1.53 anton 8985: Branches and jumps in the MIPS architecture have a delay slot. You have
8986: to fill it yourself (the simplest way is to use @code{nop,}), the
8987: assembler does not do it for you (unlike @command{as}). Even
8988: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
8989: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
8990: and @code{then,} just specify branch targets, they are not affected.
8991:
8992: Note that you must not put branches, jumps, or @code{li,} into the delay
8993: slot: @code{li,} may expand to several instructions, and control flow
8994: instructions may not be put into the branch delay slot in any case.
1.52 anton 8995:
8996: For branches the argument specifying the target is a relative address;
8997: You have to add the address of the delay slot to get the absolute
8998: address.
1.53 anton 8999:
9000: The MIPS architecture also has load delay slots and restrictions on
9001: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
9002: yourself to satisfy these restrictions, the assembler does not do it for
9003: you.
9004:
9005: You can specify the conditions for @code{if,} etc. by taking a
9006: conditional branch and leaving away the @code{b} at the start and the
9007: @code{,} at the end. E.g.,
9008:
9009: @example
9010: 4 5 eq if,
9011: ... \ do something if $4 equals $5
9012: then,
9013: @end example
9014:
9015: @node Other assemblers, , MIPS assembler, Assembler and Code Words
9016: @subsection Other assemblers
9017:
9018: If you want to contribute another assembler/disassembler, please contact
9019: us (@email{bug-gforth@@gnu.org}) to check if we have such an assembler
9020: already. If you are writing them from scratch, please use a similar
9021: syntax style as the one we use (i.e., postfix, commas at the end of the
9022: instruction names, @pxref{Common Assembler}); make the output of the
9023: disassembler be valid input for the assembler, and keep the style
9024: similar to the style we used.
9025:
9026: Hints on implementation: The most important part is to have a good test
9027: suite that contains all instructions. Once you have that, the rest is
9028: easy. For actual coding you can take a look at
9029: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
9030: the assembler and disassembler, avoiding redundancy and some potential
1.63 anton 9031: bugs. You can also look at that file (and @pxref{Advanced does> usage
9032: example}) to get ideas how to factor a disassembler.
1.5 anton 9033:
1.54 anton 9034: Start with the disassembler, because it's easier to reuse data from the
9035: disassembler for the assembler than the other way round.
9036:
9037: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
9038: how simple it can be.
9039:
1.26 crook 9040: @c -------------------------------------------------------------
9041: @node Threading Words, Locals, Assembler and Code Words, Words
9042: @section Threading Words
9043: @cindex threading words
1.5 anton 9044:
1.26 crook 9045: @cindex code address
9046: These words provide access to code addresses and other threading stuff
9047: in Gforth (and, possibly, other interpretive Forths). It more or less
9048: abstracts away the differences between direct and indirect threading
9049: (and, for direct threading, the machine dependences). However, at
9050: present this wordset is still incomplete. It is also pretty low-level;
9051: some day it will hopefully be made unnecessary by an internals wordset
9052: that abstracts implementation details away completely.
1.5 anton 9053:
1.44 crook 9054:
1.26 crook 9055: doc-threading-method
9056: doc->code-address
9057: doc->does-code
9058: doc-code-address!
9059: doc-does-code!
9060: doc-does-handler!
9061: doc-/does-handler
1.5 anton 9062:
1.44 crook 9063:
1.26 crook 9064: The code addresses produced by various defining words are produced by
9065: the following words:
1.5 anton 9066:
1.44 crook 9067:
1.26 crook 9068: doc-docol:
9069: doc-docon:
9070: doc-dovar:
9071: doc-douser:
9072: doc-dodefer:
9073: doc-dofield:
1.5 anton 9074:
1.44 crook 9075:
1.26 crook 9076: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
9077: with @code{>does-code}. If the word was defined in that way, the value
9078: returned is non-zero and identifies the @code{DOES>} used by the
9079: defining word.
9080: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5 anton 9081:
1.26 crook 9082: @c -------------------------------------------------------------
9083: @node Locals, Structures, Threading Words, Words
9084: @section Locals
9085: @cindex locals
1.5 anton 9086:
1.26 crook 9087: Local variables can make Forth programming more enjoyable and Forth
9088: programs easier to read. Unfortunately, the locals of ANS Forth are
9089: laden with restrictions. Therefore, we provide not only the ANS Forth
9090: locals wordset, but also our own, more powerful locals wordset (we
9091: implemented the ANS Forth locals wordset through our locals wordset).
1.5 anton 9092:
1.26 crook 9093: The ideas in this section have also been published in the paper
9094: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
9095: at EuroForth '94; it is available at
1.47 crook 9096: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
1.5 anton 9097:
1.26 crook 9098: @menu
9099: * Gforth locals::
9100: * ANS Forth locals::
9101: @end menu
1.5 anton 9102:
1.26 crook 9103: @node Gforth locals, ANS Forth locals, Locals, Locals
9104: @subsection Gforth locals
9105: @cindex Gforth locals
9106: @cindex locals, Gforth style
1.5 anton 9107:
1.26 crook 9108: Locals can be defined with
1.5 anton 9109:
9110: @example
1.26 crook 9111: @{ local1 local2 ... -- comment @}
9112: @end example
9113: or
9114: @example
9115: @{ local1 local2 ... @}
1.5 anton 9116: @end example
9117:
1.26 crook 9118: E.g.,
1.5 anton 9119: @example
1.26 crook 9120: : max @{ n1 n2 -- n3 @}
9121: n1 n2 > if
9122: n1
9123: else
9124: n2
9125: endif ;
1.5 anton 9126: @end example
9127:
1.26 crook 9128: The similarity of locals definitions with stack comments is intended. A
9129: locals definition often replaces the stack comment of a word. The order
9130: of the locals corresponds to the order in a stack comment and everything
9131: after the @code{--} is really a comment.
1.5 anton 9132:
1.26 crook 9133: This similarity has one disadvantage: It is too easy to confuse locals
9134: declarations with stack comments, causing bugs and making them hard to
9135: find. However, this problem can be avoided by appropriate coding
9136: conventions: Do not use both notations in the same program. If you do,
9137: they should be distinguished using additional means, e.g. by position.
9138:
9139: @cindex types of locals
9140: @cindex locals types
9141: The name of the local may be preceded by a type specifier, e.g.,
9142: @code{F:} for a floating point value:
9143:
9144: @example
9145: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9146: \ complex multiplication
9147: Ar Br f* Ai Bi f* f-
9148: Ar Bi f* Ai Br f* f+ ;
9149: @end example
9150:
9151: @cindex flavours of locals
9152: @cindex locals flavours
9153: @cindex value-flavoured locals
9154: @cindex variable-flavoured locals
9155: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9156: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9157: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9158: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9159: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9160: produces its address (which becomes invalid when the variable's scope is
9161: left). E.g., the standard word @code{emit} can be defined in terms of
9162: @code{type} like this:
1.5 anton 9163:
9164: @example
1.26 crook 9165: : emit @{ C^ char* -- @}
9166: char* 1 type ;
1.5 anton 9167: @end example
9168:
1.26 crook 9169: @cindex default type of locals
9170: @cindex locals, default type
9171: A local without type specifier is a @code{W:} local. Both flavours of
9172: locals are initialized with values from the data or FP stack.
1.5 anton 9173:
1.26 crook 9174: Currently there is no way to define locals with user-defined data
9175: structures, but we are working on it.
1.5 anton 9176:
1.26 crook 9177: Gforth allows defining locals everywhere in a colon definition. This
9178: poses the following questions:
1.5 anton 9179:
1.26 crook 9180: @menu
9181: * Where are locals visible by name?::
9182: * How long do locals live?::
9183: * Programming Style::
9184: * Implementation::
9185: @end menu
1.5 anton 9186:
1.26 crook 9187: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9188: @subsubsection Where are locals visible by name?
9189: @cindex locals visibility
9190: @cindex visibility of locals
9191: @cindex scope of locals
1.5 anton 9192:
1.26 crook 9193: Basically, the answer is that locals are visible where you would expect
9194: it in block-structured languages, and sometimes a little longer. If you
9195: want to restrict the scope of a local, enclose its definition in
9196: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9197:
1.44 crook 9198:
1.26 crook 9199: doc-scope
9200: doc-endscope
1.5 anton 9201:
1.44 crook 9202:
1.26 crook 9203: These words behave like control structure words, so you can use them
9204: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9205: arbitrary ways.
1.5 anton 9206:
1.26 crook 9207: If you want a more exact answer to the visibility question, here's the
9208: basic principle: A local is visible in all places that can only be
9209: reached through the definition of the local@footnote{In compiler
9210: construction terminology, all places dominated by the definition of the
9211: local.}. In other words, it is not visible in places that can be reached
9212: without going through the definition of the local. E.g., locals defined
9213: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9214: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9215: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5 anton 9216:
1.26 crook 9217: The reasoning behind this solution is: We want to have the locals
9218: visible as long as it is meaningful. The user can always make the
9219: visibility shorter by using explicit scoping. In a place that can
9220: only be reached through the definition of a local, the meaning of a
9221: local name is clear. In other places it is not: How is the local
9222: initialized at the control flow path that does not contain the
9223: definition? Which local is meant, if the same name is defined twice in
9224: two independent control flow paths?
1.5 anton 9225:
1.26 crook 9226: This should be enough detail for nearly all users, so you can skip the
9227: rest of this section. If you really must know all the gory details and
9228: options, read on.
1.5 anton 9229:
1.26 crook 9230: In order to implement this rule, the compiler has to know which places
9231: are unreachable. It knows this automatically after @code{AHEAD},
9232: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9233: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9234: compiler that the control flow never reaches that place. If
9235: @code{UNREACHABLE} is not used where it could, the only consequence is
9236: that the visibility of some locals is more limited than the rule above
9237: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9238: lie to the compiler), buggy code will be produced.
1.5 anton 9239:
1.44 crook 9240:
1.26 crook 9241: doc-unreachable
1.5 anton 9242:
1.44 crook 9243:
1.26 crook 9244: Another problem with this rule is that at @code{BEGIN}, the compiler
9245: does not know which locals will be visible on the incoming
9246: back-edge. All problems discussed in the following are due to this
9247: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9248: loops as examples; the discussion also applies to @code{?DO} and other
9249: loops). Perhaps the most insidious example is:
1.5 anton 9250: @example
1.26 crook 9251: AHEAD
9252: BEGIN
9253: x
9254: [ 1 CS-ROLL ] THEN
9255: @{ x @}
9256: ...
9257: UNTIL
9258: @end example
1.5 anton 9259:
1.26 crook 9260: This should be legal according to the visibility rule. The use of
9261: @code{x} can only be reached through the definition; but that appears
9262: textually below the use.
1.5 anton 9263:
1.26 crook 9264: From this example it is clear that the visibility rules cannot be fully
9265: implemented without major headaches. Our implementation treats common
9266: cases as advertised and the exceptions are treated in a safe way: The
9267: compiler makes a reasonable guess about the locals visible after a
9268: @code{BEGIN}; if it is too pessimistic, the
9269: user will get a spurious error about the local not being defined; if the
9270: compiler is too optimistic, it will notice this later and issue a
9271: warning. In the case above the compiler would complain about @code{x}
9272: being undefined at its use. You can see from the obscure examples in
9273: this section that it takes quite unusual control structures to get the
9274: compiler into trouble, and even then it will often do fine.
1.5 anton 9275:
1.26 crook 9276: If the @code{BEGIN} is reachable from above, the most optimistic guess
9277: is that all locals visible before the @code{BEGIN} will also be
9278: visible after the @code{BEGIN}. This guess is valid for all loops that
9279: are entered only through the @code{BEGIN}, in particular, for normal
9280: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9281: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9282: compiler. When the branch to the @code{BEGIN} is finally generated by
9283: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9284: warns the user if it was too optimistic:
9285: @example
9286: IF
9287: @{ x @}
9288: BEGIN
9289: \ x ?
9290: [ 1 cs-roll ] THEN
9291: ...
9292: UNTIL
1.5 anton 9293: @end example
9294:
1.26 crook 9295: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9296: optimistically assumes that it lives until the @code{THEN}. It notices
9297: this difference when it compiles the @code{UNTIL} and issues a
9298: warning. The user can avoid the warning, and make sure that @code{x}
9299: is not used in the wrong area by using explicit scoping:
9300: @example
9301: IF
9302: SCOPE
9303: @{ x @}
9304: ENDSCOPE
9305: BEGIN
9306: [ 1 cs-roll ] THEN
9307: ...
9308: UNTIL
9309: @end example
1.5 anton 9310:
1.26 crook 9311: Since the guess is optimistic, there will be no spurious error messages
9312: about undefined locals.
1.5 anton 9313:
1.26 crook 9314: If the @code{BEGIN} is not reachable from above (e.g., after
9315: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9316: optimistic guess, as the locals visible after the @code{BEGIN} may be
9317: defined later. Therefore, the compiler assumes that no locals are
9318: visible after the @code{BEGIN}. However, the user can use
9319: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9320: visible at the BEGIN as at the point where the top control-flow stack
9321: item was created.
1.5 anton 9322:
1.44 crook 9323:
1.26 crook 9324: doc-assume-live
1.5 anton 9325:
1.44 crook 9326:
9327: @noindent
1.26 crook 9328: E.g.,
1.5 anton 9329: @example
1.26 crook 9330: @{ x @}
9331: AHEAD
9332: ASSUME-LIVE
9333: BEGIN
9334: x
9335: [ 1 CS-ROLL ] THEN
9336: ...
9337: UNTIL
1.5 anton 9338: @end example
9339:
1.26 crook 9340: Other cases where the locals are defined before the @code{BEGIN} can be
9341: handled by inserting an appropriate @code{CS-ROLL} before the
9342: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9343: behind the @code{ASSUME-LIVE}).
1.5 anton 9344:
1.26 crook 9345: Cases where locals are defined after the @code{BEGIN} (but should be
9346: visible immediately after the @code{BEGIN}) can only be handled by
9347: rearranging the loop. E.g., the ``most insidious'' example above can be
9348: arranged into:
1.5 anton 9349: @example
1.26 crook 9350: BEGIN
9351: @{ x @}
9352: ... 0=
9353: WHILE
9354: x
9355: REPEAT
1.5 anton 9356: @end example
9357:
1.26 crook 9358: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
9359: @subsubsection How long do locals live?
9360: @cindex locals lifetime
9361: @cindex lifetime of locals
1.5 anton 9362:
1.26 crook 9363: The right answer for the lifetime question would be: A local lives at
9364: least as long as it can be accessed. For a value-flavoured local this
9365: means: until the end of its visibility. However, a variable-flavoured
9366: local could be accessed through its address far beyond its visibility
9367: scope. Ultimately, this would mean that such locals would have to be
9368: garbage collected. Since this entails un-Forth-like implementation
9369: complexities, I adopted the same cowardly solution as some other
9370: languages (e.g., C): The local lives only as long as it is visible;
9371: afterwards its address is invalid (and programs that access it
9372: afterwards are erroneous).
1.5 anton 9373:
1.26 crook 9374: @node Programming Style, Implementation, How long do locals live?, Gforth locals
9375: @subsubsection Programming Style
9376: @cindex locals programming style
9377: @cindex programming style, locals
1.5 anton 9378:
1.26 crook 9379: The freedom to define locals anywhere has the potential to change
9380: programming styles dramatically. In particular, the need to use the
9381: return stack for intermediate storage vanishes. Moreover, all stack
9382: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9383: determined arguments) can be eliminated: If the stack items are in the
9384: wrong order, just write a locals definition for all of them; then
9385: write the items in the order you want.
1.5 anton 9386:
1.26 crook 9387: This seems a little far-fetched and eliminating stack manipulations is
9388: unlikely to become a conscious programming objective. Still, the number
9389: of stack manipulations will be reduced dramatically if local variables
1.49 anton 9390: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
1.26 crook 9391: a traditional implementation of @code{max}).
1.5 anton 9392:
1.26 crook 9393: This shows one potential benefit of locals: making Forth programs more
9394: readable. Of course, this benefit will only be realized if the
9395: programmers continue to honour the principle of factoring instead of
9396: using the added latitude to make the words longer.
1.5 anton 9397:
1.26 crook 9398: @cindex single-assignment style for locals
9399: Using @code{TO} can and should be avoided. Without @code{TO},
9400: every value-flavoured local has only a single assignment and many
9401: advantages of functional languages apply to Forth. I.e., programs are
9402: easier to analyse, to optimize and to read: It is clear from the
9403: definition what the local stands for, it does not turn into something
9404: different later.
1.5 anton 9405:
1.26 crook 9406: E.g., a definition using @code{TO} might look like this:
1.5 anton 9407: @example
1.26 crook 9408: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9409: u1 u2 min 0
9410: ?do
9411: addr1 c@@ addr2 c@@ -
9412: ?dup-if
9413: unloop exit
9414: then
9415: addr1 char+ TO addr1
9416: addr2 char+ TO addr2
9417: loop
9418: u1 u2 - ;
1.5 anton 9419: @end example
1.26 crook 9420: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9421: every loop iteration. @code{strcmp} is a typical example of the
9422: readability problems of using @code{TO}. When you start reading
9423: @code{strcmp}, you think that @code{addr1} refers to the start of the
9424: string. Only near the end of the loop you realize that it is something
9425: else.
1.5 anton 9426:
1.26 crook 9427: This can be avoided by defining two locals at the start of the loop that
9428: are initialized with the right value for the current iteration.
1.5 anton 9429: @example
1.26 crook 9430: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9431: addr1 addr2
9432: u1 u2 min 0
9433: ?do @{ s1 s2 @}
9434: s1 c@@ s2 c@@ -
9435: ?dup-if
9436: unloop exit
9437: then
9438: s1 char+ s2 char+
9439: loop
9440: 2drop
9441: u1 u2 - ;
1.5 anton 9442: @end example
1.26 crook 9443: Here it is clear from the start that @code{s1} has a different value
9444: in every loop iteration.
1.5 anton 9445:
1.26 crook 9446: @node Implementation, , Programming Style, Gforth locals
9447: @subsubsection Implementation
9448: @cindex locals implementation
9449: @cindex implementation of locals
1.5 anton 9450:
1.26 crook 9451: @cindex locals stack
9452: Gforth uses an extra locals stack. The most compelling reason for
9453: this is that the return stack is not float-aligned; using an extra stack
9454: also eliminates the problems and restrictions of using the return stack
9455: as locals stack. Like the other stacks, the locals stack grows toward
9456: lower addresses. A few primitives allow an efficient implementation:
1.5 anton 9457:
1.44 crook 9458:
1.26 crook 9459: doc-@local#
9460: doc-f@local#
9461: doc-laddr#
9462: doc-lp+!#
9463: doc-lp!
9464: doc->l
9465: doc-f>l
1.5 anton 9466:
1.44 crook 9467:
1.26 crook 9468: In addition to these primitives, some specializations of these
9469: primitives for commonly occurring inline arguments are provided for
9470: efficiency reasons, e.g., @code{@@local0} as specialization of
9471: @code{@@local#} for the inline argument 0. The following compiling words
9472: compile the right specialized version, or the general version, as
9473: appropriate:
1.6 pazsan 9474:
1.44 crook 9475:
1.26 crook 9476: doc-compile-@local
9477: doc-compile-f@local
9478: doc-compile-lp+!
1.12 anton 9479:
1.44 crook 9480:
1.26 crook 9481: Combinations of conditional branches and @code{lp+!#} like
9482: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9483: is taken) are provided for efficiency and correctness in loops.
1.6 pazsan 9484:
1.26 crook 9485: A special area in the dictionary space is reserved for keeping the
9486: local variable names. @code{@{} switches the dictionary pointer to this
9487: area and @code{@}} switches it back and generates the locals
9488: initializing code. @code{W:} etc.@ are normal defining words. This
9489: special area is cleared at the start of every colon definition.
1.6 pazsan 9490:
1.26 crook 9491: @cindex word list for defining locals
9492: A special feature of Gforth's dictionary is used to implement the
9493: definition of locals without type specifiers: every word list (aka
9494: vocabulary) has its own methods for searching
9495: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9496: with a special search method: When it is searched for a word, it
9497: actually creates that word using @code{W:}. @code{@{} changes the search
9498: order to first search the word list containing @code{@}}, @code{W:} etc.,
9499: and then the word list for defining locals without type specifiers.
1.12 anton 9500:
1.26 crook 9501: The lifetime rules support a stack discipline within a colon
9502: definition: The lifetime of a local is either nested with other locals
9503: lifetimes or it does not overlap them.
1.6 pazsan 9504:
1.26 crook 9505: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9506: pointer manipulation is generated. Between control structure words
9507: locals definitions can push locals onto the locals stack. @code{AGAIN}
9508: is the simplest of the other three control flow words. It has to
9509: restore the locals stack depth of the corresponding @code{BEGIN}
9510: before branching. The code looks like this:
9511: @format
9512: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9513: @code{branch} <begin>
9514: @end format
1.6 pazsan 9515:
1.26 crook 9516: @code{UNTIL} is a little more complicated: If it branches back, it
9517: must adjust the stack just like @code{AGAIN}. But if it falls through,
9518: the locals stack must not be changed. The compiler generates the
9519: following code:
9520: @format
9521: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9522: @end format
9523: The locals stack pointer is only adjusted if the branch is taken.
1.6 pazsan 9524:
1.26 crook 9525: @code{THEN} can produce somewhat inefficient code:
9526: @format
9527: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9528: <orig target>:
9529: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9530: @end format
9531: The second @code{lp+!#} adjusts the locals stack pointer from the
1.29 crook 9532: level at the @i{orig} point to the level after the @code{THEN}. The
1.26 crook 9533: first @code{lp+!#} adjusts the locals stack pointer from the current
9534: level to the level at the orig point, so the complete effect is an
9535: adjustment from the current level to the right level after the
9536: @code{THEN}.
1.6 pazsan 9537:
1.26 crook 9538: @cindex locals information on the control-flow stack
9539: @cindex control-flow stack items, locals information
9540: In a conventional Forth implementation a dest control-flow stack entry
9541: is just the target address and an orig entry is just the address to be
9542: patched. Our locals implementation adds a word list to every orig or dest
9543: item. It is the list of locals visible (or assumed visible) at the point
9544: described by the entry. Our implementation also adds a tag to identify
9545: the kind of entry, in particular to differentiate between live and dead
9546: (reachable and unreachable) orig entries.
1.6 pazsan 9547:
1.26 crook 9548: A few unusual operations have to be performed on locals word lists:
1.6 pazsan 9549:
1.44 crook 9550:
1.26 crook 9551: doc-common-list
9552: doc-sub-list?
9553: doc-list-size
1.6 pazsan 9554:
1.44 crook 9555:
1.26 crook 9556: Several features of our locals word list implementation make these
9557: operations easy to implement: The locals word lists are organised as
9558: linked lists; the tails of these lists are shared, if the lists
9559: contain some of the same locals; and the address of a name is greater
9560: than the address of the names behind it in the list.
1.6 pazsan 9561:
1.26 crook 9562: Another important implementation detail is the variable
9563: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9564: determine if they can be reached directly or only through the branch
9565: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9566: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9567: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6 pazsan 9568:
1.26 crook 9569: Counted loops are similar to other loops in most respects, but
9570: @code{LEAVE} requires special attention: It performs basically the same
9571: service as @code{AHEAD}, but it does not create a control-flow stack
9572: entry. Therefore the information has to be stored elsewhere;
9573: traditionally, the information was stored in the target fields of the
9574: branches created by the @code{LEAVE}s, by organizing these fields into a
9575: linked list. Unfortunately, this clever trick does not provide enough
9576: space for storing our extended control flow information. Therefore, we
9577: introduce another stack, the leave stack. It contains the control-flow
9578: stack entries for all unresolved @code{LEAVE}s.
1.6 pazsan 9579:
1.26 crook 9580: Local names are kept until the end of the colon definition, even if
9581: they are no longer visible in any control-flow path. In a few cases
9582: this may lead to increased space needs for the locals name area, but
9583: usually less than reclaiming this space would cost in code size.
1.6 pazsan 9584:
9585:
1.26 crook 9586: @node ANS Forth locals, , Gforth locals, Locals
9587: @subsection ANS Forth locals
9588: @cindex locals, ANS Forth style
1.6 pazsan 9589:
1.26 crook 9590: The ANS Forth locals wordset does not define a syntax for locals, but
9591: words that make it possible to define various syntaxes. One of the
9592: possible syntaxes is a subset of the syntax we used in the Gforth locals
9593: wordset, i.e.:
1.6 pazsan 9594:
9595: @example
1.26 crook 9596: @{ local1 local2 ... -- comment @}
1.6 pazsan 9597: @end example
1.23 crook 9598: @noindent
1.26 crook 9599: or
1.6 pazsan 9600: @example
1.26 crook 9601: @{ local1 local2 ... @}
1.6 pazsan 9602: @end example
9603:
1.26 crook 9604: The order of the locals corresponds to the order in a stack comment. The
9605: restrictions are:
1.6 pazsan 9606:
9607: @itemize @bullet
9608: @item
1.26 crook 9609: Locals can only be cell-sized values (no type specifiers are allowed).
1.6 pazsan 9610: @item
1.26 crook 9611: Locals can be defined only outside control structures.
1.6 pazsan 9612: @item
1.26 crook 9613: Locals can interfere with explicit usage of the return stack. For the
9614: exact (and long) rules, see the standard. If you don't use return stack
9615: accessing words in a definition using locals, you will be all right. The
9616: purpose of this rule is to make locals implementation on the return
9617: stack easier.
1.6 pazsan 9618: @item
1.26 crook 9619: The whole definition must be in one line.
9620: @end itemize
1.6 pazsan 9621:
1.44 crook 9622: Locals defined in this way behave like @code{VALUE}s
1.49 anton 9623: (@pxref{Values}). I.e., they are initialized from the stack. Using their
1.26 crook 9624: name produces their value. Their value can be changed using @code{TO}.
1.6 pazsan 9625:
1.26 crook 9626: Since this syntax is supported by Gforth directly, you need not do
9627: anything to use it. If you want to port a program using this syntax to
9628: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9629: syntax on the other system.
1.6 pazsan 9630:
1.26 crook 9631: Note that a syntax shown in the standard, section A.13 looks
9632: similar, but is quite different in having the order of locals
9633: reversed. Beware!
1.6 pazsan 9634:
1.26 crook 9635: The ANS Forth locals wordset itself consists of a word:
1.6 pazsan 9636:
1.44 crook 9637:
1.26 crook 9638: doc-(local)
1.6 pazsan 9639:
1.44 crook 9640:
1.26 crook 9641: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
9642: awful that we strongly recommend not to use it. We have implemented this
9643: syntax to make porting to Gforth easy, but do not document it here. The
9644: problem with this syntax is that the locals are defined in an order
9645: reversed with respect to the standard stack comment notation, making
9646: programs harder to read, and easier to misread and miswrite. The only
9647: merit of this syntax is that it is easy to implement using the ANS Forth
9648: locals wordset.
1.7 pazsan 9649:
9650:
1.26 crook 9651: @c ----------------------------------------------------------
9652: @node Structures, Object-oriented Forth, Locals, Words
9653: @section Structures
9654: @cindex structures
9655: @cindex records
1.7 pazsan 9656:
1.26 crook 9657: This section presents the structure package that comes with Gforth. A
9658: version of the package implemented in ANS Forth is available in
9659: @file{compat/struct.fs}. This package was inspired by a posting on
9660: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9661: possibly John Hayes). A version of this section has been published in
9662: ???. Marcel Hendrix provided helpful comments.
1.7 pazsan 9663:
1.26 crook 9664: @menu
9665: * Why explicit structure support?::
9666: * Structure Usage::
9667: * Structure Naming Convention::
9668: * Structure Implementation::
9669: * Structure Glossary::
9670: @end menu
1.7 pazsan 9671:
1.26 crook 9672: @node Why explicit structure support?, Structure Usage, Structures, Structures
9673: @subsection Why explicit structure support?
1.7 pazsan 9674:
1.26 crook 9675: @cindex address arithmetic for structures
9676: @cindex structures using address arithmetic
9677: If we want to use a structure containing several fields, we could simply
9678: reserve memory for it, and access the fields using address arithmetic
1.32 anton 9679: (@pxref{Address arithmetic}). As an example, consider a structure with
1.26 crook 9680: the following fields
1.7 pazsan 9681:
1.26 crook 9682: @table @code
9683: @item a
9684: is a float
9685: @item b
9686: is a cell
9687: @item c
9688: is a float
9689: @end table
1.7 pazsan 9690:
1.26 crook 9691: Given the (float-aligned) base address of the structure we get the
9692: address of the field
1.13 pazsan 9693:
1.26 crook 9694: @table @code
9695: @item a
9696: without doing anything further.
9697: @item b
9698: with @code{float+}
9699: @item c
9700: with @code{float+ cell+ faligned}
9701: @end table
1.13 pazsan 9702:
1.26 crook 9703: It is easy to see that this can become quite tiring.
1.13 pazsan 9704:
1.26 crook 9705: Moreover, it is not very readable, because seeing a
9706: @code{cell+} tells us neither which kind of structure is
9707: accessed nor what field is accessed; we have to somehow infer the kind
9708: of structure, and then look up in the documentation, which field of
9709: that structure corresponds to that offset.
1.13 pazsan 9710:
1.26 crook 9711: Finally, this kind of address arithmetic also causes maintenance
9712: troubles: If you add or delete a field somewhere in the middle of the
9713: structure, you have to find and change all computations for the fields
9714: afterwards.
1.13 pazsan 9715:
1.26 crook 9716: So, instead of using @code{cell+} and friends directly, how
9717: about storing the offsets in constants:
1.13 pazsan 9718:
9719: @example
1.26 crook 9720: 0 constant a-offset
9721: 0 float+ constant b-offset
9722: 0 float+ cell+ faligned c-offset
1.13 pazsan 9723: @end example
9724:
1.26 crook 9725: Now we can get the address of field @code{x} with @code{x-offset
9726: +}. This is much better in all respects. Of course, you still
9727: have to change all later offset definitions if you add a field. You can
9728: fix this by declaring the offsets in the following way:
1.13 pazsan 9729:
9730: @example
1.26 crook 9731: 0 constant a-offset
9732: a-offset float+ constant b-offset
9733: b-offset cell+ faligned constant c-offset
1.13 pazsan 9734: @end example
9735:
1.26 crook 9736: Since we always use the offsets with @code{+}, we could use a defining
9737: word @code{cfield} that includes the @code{+} in the action of the
9738: defined word:
1.8 pazsan 9739:
9740: @example
1.26 crook 9741: : cfield ( n "name" -- )
9742: create ,
9743: does> ( name execution: addr1 -- addr2 )
9744: @@ + ;
1.13 pazsan 9745:
1.26 crook 9746: 0 cfield a
9747: 0 a float+ cfield b
9748: 0 b cell+ faligned cfield c
1.13 pazsan 9749: @end example
9750:
1.26 crook 9751: Instead of @code{x-offset +}, we now simply write @code{x}.
9752:
9753: The structure field words now can be used quite nicely. However,
9754: their definition is still a bit cumbersome: We have to repeat the
9755: name, the information about size and alignment is distributed before
9756: and after the field definitions etc. The structure package presented
9757: here addresses these problems.
9758:
9759: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9760: @subsection Structure Usage
9761: @cindex structure usage
1.13 pazsan 9762:
1.26 crook 9763: @cindex @code{field} usage
9764: @cindex @code{struct} usage
9765: @cindex @code{end-struct} usage
9766: You can define a structure for a (data-less) linked list with:
1.13 pazsan 9767: @example
1.26 crook 9768: struct
9769: cell% field list-next
9770: end-struct list%
1.13 pazsan 9771: @end example
9772:
1.26 crook 9773: With the address of the list node on the stack, you can compute the
9774: address of the field that contains the address of the next node with
9775: @code{list-next}. E.g., you can determine the length of a list
9776: with:
1.13 pazsan 9777:
9778: @example
1.26 crook 9779: : list-length ( list -- n )
9780: \ "list" is a pointer to the first element of a linked list
9781: \ "n" is the length of the list
9782: 0 BEGIN ( list1 n1 )
9783: over
9784: WHILE ( list1 n1 )
9785: 1+ swap list-next @@ swap
9786: REPEAT
9787: nip ;
1.13 pazsan 9788: @end example
9789:
1.26 crook 9790: You can reserve memory for a list node in the dictionary with
9791: @code{list% %allot}, which leaves the address of the list node on the
9792: stack. For the equivalent allocation on the heap you can use @code{list%
9793: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9794: use @code{list% %allocate}). You can get the the size of a list
9795: node with @code{list% %size} and its alignment with @code{list%
9796: %alignment}.
1.13 pazsan 9797:
1.26 crook 9798: Note that in ANS Forth the body of a @code{create}d word is
9799: @code{aligned} but not necessarily @code{faligned};
9800: therefore, if you do a:
1.13 pazsan 9801: @example
1.26 crook 9802: create @emph{name} foo% %allot
1.8 pazsan 9803: @end example
9804:
1.26 crook 9805: @noindent
9806: then the memory alloted for @code{foo%} is
9807: guaranteed to start at the body of @code{@emph{name}} only if
9808: @code{foo%} contains only character, cell and double fields.
1.20 pazsan 9809:
1.45 crook 9810: @cindex structures containing structures
1.26 crook 9811: You can include a structure @code{foo%} as a field of
9812: another structure, like this:
1.20 pazsan 9813: @example
1.26 crook 9814: struct
9815: ...
9816: foo% field ...
9817: ...
9818: end-struct ...
1.20 pazsan 9819: @end example
9820:
1.26 crook 9821: @cindex structure extension
9822: @cindex extended records
9823: Instead of starting with an empty structure, you can extend an
9824: existing structure. E.g., a plain linked list without data, as defined
9825: above, is hardly useful; You can extend it to a linked list of integers,
9826: like this:@footnote{This feature is also known as @emph{extended
9827: records}. It is the main innovation in the Oberon language; in other
9828: words, adding this feature to Modula-2 led Wirth to create a new
9829: language, write a new compiler etc. Adding this feature to Forth just
9830: required a few lines of code.}
1.20 pazsan 9831:
9832: @example
1.26 crook 9833: list%
9834: cell% field intlist-int
9835: end-struct intlist%
1.20 pazsan 9836: @end example
9837:
1.26 crook 9838: @code{intlist%} is a structure with two fields:
9839: @code{list-next} and @code{intlist-int}.
1.20 pazsan 9840:
1.26 crook 9841: @cindex structures containing arrays
9842: You can specify an array type containing @emph{n} elements of
9843: type @code{foo%} like this:
1.20 pazsan 9844:
9845: @example
1.26 crook 9846: foo% @emph{n} *
1.20 pazsan 9847: @end example
9848:
1.26 crook 9849: You can use this array type in any place where you can use a normal
9850: type, e.g., when defining a @code{field}, or with
9851: @code{%allot}.
1.20 pazsan 9852:
1.26 crook 9853: @cindex first field optimization
9854: The first field is at the base address of a structure and the word
9855: for this field (e.g., @code{list-next}) actually does not change
9856: the address on the stack. You may be tempted to leave it away in the
9857: interest of run-time and space efficiency. This is not necessary,
9858: because the structure package optimizes this case and compiling such
9859: words does not generate any code. So, in the interest of readability
9860: and maintainability you should include the word for the field when
9861: accessing the field.
1.20 pazsan 9862:
1.26 crook 9863: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9864: @subsection Structure Naming Convention
9865: @cindex structure naming convention
1.20 pazsan 9866:
1.26 crook 9867: The field names that come to (my) mind are often quite generic, and,
9868: if used, would cause frequent name clashes. E.g., many structures
9869: probably contain a @code{counter} field. The structure names
9870: that come to (my) mind are often also the logical choice for the names
9871: of words that create such a structure.
1.20 pazsan 9872:
1.26 crook 9873: Therefore, I have adopted the following naming conventions:
1.20 pazsan 9874:
1.26 crook 9875: @itemize @bullet
9876: @cindex field naming convention
9877: @item
9878: The names of fields are of the form
9879: @code{@emph{struct}-@emph{field}}, where
9880: @code{@emph{struct}} is the basic name of the structure, and
9881: @code{@emph{field}} is the basic name of the field. You can
9882: think of field words as converting the (address of the)
9883: structure into the (address of the) field.
1.20 pazsan 9884:
1.26 crook 9885: @cindex structure naming convention
9886: @item
9887: The names of structures are of the form
9888: @code{@emph{struct}%}, where
9889: @code{@emph{struct}} is the basic name of the structure.
9890: @end itemize
1.20 pazsan 9891:
1.26 crook 9892: This naming convention does not work that well for fields of extended
9893: structures; e.g., the integer list structure has a field
9894: @code{intlist-int}, but has @code{list-next}, not
9895: @code{intlist-next}.
1.20 pazsan 9896:
1.26 crook 9897: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9898: @subsection Structure Implementation
9899: @cindex structure implementation
9900: @cindex implementation of structures
1.20 pazsan 9901:
1.26 crook 9902: The central idea in the implementation is to pass the data about the
9903: structure being built on the stack, not in some global
9904: variable. Everything else falls into place naturally once this design
9905: decision is made.
1.20 pazsan 9906:
1.26 crook 9907: The type description on the stack is of the form @emph{align
9908: size}. Keeping the size on the top-of-stack makes dealing with arrays
9909: very simple.
1.20 pazsan 9910:
1.26 crook 9911: @code{field} is a defining word that uses @code{Create}
9912: and @code{DOES>}. The body of the field contains the offset
9913: of the field, and the normal @code{DOES>} action is simply:
1.20 pazsan 9914:
9915: @example
1.48 anton 9916: @@ +
1.20 pazsan 9917: @end example
9918:
1.23 crook 9919: @noindent
1.26 crook 9920: i.e., add the offset to the address, giving the stack effect
1.29 crook 9921: @i{addr1 -- addr2} for a field.
1.20 pazsan 9922:
1.26 crook 9923: @cindex first field optimization, implementation
9924: This simple structure is slightly complicated by the optimization
9925: for fields with offset 0, which requires a different
9926: @code{DOES>}-part (because we cannot rely on there being
9927: something on the stack if such a field is invoked during
9928: compilation). Therefore, we put the different @code{DOES>}-parts
9929: in separate words, and decide which one to invoke based on the
9930: offset. For a zero offset, the field is basically a noop; it is
9931: immediate, and therefore no code is generated when it is compiled.
1.20 pazsan 9932:
1.26 crook 9933: @node Structure Glossary, , Structure Implementation, Structures
9934: @subsection Structure Glossary
9935: @cindex structure glossary
1.20 pazsan 9936:
1.44 crook 9937:
1.26 crook 9938: doc-%align
9939: doc-%alignment
9940: doc-%alloc
9941: doc-%allocate
9942: doc-%allot
9943: doc-cell%
9944: doc-char%
9945: doc-dfloat%
9946: doc-double%
9947: doc-end-struct
9948: doc-field
9949: doc-float%
9950: doc-naligned
9951: doc-sfloat%
9952: doc-%size
9953: doc-struct
1.23 crook 9954:
1.44 crook 9955:
1.26 crook 9956: @c -------------------------------------------------------------
9957: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
9958: @section Object-oriented Forth
1.20 pazsan 9959:
1.26 crook 9960: Gforth comes with three packages for object-oriented programming:
9961: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9962: is preloaded, so you have to @code{include} them before use. The most
9963: important differences between these packages (and others) are discussed
9964: in @ref{Comparison with other object models}. All packages are written
9965: in ANS Forth and can be used with any other ANS Forth.
1.20 pazsan 9966:
1.26 crook 9967: @menu
1.48 anton 9968: * Why object-oriented programming?::
9969: * Object-Oriented Terminology::
9970: * Objects::
9971: * OOF::
9972: * Mini-OOF::
1.26 crook 9973: * Comparison with other object models::
9974: @end menu
1.20 pazsan 9975:
1.48 anton 9976: @c ----------------------------------------------------------------
9977: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9978: @subsection Why object-oriented programming?
1.26 crook 9979: @cindex object-oriented programming motivation
9980: @cindex motivation for object-oriented programming
1.23 crook 9981:
1.26 crook 9982: Often we have to deal with several data structures (@emph{objects}),
9983: that have to be treated similarly in some respects, but differently in
9984: others. Graphical objects are the textbook example: circles, triangles,
9985: dinosaurs, icons, and others, and we may want to add more during program
9986: development. We want to apply some operations to any graphical object,
9987: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9988: has to do something different for every kind of object.
9989: @comment TODO add some other operations eg perimeter, area
9990: @comment and tie in to concrete examples later..
1.23 crook 9991:
1.26 crook 9992: We could implement @code{draw} as a big @code{CASE}
9993: control structure that executes the appropriate code depending on the
9994: kind of object to be drawn. This would be not be very elegant, and,
9995: moreover, we would have to change @code{draw} every time we add
9996: a new kind of graphical object (say, a spaceship).
1.23 crook 9997:
1.26 crook 9998: What we would rather do is: When defining spaceships, we would tell
9999: the system: ``Here's how you @code{draw} a spaceship; you figure
10000: out the rest''.
1.23 crook 10001:
1.26 crook 10002: This is the problem that all systems solve that (rightfully) call
10003: themselves object-oriented; the object-oriented packages presented here
10004: solve this problem (and not much else).
10005: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23 crook 10006:
1.48 anton 10007: @c ------------------------------------------------------------------------
1.26 crook 10008: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
1.48 anton 10009: @subsection Object-Oriented Terminology
1.26 crook 10010: @cindex object-oriented terminology
10011: @cindex terminology for object-oriented programming
1.23 crook 10012:
1.26 crook 10013: This section is mainly for reference, so you don't have to understand
10014: all of it right away. The terminology is mainly Smalltalk-inspired. In
10015: short:
1.23 crook 10016:
1.26 crook 10017: @table @emph
10018: @cindex class
10019: @item class
10020: a data structure definition with some extras.
1.23 crook 10021:
1.26 crook 10022: @cindex object
10023: @item object
10024: an instance of the data structure described by the class definition.
1.23 crook 10025:
1.26 crook 10026: @cindex instance variables
10027: @item instance variables
10028: fields of the data structure.
1.23 crook 10029:
1.26 crook 10030: @cindex selector
10031: @cindex method selector
10032: @cindex virtual function
10033: @item selector
10034: (or @emph{method selector}) a word (e.g.,
10035: @code{draw}) that performs an operation on a variety of data
10036: structures (classes). A selector describes @emph{what} operation to
10037: perform. In C++ terminology: a (pure) virtual function.
1.23 crook 10038:
1.26 crook 10039: @cindex method
10040: @item method
10041: the concrete definition that performs the operation
10042: described by the selector for a specific class. A method specifies
10043: @emph{how} the operation is performed for a specific class.
1.23 crook 10044:
1.26 crook 10045: @cindex selector invocation
10046: @cindex message send
10047: @cindex invoking a selector
10048: @item selector invocation
10049: a call of a selector. One argument of the call (the TOS (top-of-stack))
10050: is used for determining which method is used. In Smalltalk terminology:
10051: a message (consisting of the selector and the other arguments) is sent
10052: to the object.
1.1 anton 10053:
1.26 crook 10054: @cindex receiving object
10055: @item receiving object
10056: the object used for determining the method executed by a selector
10057: invocation. In the @file{objects.fs} model, it is the object that is on
10058: the TOS when the selector is invoked. (@emph{Receiving} comes from
10059: the Smalltalk @emph{message} terminology.)
1.1 anton 10060:
1.26 crook 10061: @cindex child class
10062: @cindex parent class
10063: @cindex inheritance
10064: @item child class
10065: a class that has (@emph{inherits}) all properties (instance variables,
10066: selectors, methods) from a @emph{parent class}. In Smalltalk
10067: terminology: The subclass inherits from the superclass. In C++
10068: terminology: The derived class inherits from the base class.
1.1 anton 10069:
1.26 crook 10070: @end table
1.21 crook 10071:
1.26 crook 10072: @c If you wonder about the message sending terminology, it comes from
10073: @c a time when each object had it's own task and objects communicated via
10074: @c message passing; eventually the Smalltalk developers realized that
10075: @c they can do most things through simple (indirect) calls. They kept the
10076: @c terminology.
1.1 anton 10077:
1.48 anton 10078: @c --------------------------------------------------------------
1.26 crook 10079: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10080: @subsection The @file{objects.fs} model
10081: @cindex objects
10082: @cindex object-oriented programming
1.1 anton 10083:
1.26 crook 10084: @cindex @file{objects.fs}
10085: @cindex @file{oof.fs}
1.1 anton 10086:
1.37 anton 10087: This section describes the @file{objects.fs} package. This material also
10088: has been published in @cite{Yet Another Forth Objects Package} by Anton
10089: Ertl and appeared in Forth Dimensions 19(2), pages 37--43
1.47 crook 10090: (@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html}).
1.26 crook 10091: @c McKewan's and Zsoter's packages
1.1 anton 10092:
1.26 crook 10093: This section assumes that you have read @ref{Structures}.
1.1 anton 10094:
1.26 crook 10095: The techniques on which this model is based have been used to implement
10096: the parser generator, Gray, and have also been used in Gforth for
10097: implementing the various flavours of word lists (hashed or not,
10098: case-sensitive or not, special-purpose word lists for locals etc.).
1.1 anton 10099:
10100:
1.26 crook 10101: @menu
10102: * Properties of the Objects model::
10103: * Basic Objects Usage::
1.37 anton 10104: * The Objects base class::
1.26 crook 10105: * Creating objects::
10106: * Object-Oriented Programming Style::
10107: * Class Binding::
10108: * Method conveniences::
10109: * Classes and Scoping::
1.37 anton 10110: * Dividing classes::
1.26 crook 10111: * Object Interfaces::
10112: * Objects Implementation::
10113: * Objects Glossary::
10114: @end menu
1.1 anton 10115:
1.26 crook 10116: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
10117: and Bernd Paysan helped me with the related works section.
1.1 anton 10118:
1.26 crook 10119: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10120: @subsubsection Properties of the @file{objects.fs} model
10121: @cindex @file{objects.fs} properties
1.1 anton 10122:
1.26 crook 10123: @itemize @bullet
10124: @item
10125: It is straightforward to pass objects on the stack. Passing
10126: selectors on the stack is a little less convenient, but possible.
1.1 anton 10127:
1.26 crook 10128: @item
10129: Objects are just data structures in memory, and are referenced by their
10130: address. You can create words for objects with normal defining words
10131: like @code{constant}. Likewise, there is no difference between instance
10132: variables that contain objects and those that contain other data.
1.1 anton 10133:
1.26 crook 10134: @item
10135: Late binding is efficient and easy to use.
1.21 crook 10136:
1.26 crook 10137: @item
10138: It avoids parsing, and thus avoids problems with state-smartness
10139: and reduced extensibility; for convenience there are a few parsing
10140: words, but they have non-parsing counterparts. There are also a few
10141: defining words that parse. This is hard to avoid, because all standard
10142: defining words parse (except @code{:noname}); however, such
10143: words are not as bad as many other parsing words, because they are not
10144: state-smart.
1.21 crook 10145:
1.26 crook 10146: @item
10147: It does not try to incorporate everything. It does a few things and does
10148: them well (IMO). In particular, this model was not designed to support
10149: information hiding (although it has features that may help); you can use
10150: a separate package for achieving this.
1.21 crook 10151:
1.26 crook 10152: @item
10153: It is layered; you don't have to learn and use all features to use this
1.49 anton 10154: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10155: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
1.26 crook 10156: are optional and independent of each other.
1.21 crook 10157:
1.26 crook 10158: @item
10159: An implementation in ANS Forth is available.
1.21 crook 10160:
1.26 crook 10161: @end itemize
1.21 crook 10162:
10163:
1.26 crook 10164: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10165: @subsubsection Basic @file{objects.fs} Usage
10166: @cindex basic objects usage
10167: @cindex objects, basic usage
1.21 crook 10168:
1.26 crook 10169: You can define a class for graphical objects like this:
1.21 crook 10170:
1.26 crook 10171: @cindex @code{class} usage
10172: @cindex @code{end-class} usage
10173: @cindex @code{selector} usage
10174: @example
10175: object class \ "object" is the parent class
10176: selector draw ( x y graphical -- )
10177: end-class graphical
10178: @end example
1.21 crook 10179:
1.26 crook 10180: This code defines a class @code{graphical} with an
10181: operation @code{draw}. We can perform the operation
10182: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 10183:
1.26 crook 10184: @example
10185: 100 100 t-rex draw
10186: @end example
1.21 crook 10187:
1.26 crook 10188: @noindent
10189: where @code{t-rex} is a word (say, a constant) that produces a
10190: graphical object.
1.21 crook 10191:
1.29 crook 10192: @comment TODO add a 2nd operation eg perimeter.. and use for
1.26 crook 10193: @comment a concrete example
1.21 crook 10194:
1.26 crook 10195: @cindex abstract class
10196: How do we create a graphical object? With the present definitions,
10197: we cannot create a useful graphical object. The class
10198: @code{graphical} describes graphical objects in general, but not
10199: any concrete graphical object type (C++ users would call it an
10200: @emph{abstract class}); e.g., there is no method for the selector
10201: @code{draw} in the class @code{graphical}.
1.21 crook 10202:
1.26 crook 10203: For concrete graphical objects, we define child classes of the
10204: class @code{graphical}, e.g.:
1.21 crook 10205:
1.26 crook 10206: @cindex @code{overrides} usage
10207: @cindex @code{field} usage in class definition
10208: @example
10209: graphical class \ "graphical" is the parent class
10210: cell% field circle-radius
1.21 crook 10211:
1.26 crook 10212: :noname ( x y circle -- )
10213: circle-radius @@ draw-circle ;
10214: overrides draw
1.21 crook 10215:
1.26 crook 10216: :noname ( n-radius circle -- )
10217: circle-radius ! ;
10218: overrides construct
1.21 crook 10219:
1.26 crook 10220: end-class circle
1.21 crook 10221: @end example
10222:
1.26 crook 10223: Here we define a class @code{circle} as a child of @code{graphical},
10224: with field @code{circle-radius} (which behaves just like a field
10225: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10226: for the selectors @code{draw} and @code{construct} (@code{construct} is
10227: defined in @code{object}, the parent class of @code{graphical}).
1.21 crook 10228:
1.26 crook 10229: Now we can create a circle on the heap (i.e.,
10230: @code{allocate}d memory) with:
1.21 crook 10231:
1.26 crook 10232: @cindex @code{heap-new} usage
1.21 crook 10233: @example
1.26 crook 10234: 50 circle heap-new constant my-circle
10235: @end example
1.21 crook 10236:
1.26 crook 10237: @noindent
10238: @code{heap-new} invokes @code{construct}, thus
10239: initializing the field @code{circle-radius} with 50. We can draw
10240: this new circle at (100,100) with:
1.21 crook 10241:
1.26 crook 10242: @example
10243: 100 100 my-circle draw
1.21 crook 10244: @end example
10245:
1.26 crook 10246: @cindex selector invocation, restrictions
10247: @cindex class definition, restrictions
10248: Note: You can only invoke a selector if the object on the TOS
10249: (the receiving object) belongs to the class where the selector was
10250: defined or one of its descendents; e.g., you can invoke
10251: @code{draw} only for objects belonging to @code{graphical}
10252: or its descendents (e.g., @code{circle}). Immediately before
10253: @code{end-class}, the search order has to be the same as
10254: immediately after @code{class}.
1.21 crook 10255:
1.26 crook 10256: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10257: @subsubsection The @file{object.fs} base class
10258: @cindex @code{object} class
1.21 crook 10259:
1.26 crook 10260: When you define a class, you have to specify a parent class. So how do
10261: you start defining classes? There is one class available from the start:
10262: @code{object}. It is ancestor for all classes and so is the
10263: only class that has no parent. It has two selectors: @code{construct}
10264: and @code{print}.
1.21 crook 10265:
1.26 crook 10266: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10267: @subsubsection Creating objects
10268: @cindex creating objects
10269: @cindex object creation
10270: @cindex object allocation options
1.21 crook 10271:
1.26 crook 10272: @cindex @code{heap-new} discussion
10273: @cindex @code{dict-new} discussion
10274: @cindex @code{construct} discussion
10275: You can create and initialize an object of a class on the heap with
10276: @code{heap-new} ( ... class -- object ) and in the dictionary
10277: (allocation with @code{allot}) with @code{dict-new} (
10278: ... class -- object ). Both words invoke @code{construct}, which
10279: consumes the stack items indicated by "..." above.
1.21 crook 10280:
1.26 crook 10281: @cindex @code{init-object} discussion
10282: @cindex @code{class-inst-size} discussion
10283: If you want to allocate memory for an object yourself, you can get its
10284: alignment and size with @code{class-inst-size 2@@} ( class --
10285: align size ). Once you have memory for an object, you can initialize
10286: it with @code{init-object} ( ... class object -- );
10287: @code{construct} does only a part of the necessary work.
1.21 crook 10288:
1.26 crook 10289: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10290: @subsubsection Object-Oriented Programming Style
10291: @cindex object-oriented programming style
1.47 crook 10292: @cindex programming style, object-oriented
1.21 crook 10293:
1.26 crook 10294: This section is not exhaustive.
1.1 anton 10295:
1.26 crook 10296: @cindex stack effects of selectors
10297: @cindex selectors and stack effects
10298: In general, it is a good idea to ensure that all methods for the
10299: same selector have the same stack effect: when you invoke a selector,
10300: you often have no idea which method will be invoked, so, unless all
10301: methods have the same stack effect, you will not know the stack effect
10302: of the selector invocation.
1.21 crook 10303:
1.26 crook 10304: One exception to this rule is methods for the selector
10305: @code{construct}. We know which method is invoked, because we
10306: specify the class to be constructed at the same place. Actually, I
10307: defined @code{construct} as a selector only to give the users a
10308: convenient way to specify initialization. The way it is used, a
10309: mechanism different from selector invocation would be more natural
10310: (but probably would take more code and more space to explain).
1.21 crook 10311:
1.26 crook 10312: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10313: @subsubsection Class Binding
10314: @cindex class binding
10315: @cindex early binding
1.21 crook 10316:
1.26 crook 10317: @cindex late binding
10318: Normal selector invocations determine the method at run-time depending
10319: on the class of the receiving object. This run-time selection is called
1.29 crook 10320: @i{late binding}.
1.21 crook 10321:
1.26 crook 10322: Sometimes it's preferable to invoke a different method. For example,
10323: you might want to use the simple method for @code{print}ing
10324: @code{object}s instead of the possibly long-winded @code{print} method
10325: of the receiver class. You can achieve this by replacing the invocation
10326: of @code{print} with:
1.21 crook 10327:
1.26 crook 10328: @cindex @code{[bind]} usage
10329: @example
10330: [bind] object print
1.21 crook 10331: @end example
10332:
1.26 crook 10333: @noindent
10334: in compiled code or:
1.21 crook 10335:
1.26 crook 10336: @cindex @code{bind} usage
1.21 crook 10337: @example
1.26 crook 10338: bind object print
1.21 crook 10339: @end example
10340:
1.26 crook 10341: @cindex class binding, alternative to
10342: @noindent
10343: in interpreted code. Alternatively, you can define the method with a
10344: name (e.g., @code{print-object}), and then invoke it through the
10345: name. Class binding is just a (often more convenient) way to achieve
10346: the same effect; it avoids name clutter and allows you to invoke
10347: methods directly without naming them first.
10348:
10349: @cindex superclass binding
10350: @cindex parent class binding
10351: A frequent use of class binding is this: When we define a method
10352: for a selector, we often want the method to do what the selector does
10353: in the parent class, and a little more. There is a special word for
10354: this purpose: @code{[parent]}; @code{[parent]
10355: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10356: selector}}, where @code{@emph{parent}} is the parent
10357: class of the current class. E.g., a method definition might look like:
1.21 crook 10358:
1.26 crook 10359: @cindex @code{[parent]} usage
1.21 crook 10360: @example
1.26 crook 10361: :noname
10362: dup [parent] foo \ do parent's foo on the receiving object
10363: ... \ do some more
10364: ; overrides foo
1.21 crook 10365: @end example
10366:
1.26 crook 10367: @cindex class binding as optimization
10368: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10369: March 1997), Andrew McKewan presents class binding as an optimization
10370: technique. I recommend not using it for this purpose unless you are in
10371: an emergency. Late binding is pretty fast with this model anyway, so the
10372: benefit of using class binding is small; the cost of using class binding
10373: where it is not appropriate is reduced maintainability.
1.21 crook 10374:
1.26 crook 10375: While we are at programming style questions: You should bind
10376: selectors only to ancestor classes of the receiving object. E.g., say,
10377: you know that the receiving object is of class @code{foo} or its
10378: descendents; then you should bind only to @code{foo} and its
10379: ancestors.
1.21 crook 10380:
1.26 crook 10381: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10382: @subsubsection Method conveniences
10383: @cindex method conveniences
1.1 anton 10384:
1.26 crook 10385: In a method you usually access the receiving object pretty often. If
10386: you define the method as a plain colon definition (e.g., with
10387: @code{:noname}), you may have to do a lot of stack
10388: gymnastics. To avoid this, you can define the method with @code{m:
10389: ... ;m}. E.g., you could define the method for
10390: @code{draw}ing a @code{circle} with
1.20 pazsan 10391:
1.26 crook 10392: @cindex @code{this} usage
10393: @cindex @code{m:} usage
10394: @cindex @code{;m} usage
10395: @example
10396: m: ( x y circle -- )
10397: ( x y ) this circle-radius @@ draw-circle ;m
10398: @end example
1.20 pazsan 10399:
1.26 crook 10400: @cindex @code{exit} in @code{m: ... ;m}
10401: @cindex @code{exitm} discussion
10402: @cindex @code{catch} in @code{m: ... ;m}
10403: When this method is executed, the receiver object is removed from the
10404: stack; you can access it with @code{this} (admittedly, in this
10405: example the use of @code{m: ... ;m} offers no advantage). Note
10406: that I specify the stack effect for the whole method (i.e. including
10407: the receiver object), not just for the code between @code{m:}
10408: and @code{;m}. You cannot use @code{exit} in
10409: @code{m:...;m}; instead, use
10410: @code{exitm}.@footnote{Moreover, for any word that calls
10411: @code{catch} and was defined before loading
10412: @code{objects.fs}, you have to redefine it like I redefined
10413: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20 pazsan 10414:
1.26 crook 10415: @cindex @code{inst-var} usage
10416: You will frequently use sequences of the form @code{this
10417: @emph{field}} (in the example above: @code{this
10418: circle-radius}). If you use the field only in this way, you can
10419: define it with @code{inst-var} and eliminate the
10420: @code{this} before the field name. E.g., the @code{circle}
10421: class above could also be defined with:
1.20 pazsan 10422:
1.26 crook 10423: @example
10424: graphical class
10425: cell% inst-var radius
1.20 pazsan 10426:
1.26 crook 10427: m: ( x y circle -- )
10428: radius @@ draw-circle ;m
10429: overrides draw
1.20 pazsan 10430:
1.26 crook 10431: m: ( n-radius circle -- )
10432: radius ! ;m
10433: overrides construct
1.12 anton 10434:
1.26 crook 10435: end-class circle
10436: @end example
1.12 anton 10437:
1.26 crook 10438: @code{radius} can only be used in @code{circle} and its
10439: descendent classes and inside @code{m:...;m}.
1.12 anton 10440:
1.26 crook 10441: @cindex @code{inst-value} usage
10442: You can also define fields with @code{inst-value}, which is
10443: to @code{inst-var} what @code{value} is to
10444: @code{variable}. You can change the value of such a field with
10445: @code{[to-inst]}. E.g., we could also define the class
10446: @code{circle} like this:
1.12 anton 10447:
1.26 crook 10448: @example
10449: graphical class
10450: inst-value radius
1.12 anton 10451:
1.26 crook 10452: m: ( x y circle -- )
10453: radius draw-circle ;m
10454: overrides draw
1.12 anton 10455:
1.26 crook 10456: m: ( n-radius circle -- )
10457: [to-inst] radius ;m
10458: overrides construct
1.21 crook 10459:
1.26 crook 10460: end-class circle
1.12 anton 10461: @end example
10462:
1.38 anton 10463: Finally, you can define named methods with @code{:m}. One use of this
10464: feature is the definition of words that occur only in one class and are
10465: not intended to be overridden, but which still need method context
10466: (e.g., for accessing @code{inst-var}s). Another use is for methods that
10467: would be bound frequently, if defined anonymously.
10468:
1.12 anton 10469:
1.37 anton 10470: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
1.26 crook 10471: @subsubsection Classes and Scoping
10472: @cindex classes and scoping
10473: @cindex scoping and classes
1.12 anton 10474:
1.26 crook 10475: Inheritance is frequent, unlike structure extension. This exacerbates
10476: the problem with the field name convention (@pxref{Structure Naming
10477: Convention}): One always has to remember in which class the field was
10478: originally defined; changing a part of the class structure would require
10479: changes for renaming in otherwise unaffected code.
1.12 anton 10480:
1.26 crook 10481: @cindex @code{inst-var} visibility
10482: @cindex @code{inst-value} visibility
10483: To solve this problem, I added a scoping mechanism (which was not in my
10484: original charter): A field defined with @code{inst-var} (or
10485: @code{inst-value}) is visible only in the class where it is defined and in
10486: the descendent classes of this class. Using such fields only makes
10487: sense in @code{m:}-defined methods in these classes anyway.
1.12 anton 10488:
1.26 crook 10489: This scoping mechanism allows us to use the unadorned field name,
10490: because name clashes with unrelated words become much less likely.
1.12 anton 10491:
1.26 crook 10492: @cindex @code{protected} discussion
10493: @cindex @code{private} discussion
10494: Once we have this mechanism, we can also use it for controlling the
10495: visibility of other words: All words defined after
10496: @code{protected} are visible only in the current class and its
10497: descendents. @code{public} restores the compilation
10498: (i.e. @code{current}) word list that was in effect before. If you
10499: have several @code{protected}s without an intervening
10500: @code{public} or @code{set-current}, @code{public}
10501: will restore the compilation word list in effect before the first of
10502: these @code{protected}s.
1.12 anton 10503:
1.37 anton 10504: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10505: @subsubsection Dividing classes
10506: @cindex Dividing classes
10507: @cindex @code{methods}...@code{end-methods}
10508:
10509: You may want to do the definition of methods separate from the
10510: definition of the class, its selectors, fields, and instance variables,
10511: i.e., separate the implementation from the definition. You can do this
10512: in the following way:
10513:
10514: @example
10515: graphical class
10516: inst-value radius
10517: end-class circle
10518:
10519: ... \ do some other stuff
10520:
10521: circle methods \ now we are ready
10522:
10523: m: ( x y circle -- )
10524: radius draw-circle ;m
10525: overrides draw
10526:
10527: m: ( n-radius circle -- )
10528: [to-inst] radius ;m
10529: overrides construct
10530:
10531: end-methods
10532: @end example
10533:
10534: You can use several @code{methods}...@code{end-methods} sections. The
10535: only things you can do to the class in these sections are: defining
10536: methods, and overriding the class's selectors. You must not define new
10537: selectors or fields.
10538:
10539: Note that you often have to override a selector before using it. In
10540: particular, you usually have to override @code{construct} with a new
10541: method before you can invoke @code{heap-new} and friends. E.g., you
10542: must not create a circle before the @code{overrides construct} sequence
10543: in the example above.
10544:
10545: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
1.26 crook 10546: @subsubsection Object Interfaces
10547: @cindex object interfaces
10548: @cindex interfaces for objects
1.12 anton 10549:
1.26 crook 10550: In this model you can only call selectors defined in the class of the
10551: receiving objects or in one of its ancestors. If you call a selector
10552: with a receiving object that is not in one of these classes, the
10553: result is undefined; if you are lucky, the program crashes
10554: immediately.
1.12 anton 10555:
1.26 crook 10556: @cindex selectors common to hardly-related classes
10557: Now consider the case when you want to have a selector (or several)
10558: available in two classes: You would have to add the selector to a
10559: common ancestor class, in the worst case to @code{object}. You
10560: may not want to do this, e.g., because someone else is responsible for
10561: this ancestor class.
1.12 anton 10562:
1.26 crook 10563: The solution for this problem is interfaces. An interface is a
10564: collection of selectors. If a class implements an interface, the
10565: selectors become available to the class and its descendents. A class
10566: can implement an unlimited number of interfaces. For the problem
10567: discussed above, we would define an interface for the selector(s), and
10568: both classes would implement the interface.
1.12 anton 10569:
1.26 crook 10570: As an example, consider an interface @code{storage} for
10571: writing objects to disk and getting them back, and a class
10572: @code{foo} that implements it. The code would look like this:
1.12 anton 10573:
1.26 crook 10574: @cindex @code{interface} usage
10575: @cindex @code{end-interface} usage
10576: @cindex @code{implementation} usage
10577: @example
10578: interface
10579: selector write ( file object -- )
10580: selector read1 ( file object -- )
10581: end-interface storage
1.12 anton 10582:
1.26 crook 10583: bar class
10584: storage implementation
1.12 anton 10585:
1.26 crook 10586: ... overrides write
1.37 anton 10587: ... overrides read1
1.26 crook 10588: ...
10589: end-class foo
1.12 anton 10590: @end example
10591:
1.26 crook 10592: @noindent
1.29 crook 10593: (I would add a word @code{read} @i{( file -- object )} that uses
1.26 crook 10594: @code{read1} internally, but that's beyond the point illustrated
10595: here.)
1.12 anton 10596:
1.26 crook 10597: Note that you cannot use @code{protected} in an interface; and
10598: of course you cannot define fields.
1.12 anton 10599:
1.26 crook 10600: In the Neon model, all selectors are available for all classes;
10601: therefore it does not need interfaces. The price you pay in this model
10602: is slower late binding, and therefore, added complexity to avoid late
10603: binding.
1.12 anton 10604:
1.26 crook 10605: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10606: @subsubsection @file{objects.fs} Implementation
10607: @cindex @file{objects.fs} implementation
1.12 anton 10608:
1.26 crook 10609: @cindex @code{object-map} discussion
10610: An object is a piece of memory, like one of the data structures
10611: described with @code{struct...end-struct}. It has a field
10612: @code{object-map} that points to the method map for the object's
10613: class.
1.12 anton 10614:
1.26 crook 10615: @cindex method map
10616: @cindex virtual function table
10617: The @emph{method map}@footnote{This is Self terminology; in C++
10618: terminology: virtual function table.} is an array that contains the
1.29 crook 10619: execution tokens (@i{xt}s) of the methods for the object's class. Each
1.26 crook 10620: selector contains an offset into a method map.
1.12 anton 10621:
1.26 crook 10622: @cindex @code{selector} implementation, class
10623: @code{selector} is a defining word that uses
10624: @code{CREATE} and @code{DOES>}. The body of the
1.44 crook 10625: selector contains the offset; the @code{DOES>} action for a
1.26 crook 10626: class selector is, basically:
1.21 crook 10627:
1.26 crook 10628: @example
10629: ( object addr ) @@ over object-map @@ + @@ execute
10630: @end example
1.12 anton 10631:
1.26 crook 10632: Since @code{object-map} is the first field of the object, it
10633: does not generate any code. As you can see, calling a selector has a
10634: small, constant cost.
1.12 anton 10635:
1.26 crook 10636: @cindex @code{current-interface} discussion
10637: @cindex class implementation and representation
10638: A class is basically a @code{struct} combined with a method
10639: map. During the class definition the alignment and size of the class
10640: are passed on the stack, just as with @code{struct}s, so
10641: @code{field} can also be used for defining class
10642: fields. However, passing more items on the stack would be
10643: inconvenient, so @code{class} builds a data structure in memory,
10644: which is accessed through the variable
10645: @code{current-interface}. After its definition is complete, the
10646: class is represented on the stack by a pointer (e.g., as parameter for
10647: a child class definition).
1.1 anton 10648:
1.26 crook 10649: A new class starts off with the alignment and size of its parent,
10650: and a copy of the parent's method map. Defining new fields extends the
10651: size and alignment; likewise, defining new selectors extends the
1.29 crook 10652: method map. @code{overrides} just stores a new @i{xt} in the method
1.26 crook 10653: map at the offset given by the selector.
1.20 pazsan 10654:
1.26 crook 10655: @cindex class binding, implementation
1.29 crook 10656: Class binding just gets the @i{xt} at the offset given by the selector
1.26 crook 10657: from the class's method map and @code{compile,}s (in the case of
10658: @code{[bind]}) it.
1.21 crook 10659:
1.26 crook 10660: @cindex @code{this} implementation
10661: @cindex @code{catch} and @code{this}
10662: @cindex @code{this} and @code{catch}
10663: I implemented @code{this} as a @code{value}. At the
10664: start of an @code{m:...;m} method the old @code{this} is
10665: stored to the return stack and restored at the end; and the object on
10666: the TOS is stored @code{TO this}. This technique has one
10667: disadvantage: If the user does not leave the method via
10668: @code{;m}, but via @code{throw} or @code{exit},
10669: @code{this} is not restored (and @code{exit} may
10670: crash). To deal with the @code{throw} problem, I have redefined
10671: @code{catch} to save and restore @code{this}; the same
10672: should be done with any word that can catch an exception. As for
10673: @code{exit}, I simply forbid it (as a replacement, there is
10674: @code{exitm}).
1.21 crook 10675:
1.26 crook 10676: @cindex @code{inst-var} implementation
10677: @code{inst-var} is just the same as @code{field}, with
10678: a different @code{DOES>} action:
10679: @example
10680: @@ this +
10681: @end example
10682: Similar for @code{inst-value}.
1.21 crook 10683:
1.26 crook 10684: @cindex class scoping implementation
10685: Each class also has a word list that contains the words defined with
10686: @code{inst-var} and @code{inst-value}, and its protected
10687: words. It also has a pointer to its parent. @code{class} pushes
10688: the word lists of the class and all its ancestors onto the search order stack,
10689: and @code{end-class} drops them.
1.21 crook 10690:
1.26 crook 10691: @cindex interface implementation
10692: An interface is like a class without fields, parent and protected
10693: words; i.e., it just has a method map. If a class implements an
10694: interface, its method map contains a pointer to the method map of the
10695: interface. The positive offsets in the map are reserved for class
10696: methods, therefore interface map pointers have negative
10697: offsets. Interfaces have offsets that are unique throughout the
10698: system, unlike class selectors, whose offsets are only unique for the
10699: classes where the selector is available (invokable).
1.21 crook 10700:
1.26 crook 10701: This structure means that interface selectors have to perform one
10702: indirection more than class selectors to find their method. Their body
10703: contains the interface map pointer offset in the class method map, and
10704: the method offset in the interface method map. The
10705: @code{does>} action for an interface selector is, basically:
1.21 crook 10706:
10707: @example
1.26 crook 10708: ( object selector-body )
10709: 2dup selector-interface @@ ( object selector-body object interface-offset )
10710: swap object-map @@ + @@ ( object selector-body map )
10711: swap selector-offset @@ + @@ execute
1.21 crook 10712: @end example
10713:
1.26 crook 10714: where @code{object-map} and @code{selector-offset} are
10715: first fields and generate no code.
10716:
10717: As a concrete example, consider the following code:
1.21 crook 10718:
1.26 crook 10719: @example
10720: interface
10721: selector if1sel1
10722: selector if1sel2
10723: end-interface if1
1.21 crook 10724:
1.26 crook 10725: object class
10726: if1 implementation
10727: selector cl1sel1
10728: cell% inst-var cl1iv1
1.21 crook 10729:
1.26 crook 10730: ' m1 overrides construct
10731: ' m2 overrides if1sel1
10732: ' m3 overrides if1sel2
10733: ' m4 overrides cl1sel2
10734: end-class cl1
1.21 crook 10735:
1.26 crook 10736: create obj1 object dict-new drop
10737: create obj2 cl1 dict-new drop
10738: @end example
1.21 crook 10739:
1.26 crook 10740: The data structure created by this code (including the data structure
10741: for @code{object}) is shown in the <a
10742: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.29 crook 10743: @comment TODO add this diagram..
1.21 crook 10744:
1.26 crook 10745: @node Objects Glossary, , Objects Implementation, Objects
10746: @subsubsection @file{objects.fs} Glossary
10747: @cindex @file{objects.fs} Glossary
1.21 crook 10748:
1.44 crook 10749:
1.26 crook 10750: doc---objects-bind
10751: doc---objects-<bind>
10752: doc---objects-bind'
10753: doc---objects-[bind]
10754: doc---objects-class
10755: doc---objects-class->map
10756: doc---objects-class-inst-size
10757: doc---objects-class-override!
10758: doc---objects-construct
10759: doc---objects-current'
10760: doc---objects-[current]
10761: doc---objects-current-interface
10762: doc---objects-dict-new
10763: doc---objects-drop-order
10764: doc---objects-end-class
10765: doc---objects-end-class-noname
10766: doc---objects-end-interface
10767: doc---objects-end-interface-noname
1.37 anton 10768: doc---objects-end-methods
1.26 crook 10769: doc---objects-exitm
10770: doc---objects-heap-new
10771: doc---objects-implementation
10772: doc---objects-init-object
10773: doc---objects-inst-value
10774: doc---objects-inst-var
10775: doc---objects-interface
1.38 anton 10776: doc---objects-m:
10777: doc---objects-:m
1.26 crook 10778: doc---objects-;m
10779: doc---objects-method
1.37 anton 10780: doc---objects-methods
1.26 crook 10781: doc---objects-object
10782: doc---objects-overrides
10783: doc---objects-[parent]
10784: doc---objects-print
10785: doc---objects-protected
10786: doc---objects-public
10787: doc---objects-push-order
10788: doc---objects-selector
10789: doc---objects-this
10790: doc---objects-<to-inst>
10791: doc---objects-[to-inst]
10792: doc---objects-to-this
10793: doc---objects-xt-new
1.21 crook 10794:
1.44 crook 10795:
1.26 crook 10796: @c -------------------------------------------------------------
10797: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10798: @subsection The @file{oof.fs} model
10799: @cindex oof
10800: @cindex object-oriented programming
1.21 crook 10801:
1.26 crook 10802: @cindex @file{objects.fs}
10803: @cindex @file{oof.fs}
1.21 crook 10804:
1.26 crook 10805: This section describes the @file{oof.fs} package.
1.21 crook 10806:
1.26 crook 10807: The package described in this section has been used in bigFORTH since 1991, and
10808: used for two large applications: a chromatographic system used to
10809: create new medicaments, and a graphic user interface library (MINOS).
1.21 crook 10810:
1.26 crook 10811: You can find a description (in German) of @file{oof.fs} in @cite{Object
10812: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10813: 10(2), 1994.
1.21 crook 10814:
1.26 crook 10815: @menu
10816: * Properties of the OOF model::
10817: * Basic OOF Usage::
10818: * The OOF base class::
10819: * Class Declaration::
10820: * Class Implementation::
10821: @end menu
1.21 crook 10822:
1.26 crook 10823: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10824: @subsubsection Properties of the @file{oof.fs} model
10825: @cindex @file{oof.fs} properties
1.21 crook 10826:
1.26 crook 10827: @itemize @bullet
10828: @item
10829: This model combines object oriented programming with information
10830: hiding. It helps you writing large application, where scoping is
10831: necessary, because it provides class-oriented scoping.
1.21 crook 10832:
1.26 crook 10833: @item
10834: Named objects, object pointers, and object arrays can be created,
10835: selector invocation uses the ``object selector'' syntax. Selector invocation
10836: to objects and/or selectors on the stack is a bit less convenient, but
10837: possible.
1.21 crook 10838:
1.26 crook 10839: @item
10840: Selector invocation and instance variable usage of the active object is
10841: straightforward, since both make use of the active object.
1.21 crook 10842:
1.26 crook 10843: @item
10844: Late binding is efficient and easy to use.
1.21 crook 10845:
1.26 crook 10846: @item
10847: State-smart objects parse selectors. However, extensibility is provided
10848: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21 crook 10849:
10850: @item
1.26 crook 10851: An implementation in ANS Forth is available.
10852:
1.21 crook 10853: @end itemize
10854:
10855:
1.26 crook 10856: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10857: @subsubsection Basic @file{oof.fs} Usage
10858: @cindex @file{oof.fs} usage
10859:
10860: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21 crook 10861:
1.26 crook 10862: You can define a class for graphical objects like this:
1.21 crook 10863:
1.26 crook 10864: @cindex @code{class} usage
10865: @cindex @code{class;} usage
10866: @cindex @code{method} usage
10867: @example
10868: object class graphical \ "object" is the parent class
10869: method draw ( x y graphical -- )
10870: class;
10871: @end example
1.21 crook 10872:
1.26 crook 10873: This code defines a class @code{graphical} with an
10874: operation @code{draw}. We can perform the operation
10875: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 10876:
1.26 crook 10877: @example
10878: 100 100 t-rex draw
10879: @end example
1.21 crook 10880:
1.26 crook 10881: @noindent
10882: where @code{t-rex} is an object or object pointer, created with e.g.
10883: @code{graphical : t-rex}.
1.21 crook 10884:
1.26 crook 10885: @cindex abstract class
10886: How do we create a graphical object? With the present definitions,
10887: we cannot create a useful graphical object. The class
10888: @code{graphical} describes graphical objects in general, but not
10889: any concrete graphical object type (C++ users would call it an
10890: @emph{abstract class}); e.g., there is no method for the selector
10891: @code{draw} in the class @code{graphical}.
1.21 crook 10892:
1.26 crook 10893: For concrete graphical objects, we define child classes of the
10894: class @code{graphical}, e.g.:
1.21 crook 10895:
10896: @example
1.26 crook 10897: graphical class circle \ "graphical" is the parent class
10898: cell var circle-radius
10899: how:
10900: : draw ( x y -- )
10901: circle-radius @@ draw-circle ;
10902:
10903: : init ( n-radius -- (
10904: circle-radius ! ;
10905: class;
10906: @end example
10907:
10908: Here we define a class @code{circle} as a child of @code{graphical},
10909: with a field @code{circle-radius}; it defines new methods for the
10910: selectors @code{draw} and @code{init} (@code{init} is defined in
10911: @code{object}, the parent class of @code{graphical}).
1.21 crook 10912:
1.26 crook 10913: Now we can create a circle in the dictionary with:
1.21 crook 10914:
1.26 crook 10915: @example
10916: 50 circle : my-circle
1.21 crook 10917: @end example
10918:
1.26 crook 10919: @noindent
10920: @code{:} invokes @code{init}, thus initializing the field
10921: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10922: with:
1.21 crook 10923:
10924: @example
1.26 crook 10925: 100 100 my-circle draw
1.21 crook 10926: @end example
10927:
1.26 crook 10928: @cindex selector invocation, restrictions
10929: @cindex class definition, restrictions
10930: Note: You can only invoke a selector if the receiving object belongs to
10931: the class where the selector was defined or one of its descendents;
10932: e.g., you can invoke @code{draw} only for objects belonging to
10933: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10934: mechanism will check if you try to invoke a selector that is not
10935: defined in this class hierarchy, so you'll get an error at compilation
10936: time.
10937:
10938:
10939: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10940: @subsubsection The @file{oof.fs} base class
10941: @cindex @file{oof.fs} base class
10942:
10943: When you define a class, you have to specify a parent class. So how do
10944: you start defining classes? There is one class available from the start:
10945: @code{object}. You have to use it as ancestor for all classes. It is the
10946: only class that has no parent. Classes are also objects, except that
10947: they don't have instance variables; class manipulation such as
10948: inheritance or changing definitions of a class is handled through
10949: selectors of the class @code{object}.
10950:
10951: @code{object} provides a number of selectors:
10952:
1.21 crook 10953: @itemize @bullet
10954: @item
1.26 crook 10955: @code{class} for subclassing, @code{definitions} to add definitions
10956: later on, and @code{class?} to get type informations (is the class a
10957: subclass of the class passed on the stack?).
1.44 crook 10958:
1.26 crook 10959: doc---object-class
10960: doc---object-definitions
10961: doc---object-class?
10962:
1.44 crook 10963:
1.21 crook 10964: @item
1.26 crook 10965: @code{init} and @code{dispose} as constructor and destructor of the
10966: object. @code{init} is invocated after the object's memory is allocated,
10967: while @code{dispose} also handles deallocation. Thus if you redefine
10968: @code{dispose}, you have to call the parent's dispose with @code{super
10969: dispose}, too.
1.44 crook 10970:
1.26 crook 10971: doc---object-init
10972: doc---object-dispose
10973:
1.44 crook 10974:
1.21 crook 10975: @item
1.26 crook 10976: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10977: @code{[]} to create named and unnamed objects and object arrays or
10978: object pointers.
1.44 crook 10979:
1.26 crook 10980: doc---object-new
10981: doc---object-new[]
10982: doc---object-:
10983: doc---object-ptr
10984: doc---object-asptr
10985: doc---object-[]
1.21 crook 10986:
1.44 crook 10987:
1.26 crook 10988: @item
10989: @code{::} and @code{super} for explicit scoping. You should use explicit
10990: scoping only for super classes or classes with the same set of instance
10991: variables. Explicitly-scoped selectors use early binding.
1.44 crook 10992:
1.26 crook 10993: doc---object-::
10994: doc---object-super
1.21 crook 10995:
1.44 crook 10996:
1.26 crook 10997: @item
10998: @code{self} to get the address of the object
1.44 crook 10999:
1.26 crook 11000: doc---object-self
1.21 crook 11001:
1.44 crook 11002:
1.21 crook 11003: @item
1.26 crook 11004: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11005: pointers and instance defers.
1.44 crook 11006:
1.26 crook 11007: doc---object-bind
11008: doc---object-bound
11009: doc---object-link
11010: doc---object-is
11011:
1.44 crook 11012:
1.21 crook 11013: @item
1.26 crook 11014: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11015: form the stack, and @code{postpone} to generate selector invocation code.
1.44 crook 11016:
1.26 crook 11017: doc---object-'
11018: doc---object-postpone
11019:
1.44 crook 11020:
1.21 crook 11021: @item
1.26 crook 11022: @code{with} and @code{endwith} to select the active object from the
11023: stack, and enable its scope. Using @code{with} and @code{endwith}
11024: also allows you to create code using selector @code{postpone} without being
11025: trapped by the state-smart objects.
1.44 crook 11026:
1.26 crook 11027: doc---object-with
11028: doc---object-endwith
11029:
1.44 crook 11030:
1.21 crook 11031: @end itemize
11032:
1.26 crook 11033: @node Class Declaration, Class Implementation, The OOF base class, OOF
11034: @subsubsection Class Declaration
11035: @cindex class declaration
11036:
11037: @itemize @bullet
11038: @item
11039: Instance variables
1.44 crook 11040:
1.26 crook 11041: doc---oof-var
1.21 crook 11042:
1.44 crook 11043:
1.26 crook 11044: @item
11045: Object pointers
1.44 crook 11046:
1.26 crook 11047: doc---oof-ptr
11048: doc---oof-asptr
1.21 crook 11049:
1.44 crook 11050:
1.26 crook 11051: @item
11052: Instance defers
1.44 crook 11053:
1.26 crook 11054: doc---oof-defer
1.21 crook 11055:
1.44 crook 11056:
1.26 crook 11057: @item
11058: Method selectors
1.44 crook 11059:
1.26 crook 11060: doc---oof-early
11061: doc---oof-method
1.21 crook 11062:
1.44 crook 11063:
1.26 crook 11064: @item
11065: Class-wide variables
1.44 crook 11066:
1.26 crook 11067: doc---oof-static
1.21 crook 11068:
1.44 crook 11069:
1.26 crook 11070: @item
11071: End declaration
1.44 crook 11072:
1.26 crook 11073: doc---oof-how:
11074: doc---oof-class;
1.21 crook 11075:
1.44 crook 11076:
1.26 crook 11077: @end itemize
1.21 crook 11078:
1.26 crook 11079: @c -------------------------------------------------------------
11080: @node Class Implementation, , Class Declaration, OOF
11081: @subsubsection Class Implementation
11082: @cindex class implementation
1.21 crook 11083:
1.26 crook 11084: @c -------------------------------------------------------------
11085: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11086: @subsection The @file{mini-oof.fs} model
11087: @cindex mini-oof
1.1 anton 11088:
1.26 crook 11089: Gforth's third object oriented Forth package is a 12-liner. It uses a
11090: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
11091: and reduces to the bare minimum of features. This is based on a posting
11092: of Bernd Paysan in comp.arch.
1.1 anton 11093:
11094: @menu
1.48 anton 11095: * Basic Mini-OOF Usage::
11096: * Mini-OOF Example::
11097: * Mini-OOF Implementation::
11098: * Comparison with other object models::
1.1 anton 11099: @end menu
11100:
1.26 crook 11101: @c -------------------------------------------------------------
1.48 anton 11102: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
1.26 crook 11103: @subsubsection Basic @file{mini-oof.fs} Usage
11104: @cindex mini-oof usage
1.1 anton 11105:
1.28 crook 11106: There is a base class (@code{class}, which allocates one cell for the
11107: object pointer) plus seven other words: to define a method, a variable,
11108: a class; to end a class, to resolve binding, to allocate an object and
11109: to compile a class method.
1.26 crook 11110: @comment TODO better description of the last one
1.1 anton 11111:
1.44 crook 11112:
1.26 crook 11113: doc-object
11114: doc-method
11115: doc-var
11116: doc-class
11117: doc-end-class
11118: doc-defines
11119: doc-new
11120: doc-::
1.1 anton 11121:
1.21 crook 11122:
1.44 crook 11123:
1.26 crook 11124: @c -------------------------------------------------------------
11125: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11126: @subsubsection Mini-OOF Example
11127: @cindex mini-oof example
1.21 crook 11128:
1.26 crook 11129: A short example shows how to use this package. This example, in slightly
11130: extended form, is supplied as @file{moof-exm.fs}
1.29 crook 11131: @comment TODO could flesh this out with some comments from the Forthwrite article
1.21 crook 11132:
1.26 crook 11133: @example
11134: object class
11135: method init
11136: method draw
11137: end-class graphical
11138: @end example
1.21 crook 11139:
1.26 crook 11140: This code defines a class @code{graphical} with an
11141: operation @code{draw}. We can perform the operation
11142: @code{draw} on any @code{graphical} object, e.g.:
1.1 anton 11143:
1.26 crook 11144: @example
11145: 100 100 t-rex draw
11146: @end example
1.1 anton 11147:
1.26 crook 11148: where @code{t-rex} is an object or object pointer, created with e.g.
11149: @code{graphical new Constant t-rex}.
1.1 anton 11150:
1.26 crook 11151: For concrete graphical objects, we define child classes of the
11152: class @code{graphical}, e.g.:
1.21 crook 11153:
11154: @example
1.26 crook 11155: graphical class
11156: cell var circle-radius
11157: end-class circle \ "graphical" is the parent class
1.21 crook 11158:
1.26 crook 11159: :noname ( x y -- )
11160: circle-radius @@ draw-circle ; circle defines draw
11161: :noname ( r -- )
11162: circle-radius ! ; circle defines init
1.21 crook 11163: @end example
11164:
1.26 crook 11165: There is no implicit init method, so we have to define one. The creation
11166: code of the object now has to call init explicitely.
1.21 crook 11167:
1.26 crook 11168: @example
11169: circle new Constant my-circle
11170: 50 my-circle init
11171: @end example
1.21 crook 11172:
1.26 crook 11173: It is also possible to add a function to create named objects with
11174: automatic call of @code{init}, given that all objects have @code{init}
11175: on the same place:
1.1 anton 11176:
11177: @example
1.26 crook 11178: : new: ( .. o "name" -- )
11179: new dup Constant init ;
11180: 80 circle new: large-circle
1.1 anton 11181: @end example
11182:
1.26 crook 11183: We can draw this new circle at (100,100) with:
1.1 anton 11184:
11185: @example
1.26 crook 11186: 100 100 my-circle draw
1.1 anton 11187: @end example
11188:
1.48 anton 11189: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
1.26 crook 11190: @subsubsection @file{mini-oof.fs} Implementation
1.1 anton 11191:
1.26 crook 11192: Object-oriented systems with late binding typically use a
11193: ``vtable''-approach: the first variable in each object is a pointer to a
11194: table, which contains the methods as function pointers. The vtable
11195: may also contain other information.
1.1 anton 11196:
1.26 crook 11197: So first, let's declare methods:
1.1 anton 11198:
1.26 crook 11199: @example
11200: : method ( m v -- m' v ) Create over , swap cell+ swap
11201: DOES> ( ... o -- ... ) @ over @ + @ execute ;
11202: @end example
1.1 anton 11203:
1.26 crook 11204: During method declaration, the number of methods and instance
11205: variables is on the stack (in address units). @code{method} creates
11206: one method and increments the method number. To execute a method, it
11207: takes the object, fetches the vtable pointer, adds the offset, and
1.29 crook 11208: executes the @i{xt} stored there. Each method takes the object it is
1.26 crook 11209: invoked from as top of stack parameter. The method itself should
11210: consume that object.
1.1 anton 11211:
1.26 crook 11212: Now, we also have to declare instance variables
1.21 crook 11213:
1.26 crook 11214: @example
11215: : var ( m v size -- m v' ) Create over , +
11216: DOES> ( o -- addr ) @ + ;
11217: @end example
1.21 crook 11218:
1.26 crook 11219: As before, a word is created with the current offset. Instance
11220: variables can have different sizes (cells, floats, doubles, chars), so
11221: all we do is take the size and add it to the offset. If your machine
11222: has alignment restrictions, put the proper @code{aligned} or
11223: @code{faligned} before the variable, to adjust the variable
11224: offset. That's why it is on the top of stack.
1.2 jwilke 11225:
1.26 crook 11226: We need a starting point (the base object) and some syntactic sugar:
1.21 crook 11227:
1.26 crook 11228: @example
11229: Create object 1 cells , 2 cells ,
11230: : class ( class -- class methods vars ) dup 2@ ;
11231: @end example
1.21 crook 11232:
1.26 crook 11233: For inheritance, the vtable of the parent object has to be
11234: copied when a new, derived class is declared. This gives all the
11235: methods of the parent class, which can be overridden, though.
1.21 crook 11236:
1.2 jwilke 11237: @example
1.26 crook 11238: : end-class ( class methods vars -- )
11239: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11240: cell+ dup cell+ r> rot @ 2 cells /string move ;
11241: @end example
11242:
11243: The first line creates the vtable, initialized with
11244: @code{noop}s. The second line is the inheritance mechanism, it
11245: copies the xts from the parent vtable.
1.2 jwilke 11246:
1.26 crook 11247: We still have no way to define new methods, let's do that now:
1.2 jwilke 11248:
1.26 crook 11249: @example
11250: : defines ( xt class -- ) ' >body @ + ! ;
1.2 jwilke 11251: @end example
11252:
1.26 crook 11253: To allocate a new object, we need a word, too:
1.2 jwilke 11254:
1.26 crook 11255: @example
11256: : new ( class -- o ) here over @ allot swap over ! ;
11257: @end example
1.2 jwilke 11258:
1.26 crook 11259: Sometimes derived classes want to access the method of the
11260: parent object. There are two ways to achieve this with Mini-OOF:
11261: first, you could use named words, and second, you could look up the
11262: vtable of the parent object.
1.2 jwilke 11263:
1.26 crook 11264: @example
11265: : :: ( class "name" -- ) ' >body @ + @ compile, ;
11266: @end example
1.2 jwilke 11267:
11268:
1.26 crook 11269: Nothing can be more confusing than a good example, so here is
11270: one. First let's declare a text object (called
11271: @code{button}), that stores text and position:
1.2 jwilke 11272:
1.26 crook 11273: @example
11274: object class
11275: cell var text
11276: cell var len
11277: cell var x
11278: cell var y
11279: method init
11280: method draw
11281: end-class button
11282: @end example
1.2 jwilke 11283:
1.26 crook 11284: @noindent
11285: Now, implement the two methods, @code{draw} and @code{init}:
1.2 jwilke 11286:
1.26 crook 11287: @example
11288: :noname ( o -- )
11289: >r r@ x @ r@ y @ at-xy r@ text @ r> len @ type ;
11290: button defines draw
11291: :noname ( addr u o -- )
11292: >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
11293: button defines init
11294: @end example
1.2 jwilke 11295:
1.26 crook 11296: @noindent
11297: To demonstrate inheritance, we define a class @code{bold-button}, with no
11298: new data and no new methods:
1.2 jwilke 11299:
1.26 crook 11300: @example
11301: button class
11302: end-class bold-button
1.1 anton 11303:
1.26 crook 11304: : bold 27 emit ." [1m" ;
11305: : normal 27 emit ." [0m" ;
11306: @end example
1.1 anton 11307:
1.26 crook 11308: @noindent
11309: The class @code{bold-button} has a different draw method to
11310: @code{button}, but the new method is defined in terms of the draw method
11311: for @code{button}:
1.1 anton 11312:
1.26 crook 11313: @example
11314: :noname bold [ button :: draw ] normal ; bold-button defines draw
11315: @end example
1.1 anton 11316:
1.26 crook 11317: @noindent
11318: Finally, create two objects and apply methods:
1.1 anton 11319:
1.26 crook 11320: @example
11321: button new Constant foo
11322: s" thin foo" foo init
11323: page
11324: foo draw
11325: bold-button new Constant bar
11326: s" fat bar" bar init
11327: 1 bar y !
11328: bar draw
11329: @end example
1.1 anton 11330:
11331:
1.48 anton 11332: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11333: @subsection Comparison with other object models
1.26 crook 11334: @cindex comparison of object models
11335: @cindex object models, comparison
1.1 anton 11336:
1.26 crook 11337: Many object-oriented Forth extensions have been proposed (@cite{A survey
11338: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11339: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11340: relation of the object models described here to two well-known and two
11341: closely-related (by the use of method maps) models.
1.1 anton 11342:
1.26 crook 11343: @cindex Neon model
11344: The most popular model currently seems to be the Neon model (see
11345: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11346: 1997) by Andrew McKewan) but this model has a number of limitations
11347: @footnote{A longer version of this critique can be
11348: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11349: Dimensions, May 1997) by Anton Ertl.}:
1.1 anton 11350:
1.26 crook 11351: @itemize @bullet
11352: @item
1.48 anton 11353: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11354: to pass objects on the stack.
1.1 anton 11355:
1.26 crook 11356: @item
11357: It requires that the selector parses the input stream (at
11358: compile time); this leads to reduced extensibility and to bugs that are+
11359: hard to find.
1.1 anton 11360:
1.26 crook 11361: @item
11362: It allows using every selector to every object;
11363: this eliminates the need for classes, but makes it harder to create
11364: efficient implementations.
11365: @end itemize
1.1 anton 11366:
1.26 crook 11367: @cindex Pountain's object-oriented model
11368: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11369: Press, London, 1987) by Dick Pountain. However, it is not really about
11370: object-oriented programming, because it hardly deals with late
11371: binding. Instead, it focuses on features like information hiding and
11372: overloading that are characteristic of modular languages like Ada (83).
1.1 anton 11373:
1.26 crook 11374: @cindex Zsoter's object-oriented model
1.48 anton 11375: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1)
11376: 1996, pages 31-35) Andras Zsoter describes a model that makes heavy use
11377: of an active object (like @code{this} in @file{objects.fs}): The active
11378: object is not only used for accessing all fields, but also specifies the
11379: receiving object of every selector invocation; you have to change the
11380: active object explicitly with @code{@{ ... @}}, whereas in
11381: @file{objects.fs} it changes more or less implicitly at @code{m:
11382: ... ;m}. Such a change at the method entry point is unnecessary with the
11383: Zsoter's model, because the receiving object is the active object
11384: already. On the other hand, the explicit change is absolutely necessary
11385: in that model, because otherwise no one could ever change the active
11386: object. An ANS Forth implementation of this model is available at
11387: @uref{http://www.forth.org/fig/oopf.html}.
1.1 anton 11388:
1.26 crook 11389: @cindex @file{oof.fs}, differences to other models
11390: The @file{oof.fs} model combines information hiding and overloading
11391: resolution (by keeping names in various word lists) with object-oriented
11392: programming. It sets the active object implicitly on method entry, but
11393: also allows explicit changing (with @code{>o...o>} or with
11394: @code{with...endwith}). It uses parsing and state-smart objects and
11395: classes for resolving overloading and for early binding: the object or
11396: class parses the selector and determines the method from this. If the
11397: selector is not parsed by an object or class, it performs a call to the
11398: selector for the active object (late binding), like Zsoter's model.
11399: Fields are always accessed through the active object. The big
11400: disadvantage of this model is the parsing and the state-smartness, which
11401: reduces extensibility and increases the opportunities for subtle bugs;
11402: essentially, you are only safe if you never tick or @code{postpone} an
11403: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1 anton 11404:
1.26 crook 11405: @cindex @file{mini-oof.fs}, differences to other models
1.48 anton 11406: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11407: version of the @file{objects.fs} model, but syntactically it is a
11408: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.1 anton 11409:
1.26 crook 11410: @c -------------------------------------------------------------
1.47 crook 11411: @node Passing Commands to the OS, Keeping track of Time, Object-oriented Forth, Words
1.21 crook 11412: @section Passing Commands to the Operating System
11413: @cindex operating system - passing commands
11414: @cindex shell commands
11415:
11416: Gforth allows you to pass an arbitrary string to the host operating
11417: system shell (if such a thing exists) for execution.
11418:
1.44 crook 11419:
1.21 crook 11420: doc-sh
11421: doc-system
11422: doc-$?
1.23 crook 11423: doc-getenv
1.21 crook 11424:
1.44 crook 11425:
1.26 crook 11426: @c -------------------------------------------------------------
1.47 crook 11427: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
11428: @section Keeping track of Time
11429: @cindex time-related words
11430:
11431: Gforth implements time-related operations by making calls to the C
11432: library function, @code{gettimeofday}.
11433:
11434: doc-ms
11435: doc-time&date
11436:
11437:
11438:
11439: @c -------------------------------------------------------------
11440: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 11441: @section Miscellaneous Words
11442: @cindex miscellaneous words
11443:
1.29 crook 11444: @comment TODO find homes for these
11445:
1.26 crook 11446: These section lists the ANS Forth words that are not documented
1.21 crook 11447: elsewhere in this manual. Ultimately, they all need proper homes.
11448:
11449: doc-[compile]
11450:
1.44 crook 11451:
1.26 crook 11452: The following ANS Forth words are not currently supported by Gforth
1.27 crook 11453: (@pxref{ANS conformance}):
1.21 crook 11454:
11455: @code{EDITOR}
11456: @code{EMIT?}
11457: @code{FORGET}
11458:
1.24 anton 11459: @c ******************************************************************
11460: @node Error messages, Tools, Words, Top
11461: @chapter Error messages
11462: @cindex error messages
11463: @cindex backtrace
11464:
11465: A typical Gforth error message looks like this:
11466:
11467: @example
11468: in file included from :-1
11469: in file included from ./yyy.fs:1
11470: ./xxx.fs:4: Invalid memory address
11471: bar
11472: ^^^
1.25 anton 11473: $400E664C @@
11474: $400E6664 foo
1.24 anton 11475: @end example
11476:
11477: The message identifying the error is @code{Invalid memory address}. The
11478: error happened when text-interpreting line 4 of the file
11479: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
11480: word on the line where the error happened, is pointed out (with
11481: @code{^^^}).
11482:
11483: The file containing the error was included in line 1 of @file{./yyy.fs},
11484: and @file{yyy.fs} was included from a non-file (in this case, by giving
11485: @file{yyy.fs} as command-line parameter to Gforth).
11486:
11487: At the end of the error message you find a return stack dump that can be
11488: interpreted as a backtrace (possibly empty). On top you find the top of
11489: the return stack when the @code{throw} happened, and at the bottom you
11490: find the return stack entry just above the return stack of the topmost
11491: text interpreter.
11492:
11493: To the right of most return stack entries you see a guess for the word
11494: that pushed that return stack entry as its return address. This gives a
11495: backtrace. In our case we see that @code{bar} called @code{foo}, and
11496: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
11497: address} exception).
11498:
11499: Note that the backtrace is not perfect: We don't know which return stack
11500: entries are return addresses (so we may get false positives); and in
11501: some cases (e.g., for @code{abort"}) we cannot determine from the return
11502: address the word that pushed the return address, so for some return
11503: addresses you see no names in the return stack dump.
1.25 anton 11504:
11505: @cindex @code{catch} and backtraces
11506: The return stack dump represents the return stack at the time when a
11507: specific @code{throw} was executed. In programs that make use of
11508: @code{catch}, it is not necessarily clear which @code{throw} should be
11509: used for the return stack dump (e.g., consider one @code{throw} that
11510: indicates an error, which is caught, and during recovery another error
1.42 anton 11511: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 11512: presents the return stack dump for the first @code{throw} after the last
11513: executed (not returned-to) @code{catch}; this works well in the usual
11514: case.
11515:
11516: @cindex @code{gforth-fast} and backtraces
11517: @cindex @code{gforth-fast}, difference from @code{gforth}
11518: @cindex backtraces with @code{gforth-fast}
11519: @cindex return stack dump with @code{gforth-fast}
11520: @code{gforth} is able to do a return stack dump for throws generated
11521: from primitives (e.g., invalid memory address, stack empty etc.);
11522: @code{gforth-fast} is only able to do a return stack dump from a
11523: directly called @code{throw} (including @code{abort} etc.). This is the
1.30 anton 11524: only difference (apart from a speed factor of between 1.15 (K6-2) and
11525: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}. Given an
11526: exception caused by a primitive in @code{gforth-fast}, you will
11527: typically see no return stack dump at all; however, if the exception is
11528: caught by @code{catch} (e.g., for restoring some state), and then
11529: @code{throw}n again, the return stack dump will be for the first such
11530: @code{throw}.
1.2 jwilke 11531:
1.5 anton 11532: @c ******************************************************************
1.24 anton 11533: @node Tools, ANS conformance, Error messages, Top
1.1 anton 11534: @chapter Tools
11535:
11536: @menu
11537: * ANS Report:: Report the words used, sorted by wordset.
11538: @end menu
11539:
11540: See also @ref{Emacs and Gforth}.
11541:
11542: @node ANS Report, , Tools, Tools
11543: @section @file{ans-report.fs}: Report the words used, sorted by wordset
11544: @cindex @file{ans-report.fs}
11545: @cindex report the words used in your program
11546: @cindex words used in your program
11547:
11548: If you want to label a Forth program as ANS Forth Program, you must
11549: document which wordsets the program uses; for extension wordsets, it is
11550: helpful to list the words the program requires from these wordsets
11551: (because Forth systems are allowed to provide only some words of them).
11552:
11553: The @file{ans-report.fs} tool makes it easy for you to determine which
11554: words from which wordset and which non-ANS words your application
11555: uses. You simply have to include @file{ans-report.fs} before loading the
11556: program you want to check. After loading your program, you can get the
11557: report with @code{print-ans-report}. A typical use is to run this as
11558: batch job like this:
11559: @example
11560: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
11561: @end example
11562:
11563: The output looks like this (for @file{compat/control.fs}):
11564: @example
11565: The program uses the following words
11566: from CORE :
11567: : POSTPONE THEN ; immediate ?dup IF 0=
11568: from BLOCK-EXT :
11569: \
11570: from FILE :
11571: (
11572: @end example
11573:
11574: @subsection Caveats
11575:
11576: Note that @file{ans-report.fs} just checks which words are used, not whether
11577: they are used in an ANS Forth conforming way!
11578:
11579: Some words are defined in several wordsets in the
11580: standard. @file{ans-report.fs} reports them for only one of the
11581: wordsets, and not necessarily the one you expect. It depends on usage
11582: which wordset is the right one to specify. E.g., if you only use the
11583: compilation semantics of @code{S"}, it is a Core word; if you also use
11584: its interpretation semantics, it is a File word.
11585:
11586: @c ******************************************************************
11587: @node ANS conformance, Model, Tools, Top
11588: @chapter ANS conformance
11589: @cindex ANS conformance of Gforth
11590:
11591: To the best of our knowledge, Gforth is an
11592:
11593: ANS Forth System
11594: @itemize @bullet
11595: @item providing the Core Extensions word set
11596: @item providing the Block word set
11597: @item providing the Block Extensions word set
11598: @item providing the Double-Number word set
11599: @item providing the Double-Number Extensions word set
11600: @item providing the Exception word set
11601: @item providing the Exception Extensions word set
11602: @item providing the Facility word set
1.40 anton 11603: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 11604: @item providing the File Access word set
11605: @item providing the File Access Extensions word set
11606: @item providing the Floating-Point word set
11607: @item providing the Floating-Point Extensions word set
11608: @item providing the Locals word set
11609: @item providing the Locals Extensions word set
11610: @item providing the Memory-Allocation word set
11611: @item providing the Memory-Allocation Extensions word set (that one's easy)
11612: @item providing the Programming-Tools word set
11613: @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
11614: @item providing the Search-Order word set
11615: @item providing the Search-Order Extensions word set
11616: @item providing the String word set
11617: @item providing the String Extensions word set (another easy one)
11618: @end itemize
11619:
11620: @cindex system documentation
11621: In addition, ANS Forth systems are required to document certain
11622: implementation choices. This chapter tries to meet these
11623: requirements. In many cases it gives a way to ask the system for the
11624: information instead of providing the information directly, in
11625: particular, if the information depends on the processor, the operating
11626: system or the installation options chosen, or if they are likely to
11627: change during the maintenance of Gforth.
11628:
11629: @comment The framework for the rest has been taken from pfe.
11630:
11631: @menu
11632: * The Core Words::
11633: * The optional Block word set::
11634: * The optional Double Number word set::
11635: * The optional Exception word set::
11636: * The optional Facility word set::
11637: * The optional File-Access word set::
11638: * The optional Floating-Point word set::
11639: * The optional Locals word set::
11640: * The optional Memory-Allocation word set::
11641: * The optional Programming-Tools word set::
11642: * The optional Search-Order word set::
11643: @end menu
11644:
11645:
11646: @c =====================================================================
11647: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
11648: @comment node-name, next, previous, up
11649: @section The Core Words
11650: @c =====================================================================
11651: @cindex core words, system documentation
11652: @cindex system documentation, core words
11653:
11654: @menu
11655: * core-idef:: Implementation Defined Options
11656: * core-ambcond:: Ambiguous Conditions
11657: * core-other:: Other System Documentation
11658: @end menu
11659:
11660: @c ---------------------------------------------------------------------
11661: @node core-idef, core-ambcond, The Core Words, The Core Words
11662: @subsection Implementation Defined Options
11663: @c ---------------------------------------------------------------------
11664: @cindex core words, implementation-defined options
11665: @cindex implementation-defined options, core words
11666:
11667:
11668: @table @i
11669: @item (Cell) aligned addresses:
11670: @cindex cell-aligned addresses
11671: @cindex aligned addresses
11672: processor-dependent. Gforth's alignment words perform natural alignment
11673: (e.g., an address aligned for a datum of size 8 is divisible by
11674: 8). Unaligned accesses usually result in a @code{-23 THROW}.
11675:
11676: @item @code{EMIT} and non-graphic characters:
11677: @cindex @code{EMIT} and non-graphic characters
11678: @cindex non-graphic characters and @code{EMIT}
11679: The character is output using the C library function (actually, macro)
11680: @code{putc}.
11681:
11682: @item character editing of @code{ACCEPT} and @code{EXPECT}:
11683: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
11684: @cindex editing in @code{ACCEPT} and @code{EXPECT}
11685: @cindex @code{ACCEPT}, editing
11686: @cindex @code{EXPECT}, editing
11687: This is modeled on the GNU readline library (@pxref{Readline
11688: Interaction, , Command Line Editing, readline, The GNU Readline
11689: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
11690: producing a full word completion every time you type it (instead of
1.28 crook 11691: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 11692:
11693: @item character set:
11694: @cindex character set
11695: The character set of your computer and display device. Gforth is
11696: 8-bit-clean (but some other component in your system may make trouble).
11697:
11698: @item Character-aligned address requirements:
11699: @cindex character-aligned address requirements
11700: installation-dependent. Currently a character is represented by a C
11701: @code{unsigned char}; in the future we might switch to @code{wchar_t}
11702: (Comments on that requested).
11703:
11704: @item character-set extensions and matching of names:
11705: @cindex character-set extensions and matching of names
1.26 crook 11706: @cindex case-sensitivity for name lookup
11707: @cindex name lookup, case-sensitivity
11708: @cindex locale and case-sensitivity
1.21 crook 11709: Any character except the ASCII NUL character can be used in a
1.1 anton 11710: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 11711: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 11712: function is probably influenced by the locale. E.g., the @code{C} locale
11713: does not know about accents and umlauts, so they are matched
11714: case-sensitively in that locale. For portability reasons it is best to
11715: write programs such that they work in the @code{C} locale. Then one can
11716: use libraries written by a Polish programmer (who might use words
11717: containing ISO Latin-2 encoded characters) and by a French programmer
11718: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
11719: funny results for some of the words (which ones, depends on the font you
11720: are using)). Also, the locale you prefer may not be available in other
11721: operating systems. Hopefully, Unicode will solve these problems one day.
11722:
11723: @item conditions under which control characters match a space delimiter:
11724: @cindex space delimiters
11725: @cindex control characters as delimiters
11726: If @code{WORD} is called with the space character as a delimiter, all
11727: white-space characters (as identified by the C macro @code{isspace()})
11728: are delimiters. @code{PARSE}, on the other hand, treats space like other
1.44 crook 11729: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
1.1 anton 11730: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
11731: interpreter (aka text interpreter) by default, treats all white-space
11732: characters as delimiters.
11733:
1.26 crook 11734: @item format of the control-flow stack:
11735: @cindex control-flow stack, format
11736: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 11737: stack item in cells is given by the constant @code{cs-item-size}. At the
11738: time of this writing, an item consists of a (pointer to a) locals list
11739: (third), an address in the code (second), and a tag for identifying the
11740: item (TOS). The following tags are used: @code{defstart},
11741: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
11742: @code{scopestart}.
11743:
11744: @item conversion of digits > 35
11745: @cindex digits > 35
11746: The characters @code{[\]^_'} are the digits with the decimal value
11747: 36@minus{}41. There is no way to input many of the larger digits.
11748:
11749: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
11750: @cindex @code{EXPECT}, display after end of input
11751: @cindex @code{ACCEPT}, display after end of input
11752: The cursor is moved to the end of the entered string. If the input is
11753: terminated using the @kbd{Return} key, a space is typed.
11754:
11755: @item exception abort sequence of @code{ABORT"}:
11756: @cindex exception abort sequence of @code{ABORT"}
11757: @cindex @code{ABORT"}, exception abort sequence
11758: The error string is stored into the variable @code{"error} and a
11759: @code{-2 throw} is performed.
11760:
11761: @item input line terminator:
11762: @cindex input line terminator
11763: @cindex line terminator on input
1.26 crook 11764: @cindex newline character on input
1.1 anton 11765: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
11766: lines. One of these characters is typically produced when you type the
11767: @kbd{Enter} or @kbd{Return} key.
11768:
11769: @item maximum size of a counted string:
11770: @cindex maximum size of a counted string
11771: @cindex counted string, maximum size
11772: @code{s" /counted-string" environment? drop .}. Currently 255 characters
11773: on all ports, but this may change.
11774:
11775: @item maximum size of a parsed string:
11776: @cindex maximum size of a parsed string
11777: @cindex parsed string, maximum size
11778: Given by the constant @code{/line}. Currently 255 characters.
11779:
11780: @item maximum size of a definition name, in characters:
11781: @cindex maximum size of a definition name, in characters
11782: @cindex name, maximum length
11783: 31
11784:
11785: @item maximum string length for @code{ENVIRONMENT?}, in characters:
11786: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
11787: @cindex @code{ENVIRONMENT?} string length, maximum
11788: 31
11789:
11790: @item method of selecting the user input device:
11791: @cindex user input device, method of selecting
11792: The user input device is the standard input. There is currently no way to
11793: change it from within Gforth. However, the input can typically be
11794: redirected in the command line that starts Gforth.
11795:
11796: @item method of selecting the user output device:
11797: @cindex user output device, method of selecting
11798: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 11799: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
11800: output when the user output device is a terminal, otherwise the output
11801: is buffered.
1.1 anton 11802:
11803: @item methods of dictionary compilation:
11804: What are we expected to document here?
11805:
11806: @item number of bits in one address unit:
11807: @cindex number of bits in one address unit
11808: @cindex address unit, size in bits
11809: @code{s" address-units-bits" environment? drop .}. 8 in all current
11810: ports.
11811:
11812: @item number representation and arithmetic:
11813: @cindex number representation and arithmetic
11814: Processor-dependent. Binary two's complement on all current ports.
11815:
11816: @item ranges for integer types:
11817: @cindex ranges for integer types
11818: @cindex integer types, ranges
11819: Installation-dependent. Make environmental queries for @code{MAX-N},
11820: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
11821: unsigned (and positive) types is 0. The lower bound for signed types on
11822: two's complement and one's complement machines machines can be computed
11823: by adding 1 to the upper bound.
11824:
11825: @item read-only data space regions:
11826: @cindex read-only data space regions
11827: @cindex data-space, read-only regions
11828: The whole Forth data space is writable.
11829:
11830: @item size of buffer at @code{WORD}:
11831: @cindex size of buffer at @code{WORD}
11832: @cindex @code{WORD} buffer size
11833: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
11834: shared with the pictured numeric output string. If overwriting
11835: @code{PAD} is acceptable, it is as large as the remaining dictionary
11836: space, although only as much can be sensibly used as fits in a counted
11837: string.
11838:
11839: @item size of one cell in address units:
11840: @cindex cell size
11841: @code{1 cells .}.
11842:
11843: @item size of one character in address units:
11844: @cindex char size
11845: @code{1 chars .}. 1 on all current ports.
11846:
11847: @item size of the keyboard terminal buffer:
11848: @cindex size of the keyboard terminal buffer
11849: @cindex terminal buffer, size
11850: Varies. You can determine the size at a specific time using @code{lp@@
11851: tib - .}. It is shared with the locals stack and TIBs of files that
11852: include the current file. You can change the amount of space for TIBs
11853: and locals stack at Gforth startup with the command line option
11854: @code{-l}.
11855:
11856: @item size of the pictured numeric output buffer:
11857: @cindex size of the pictured numeric output buffer
11858: @cindex pictured numeric output buffer, size
11859: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
11860: shared with @code{WORD}.
11861:
11862: @item size of the scratch area returned by @code{PAD}:
11863: @cindex size of the scratch area returned by @code{PAD}
11864: @cindex @code{PAD} size
11865: The remainder of dictionary space. @code{unused pad here - - .}.
11866:
11867: @item system case-sensitivity characteristics:
11868: @cindex case-sensitivity characteristics
1.26 crook 11869: Dictionary searches are case-insensitive (except in
1.1 anton 11870: @code{TABLE}s). However, as explained above under @i{character-set
11871: extensions}, the matching for non-ASCII characters is determined by the
11872: locale you are using. In the default @code{C} locale all non-ASCII
11873: characters are matched case-sensitively.
11874:
11875: @item system prompt:
11876: @cindex system prompt
11877: @cindex prompt
11878: @code{ ok} in interpret state, @code{ compiled} in compile state.
11879:
11880: @item division rounding:
11881: @cindex division rounding
11882: installation dependent. @code{s" floored" environment? drop .}. We leave
11883: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
11884: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
11885:
11886: @item values of @code{STATE} when true:
11887: @cindex @code{STATE} values
11888: -1.
11889:
11890: @item values returned after arithmetic overflow:
11891: On two's complement machines, arithmetic is performed modulo
11892: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
11893: arithmetic (with appropriate mapping for signed types). Division by zero
11894: typically results in a @code{-55 throw} (Floating-point unidentified
11895: fault), although a @code{-10 throw} (divide by zero) would be more
11896: appropriate.
11897:
11898: @item whether the current definition can be found after @t{DOES>}:
11899: @cindex @t{DOES>}, visibility of current definition
11900: No.
11901:
11902: @end table
11903:
11904: @c ---------------------------------------------------------------------
11905: @node core-ambcond, core-other, core-idef, The Core Words
11906: @subsection Ambiguous conditions
11907: @c ---------------------------------------------------------------------
11908: @cindex core words, ambiguous conditions
11909: @cindex ambiguous conditions, core words
11910:
11911: @table @i
11912:
11913: @item a name is neither a word nor a number:
11914: @cindex name not found
1.26 crook 11915: @cindex undefined word
1.1 anton 11916: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
11917: preserves the data and FP stack, so you don't lose more work than
11918: necessary.
11919:
11920: @item a definition name exceeds the maximum length allowed:
1.26 crook 11921: @cindex word name too long
1.1 anton 11922: @code{-19 throw} (Word name too long)
11923:
11924: @item addressing a region not inside the various data spaces of the forth system:
11925: @cindex Invalid memory address
1.32 anton 11926: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 11927: typically readable. Accessing other addresses gives results dependent on
11928: the operating system. On decent systems: @code{-9 throw} (Invalid memory
11929: address).
11930:
11931: @item argument type incompatible with parameter:
1.26 crook 11932: @cindex argument type mismatch
1.1 anton 11933: This is usually not caught. Some words perform checks, e.g., the control
11934: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
11935: mismatch).
11936:
11937: @item attempting to obtain the execution token of a word with undefined execution semantics:
11938: @cindex Interpreting a compile-only word, for @code{'} etc.
11939: @cindex execution token of words with undefined execution semantics
11940: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
11941: get an execution token for @code{compile-only-error} (which performs a
11942: @code{-14 throw} when executed).
11943:
11944: @item dividing by zero:
11945: @cindex dividing by zero
11946: @cindex floating point unidentified fault, integer division
1.24 anton 11947: On better platforms, this produces a @code{-10 throw} (Division by
11948: zero); on other systems, this typically results in a @code{-55 throw}
11949: (Floating-point unidentified fault).
1.1 anton 11950:
11951: @item insufficient data stack or return stack space:
11952: @cindex insufficient data stack or return stack space
11953: @cindex stack overflow
1.26 crook 11954: @cindex address alignment exception, stack overflow
1.1 anton 11955: @cindex Invalid memory address, stack overflow
11956: Depending on the operating system, the installation, and the invocation
11957: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 11958: it is not checked. If it is checked, you typically get a @code{-3 throw}
11959: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
11960: throw} (Invalid memory address) (depending on the platform and how you
11961: achieved the overflow) as soon as the overflow happens. If it is not
11962: checked, overflows typically result in mysterious illegal memory
11963: accesses, producing @code{-9 throw} (Invalid memory address) or
11964: @code{-23 throw} (Address alignment exception); they might also destroy
11965: the internal data structure of @code{ALLOCATE} and friends, resulting in
11966: various errors in these words.
1.1 anton 11967:
11968: @item insufficient space for loop control parameters:
11969: @cindex insufficient space for loop control parameters
11970: like other return stack overflows.
11971:
11972: @item insufficient space in the dictionary:
11973: @cindex insufficient space in the dictionary
11974: @cindex dictionary overflow
1.12 anton 11975: If you try to allot (either directly with @code{allot}, or indirectly
11976: with @code{,}, @code{create} etc.) more memory than available in the
11977: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
11978: to access memory beyond the end of the dictionary, the results are
11979: similar to stack overflows.
1.1 anton 11980:
11981: @item interpreting a word with undefined interpretation semantics:
11982: @cindex interpreting a word with undefined interpretation semantics
11983: @cindex Interpreting a compile-only word
11984: For some words, we have defined interpretation semantics. For the
11985: others: @code{-14 throw} (Interpreting a compile-only word).
11986:
11987: @item modifying the contents of the input buffer or a string literal:
11988: @cindex modifying the contents of the input buffer or a string literal
11989: These are located in writable memory and can be modified.
11990:
11991: @item overflow of the pictured numeric output string:
11992: @cindex overflow of the pictured numeric output string
11993: @cindex pictured numeric output string, overflow
1.24 anton 11994: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 11995:
11996: @item parsed string overflow:
11997: @cindex parsed string overflow
11998: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
11999:
12000: @item producing a result out of range:
12001: @cindex result out of range
12002: On two's complement machines, arithmetic is performed modulo
12003: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12004: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12005: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12006: throw} (floating point unidentified fault). @code{convert} and
12007: @code{>number} currently overflow silently.
1.1 anton 12008:
12009: @item reading from an empty data or return stack:
12010: @cindex stack empty
12011: @cindex stack underflow
1.24 anton 12012: @cindex return stack underflow
1.1 anton 12013: The data stack is checked by the outer (aka text) interpreter after
12014: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12015: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 12016: depending on operating system, installation, and invocation. If they are
12017: caught by a check, they typically result in @code{-4 throw} (Stack
12018: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12019: (Invalid memory address), depending on the platform and which stack
12020: underflows and by how much. Note that even if the system uses checking
12021: (through the MMU), your program may have to underflow by a significant
12022: number of stack items to trigger the reaction (the reason for this is
12023: that the MMU, and therefore the checking, works with a page-size
12024: granularity). If there is no checking, the symptoms resulting from an
12025: underflow are similar to those from an overflow. Unbalanced return
12026: stack errors result in a variaty of symptoms, including @code{-9 throw}
12027: (Invalid memory address) and Illegal Instruction (typically @code{-260
12028: throw}).
1.1 anton 12029:
12030: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12031: @cindex unexpected end of the input buffer
12032: @cindex zero-length string as a name
12033: @cindex Attempt to use zero-length string as a name
12034: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12035: use zero-length string as a name). Words like @code{'} probably will not
12036: find what they search. Note that it is possible to create zero-length
12037: names with @code{nextname} (should it not?).
12038:
12039: @item @code{>IN} greater than input buffer:
12040: @cindex @code{>IN} greater than input buffer
12041: The next invocation of a parsing word returns a string with length 0.
12042:
12043: @item @code{RECURSE} appears after @code{DOES>}:
12044: @cindex @code{RECURSE} appears after @code{DOES>}
12045: Compiles a recursive call to the defining word, not to the defined word.
12046:
12047: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12048: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 12049: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 12050: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12051: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12052: the end of the file was reached), its source-id may be
12053: reused. Therefore, restoring an input source specification referencing a
12054: closed file may lead to unpredictable results instead of a @code{-12
12055: THROW}.
12056:
12057: In the future, Gforth may be able to restore input source specifications
12058: from other than the current input source.
12059:
12060: @item data space containing definitions gets de-allocated:
12061: @cindex data space containing definitions gets de-allocated
12062: Deallocation with @code{allot} is not checked. This typically results in
12063: memory access faults or execution of illegal instructions.
12064:
12065: @item data space read/write with incorrect alignment:
12066: @cindex data space read/write with incorrect alignment
12067: @cindex alignment faults
1.26 crook 12068: @cindex address alignment exception
1.1 anton 12069: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 12070: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 12071: alignment turned on, incorrect alignment results in a @code{-9 throw}
12072: (Invalid memory address). There are reportedly some processors with
1.12 anton 12073: alignment restrictions that do not report violations.
1.1 anton 12074:
12075: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12076: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12077: Like other alignment errors.
12078:
12079: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12080: Like other stack underflows.
12081:
12082: @item loop control parameters not available:
12083: @cindex loop control parameters not available
12084: Not checked. The counted loop words simply assume that the top of return
12085: stack items are loop control parameters and behave accordingly.
12086:
12087: @item most recent definition does not have a name (@code{IMMEDIATE}):
12088: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12089: @cindex last word was headerless
12090: @code{abort" last word was headerless"}.
12091:
12092: @item name not defined by @code{VALUE} used by @code{TO}:
12093: @cindex name not defined by @code{VALUE} used by @code{TO}
12094: @cindex @code{TO} on non-@code{VALUE}s
12095: @cindex Invalid name argument, @code{TO}
12096: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12097: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12098:
12099: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12100: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 12101: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 12102: @code{-13 throw} (Undefined word)
12103:
12104: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12105: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12106: Gforth behaves as if they were of the same type. I.e., you can predict
12107: the behaviour by interpreting all parameters as, e.g., signed.
12108:
12109: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12110: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12111: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12112: compilation semantics of @code{TO}.
12113:
12114: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 12115: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 12116: @cindex @code{WORD}, string overflow
12117: Not checked. The string will be ok, but the count will, of course,
12118: contain only the least significant bits of the length.
12119:
12120: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12121: @cindex @code{LSHIFT}, large shift counts
12122: @cindex @code{RSHIFT}, large shift counts
12123: Processor-dependent. Typical behaviours are returning 0 and using only
12124: the low bits of the shift count.
12125:
12126: @item word not defined via @code{CREATE}:
12127: @cindex @code{>BODY} of non-@code{CREATE}d words
12128: @code{>BODY} produces the PFA of the word no matter how it was defined.
12129:
12130: @cindex @code{DOES>} of non-@code{CREATE}d words
12131: @code{DOES>} changes the execution semantics of the last defined word no
12132: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12133: @code{CREATE , DOES>}.
12134:
12135: @item words improperly used outside @code{<#} and @code{#>}:
12136: Not checked. As usual, you can expect memory faults.
12137:
12138: @end table
12139:
12140:
12141: @c ---------------------------------------------------------------------
12142: @node core-other, , core-ambcond, The Core Words
12143: @subsection Other system documentation
12144: @c ---------------------------------------------------------------------
12145: @cindex other system documentation, core words
12146: @cindex core words, other system documentation
12147:
12148: @table @i
12149: @item nonstandard words using @code{PAD}:
12150: @cindex @code{PAD} use by nonstandard words
12151: None.
12152:
12153: @item operator's terminal facilities available:
12154: @cindex operator's terminal facilities available
12155: After processing the command line, Gforth goes into interactive mode,
12156: and you can give commands to Gforth interactively. The actual facilities
12157: available depend on how you invoke Gforth.
12158:
12159: @item program data space available:
12160: @cindex program data space available
12161: @cindex data space available
12162: @code{UNUSED .} gives the remaining dictionary space. The total
12163: dictionary space can be specified with the @code{-m} switch
12164: (@pxref{Invoking Gforth}) when Gforth starts up.
12165:
12166: @item return stack space available:
12167: @cindex return stack space available
12168: You can compute the total return stack space in cells with
12169: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12170: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12171:
12172: @item stack space available:
12173: @cindex stack space available
12174: You can compute the total data stack space in cells with
12175: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12176: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12177:
12178: @item system dictionary space required, in address units:
12179: @cindex system dictionary space required, in address units
12180: Type @code{here forthstart - .} after startup. At the time of this
12181: writing, this gives 80080 (bytes) on a 32-bit system.
12182: @end table
12183:
12184:
12185: @c =====================================================================
12186: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12187: @section The optional Block word set
12188: @c =====================================================================
12189: @cindex system documentation, block words
12190: @cindex block words, system documentation
12191:
12192: @menu
12193: * block-idef:: Implementation Defined Options
12194: * block-ambcond:: Ambiguous Conditions
12195: * block-other:: Other System Documentation
12196: @end menu
12197:
12198:
12199: @c ---------------------------------------------------------------------
12200: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12201: @subsection Implementation Defined Options
12202: @c ---------------------------------------------------------------------
12203: @cindex implementation-defined options, block words
12204: @cindex block words, implementation-defined options
12205:
12206: @table @i
12207: @item the format for display by @code{LIST}:
12208: @cindex @code{LIST} display format
12209: First the screen number is displayed, then 16 lines of 64 characters,
12210: each line preceded by the line number.
12211:
12212: @item the length of a line affected by @code{\}:
12213: @cindex length of a line affected by @code{\}
12214: @cindex @code{\}, line length in blocks
12215: 64 characters.
12216: @end table
12217:
12218:
12219: @c ---------------------------------------------------------------------
12220: @node block-ambcond, block-other, block-idef, The optional Block word set
12221: @subsection Ambiguous conditions
12222: @c ---------------------------------------------------------------------
12223: @cindex block words, ambiguous conditions
12224: @cindex ambiguous conditions, block words
12225:
12226: @table @i
12227: @item correct block read was not possible:
12228: @cindex block read not possible
12229: Typically results in a @code{throw} of some OS-derived value (between
12230: -512 and -2048). If the blocks file was just not long enough, blanks are
12231: supplied for the missing portion.
12232:
12233: @item I/O exception in block transfer:
12234: @cindex I/O exception in block transfer
12235: @cindex block transfer, I/O exception
12236: Typically results in a @code{throw} of some OS-derived value (between
12237: -512 and -2048).
12238:
12239: @item invalid block number:
12240: @cindex invalid block number
12241: @cindex block number invalid
12242: @code{-35 throw} (Invalid block number)
12243:
12244: @item a program directly alters the contents of @code{BLK}:
12245: @cindex @code{BLK}, altering @code{BLK}
12246: The input stream is switched to that other block, at the same
12247: position. If the storing to @code{BLK} happens when interpreting
12248: non-block input, the system will get quite confused when the block ends.
12249:
12250: @item no current block buffer for @code{UPDATE}:
12251: @cindex @code{UPDATE}, no current block buffer
12252: @code{UPDATE} has no effect.
12253:
12254: @end table
12255:
12256: @c ---------------------------------------------------------------------
12257: @node block-other, , block-ambcond, The optional Block word set
12258: @subsection Other system documentation
12259: @c ---------------------------------------------------------------------
12260: @cindex other system documentation, block words
12261: @cindex block words, other system documentation
12262:
12263: @table @i
12264: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12265: No restrictions (yet).
12266:
12267: @item the number of blocks available for source and data:
12268: depends on your disk space.
12269:
12270: @end table
12271:
12272:
12273: @c =====================================================================
12274: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12275: @section The optional Double Number word set
12276: @c =====================================================================
12277: @cindex system documentation, double words
12278: @cindex double words, system documentation
12279:
12280: @menu
12281: * double-ambcond:: Ambiguous Conditions
12282: @end menu
12283:
12284:
12285: @c ---------------------------------------------------------------------
12286: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
12287: @subsection Ambiguous conditions
12288: @c ---------------------------------------------------------------------
12289: @cindex double words, ambiguous conditions
12290: @cindex ambiguous conditions, double words
12291:
12292: @table @i
1.29 crook 12293: @item @i{d} outside of range of @i{n} in @code{D>S}:
12294: @cindex @code{D>S}, @i{d} out of range of @i{n}
12295: The least significant cell of @i{d} is produced.
1.1 anton 12296:
12297: @end table
12298:
12299:
12300: @c =====================================================================
12301: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
12302: @section The optional Exception word set
12303: @c =====================================================================
12304: @cindex system documentation, exception words
12305: @cindex exception words, system documentation
12306:
12307: @menu
12308: * exception-idef:: Implementation Defined Options
12309: @end menu
12310:
12311:
12312: @c ---------------------------------------------------------------------
12313: @node exception-idef, , The optional Exception word set, The optional Exception word set
12314: @subsection Implementation Defined Options
12315: @c ---------------------------------------------------------------------
12316: @cindex implementation-defined options, exception words
12317: @cindex exception words, implementation-defined options
12318:
12319: @table @i
12320: @item @code{THROW}-codes used in the system:
12321: @cindex @code{THROW}-codes used in the system
12322: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 12323: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 12324: codes -512@minus{}-2047 are used for OS errors (for file and memory
12325: allocation operations). The mapping from OS error numbers to throw codes
12326: is -512@minus{}@code{errno}. One side effect of this mapping is that
12327: undefined OS errors produce a message with a strange number; e.g.,
12328: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
12329: @end table
12330:
12331: @c =====================================================================
12332: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
12333: @section The optional Facility word set
12334: @c =====================================================================
12335: @cindex system documentation, facility words
12336: @cindex facility words, system documentation
12337:
12338: @menu
12339: * facility-idef:: Implementation Defined Options
12340: * facility-ambcond:: Ambiguous Conditions
12341: @end menu
12342:
12343:
12344: @c ---------------------------------------------------------------------
12345: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
12346: @subsection Implementation Defined Options
12347: @c ---------------------------------------------------------------------
12348: @cindex implementation-defined options, facility words
12349: @cindex facility words, implementation-defined options
12350:
12351: @table @i
12352: @item encoding of keyboard events (@code{EKEY}):
12353: @cindex keyboard events, encoding in @code{EKEY}
12354: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 12355: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 12356: Other keys are encoded with the constants @code{k-left}, @code{k-right},
12357: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
12358: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
12359: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 12360:
1.1 anton 12361:
12362: @item duration of a system clock tick:
12363: @cindex duration of a system clock tick
12364: @cindex clock tick duration
12365: System dependent. With respect to @code{MS}, the time is specified in
12366: microseconds. How well the OS and the hardware implement this, is
12367: another question.
12368:
12369: @item repeatability to be expected from the execution of @code{MS}:
12370: @cindex repeatability to be expected from the execution of @code{MS}
12371: @cindex @code{MS}, repeatability to be expected
12372: System dependent. On Unix, a lot depends on load. If the system is
12373: lightly loaded, and the delay is short enough that Gforth does not get
12374: swapped out, the performance should be acceptable. Under MS-DOS and
12375: other single-tasking systems, it should be good.
12376:
12377: @end table
12378:
12379:
12380: @c ---------------------------------------------------------------------
12381: @node facility-ambcond, , facility-idef, The optional Facility word set
12382: @subsection Ambiguous conditions
12383: @c ---------------------------------------------------------------------
12384: @cindex facility words, ambiguous conditions
12385: @cindex ambiguous conditions, facility words
12386:
12387: @table @i
12388: @item @code{AT-XY} can't be performed on user output device:
12389: @cindex @code{AT-XY} can't be performed on user output device
12390: Largely terminal dependent. No range checks are done on the arguments.
12391: No errors are reported. You may see some garbage appearing, you may see
12392: simply nothing happen.
12393:
12394: @end table
12395:
12396:
12397: @c =====================================================================
12398: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
12399: @section The optional File-Access word set
12400: @c =====================================================================
12401: @cindex system documentation, file words
12402: @cindex file words, system documentation
12403:
12404: @menu
12405: * file-idef:: Implementation Defined Options
12406: * file-ambcond:: Ambiguous Conditions
12407: @end menu
12408:
12409: @c ---------------------------------------------------------------------
12410: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
12411: @subsection Implementation Defined Options
12412: @c ---------------------------------------------------------------------
12413: @cindex implementation-defined options, file words
12414: @cindex file words, implementation-defined options
12415:
12416: @table @i
12417: @item file access methods used:
12418: @cindex file access methods used
12419: @code{R/O}, @code{R/W} and @code{BIN} work as you would
12420: expect. @code{W/O} translates into the C file opening mode @code{w} (or
12421: @code{wb}): The file is cleared, if it exists, and created, if it does
12422: not (with both @code{open-file} and @code{create-file}). Under Unix
12423: @code{create-file} creates a file with 666 permissions modified by your
12424: umask.
12425:
12426: @item file exceptions:
12427: @cindex file exceptions
12428: The file words do not raise exceptions (except, perhaps, memory access
12429: faults when you pass illegal addresses or file-ids).
12430:
12431: @item file line terminator:
12432: @cindex file line terminator
12433: System-dependent. Gforth uses C's newline character as line
12434: terminator. What the actual character code(s) of this are is
12435: system-dependent.
12436:
12437: @item file name format:
12438: @cindex file name format
12439: System dependent. Gforth just uses the file name format of your OS.
12440:
12441: @item information returned by @code{FILE-STATUS}:
12442: @cindex @code{FILE-STATUS}, returned information
12443: @code{FILE-STATUS} returns the most powerful file access mode allowed
12444: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
12445: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
12446: along with the returned mode.
12447:
12448: @item input file state after an exception when including source:
12449: @cindex exception when including source
12450: All files that are left via the exception are closed.
12451:
1.29 crook 12452: @item @i{ior} values and meaning:
12453: @cindex @i{ior} values and meaning
12454: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 12455: intended as throw codes. They typically are in the range
12456: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 12457: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 12458:
12459: @item maximum depth of file input nesting:
12460: @cindex maximum depth of file input nesting
12461: @cindex file input nesting, maximum depth
12462: limited by the amount of return stack, locals/TIB stack, and the number
12463: of open files available. This should not give you troubles.
12464:
12465: @item maximum size of input line:
12466: @cindex maximum size of input line
12467: @cindex input line size, maximum
12468: @code{/line}. Currently 255.
12469:
12470: @item methods of mapping block ranges to files:
12471: @cindex mapping block ranges to files
12472: @cindex files containing blocks
12473: @cindex blocks in files
12474: By default, blocks are accessed in the file @file{blocks.fb} in the
12475: current working directory. The file can be switched with @code{USE}.
12476:
12477: @item number of string buffers provided by @code{S"}:
12478: @cindex @code{S"}, number of string buffers
12479: 1
12480:
12481: @item size of string buffer used by @code{S"}:
12482: @cindex @code{S"}, size of string buffer
12483: @code{/line}. currently 255.
12484:
12485: @end table
12486:
12487: @c ---------------------------------------------------------------------
12488: @node file-ambcond, , file-idef, The optional File-Access word set
12489: @subsection Ambiguous conditions
12490: @c ---------------------------------------------------------------------
12491: @cindex file words, ambiguous conditions
12492: @cindex ambiguous conditions, file words
12493:
12494: @table @i
12495: @item attempting to position a file outside its boundaries:
12496: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
12497: @code{REPOSITION-FILE} is performed as usual: Afterwards,
12498: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
12499:
12500: @item attempting to read from file positions not yet written:
12501: @cindex reading from file positions not yet written
12502: End-of-file, i.e., zero characters are read and no error is reported.
12503:
1.29 crook 12504: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
12505: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 12506: An appropriate exception may be thrown, but a memory fault or other
12507: problem is more probable.
12508:
1.29 crook 12509: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
12510: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
12511: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
12512: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 12513: thrown.
12514:
12515: @item named file cannot be opened (@code{INCLUDED}):
12516: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 12517: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 12518:
12519: @item requesting an unmapped block number:
12520: @cindex unmapped block numbers
12521: There are no unmapped legal block numbers. On some operating systems,
12522: writing a block with a large number may overflow the file system and
12523: have an error message as consequence.
12524:
12525: @item using @code{source-id} when @code{blk} is non-zero:
12526: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
12527: @code{source-id} performs its function. Typically it will give the id of
12528: the source which loaded the block. (Better ideas?)
12529:
12530: @end table
12531:
12532:
12533: @c =====================================================================
12534: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
12535: @section The optional Floating-Point word set
12536: @c =====================================================================
12537: @cindex system documentation, floating-point words
12538: @cindex floating-point words, system documentation
12539:
12540: @menu
12541: * floating-idef:: Implementation Defined Options
12542: * floating-ambcond:: Ambiguous Conditions
12543: @end menu
12544:
12545:
12546: @c ---------------------------------------------------------------------
12547: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
12548: @subsection Implementation Defined Options
12549: @c ---------------------------------------------------------------------
12550: @cindex implementation-defined options, floating-point words
12551: @cindex floating-point words, implementation-defined options
12552:
12553: @table @i
12554: @item format and range of floating point numbers:
12555: @cindex format and range of floating point numbers
12556: @cindex floating point numbers, format and range
12557: System-dependent; the @code{double} type of C.
12558:
1.29 crook 12559: @item results of @code{REPRESENT} when @i{float} is out of range:
12560: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 12561: System dependent; @code{REPRESENT} is implemented using the C library
12562: function @code{ecvt()} and inherits its behaviour in this respect.
12563:
12564: @item rounding or truncation of floating-point numbers:
12565: @cindex rounding of floating-point numbers
12566: @cindex truncation of floating-point numbers
12567: @cindex floating-point numbers, rounding or truncation
12568: System dependent; the rounding behaviour is inherited from the hosting C
12569: compiler. IEEE-FP-based (i.e., most) systems by default round to
12570: nearest, and break ties by rounding to even (i.e., such that the last
12571: bit of the mantissa is 0).
12572:
12573: @item size of floating-point stack:
12574: @cindex floating-point stack size
12575: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
12576: the floating-point stack (in floats). You can specify this on startup
12577: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
12578:
12579: @item width of floating-point stack:
12580: @cindex floating-point stack width
12581: @code{1 floats}.
12582:
12583: @end table
12584:
12585:
12586: @c ---------------------------------------------------------------------
12587: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
12588: @subsection Ambiguous conditions
12589: @c ---------------------------------------------------------------------
12590: @cindex floating-point words, ambiguous conditions
12591: @cindex ambiguous conditions, floating-point words
12592:
12593: @table @i
12594: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
12595: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
12596: System-dependent. Typically results in a @code{-23 THROW} like other
12597: alignment violations.
12598:
12599: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
12600: @cindex @code{f@@} used with an address that is not float aligned
12601: @cindex @code{f!} used with an address that is not float aligned
12602: System-dependent. Typically results in a @code{-23 THROW} like other
12603: alignment violations.
12604:
12605: @item floating-point result out of range:
12606: @cindex floating-point result out of range
12607: System-dependent. Can result in a @code{-55 THROW} (Floating-point
12608: unidentified fault), or can produce a special value representing, e.g.,
12609: Infinity.
12610:
12611: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
12612: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
12613: System-dependent. Typically results in an alignment fault like other
12614: alignment violations.
12615:
1.35 anton 12616: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
12617: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 12618: The floating-point number is converted into decimal nonetheless.
12619:
12620: @item Both arguments are equal to zero (@code{FATAN2}):
12621: @cindex @code{FATAN2}, both arguments are equal to zero
12622: System-dependent. @code{FATAN2} is implemented using the C library
12623: function @code{atan2()}.
12624:
1.29 crook 12625: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
12626: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
12627: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 12628: because of small errors and the tan will be a very large (or very small)
12629: but finite number.
12630:
1.29 crook 12631: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
12632: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 12633: The result is rounded to the nearest float.
12634:
12635: @item dividing by zero:
12636: @cindex dividing by zero, floating-point
12637: @cindex floating-point dividing by zero
12638: @cindex floating-point unidentified fault, FP divide-by-zero
12639: @code{-55 throw} (Floating-point unidentified fault)
12640:
12641: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
12642: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
12643: System dependent. On IEEE-FP based systems the number is converted into
12644: an infinity.
12645:
1.29 crook 12646: @item @i{float}<1 (@code{FACOSH}):
12647: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 12648: @cindex floating-point unidentified fault, @code{FACOSH}
12649: @code{-55 throw} (Floating-point unidentified fault)
12650:
1.29 crook 12651: @item @i{float}=<-1 (@code{FLNP1}):
12652: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 12653: @cindex floating-point unidentified fault, @code{FLNP1}
12654: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29 crook 12655: negative infinity is typically produced for @i{float}=-1.
1.1 anton 12656:
1.29 crook 12657: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
12658: @cindex @code{FLN}, @i{float}=<0
12659: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 12660: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
12661: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29 crook 12662: negative infinity is typically produced for @i{float}=0.
1.1 anton 12663:
1.29 crook 12664: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
12665: @cindex @code{FASINH}, @i{float}<0
12666: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 12667: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
12668: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
12669: produces values for these inputs on my Linux box (Bug in the C library?)
12670:
1.29 crook 12671: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
12672: @cindex @code{FACOS}, |@i{float}|>1
12673: @cindex @code{FASIN}, |@i{float}|>1
12674: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 12675: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
12676: @code{-55 throw} (Floating-point unidentified fault).
12677:
1.29 crook 12678: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
12679: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 12680: @cindex floating-point unidentified fault, @code{F>D}
12681: @code{-55 throw} (Floating-point unidentified fault).
12682:
12683: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
12684: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
12685: This does not happen.
12686: @end table
12687:
12688: @c =====================================================================
12689: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
12690: @section The optional Locals word set
12691: @c =====================================================================
12692: @cindex system documentation, locals words
12693: @cindex locals words, system documentation
12694:
12695: @menu
12696: * locals-idef:: Implementation Defined Options
12697: * locals-ambcond:: Ambiguous Conditions
12698: @end menu
12699:
12700:
12701: @c ---------------------------------------------------------------------
12702: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
12703: @subsection Implementation Defined Options
12704: @c ---------------------------------------------------------------------
12705: @cindex implementation-defined options, locals words
12706: @cindex locals words, implementation-defined options
12707:
12708: @table @i
12709: @item maximum number of locals in a definition:
12710: @cindex maximum number of locals in a definition
12711: @cindex locals, maximum number in a definition
12712: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
12713: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
12714: characters. The number of locals in a definition is bounded by the size
12715: of locals-buffer, which contains the names of the locals.
12716:
12717: @end table
12718:
12719:
12720: @c ---------------------------------------------------------------------
12721: @node locals-ambcond, , locals-idef, The optional Locals word set
12722: @subsection Ambiguous conditions
12723: @c ---------------------------------------------------------------------
12724: @cindex locals words, ambiguous conditions
12725: @cindex ambiguous conditions, locals words
12726:
12727: @table @i
12728: @item executing a named local in interpretation state:
12729: @cindex local in interpretation state
12730: @cindex Interpreting a compile-only word, for a local
12731: Locals have no interpretation semantics. If you try to perform the
12732: interpretation semantics, you will get a @code{-14 throw} somewhere
12733: (Interpreting a compile-only word). If you perform the compilation
12734: semantics, the locals access will be compiled (irrespective of state).
12735:
1.29 crook 12736: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 12737: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
12738: @cindex @code{TO} on non-@code{VALUE}s and non-locals
12739: @cindex Invalid name argument, @code{TO}
12740: @code{-32 throw} (Invalid name argument)
12741:
12742: @end table
12743:
12744:
12745: @c =====================================================================
12746: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
12747: @section The optional Memory-Allocation word set
12748: @c =====================================================================
12749: @cindex system documentation, memory-allocation words
12750: @cindex memory-allocation words, system documentation
12751:
12752: @menu
12753: * memory-idef:: Implementation Defined Options
12754: @end menu
12755:
12756:
12757: @c ---------------------------------------------------------------------
12758: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
12759: @subsection Implementation Defined Options
12760: @c ---------------------------------------------------------------------
12761: @cindex implementation-defined options, memory-allocation words
12762: @cindex memory-allocation words, implementation-defined options
12763:
12764: @table @i
1.29 crook 12765: @item values and meaning of @i{ior}:
12766: @cindex @i{ior} values and meaning
12767: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 12768: intended as throw codes. They typically are in the range
12769: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 12770: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 12771:
12772: @end table
12773:
12774: @c =====================================================================
12775: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
12776: @section The optional Programming-Tools word set
12777: @c =====================================================================
12778: @cindex system documentation, programming-tools words
12779: @cindex programming-tools words, system documentation
12780:
12781: @menu
12782: * programming-idef:: Implementation Defined Options
12783: * programming-ambcond:: Ambiguous Conditions
12784: @end menu
12785:
12786:
12787: @c ---------------------------------------------------------------------
12788: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
12789: @subsection Implementation Defined Options
12790: @c ---------------------------------------------------------------------
12791: @cindex implementation-defined options, programming-tools words
12792: @cindex programming-tools words, implementation-defined options
12793:
12794: @table @i
12795: @item ending sequence for input following @code{;CODE} and @code{CODE}:
12796: @cindex @code{;CODE} ending sequence
12797: @cindex @code{CODE} ending sequence
12798: @code{END-CODE}
12799:
12800: @item manner of processing input following @code{;CODE} and @code{CODE}:
12801: @cindex @code{;CODE}, processing input
12802: @cindex @code{CODE}, processing input
12803: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
12804: the input is processed by the text interpreter, (starting) in interpret
12805: state.
12806:
12807: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
12808: @cindex @code{ASSEMBLER}, search order capability
12809: The ANS Forth search order word set.
12810:
12811: @item source and format of display by @code{SEE}:
12812: @cindex @code{SEE}, source and format of output
12813: The source for @code{see} is the intermediate code used by the inner
12814: interpreter. The current @code{see} tries to output Forth source code
12815: as well as possible.
12816:
12817: @end table
12818:
12819: @c ---------------------------------------------------------------------
12820: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
12821: @subsection Ambiguous conditions
12822: @c ---------------------------------------------------------------------
12823: @cindex programming-tools words, ambiguous conditions
12824: @cindex ambiguous conditions, programming-tools words
12825:
12826: @table @i
12827:
1.21 crook 12828: @item deleting the compilation word list (@code{FORGET}):
12829: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 12830: Not implemented (yet).
12831:
1.29 crook 12832: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
12833: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
12834: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 12835: @cindex control-flow stack underflow
12836: This typically results in an @code{abort"} with a descriptive error
12837: message (may change into a @code{-22 throw} (Control structure mismatch)
12838: in the future). You may also get a memory access error. If you are
12839: unlucky, this ambiguous condition is not caught.
12840:
1.29 crook 12841: @item @i{name} can't be found (@code{FORGET}):
12842: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 12843: Not implemented (yet).
12844:
1.29 crook 12845: @item @i{name} not defined via @code{CREATE}:
12846: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 12847: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
12848: the execution semantics of the last defined word no matter how it was
12849: defined.
12850:
12851: @item @code{POSTPONE} applied to @code{[IF]}:
12852: @cindex @code{POSTPONE} applied to @code{[IF]}
12853: @cindex @code{[IF]} and @code{POSTPONE}
12854: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
12855: equivalent to @code{[IF]}.
12856:
12857: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
12858: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
12859: Continue in the same state of conditional compilation in the next outer
12860: input source. Currently there is no warning to the user about this.
12861:
12862: @item removing a needed definition (@code{FORGET}):
12863: @cindex @code{FORGET}, removing a needed definition
12864: Not implemented (yet).
12865:
12866: @end table
12867:
12868:
12869: @c =====================================================================
12870: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
12871: @section The optional Search-Order word set
12872: @c =====================================================================
12873: @cindex system documentation, search-order words
12874: @cindex search-order words, system documentation
12875:
12876: @menu
12877: * search-idef:: Implementation Defined Options
12878: * search-ambcond:: Ambiguous Conditions
12879: @end menu
12880:
12881:
12882: @c ---------------------------------------------------------------------
12883: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
12884: @subsection Implementation Defined Options
12885: @c ---------------------------------------------------------------------
12886: @cindex implementation-defined options, search-order words
12887: @cindex search-order words, implementation-defined options
12888:
12889: @table @i
12890: @item maximum number of word lists in search order:
12891: @cindex maximum number of word lists in search order
12892: @cindex search order, maximum depth
12893: @code{s" wordlists" environment? drop .}. Currently 16.
12894:
12895: @item minimum search order:
12896: @cindex minimum search order
12897: @cindex search order, minimum
12898: @code{root root}.
12899:
12900: @end table
12901:
12902: @c ---------------------------------------------------------------------
12903: @node search-ambcond, , search-idef, The optional Search-Order word set
12904: @subsection Ambiguous conditions
12905: @c ---------------------------------------------------------------------
12906: @cindex search-order words, ambiguous conditions
12907: @cindex ambiguous conditions, search-order words
12908:
12909: @table @i
1.21 crook 12910: @item changing the compilation word list (during compilation):
12911: @cindex changing the compilation word list (during compilation)
12912: @cindex compilation word list, change before definition ends
12913: The word is entered into the word list that was the compilation word list
1.1 anton 12914: at the start of the definition. Any changes to the name field (e.g.,
12915: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
12916: are applied to the latest defined word (as reported by @code{last} or
1.21 crook 12917: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1 anton 12918:
12919: @item search order empty (@code{previous}):
12920: @cindex @code{previous}, search order empty
1.26 crook 12921: @cindex vocstack empty, @code{previous}
1.1 anton 12922: @code{abort" Vocstack empty"}.
12923:
12924: @item too many word lists in search order (@code{also}):
12925: @cindex @code{also}, too many word lists in search order
1.26 crook 12926: @cindex vocstack full, @code{also}
1.1 anton 12927: @code{abort" Vocstack full"}.
12928:
12929: @end table
12930:
12931: @c ***************************************************************
12932: @node Model, Integrating Gforth, ANS conformance, Top
12933: @chapter Model
12934:
12935: This chapter has yet to be written. It will contain information, on
12936: which internal structures you can rely.
12937:
12938: @c ***************************************************************
12939: @node Integrating Gforth, Emacs and Gforth, Model, Top
12940: @chapter Integrating Gforth into C programs
12941:
12942: This is not yet implemented.
12943:
12944: Several people like to use Forth as scripting language for applications
12945: that are otherwise written in C, C++, or some other language.
12946:
12947: The Forth system ATLAST provides facilities for embedding it into
12948: applications; unfortunately it has several disadvantages: most
12949: importantly, it is not based on ANS Forth, and it is apparently dead
12950: (i.e., not developed further and not supported). The facilities
1.21 crook 12951: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 12952: making the switch should not be hard.
12953:
12954: We also tried to design the interface such that it can easily be
12955: implemented by other Forth systems, so that we may one day arrive at a
12956: standardized interface. Such a standard interface would allow you to
12957: replace the Forth system without having to rewrite C code.
12958:
12959: You embed the Gforth interpreter by linking with the library
12960: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
12961: global symbols in this library that belong to the interface, have the
12962: prefix @code{forth_}. (Global symbols that are used internally have the
12963: prefix @code{gforth_}).
12964:
12965: You can include the declarations of Forth types and the functions and
12966: variables of the interface with @code{#include <forth.h>}.
12967:
12968: Types.
12969:
12970: Variables.
12971:
12972: Data and FP Stack pointer. Area sizes.
12973:
12974: functions.
12975:
12976: forth_init(imagefile)
12977: forth_evaluate(string) exceptions?
12978: forth_goto(address) (or forth_execute(xt)?)
12979: forth_continue() (a corountining mechanism)
12980:
12981: Adding primitives.
12982:
12983: No checking.
12984:
12985: Signals?
12986:
12987: Accessing the Stacks
12988:
1.26 crook 12989: @c ******************************************************************
1.1 anton 12990: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
12991: @chapter Emacs and Gforth
12992: @cindex Emacs and Gforth
12993:
12994: @cindex @file{gforth.el}
12995: @cindex @file{forth.el}
12996: @cindex Rydqvist, Goran
12997: @cindex comment editing commands
12998: @cindex @code{\}, editing with Emacs
12999: @cindex debug tracer editing commands
13000: @cindex @code{~~}, removal with Emacs
13001: @cindex Forth mode in Emacs
13002: Gforth comes with @file{gforth.el}, an improved version of
13003: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 13004: improvements are:
13005:
13006: @itemize @bullet
13007: @item
13008: A better (but still not perfect) handling of indentation.
13009: @item
13010: Comment paragraph filling (@kbd{M-q})
13011: @item
13012: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13013: @item
13014: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 13015: @item
13016: Support of the @code{info-lookup} feature for looking up the
13017: documentation of a word.
1.26 crook 13018: @end itemize
13019:
13020: I left the stuff I do not use alone, even though some of it only makes
13021: sense for TILE. To get a description of these features, enter Forth mode
13022: and type @kbd{C-h m}.
1.1 anton 13023:
13024: @cindex source location of error or debugging output in Emacs
13025: @cindex error output, finding the source location in Emacs
13026: @cindex debugging output, finding the source location in Emacs
13027: In addition, Gforth supports Emacs quite well: The source code locations
13028: given in error messages, debugging output (from @code{~~}) and failed
13029: assertion messages are in the right format for Emacs' compilation mode
13030: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13031: Manual}) so the source location corresponding to an error or other
13032: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13033: @kbd{C-c C-c} for the error under the cursor).
13034:
13035: @cindex @file{TAGS} file
13036: @cindex @file{etags.fs}
13037: @cindex viewing the source of a word in Emacs
1.43 anton 13038: @cindex @code{require}, placement in files
13039: @cindex @code{include}, placement in files
13040: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
1.26 crook 13041: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 13042: contains the definitions of all words defined afterwards. You can then
13043: find the source for a word using @kbd{M-.}. Note that emacs can use
13044: several tags files at the same time (e.g., one for the Gforth sources
13045: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13046: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13047: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 13048: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
13049: with @file{etags.fs}, you should avoid putting definitions both before
13050: and after @code{require} etc., otherwise you will see the same file
13051: visited several times by commands like @code{tags-search}.
1.1 anton 13052:
1.41 anton 13053: @cindex viewing the documentation of a word in Emacs
13054: @cindex context-sensitive help
13055: Moreover, for words documented in this manual, you can look up the
13056: glossary entry quickly by using @kbd{C-h TAB}
13057: (@code{info-lookup-symbol}, see @pxref{Documentation, ,Documentation
13058: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
1.42 anton 13059: later and does not work for words containing @code{:}.
1.41 anton 13060:
13061:
1.1 anton 13062: @cindex @file{.emacs}
13063: To get all these benefits, add the following lines to your @file{.emacs}
13064: file:
13065:
13066: @example
13067: (autoload 'forth-mode "gforth.el")
13068: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
13069: @end example
13070:
1.26 crook 13071: @c ******************************************************************
1.1 anton 13072: @node Image Files, Engine, Emacs and Gforth, Top
13073: @chapter Image Files
1.26 crook 13074: @cindex image file
13075: @cindex @file{.fi} files
1.1 anton 13076: @cindex precompiled Forth code
13077: @cindex dictionary in persistent form
13078: @cindex persistent form of dictionary
13079:
13080: An image file is a file containing an image of the Forth dictionary,
13081: i.e., compiled Forth code and data residing in the dictionary. By
13082: convention, we use the extension @code{.fi} for image files.
13083:
13084: @menu
1.18 anton 13085: * Image Licensing Issues:: Distribution terms for images.
13086: * Image File Background:: Why have image files?
1.29 crook 13087: * Non-Relocatable Image Files:: don't always work.
1.18 anton 13088: * Data-Relocatable Image Files:: are better.
1.29 crook 13089: * Fully Relocatable Image Files:: better yet.
1.18 anton 13090: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 13091: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 13092: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 13093: @end menu
13094:
1.18 anton 13095: @node Image Licensing Issues, Image File Background, Image Files, Image Files
13096: @section Image Licensing Issues
13097: @cindex license for images
13098: @cindex image license
13099:
13100: An image created with @code{gforthmi} (@pxref{gforthmi}) or
13101: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
13102: original image; i.e., according to copyright law it is a derived work of
13103: the original image.
13104:
13105: Since Gforth is distributed under the GNU GPL, the newly created image
13106: falls under the GNU GPL, too. In particular, this means that if you
13107: distribute the image, you have to make all of the sources for the image
13108: available, including those you wrote. For details see @ref{License, ,
13109: GNU General Public License (Section 3)}.
13110:
13111: If you create an image with @code{cross} (@pxref{cross.fs}), the image
13112: contains only code compiled from the sources you gave it; if none of
13113: these sources is under the GPL, the terms discussed above do not apply
13114: to the image. However, if your image needs an engine (a gforth binary)
13115: that is under the GPL, you should make sure that you distribute both in
13116: a way that is at most a @emph{mere aggregation}, if you don't want the
13117: terms of the GPL to apply to the image.
13118:
13119: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 13120: @section Image File Background
13121: @cindex image file background
13122:
13123: Our Forth system consists not only of primitives, but also of
13124: definitions written in Forth. Since the Forth compiler itself belongs to
13125: those definitions, it is not possible to start the system with the
13126: primitives and the Forth source alone. Therefore we provide the Forth
1.26 crook 13127: code as an image file in nearly executable form. When Gforth starts up,
13128: a C routine loads the image file into memory, optionally relocates the
13129: addresses, then sets up the memory (stacks etc.) according to
13130: information in the image file, and (finally) starts executing Forth
13131: code.
1.1 anton 13132:
13133: The image file variants represent different compromises between the
13134: goals of making it easy to generate image files and making them
13135: portable.
13136:
13137: @cindex relocation at run-time
1.26 crook 13138: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 13139: run-time. This avoids many of the complications discussed below (image
13140: files are data relocatable without further ado), but costs performance
13141: (one addition per memory access).
13142:
13143: @cindex relocation at load-time
1.26 crook 13144: By contrast, the Gforth loader performs relocation at image load time. The
13145: loader also has to replace tokens that represent primitive calls with the
1.1 anton 13146: appropriate code-field addresses (or code addresses in the case of
13147: direct threading).
13148:
13149: There are three kinds of image files, with different degrees of
13150: relocatability: non-relocatable, data-relocatable, and fully relocatable
13151: image files.
13152:
13153: @cindex image file loader
13154: @cindex relocating loader
13155: @cindex loader for image files
13156: These image file variants have several restrictions in common; they are
13157: caused by the design of the image file loader:
13158:
13159: @itemize @bullet
13160: @item
13161: There is only one segment; in particular, this means, that an image file
13162: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 13163: them). The contents of the stacks are not represented, either.
1.1 anton 13164:
13165: @item
13166: The only kinds of relocation supported are: adding the same offset to
13167: all cells that represent data addresses; and replacing special tokens
13168: with code addresses or with pieces of machine code.
13169:
13170: If any complex computations involving addresses are performed, the
13171: results cannot be represented in the image file. Several applications that
13172: use such computations come to mind:
13173: @itemize @minus
13174: @item
13175: Hashing addresses (or data structures which contain addresses) for table
13176: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
13177: purpose, you will have no problem, because the hash tables are
13178: recomputed automatically when the system is started. If you use your own
13179: hash tables, you will have to do something similar.
13180:
13181: @item
13182: There's a cute implementation of doubly-linked lists that uses
13183: @code{XOR}ed addresses. You could represent such lists as singly-linked
13184: in the image file, and restore the doubly-linked representation on
13185: startup.@footnote{In my opinion, though, you should think thrice before
13186: using a doubly-linked list (whatever implementation).}
13187:
13188: @item
13189: The code addresses of run-time routines like @code{docol:} cannot be
13190: represented in the image file (because their tokens would be replaced by
13191: machine code in direct threaded implementations). As a workaround,
13192: compute these addresses at run-time with @code{>code-address} from the
13193: executions tokens of appropriate words (see the definitions of
13194: @code{docol:} and friends in @file{kernel.fs}).
13195:
13196: @item
13197: On many architectures addresses are represented in machine code in some
13198: shifted or mangled form. You cannot put @code{CODE} words that contain
13199: absolute addresses in this form in a relocatable image file. Workarounds
13200: are representing the address in some relative form (e.g., relative to
13201: the CFA, which is present in some register), or loading the address from
13202: a place where it is stored in a non-mangled form.
13203: @end itemize
13204: @end itemize
13205:
13206: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
13207: @section Non-Relocatable Image Files
13208: @cindex non-relocatable image files
1.26 crook 13209: @cindex image file, non-relocatable
1.1 anton 13210:
13211: These files are simple memory dumps of the dictionary. They are specific
13212: to the executable (i.e., @file{gforth} file) they were created
13213: with. What's worse, they are specific to the place on which the
13214: dictionary resided when the image was created. Now, there is no
13215: guarantee that the dictionary will reside at the same place the next
13216: time you start Gforth, so there's no guarantee that a non-relocatable
13217: image will work the next time (Gforth will complain instead of crashing,
13218: though).
13219:
13220: You can create a non-relocatable image file with
13221:
1.44 crook 13222:
1.1 anton 13223: doc-savesystem
13224:
1.44 crook 13225:
1.1 anton 13226: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
13227: @section Data-Relocatable Image Files
13228: @cindex data-relocatable image files
1.26 crook 13229: @cindex image file, data-relocatable
1.1 anton 13230:
13231: These files contain relocatable data addresses, but fixed code addresses
13232: (instead of tokens). They are specific to the executable (i.e.,
13233: @file{gforth} file) they were created with. For direct threading on some
13234: architectures (e.g., the i386), data-relocatable images do not work. You
13235: get a data-relocatable image, if you use @file{gforthmi} with a
13236: Gforth binary that is not doubly indirect threaded (@pxref{Fully
13237: Relocatable Image Files}).
13238:
13239: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
13240: @section Fully Relocatable Image Files
13241: @cindex fully relocatable image files
1.26 crook 13242: @cindex image file, fully relocatable
1.1 anton 13243:
13244: @cindex @file{kern*.fi}, relocatability
13245: @cindex @file{gforth.fi}, relocatability
13246: These image files have relocatable data addresses, and tokens for code
13247: addresses. They can be used with different binaries (e.g., with and
13248: without debugging) on the same machine, and even across machines with
13249: the same data formats (byte order, cell size, floating point
13250: format). However, they are usually specific to the version of Gforth
13251: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
13252: are fully relocatable.
13253:
13254: There are two ways to create a fully relocatable image file:
13255:
13256: @menu
1.29 crook 13257: * gforthmi:: The normal way
1.1 anton 13258: * cross.fs:: The hard way
13259: @end menu
13260:
13261: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
13262: @subsection @file{gforthmi}
13263: @cindex @file{comp-i.fs}
13264: @cindex @file{gforthmi}
13265:
13266: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 13267: image @i{file} that contains everything you would load by invoking
13268: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 13269: @example
1.29 crook 13270: gforthmi @i{file} @i{options}
1.1 anton 13271: @end example
13272:
13273: E.g., if you want to create an image @file{asm.fi} that has the file
13274: @file{asm.fs} loaded in addition to the usual stuff, you could do it
13275: like this:
13276:
13277: @example
13278: gforthmi asm.fi asm.fs
13279: @end example
13280:
1.27 crook 13281: @file{gforthmi} is implemented as a sh script and works like this: It
13282: produces two non-relocatable images for different addresses and then
13283: compares them. Its output reflects this: first you see the output (if
1.62 crook 13284: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 13285: files, then you see the output of the comparing program: It displays the
13286: offset used for data addresses and the offset used for code addresses;
1.1 anton 13287: moreover, for each cell that cannot be represented correctly in the
1.44 crook 13288: image files, it displays a line like this:
1.1 anton 13289:
13290: @example
13291: 78DC BFFFFA50 BFFFFA40
13292: @end example
13293:
13294: This means that at offset $78dc from @code{forthstart}, one input image
13295: contains $bffffa50, and the other contains $bffffa40. Since these cells
13296: cannot be represented correctly in the output image, you should examine
13297: these places in the dictionary and verify that these cells are dead
13298: (i.e., not read before they are written).
1.39 anton 13299:
13300: @cindex --application, @code{gforthmi} option
13301: If you insert the option @code{--application} in front of the image file
13302: name, you will get an image that uses the @code{--appl-image} option
13303: instead of the @code{--image-file} option (@pxref{Invoking
13304: Gforth}). When you execute such an image on Unix (by typing the image
13305: name as command), the Gforth engine will pass all options to the image
13306: instead of trying to interpret them as engine options.
1.1 anton 13307:
1.27 crook 13308: If you type @file{gforthmi} with no arguments, it prints some usage
13309: instructions.
13310:
1.1 anton 13311: @cindex @code{savesystem} during @file{gforthmi}
13312: @cindex @code{bye} during @file{gforthmi}
13313: @cindex doubly indirect threaded code
1.44 crook 13314: @cindex environment variables
13315: @cindex @code{GFORTHD} -- environment variable
13316: @cindex @code{GFORTH} -- environment variable
1.1 anton 13317: @cindex @code{gforth-ditc}
1.29 crook 13318: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 13319: words @code{savesystem} and @code{bye} must be visible. A special doubly
13320: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 13321: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 13322: this executable through the environment variable @code{GFORTHD}
13323: (default: @file{gforth-ditc}); if you pass a version that is not doubly
13324: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 13325: data-relocatable image (because there is no code address offset). The
13326: normal @file{gforth} executable is used for creating the relocatable
13327: image; you can pass the exact filename of this executable through the
13328: environment variable @code{GFORTH}.
1.1 anton 13329:
13330: @node cross.fs, , gforthmi, Fully Relocatable Image Files
13331: @subsection @file{cross.fs}
13332: @cindex @file{cross.fs}
13333: @cindex cross-compiler
13334: @cindex metacompiler
1.47 crook 13335: @cindex target compiler
1.1 anton 13336:
13337: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 13338: programming language (@pxref{Cross Compiler}).
1.1 anton 13339:
1.47 crook 13340: @code{cross} allows you to create image files for machines with
1.1 anton 13341: different data sizes and data formats than the one used for generating
13342: the image file. You can also use it to create an application image that
13343: does not contain a Forth compiler. These features are bought with
13344: restrictions and inconveniences in programming. E.g., addresses have to
13345: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
13346: order to make the code relocatable.
13347:
13348:
13349: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
13350: @section Stack and Dictionary Sizes
13351: @cindex image file, stack and dictionary sizes
13352: @cindex dictionary size default
13353: @cindex stack size default
13354:
13355: If you invoke Gforth with a command line flag for the size
13356: (@pxref{Invoking Gforth}), the size you specify is stored in the
13357: dictionary. If you save the dictionary with @code{savesystem} or create
13358: an image with @file{gforthmi}, this size will become the default
13359: for the resulting image file. E.g., the following will create a
1.21 crook 13360: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 13361:
13362: @example
13363: gforthmi gforth.fi -m 1M
13364: @end example
13365:
13366: In other words, if you want to set the default size for the dictionary
13367: and the stacks of an image, just invoke @file{gforthmi} with the
13368: appropriate options when creating the image.
13369:
13370: @cindex stack size, cache-friendly
13371: Note: For cache-friendly behaviour (i.e., good performance), you should
13372: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
13373: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
13374: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
13375:
13376: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
13377: @section Running Image Files
13378: @cindex running image files
13379: @cindex invoking image files
13380: @cindex image file invocation
13381:
13382: @cindex -i, invoke image file
13383: @cindex --image file, invoke image file
1.29 crook 13384: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 13385: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
13386: @example
1.29 crook 13387: gforth -i @i{image}
1.1 anton 13388: @end example
13389:
13390: @cindex executable image file
1.26 crook 13391: @cindex image file, executable
1.1 anton 13392: If your operating system supports starting scripts with a line of the
13393: form @code{#! ...}, you just have to type the image file name to start
13394: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 13395: just a convention). I.e., to run Gforth with the image file @i{image},
13396: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 13397: This works because every @code{.fi} file starts with a line of this
13398: format:
13399:
13400: @example
13401: #! /usr/local/bin/gforth-0.4.0 -i
13402: @end example
13403:
13404: The file and pathname for the Gforth engine specified on this line is
13405: the specific Gforth executable that it was built against; i.e. the value
13406: of the environment variable @code{GFORTH} at the time that
13407: @file{gforthmi} was executed.
1.1 anton 13408:
1.27 crook 13409: You can make use of the same shell capability to make a Forth source
13410: file into an executable. For example, if you place this text in a file:
1.26 crook 13411:
13412: @example
13413: #! /usr/local/bin/gforth
13414:
13415: ." Hello, world" CR
13416: bye
13417: @end example
13418:
13419: @noindent
1.27 crook 13420: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 13421: directly from the command line. The sequence @code{#!} is used in two
13422: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 13423: system@footnote{The Unix kernel actually recognises two types of files:
13424: executable files and files of data, where the data is processed by an
13425: interpreter that is specified on the ``interpreter line'' -- the first
13426: line of the file, starting with the sequence #!. There may be a small
13427: limit (e.g., 32) on the number of characters that may be specified on
13428: the interpreter line.} secondly it is treated as a comment character by
13429: Gforth. Because of the second usage, a space is required between
13430: @code{#!} and the path to the executable.
1.27 crook 13431:
13432: The disadvantage of this latter technique, compared with using
13433: @file{gforthmi}, is that it is slower; the Forth source code is compiled
13434: on-the-fly, each time the program is invoked.
13435:
1.26 crook 13436:
1.1 anton 13437: doc-#!
13438:
1.44 crook 13439:
1.1 anton 13440: @node Modifying the Startup Sequence, , Running Image Files, Image Files
13441: @section Modifying the Startup Sequence
13442: @cindex startup sequence for image file
13443: @cindex image file initialization sequence
13444: @cindex initialization sequence of image file
13445:
13446: You can add your own initialization to the startup sequence through the
1.26 crook 13447: deferred word @code{'cold}. @code{'cold} is invoked just before the
13448: image-specific command line processing (by default, loading files and
13449: evaluating (@code{-e}) strings) starts.
1.1 anton 13450:
13451: A sequence for adding your initialization usually looks like this:
13452:
13453: @example
13454: :noname
13455: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
13456: ... \ your stuff
13457: ; IS 'cold
13458: @end example
13459:
13460: @cindex turnkey image files
1.26 crook 13461: @cindex image file, turnkey applications
1.1 anton 13462: You can make a turnkey image by letting @code{'cold} execute a word
13463: (your turnkey application) that never returns; instead, it exits Gforth
13464: via @code{bye} or @code{throw}.
13465:
13466: @cindex command-line arguments, access
13467: @cindex arguments on the command line, access
13468: You can access the (image-specific) command-line arguments through the
1.26 crook 13469: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1 anton 13470: access to @code{argv}.
13471:
1.26 crook 13472: If @code{'cold} exits normally, Gforth processes the command-line
13473: arguments as files to be loaded and strings to be evaluated. Therefore,
13474: @code{'cold} should remove the arguments it has used in this case.
13475:
1.44 crook 13476:
13477:
1.26 crook 13478: doc-'cold
1.1 anton 13479: doc-argc
13480: doc-argv
13481: doc-arg
13482:
13483:
1.44 crook 13484:
1.1 anton 13485: @c ******************************************************************
1.13 pazsan 13486: @node Engine, Binding to System Library, Image Files, Top
1.1 anton 13487: @chapter Engine
13488: @cindex engine
13489: @cindex virtual machine
13490:
1.26 crook 13491: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 13492: may be helpful for finding your way in the Gforth sources.
13493:
13494: The ideas in this section have also been published in the papers
13495: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
13496: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
13497: Ertl, presented at EuroForth '93; the latter is available at
1.47 crook 13498: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
1.1 anton 13499:
13500: @menu
13501: * Portability::
13502: * Threading::
13503: * Primitives::
13504: * Performance::
13505: @end menu
13506:
13507: @node Portability, Threading, Engine, Engine
13508: @section Portability
13509: @cindex engine portability
13510:
1.26 crook 13511: An important goal of the Gforth Project is availability across a wide
13512: range of personal machines. fig-Forth, and, to a lesser extent, F83,
13513: achieved this goal by manually coding the engine in assembly language
13514: for several then-popular processors. This approach is very
13515: labor-intensive and the results are short-lived due to progress in
13516: computer architecture.
1.1 anton 13517:
13518: @cindex C, using C for the engine
13519: Others have avoided this problem by coding in C, e.g., Mitch Bradley
13520: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
13521: particularly popular for UNIX-based Forths due to the large variety of
13522: architectures of UNIX machines. Unfortunately an implementation in C
13523: does not mix well with the goals of efficiency and with using
13524: traditional techniques: Indirect or direct threading cannot be expressed
13525: in C, and switch threading, the fastest technique available in C, is
13526: significantly slower. Another problem with C is that it is very
13527: cumbersome to express double integer arithmetic.
13528:
13529: @cindex GNU C for the engine
13530: @cindex long long
13531: Fortunately, there is a portable language that does not have these
13532: limitations: GNU C, the version of C processed by the GNU C compiler
13533: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
13534: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
13535: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
13536: threading possible, its @code{long long} type (@pxref{Long Long, ,
13537: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
13538: double numbers@footnote{Unfortunately, long longs are not implemented
13539: properly on all machines (e.g., on alpha-osf1, long longs are only 64
13540: bits, the same size as longs (and pointers), but they should be twice as
1.4 anton 13541: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1 anton 13542: C Manual}). So, we had to implement doubles in C after all. Still, on
13543: most machines we can use long longs and achieve better performance than
13544: with the emulation package.}. GNU C is available for free on all
13545: important (and many unimportant) UNIX machines, VMS, 80386s running
13546: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
13547: on all these machines.
13548:
13549: Writing in a portable language has the reputation of producing code that
13550: is slower than assembly. For our Forth engine we repeatedly looked at
13551: the code produced by the compiler and eliminated most compiler-induced
13552: inefficiencies by appropriate changes in the source code.
13553:
13554: @cindex explicit register declarations
13555: @cindex --enable-force-reg, configuration flag
13556: @cindex -DFORCE_REG
13557: However, register allocation cannot be portably influenced by the
13558: programmer, leading to some inefficiencies on register-starved
13559: machines. We use explicit register declarations (@pxref{Explicit Reg
13560: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
13561: improve the speed on some machines. They are turned on by using the
13562: configuration flag @code{--enable-force-reg} (@code{gcc} switch
13563: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
13564: machine, but also on the compiler version: On some machines some
13565: compiler versions produce incorrect code when certain explicit register
13566: declarations are used. So by default @code{-DFORCE_REG} is not used.
13567:
13568: @node Threading, Primitives, Portability, Engine
13569: @section Threading
13570: @cindex inner interpreter implementation
13571: @cindex threaded code implementation
13572:
13573: @cindex labels as values
13574: GNU C's labels as values extension (available since @code{gcc-2.0},
13575: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 13576: makes it possible to take the address of @i{label} by writing
13577: @code{&&@i{label}}. This address can then be used in a statement like
13578: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 13579: @code{goto x}.
13580:
1.26 crook 13581: @cindex @code{NEXT}, indirect threaded
1.1 anton 13582: @cindex indirect threaded inner interpreter
13583: @cindex inner interpreter, indirect threaded
1.26 crook 13584: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 13585: @example
13586: cfa = *ip++;
13587: ca = *cfa;
13588: goto *ca;
13589: @end example
13590: @cindex instruction pointer
13591: For those unfamiliar with the names: @code{ip} is the Forth instruction
13592: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
13593: execution token and points to the code field of the next word to be
13594: executed; The @code{ca} (code address) fetched from there points to some
13595: executable code, e.g., a primitive or the colon definition handler
13596: @code{docol}.
13597:
1.26 crook 13598: @cindex @code{NEXT}, direct threaded
1.1 anton 13599: @cindex direct threaded inner interpreter
13600: @cindex inner interpreter, direct threaded
13601: Direct threading is even simpler:
13602: @example
13603: ca = *ip++;
13604: goto *ca;
13605: @end example
13606:
13607: Of course we have packaged the whole thing neatly in macros called
1.26 crook 13608: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 13609:
13610: @menu
13611: * Scheduling::
13612: * Direct or Indirect Threaded?::
13613: * DOES>::
13614: @end menu
13615:
13616: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
13617: @subsection Scheduling
13618: @cindex inner interpreter optimization
13619:
13620: There is a little complication: Pipelined and superscalar processors,
13621: i.e., RISC and some modern CISC machines can process independent
13622: instructions while waiting for the results of an instruction. The
13623: compiler usually reorders (schedules) the instructions in a way that
13624: achieves good usage of these delay slots. However, on our first tries
13625: the compiler did not do well on scheduling primitives. E.g., for
13626: @code{+} implemented as
13627: @example
13628: n=sp[0]+sp[1];
13629: sp++;
13630: sp[0]=n;
13631: NEXT;
13632: @end example
1.26 crook 13633: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1 anton 13634: scheduling. After a little thought the problem becomes clear: The
1.21 crook 13635: compiler cannot know that @code{sp} and @code{ip} point to different
13636: addresses (and the version of @code{gcc} we used would not know it even
13637: if it was possible), so it could not move the load of the cfa above the
13638: store to the TOS. Indeed the pointers could be the same, if code on or
13639: very near the top of stack were executed. In the interest of speed we
13640: chose to forbid this probably unused ``feature'' and helped the compiler
1.26 crook 13641: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21 crook 13642: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1 anton 13643: @example
13644: n=sp[0]+sp[1];
13645: sp++;
13646: NEXT_P1;
13647: sp[0]=n;
13648: NEXT_P2;
13649: @end example
13650: This can be scheduled optimally by the compiler.
13651:
13652: This division can be turned off with the switch @code{-DCISC_NEXT}. This
13653: switch is on by default on machines that do not profit from scheduling
13654: (e.g., the 80386), in order to preserve registers.
13655:
13656: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
13657: @subsection Direct or Indirect Threaded?
13658: @cindex threading, direct or indirect?
13659:
13660: @cindex -DDIRECT_THREADED
13661: Both! After packaging the nasty details in macro definitions we
13662: realized that we could switch between direct and indirect threading by
13663: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
13664: defining a few machine-specific macros for the direct-threading case.
13665: On the Forth level we also offer access words that hide the
13666: differences between the threading methods (@pxref{Threading Words}).
13667:
13668: Indirect threading is implemented completely machine-independently.
13669: Direct threading needs routines for creating jumps to the executable
1.21 crook 13670: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
13671: machine-dependent, but they do not amount to many source lines. Therefore,
13672: even porting direct threading to a new machine requires little effort.
1.1 anton 13673:
13674: @cindex --enable-indirect-threaded, configuration flag
13675: @cindex --enable-direct-threaded, configuration flag
13676: The default threading method is machine-dependent. You can enforce a
13677: specific threading method when building Gforth with the configuration
13678: flag @code{--enable-direct-threaded} or
13679: @code{--enable-indirect-threaded}. Note that direct threading is not
13680: supported on all machines.
13681:
13682: @node DOES>, , Direct or Indirect Threaded?, Threading
13683: @subsection DOES>
13684: @cindex @code{DOES>} implementation
13685:
1.26 crook 13686: @cindex @code{dodoes} routine
13687: @cindex @code{DOES>}-code
1.1 anton 13688: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
13689: the chunk of code executed by every word defined by a
13690: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
13691: the Forth code to be executed, i.e. the code after the
1.26 crook 13692: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1 anton 13693:
1.21 crook 13694: In fig-Forth the code field points directly to the @code{dodoes} and the
1.45 crook 13695: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
1.29 crook 13696: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1 anton 13697: the Forth-79 and all later standards, because in fig-Forth this address
13698: lies in the body (which is illegal in these standards). However, by
13699: making the code field larger for all words this solution becomes legal
13700: again. We use this approach for the indirect threaded version and for
13701: direct threading on some machines. Leaving a cell unused in most words
13702: is a bit wasteful, but on the machines we are targeting this is hardly a
13703: problem. The other reason for having a code field size of two cells is
13704: to avoid having different image files for direct and indirect threaded
13705: systems (direct threaded systems require two-cell code fields on many
13706: machines).
13707:
1.26 crook 13708: @cindex @code{DOES>}-handler
1.1 anton 13709: The other approach is that the code field points or jumps to the cell
1.26 crook 13710: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
13711: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
13712: @code{DOES>}-code address by computing the code address, i.e., the address of
1.45 crook 13713: the jump to @code{dodoes}, and add the length of that jump field. A variant of
1.1 anton 13714: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
13715: return address (which can be found in the return register on RISCs) is
1.26 crook 13716: the @code{DOES>}-code address. Since the two cells available in the code field
1.1 anton 13717: are used up by the jump to the code address in direct threading on many
13718: architectures, we use this approach for direct threading on these
13719: architectures. We did not want to add another cell to the code field.
13720:
13721: @node Primitives, Performance, Threading, Engine
13722: @section Primitives
13723: @cindex primitives, implementation
13724: @cindex virtual machine instructions, implementation
13725:
13726: @menu
13727: * Automatic Generation::
13728: * TOS Optimization::
13729: * Produced code::
13730: @end menu
13731:
13732: @node Automatic Generation, TOS Optimization, Primitives, Primitives
13733: @subsection Automatic Generation
13734: @cindex primitives, automatic generation
13735:
13736: @cindex @file{prims2x.fs}
13737: Since the primitives are implemented in a portable language, there is no
13738: longer any need to minimize the number of primitives. On the contrary,
13739: having many primitives has an advantage: speed. In order to reduce the
13740: number of errors in primitives and to make programming them easier, we
13741: provide a tool, the primitive generator (@file{prims2x.fs}), that
13742: automatically generates most (and sometimes all) of the C code for a
13743: primitive from the stack effect notation. The source for a primitive
13744: has the following form:
13745:
13746: @cindex primitive source format
13747: @format
1.58 anton 13748: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 13749: [@code{""}@i{glossary entry}@code{""}]
13750: @i{C code}
1.1 anton 13751: [@code{:}
1.29 crook 13752: @i{Forth code}]
1.1 anton 13753: @end format
13754:
13755: The items in brackets are optional. The category and glossary fields
13756: are there for generating the documentation, the Forth code is there
13757: for manual implementations on machines without GNU C. E.g., the source
13758: for the primitive @code{+} is:
13759: @example
1.58 anton 13760: + ( n1 n2 -- n ) core plus
1.1 anton 13761: n = n1+n2;
13762: @end example
13763:
13764: This looks like a specification, but in fact @code{n = n1+n2} is C
13765: code. Our primitive generation tool extracts a lot of information from
13766: the stack effect notations@footnote{We use a one-stack notation, even
13767: though we have separate data and floating-point stacks; The separate
13768: notation can be generated easily from the unified notation.}: The number
13769: of items popped from and pushed on the stack, their type, and by what
13770: name they are referred to in the C code. It then generates a C code
13771: prelude and postlude for each primitive. The final C code for @code{+}
13772: looks like this:
13773:
13774: @example
1.46 pazsan 13775: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 13776: /* */ /* documentation */
13777: @{
13778: DEF_CA /* definition of variable ca (indirect threading) */
13779: Cell n1; /* definitions of variables */
13780: Cell n2;
13781: Cell n;
13782: n1 = (Cell) sp[1]; /* input */
13783: n2 = (Cell) TOS;
13784: sp += 1; /* stack adjustment */
13785: NAME("+") /* debugging output (with -DDEBUG) */
13786: @{
13787: n = n1+n2; /* C code taken from the source */
13788: @}
13789: NEXT_P1; /* NEXT part 1 */
13790: TOS = (Cell)n; /* output */
13791: NEXT_P2; /* NEXT part 2 */
13792: @}
13793: @end example
13794:
13795: This looks long and inefficient, but the GNU C compiler optimizes quite
13796: well and produces optimal code for @code{+} on, e.g., the R3000 and the
13797: HP RISC machines: Defining the @code{n}s does not produce any code, and
13798: using them as intermediate storage also adds no cost.
13799:
1.26 crook 13800: There are also other optimizations that are not illustrated by this
13801: example: assignments between simple variables are usually for free (copy
1.1 anton 13802: propagation). If one of the stack items is not used by the primitive
13803: (e.g. in @code{drop}), the compiler eliminates the load from the stack
13804: (dead code elimination). On the other hand, there are some things that
13805: the compiler does not do, therefore they are performed by
13806: @file{prims2x.fs}: The compiler does not optimize code away that stores
13807: a stack item to the place where it just came from (e.g., @code{over}).
13808:
13809: While programming a primitive is usually easy, there are a few cases
13810: where the programmer has to take the actions of the generator into
13811: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 13812: fall through to @code{NEXT}.
1.1 anton 13813:
13814: @node TOS Optimization, Produced code, Automatic Generation, Primitives
13815: @subsection TOS Optimization
13816: @cindex TOS optimization for primitives
13817: @cindex primitives, keeping the TOS in a register
13818:
13819: An important optimization for stack machine emulators, e.g., Forth
13820: engines, is keeping one or more of the top stack items in
1.29 crook 13821: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
13822: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 13823: @itemize @bullet
13824: @item
1.29 crook 13825: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 13826: due to fewer loads from and stores to the stack.
1.29 crook 13827: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
13828: @i{y<n}, due to additional moves between registers.
1.1 anton 13829: @end itemize
13830:
13831: @cindex -DUSE_TOS
13832: @cindex -DUSE_NO_TOS
13833: In particular, keeping one item in a register is never a disadvantage,
13834: if there are enough registers. Keeping two items in registers is a
13835: disadvantage for frequent words like @code{?branch}, constants,
13836: variables, literals and @code{i}. Therefore our generator only produces
13837: code that keeps zero or one items in registers. The generated C code
13838: covers both cases; the selection between these alternatives is made at
13839: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
13840: code for @code{+} is just a simple variable name in the one-item case,
13841: otherwise it is a macro that expands into @code{sp[0]}. Note that the
13842: GNU C compiler tries to keep simple variables like @code{TOS} in
13843: registers, and it usually succeeds, if there are enough registers.
13844:
13845: @cindex -DUSE_FTOS
13846: @cindex -DUSE_NO_FTOS
13847: The primitive generator performs the TOS optimization for the
13848: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
13849: operations the benefit of this optimization is even larger:
13850: floating-point operations take quite long on most processors, but can be
13851: performed in parallel with other operations as long as their results are
13852: not used. If the FP-TOS is kept in a register, this works. If
13853: it is kept on the stack, i.e., in memory, the store into memory has to
13854: wait for the result of the floating-point operation, lengthening the
13855: execution time of the primitive considerably.
13856:
13857: The TOS optimization makes the automatic generation of primitives a
13858: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
13859: @code{TOS} is not sufficient. There are some special cases to
13860: consider:
13861: @itemize @bullet
13862: @item In the case of @code{dup ( w -- w w )} the generator must not
13863: eliminate the store to the original location of the item on the stack,
13864: if the TOS optimization is turned on.
13865: @item Primitives with stack effects of the form @code{--}
1.29 crook 13866: @i{out1}...@i{outy} must store the TOS to the stack at the start.
13867: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 13868: must load the TOS from the stack at the end. But for the null stack
13869: effect @code{--} no stores or loads should be generated.
13870: @end itemize
13871:
13872: @node Produced code, , TOS Optimization, Primitives
13873: @subsection Produced code
13874: @cindex primitives, assembly code listing
13875:
13876: @cindex @file{engine.s}
13877: To see what assembly code is produced for the primitives on your machine
13878: with your compiler and your flag settings, type @code{make engine.s} and
13879: look at the resulting file @file{engine.s}.
13880:
13881: @node Performance, , Primitives, Engine
13882: @section Performance
13883: @cindex performance of some Forth interpreters
13884: @cindex engine performance
13885: @cindex benchmarking Forth systems
13886: @cindex Gforth performance
13887:
13888: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
13889: impossible to write a significantly faster engine.
13890:
13891: On register-starved machines like the 386 architecture processors
13892: improvements are possible, because @code{gcc} does not utilize the
13893: registers as well as a human, even with explicit register declarations;
13894: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
13895: and hand-tuned it for the 486; this system is 1.19 times faster on the
13896: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 13897: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
13898: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
13899: registers fit in real registers (and we can even afford to use the TOS
13900: optimization), resulting in a speedup of 1.14 on the sieve over the
13901: earlier results.
1.1 anton 13902:
13903: @cindex Win32Forth performance
13904: @cindex NT Forth performance
13905: @cindex eforth performance
13906: @cindex ThisForth performance
13907: @cindex PFE performance
13908: @cindex TILE performance
1.40 anton 13909: The potential advantage of assembly language implementations
1.1 anton 13910: is not necessarily realized in complete Forth systems: We compared
1.40 anton 13911: Gforth-0.4.9 (direct threaded, compiled with @code{gcc-2.95.1} and
1.1 anton 13912: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
13913: 1994) and Eforth (with and without peephole (aka pinhole) optimization
13914: of the threaded code); all these systems were written in assembly
13915: language. We also compared Gforth with three systems written in C:
13916: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
13917: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21 crook 13918: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
13919: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1 anton 13920: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
13921: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
13922: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
13923: 486DX2/66 with similar memory performance under Windows NT. Marcel
13924: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
13925: added the peephole optimizer, ran the benchmarks and reported the
13926: results.
1.40 anton 13927:
1.1 anton 13928: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
13929: matrix multiplication come from the Stanford integer benchmarks and have
13930: been translated into Forth by Martin Fraeman; we used the versions
13931: included in the TILE Forth package, but with bigger data set sizes; and
13932: a recursive Fibonacci number computation for benchmarking calling
13933: performance. The following table shows the time taken for the benchmarks
13934: scaled by the time taken by Gforth (in other words, it shows the speedup
13935: factor that Gforth achieved over the other systems).
13936:
13937: @example
1.40 anton 13938: relative Win32- NT eforth This-
1.1 anton 13939: time Gforth Forth Forth eforth +opt PFE Forth TILE
1.40 anton 13940: sieve 1.00 1.58 1.30 1.58 0.97 1.80 3.63 9.79
13941: bubble 1.00 1.55 1.67 1.75 1.04 1.78 4.59
13942: matmul 1.00 1.67 1.53 1.66 0.84 1.79 4.63
13943: fib 1.00 1.75 1.53 1.40 0.99 1.99 3.43 4.93
1.1 anton 13944: @end example
13945:
1.26 crook 13946: You may be quite surprised by the good performance of Gforth when
13947: compared with systems written in assembly language. One important reason
13948: for the disappointing performance of these other systems is probably
13949: that they are not written optimally for the 486 (e.g., they use the
13950: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
13951: but costly method for relocating the Forth image: like @code{cforth}, it
13952: computes the actual addresses at run time, resulting in two address
13953: computations per @code{NEXT} (@pxref{Image File Background}).
13954:
1.40 anton 13955: Only Eforth with the peephole optimizer performs comparable to
13956: Gforth. The speedups achieved with peephole optimization of threaded
13957: code are quite remarkable. Adding a peephole optimizer to Gforth should
13958: cause similar speedups.
1.1 anton 13959:
13960: The speedup of Gforth over PFE, ThisForth and TILE can be easily
13961: explained with the self-imposed restriction of the latter systems to
13962: standard C, which makes efficient threading impossible (however, the
1.4 anton 13963: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 13964: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
13965: Moreover, current C compilers have a hard time optimizing other aspects
13966: of the ThisForth and the TILE source.
13967:
1.26 crook 13968: The performance of Gforth on 386 architecture processors varies widely
13969: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
13970: allocate any of the virtual machine registers into real machine
13971: registers by itself and would not work correctly with explicit register
1.40 anton 13972: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
1.26 crook 13973: the Sieve) than the one measured above.
1.1 anton 13974:
1.26 crook 13975: Note that there have been several releases of Win32Forth since the
13976: release presented here, so the results presented above may have little
1.40 anton 13977: predictive value for the performance of Win32Forth today (results for
13978: the current release on an i486DX2/66 are welcome).
1.1 anton 13979:
13980: @cindex @file{Benchres}
13981: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
13982: Maierhofer (presented at EuroForth '95), an indirect threaded version of
13983: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
1.40 anton 13984: version of Gforth is slower on a 486 than the direct threaded version
13985: used here. The paper available at
1.47 crook 13986: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
1.1 anton 13987: it also contains numbers for some native code systems. You can find a
13988: newer version of these measurements at
1.47 crook 13989: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 13990: find numbers for Gforth on various machines in @file{Benchres}.
13991:
1.26 crook 13992: @c ******************************************************************
1.13 pazsan 13993: @node Binding to System Library, Cross Compiler, Engine, Top
1.14 pazsan 13994: @chapter Binding to System Library
1.13 pazsan 13995:
13996: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14 pazsan 13997: @chapter Cross Compiler
1.47 crook 13998: @cindex @file{cross.fs}
13999: @cindex cross-compiler
14000: @cindex metacompiler
14001: @cindex target compiler
1.13 pazsan 14002:
1.46 pazsan 14003: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
14004: mostly written in Forth, including crucial parts like the outer
14005: interpreter and compiler, it needs compiled Forth code to get
14006: started. The cross compiler allows to create new images for other
14007: architectures, even running under another Forth system.
1.13 pazsan 14008:
14009: @menu
14010: * Using the Cross Compiler::
14011: * How the Cross Compiler Works::
14012: @end menu
14013:
1.21 crook 14014: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 14015: @section Using the Cross Compiler
1.46 pazsan 14016:
14017: The cross compiler uses a language that resembles Forth, but isn't. The
14018: main difference is that you can execute Forth code after definition,
14019: while you usually can't execute the code compiled by cross, because the
14020: code you are compiling is typically for a different computer than the
14021: one you are compiling on.
14022:
14023: The Makefile is already set up to allow you to create kernels for new
14024: architectures with a simple make command. The generic kernels using the
14025: GCC compiled virtual machine are created in the normal build process
14026: with @code{make}. To create a embedded Gforth executable for e.g. the
14027: 8086 processor (running on a DOS machine), type
14028:
14029: @example
14030: make kernl-8086.fi
14031: @end example
14032:
14033: This will use the machine description from the @file{arch/8086}
14034: directory to create a new kernel. A machine file may look like that:
14035:
14036: @example
14037: \ Parameter for target systems 06oct92py
14038:
14039: 4 Constant cell \ cell size in bytes
14040: 2 Constant cell<< \ cell shift to bytes
14041: 5 Constant cell>bit \ cell shift to bits
14042: 8 Constant bits/char \ bits per character
14043: 8 Constant bits/byte \ bits per byte [default: 8]
14044: 8 Constant float \ bytes per float
14045: 8 Constant /maxalign \ maximum alignment in bytes
14046: false Constant bigendian \ byte order
14047: ( true=big, false=little )
14048:
14049: include machpc.fs \ feature list
14050: @end example
14051:
14052: This part is obligatory for the cross compiler itself, the feature list
14053: is used by the kernel to conditionally compile some features in and out,
14054: depending on whether the target supports these features.
14055:
14056: There are some optional features, if you define your own primitives,
14057: have an assembler, or need special, nonstandard preparation to make the
14058: boot process work. @code{asm-include} include an assembler,
14059: @code{prims-include} includes primitives, and @code{>boot} prepares for
14060: booting.
14061:
14062: @example
14063: : asm-include ." Include assembler" cr
14064: s" arch/8086/asm.fs" included ;
14065:
14066: : prims-include ." Include primitives" cr
14067: s" arch/8086/prim.fs" included ;
14068:
14069: : >boot ." Prepare booting" cr
14070: s" ' boot >body into-forth 1+ !" evaluate ;
14071: @end example
14072:
14073: These words are used as sort of macro during the cross compilation in
14074: the file @file{kernel/main.fs}. Instead of using this macros, it would
14075: be possible --- but more complicated --- to write a new kernel project
14076: file, too.
14077:
14078: @file{kernel/main.fs} expects the machine description file name on the
14079: stack; the cross compiler itself (@file{cross.fs}) assumes that either
14080: @code{mach-file} leaves a counted string on the stack, or
14081: @code{machine-file} leaves an address, count pair of the filename on the
14082: stack.
14083:
14084: The feature list is typically controlled using @code{SetValue}, generic
14085: files that are used by several projects can use @code{DefaultValue}
14086: instead. Both functions work like @code{Value}, when the value isn't
14087: defined, but @code{SetValue} works like @code{to} if the value is
14088: defined, and @code{DefaultValue} doesn't set anything, if the value is
14089: defined.
14090:
14091: @example
14092: \ generic mach file for pc gforth 03sep97jaw
14093:
14094: true DefaultValue NIL \ relocating
14095:
14096: >ENVIRON
14097:
14098: true DefaultValue file \ controls the presence of the
14099: \ file access wordset
14100: true DefaultValue OS \ flag to indicate a operating system
14101:
14102: true DefaultValue prims \ true: primitives are c-code
14103:
14104: true DefaultValue floating \ floating point wordset is present
14105:
14106: true DefaultValue glocals \ gforth locals are present
14107: \ will be loaded
14108: true DefaultValue dcomps \ double number comparisons
14109:
14110: true DefaultValue hash \ hashing primitives are loaded/present
14111:
14112: true DefaultValue xconds \ used together with glocals,
14113: \ special conditionals supporting gforths'
14114: \ local variables
14115: true DefaultValue header \ save a header information
14116:
14117: true DefaultValue backtrace \ enables backtrace code
14118:
14119: false DefaultValue ec
14120: false DefaultValue crlf
14121:
14122: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
14123:
14124: &16 KB DefaultValue stack-size
14125: &15 KB &512 + DefaultValue fstack-size
14126: &15 KB DefaultValue rstack-size
14127: &14 KB &512 + DefaultValue lstack-size
14128: @end example
1.13 pazsan 14129:
1.48 anton 14130: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 14131: @section How the Cross Compiler Works
1.13 pazsan 14132:
14133: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 14134: @appendix Bugs
1.1 anton 14135: @cindex bug reporting
14136:
1.21 crook 14137: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 14138:
14139: If you find a bug, please send a bug report to
1.33 anton 14140: @email{bug-gforth@@gnu.org}. A bug report should include this
1.21 crook 14141: information:
14142:
14143: @itemize @bullet
14144: @item
14145: The Gforth version used (it is announced at the start of an
14146: interactive Gforth session).
14147: @item
14148: The machine and operating system (on Unix
14149: systems @code{uname -a} will report this information).
14150: @item
14151: The installation options (send the file @file{config.status}).
14152: @item
14153: A complete list of changes (if any) you (or your installer) have made to the
14154: Gforth sources.
14155: @item
14156: A program (or a sequence of keyboard commands) that reproduces the bug.
14157: @item
14158: A description of what you think constitutes the buggy behaviour.
14159: @end itemize
1.1 anton 14160:
14161: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
14162: to Report Bugs, gcc.info, GNU C Manual}.
14163:
14164:
1.21 crook 14165: @node Origin, Forth-related information, Bugs, Top
14166: @appendix Authors and Ancestors of Gforth
1.1 anton 14167:
14168: @section Authors and Contributors
14169: @cindex authors of Gforth
14170: @cindex contributors to Gforth
14171:
14172: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
14173: Ertl. The third major author was Jens Wilke. Lennart Benschop (who was
14174: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
14175: with their continuous feedback. Lennart Benshop contributed
14176: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
14177: support for calling C libraries. Helpful comments also came from Paul
14178: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.58 anton 14179: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and
14180: Robert Epprecht. Since the release of Gforth-0.2.1 there were also
14181: helpful comments from many others; thank you all, sorry for not listing
14182: you here (but digging through my mailbox to extract your names is on my
14183: to-do list). Since the release of Gforth-0.4.0 Neal Crook worked on the
14184: manual.
1.1 anton 14185:
14186: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
14187: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 14188: was developed across the Internet, and its authors did not meet
1.20 pazsan 14189: physically for the first 4 years of development.
1.1 anton 14190:
14191: @section Pedigree
1.26 crook 14192: @cindex pedigree of Gforth
1.1 anton 14193:
1.20 pazsan 14194: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1 anton 14195: Dirk Zoller) will cross-fertilize each other. Of course, a significant
14196: part of the design of Gforth was prescribed by ANS Forth.
14197:
1.20 pazsan 14198: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 14199: 32 bit native code version of VolksForth for the Atari ST, written
14200: mostly by Dietrich Weineck.
14201:
14202: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
14203: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
14204: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
14205:
14206: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
14207: Forth-83 standard. !! Pedigree? When?
14208:
14209: A team led by Bill Ragsdale implemented fig-Forth on many processors in
14210: 1979. Robert Selzer and Bill Ragsdale developed the original
14211: implementation of fig-Forth for the 6502 based on microForth.
14212:
14213: The principal architect of microForth was Dean Sanderson. microForth was
14214: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
14215: the 1802, and subsequently implemented on the 8080, the 6800 and the
14216: Z80.
14217:
14218: All earlier Forth systems were custom-made, usually by Charles Moore,
14219: who discovered (as he puts it) Forth during the late 60s. The first full
14220: Forth existed in 1971.
14221:
14222: A part of the information in this section comes from @cite{The Evolution
14223: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
14224: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
14225: Notices 28(3), 1993. You can find more historical and genealogical
14226: information about Forth there.
14227:
1.21 crook 14228: @node Forth-related information, Word Index, Origin, Top
14229: @appendix Other Forth-related information
14230: @cindex Forth-related information
14231:
14232: @menu
14233: * Internet resources::
14234: * Books::
14235: * The Forth Interest Group::
14236: * Conferences::
14237: @end menu
14238:
14239:
14240: @node Internet resources, Books, Forth-related information, Forth-related information
14241: @section Internet resources
1.26 crook 14242: @cindex internet resources
1.21 crook 14243:
14244: @cindex comp.lang.forth
14245: @cindex frequently asked questions
1.45 crook 14246: There is an active news group (comp.lang.forth) discussing Forth and
1.21 crook 14247: Forth-related issues. A frequently-asked-questions (FAQ) list
1.45 crook 14248: is posted to the news group regularly, and archived at these sites:
1.21 crook 14249:
14250: @itemize @bullet
14251: @item
1.47 crook 14252: @uref{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
1.21 crook 14253: @item
1.47 crook 14254: @uref{ftp://ftp.forth.org/pub/Forth/FAQ/}
1.21 crook 14255: @end itemize
14256:
14257: The FAQ list should be considered mandatory reading before posting to
1.45 crook 14258: the news group.
1.21 crook 14259:
14260: Here are some other web sites holding Forth-related material:
14261:
14262: @itemize @bullet
14263: @item
1.47 crook 14264: @uref{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
1.21 crook 14265: @item
1.47 crook 14266: @uref{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
1.21 crook 14267: @item
1.47 crook 14268: @uref{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
1.21 crook 14269: @item
1.47 crook 14270: @uref{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
1.21 crook 14271: Research page, including links to the Journal of Forth Application and
14272: Research (JFAR) and a searchable Forth bibliography.
14273: @end itemize
14274:
14275:
14276: @node Books, The Forth Interest Group, Internet resources, Forth-related information
14277: @section Books
1.26 crook 14278: @cindex books on Forth
1.21 crook 14279:
14280: As the Standard is relatively new, there are not many books out yet. It
14281: is not recommended to learn Forth by using Gforth and a book that is not
14282: written for ANS Forth, as you will not know your mistakes from the
14283: deviations of the book. However, books based on the Forth-83 standard
14284: should be ok, because ANS Forth is primarily an extension of Forth-83.
1.44 crook 14285: Refer to the Forth FAQ for details of Forth-related books.
1.21 crook 14286:
14287: @cindex standard document for ANS Forth
14288: @cindex ANS Forth document
14289: The definite reference if you want to write ANS Forth programs is, of
1.26 crook 14290: course, the ANS Forth document. It is available in printed form from the
1.21 crook 14291: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
14292: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
14293: $200. You can also get it from Global Engineering Documents (Tel.: USA
14294: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
14295:
14296: @cite{dpANS6}, the last draft of the standard, which was then submitted
14297: to ANSI for publication is available electronically and for free in some
14298: MS Word format, and it has been converted to HTML
1.47 crook 14299: (@uref{http://www.taygeta.com/forth/dpans.html}; this HTML version also
1.44 crook 14300: includes the answers to Requests for Interpretation (RFIs). Some
14301: pointers to these versions can be found through
1.47 crook 14302: @*@uref{http://www.complang.tuwien.ac.at/projects/forth.html}.
1.44 crook 14303:
1.21 crook 14304:
14305: @node The Forth Interest Group, Conferences, Books, Forth-related information
14306: @section The Forth Interest Group
14307: @cindex Forth interest group (FIG)
14308:
14309: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26 crook 14310: member-supported organisation. It publishes a regular magazine,
14311: @var{FORTH Dimensions}, and offers other benefits of membership. You can
14312: contact the FIG through their office email address:
14313: @email{office@@forth.org} or by visiting their web site at
1.47 crook 14314: @uref{http://www.forth.org/}. This web site also includes links to FIG
1.26 crook 14315: chapters in other countries and American cities
1.47 crook 14316: (@uref{http://www.forth.org/chapters.html}).
1.21 crook 14317:
1.48 anton 14318: @node Conferences, , The Forth Interest Group, Forth-related information
1.21 crook 14319: @section Conferences
14320: @cindex Conferences
14321:
14322: There are several regular conferences related to Forth. They are all
1.26 crook 14323: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
1.45 crook 14324: news group:
1.21 crook 14325:
14326: @itemize @bullet
14327: @item
14328: FORML -- the Forth modification laboratory convenes every year near
14329: Monterey, California.
14330: @item
14331: The Rochester Forth Conference -- an annual conference traditionally
14332: held in Rochester, New York.
14333: @item
14334: EuroForth -- this European conference takes place annually.
14335: @end itemize
14336:
14337:
1.41 anton 14338: @node Word Index, Name Index, Forth-related information, Top
1.1 anton 14339: @unnumbered Word Index
14340:
1.26 crook 14341: This index is a list of Forth words that have ``glossary'' entries
14342: within this manual. Each word is listed with its stack effect and
14343: wordset.
1.1 anton 14344:
14345: @printindex fn
14346:
1.41 anton 14347: @node Name Index, Concept Index, Word Index, Top
14348: @unnumbered Name Index
14349:
14350: This index is a list of Forth words that have ``glossary'' entries
14351: within this manual.
14352:
14353: @printindex ky
14354:
14355: @node Concept Index, , Name Index, Top
1.1 anton 14356: @unnumbered Concept and Word Index
14357:
1.26 crook 14358: Not all entries listed in this index are present verbatim in the
14359: text. This index also duplicates, in abbreviated form, all of the words
14360: listed in the Word Index (only the names are listed for the words here).
1.1 anton 14361:
14362: @printindex cp
14363:
14364: @contents
14365: @bye
14366:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>