1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
3:
4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
5: @comment 1. x-ref all ambiguous or implementation-defined features?
6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
7: @comment 3. words in miscellaneous section need a home.
8: @comment 4. search for TODO for other minor and major works required.
9: @comment 5. [rats] change all @var to @i in Forth source so that info
10: @comment file looks decent.
11: @c Not an improvement IMO - anton
12: @c and anyway, this should be taken up
13: @c with Karl Berry (the texinfo guy) - anton
14: @c
15: @c Karl Berry writes:
16: @c If they don't like the all-caps for @var Info output, all I can say is
17: @c that it's always been that way, and the usage of all-caps for
18: @c metavariables has a long tradition. I think it's best to just let it be
19: @c what it is, for the sake of consistency among manuals.
20: @c
21: @comment .. would be useful to have a word that identified all deferred words
22: @comment should semantics stuff in intro be moved to another section
23:
24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
25:
26: @comment %**start of header (This is for running Texinfo on a region.)
27: @setfilename gforth.info
28: @include version.texi
29: @settitle Gforth Manual
30: @c @syncodeindex pg cp
31:
32: @macro progstyle {}
33: Programming style note:
34: @end macro
35:
36: @macro assignment {}
37: @table @i
38: @item Assignment:
39: @end macro
40: @macro endassignment {}
41: @end table
42: @end macro
43:
44: @comment macros for beautifying glossary entries
45: @macro GLOSS-START {}
46: @iftex
47: @ninerm
48: @end iftex
49: @end macro
50:
51: @macro GLOSS-END {}
52: @iftex
53: @rm
54: @end iftex
55: @end macro
56:
57: @comment %**end of header (This is for running Texinfo on a region.)
58: @copying
59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
60: a fast and portable implementation of the ANS Forth language. It
61: serves as reference manual, but it also contains an introduction to
62: Forth and a Forth tutorial.
63:
64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003 Free Software Foundation, Inc.
65:
66: @quotation
67: Permission is granted to copy, distribute and/or modify this document
68: under the terms of the GNU Free Documentation License, Version 1.1 or
69: any later version published by the Free Software Foundation; with no
70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
71: and with the Back-Cover Texts as in (a) below. A copy of the
72: license is included in the section entitled ``GNU Free Documentation
73: License.''
74:
75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
76: this GNU Manual, like GNU software. Copies published by the Free
77: Software Foundation raise funds for GNU development.''
78: @end quotation
79: @end copying
80:
81: @dircategory Software development
82: @direntry
83: * Gforth: (gforth). A fast interpreter for the Forth language.
84: @end direntry
85: @c The Texinfo manual also recommends doing this, but for Gforth it may
86: @c not make much sense
87: @c @dircategory Individual utilities
88: @c @direntry
89: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
90: @c @end direntry
91:
92: @titlepage
93: @title Gforth
94: @subtitle for version @value{VERSION}, @value{UPDATED}
95: @author Neal Crook
96: @author Anton Ertl
97: @author David Kuehling
98: @author Bernd Paysan
99: @author Jens Wilke
100: @page
101: @vskip 0pt plus 1filll
102: @insertcopying
103: @end titlepage
104:
105: @contents
106:
107: @ifnottex
108: @node Top, Goals, (dir), (dir)
109: @top Gforth
110:
111: @insertcopying
112: @end ifnottex
113:
114: @menu
115: * Goals:: About the Gforth Project
116: * Gforth Environment:: Starting (and exiting) Gforth
117: * Tutorial:: Hands-on Forth Tutorial
118: * Introduction:: An introduction to ANS Forth
119: * Words:: Forth words available in Gforth
120: * Error messages:: How to interpret them
121: * Tools:: Programming tools
122: * ANS conformance:: Implementation-defined options etc.
123: * Standard vs Extensions:: Should I use extensions?
124: * Model:: The abstract machine of Gforth
125: * Integrating Gforth:: Forth as scripting language for applications
126: * Emacs and Gforth:: The Gforth Mode
127: * Image Files:: @code{.fi} files contain compiled code
128: * Engine:: The inner interpreter and the primitives
129: * Cross Compiler:: The Cross Compiler
130: * Bugs:: How to report them
131: * Origin:: Authors and ancestors of Gforth
132: * Forth-related information:: Books and places to look on the WWW
133: * Licenses::
134: * Word Index:: An item for each Forth word
135: * Concept Index:: A menu covering many topics
136:
137: @detailmenu
138: --- The Detailed Node Listing ---
139:
140: Gforth Environment
141:
142: * Invoking Gforth:: Getting in
143: * Leaving Gforth:: Getting out
144: * Command-line editing::
145: * Environment variables:: that affect how Gforth starts up
146: * Gforth Files:: What gets installed and where
147: * Gforth in pipes::
148: * Startup speed:: When 35ms is not fast enough ...
149:
150: Forth Tutorial
151:
152: * Starting Gforth Tutorial::
153: * Syntax Tutorial::
154: * Crash Course Tutorial::
155: * Stack Tutorial::
156: * Arithmetics Tutorial::
157: * Stack Manipulation Tutorial::
158: * Using files for Forth code Tutorial::
159: * Comments Tutorial::
160: * Colon Definitions Tutorial::
161: * Decompilation Tutorial::
162: * Stack-Effect Comments Tutorial::
163: * Types Tutorial::
164: * Factoring Tutorial::
165: * Designing the stack effect Tutorial::
166: * Local Variables Tutorial::
167: * Conditional execution Tutorial::
168: * Flags and Comparisons Tutorial::
169: * General Loops Tutorial::
170: * Counted loops Tutorial::
171: * Recursion Tutorial::
172: * Leaving definitions or loops Tutorial::
173: * Return Stack Tutorial::
174: * Memory Tutorial::
175: * Characters and Strings Tutorial::
176: * Alignment Tutorial::
177: * Files Tutorial::
178: * Interpretation and Compilation Semantics and Immediacy Tutorial::
179: * Execution Tokens Tutorial::
180: * Exceptions Tutorial::
181: * Defining Words Tutorial::
182: * Arrays and Records Tutorial::
183: * POSTPONE Tutorial::
184: * Literal Tutorial::
185: * Advanced macros Tutorial::
186: * Compilation Tokens Tutorial::
187: * Wordlists and Search Order Tutorial::
188:
189: An Introduction to ANS Forth
190:
191: * Introducing the Text Interpreter::
192: * Stacks and Postfix notation::
193: * Your first definition::
194: * How does that work?::
195: * Forth is written in Forth::
196: * Review - elements of a Forth system::
197: * Where to go next::
198: * Exercises::
199:
200: Forth Words
201:
202: * Notation::
203: * Case insensitivity::
204: * Comments::
205: * Boolean Flags::
206: * Arithmetic::
207: * Stack Manipulation::
208: * Memory::
209: * Control Structures::
210: * Defining Words::
211: * Interpretation and Compilation Semantics::
212: * Tokens for Words::
213: * Compiling words::
214: * The Text Interpreter::
215: * The Input Stream::
216: * Word Lists::
217: * Environmental Queries::
218: * Files::
219: * Blocks::
220: * Other I/O::
221: * OS command line arguments::
222: * Locals::
223: * Structures::
224: * Object-oriented Forth::
225: * Programming Tools::
226: * Assembler and Code Words::
227: * Threading Words::
228: * Passing Commands to the OS::
229: * Keeping track of Time::
230: * Miscellaneous Words::
231:
232: Arithmetic
233:
234: * Single precision::
235: * Double precision:: Double-cell integer arithmetic
236: * Bitwise operations::
237: * Numeric comparison::
238: * Mixed precision:: Operations with single and double-cell integers
239: * Floating Point::
240:
241: Stack Manipulation
242:
243: * Data stack::
244: * Floating point stack::
245: * Return stack::
246: * Locals stack::
247: * Stack pointer manipulation::
248:
249: Memory
250:
251: * Memory model::
252: * Dictionary allocation::
253: * Heap Allocation::
254: * Memory Access::
255: * Address arithmetic::
256: * Memory Blocks::
257:
258: Control Structures
259:
260: * Selection:: IF ... ELSE ... ENDIF
261: * Simple Loops:: BEGIN ...
262: * Counted Loops:: DO
263: * Arbitrary control structures::
264: * Calls and returns::
265: * Exception Handling::
266:
267: Defining Words
268:
269: * CREATE::
270: * Variables:: Variables and user variables
271: * Constants::
272: * Values:: Initialised variables
273: * Colon Definitions::
274: * Anonymous Definitions:: Definitions without names
275: * Supplying names:: Passing definition names as strings
276: * User-defined Defining Words::
277: * Deferred words:: Allow forward references
278: * Aliases::
279:
280: User-defined Defining Words
281:
282: * CREATE..DOES> applications::
283: * CREATE..DOES> details::
284: * Advanced does> usage example::
285: * @code{Const-does>}::
286:
287: Interpretation and Compilation Semantics
288:
289: * Combined words::
290:
291: Tokens for Words
292:
293: * Execution token:: represents execution/interpretation semantics
294: * Compilation token:: represents compilation semantics
295: * Name token:: represents named words
296:
297: Compiling words
298:
299: * Literals:: Compiling data values
300: * Macros:: Compiling words
301:
302: The Text Interpreter
303:
304: * Input Sources::
305: * Number Conversion::
306: * Interpret/Compile states::
307: * Interpreter Directives::
308:
309: Word Lists
310:
311: * Vocabularies::
312: * Why use word lists?::
313: * Word list example::
314:
315: Files
316:
317: * Forth source files::
318: * General files::
319: * Search Paths::
320:
321: Search Paths
322:
323: * Source Search Paths::
324: * General Search Paths::
325:
326: Other I/O
327:
328: * Simple numeric output:: Predefined formats
329: * Formatted numeric output:: Formatted (pictured) output
330: * String Formats:: How Forth stores strings in memory
331: * Displaying characters and strings:: Other stuff
332: * Input:: Input
333: * Pipes:: How to create your own pipes
334:
335: Locals
336:
337: * Gforth locals::
338: * ANS Forth locals::
339:
340: Gforth locals
341:
342: * Where are locals visible by name?::
343: * How long do locals live?::
344: * Locals programming style::
345: * Locals implementation::
346:
347: Structures
348:
349: * Why explicit structure support?::
350: * Structure Usage::
351: * Structure Naming Convention::
352: * Structure Implementation::
353: * Structure Glossary::
354:
355: Object-oriented Forth
356:
357: * Why object-oriented programming?::
358: * Object-Oriented Terminology::
359: * Objects::
360: * OOF::
361: * Mini-OOF::
362: * Comparison with other object models::
363:
364: The @file{objects.fs} model
365:
366: * Properties of the Objects model::
367: * Basic Objects Usage::
368: * The Objects base class::
369: * Creating objects::
370: * Object-Oriented Programming Style::
371: * Class Binding::
372: * Method conveniences::
373: * Classes and Scoping::
374: * Dividing classes::
375: * Object Interfaces::
376: * Objects Implementation::
377: * Objects Glossary::
378:
379: The @file{oof.fs} model
380:
381: * Properties of the OOF model::
382: * Basic OOF Usage::
383: * The OOF base class::
384: * Class Declaration::
385: * Class Implementation::
386:
387: The @file{mini-oof.fs} model
388:
389: * Basic Mini-OOF Usage::
390: * Mini-OOF Example::
391: * Mini-OOF Implementation::
392:
393: Programming Tools
394:
395: * Examining::
396: * Forgetting words::
397: * Debugging:: Simple and quick.
398: * Assertions:: Making your programs self-checking.
399: * Singlestep Debugger:: Executing your program word by word.
400:
401: Assembler and Code Words
402:
403: * Code and ;code::
404: * Common Assembler:: Assembler Syntax
405: * Common Disassembler::
406: * 386 Assembler:: Deviations and special cases
407: * Alpha Assembler:: Deviations and special cases
408: * MIPS assembler:: Deviations and special cases
409: * Other assemblers:: How to write them
410:
411: Tools
412:
413: * ANS Report:: Report the words used, sorted by wordset.
414:
415: ANS conformance
416:
417: * The Core Words::
418: * The optional Block word set::
419: * The optional Double Number word set::
420: * The optional Exception word set::
421: * The optional Facility word set::
422: * The optional File-Access word set::
423: * The optional Floating-Point word set::
424: * The optional Locals word set::
425: * The optional Memory-Allocation word set::
426: * The optional Programming-Tools word set::
427: * The optional Search-Order word set::
428:
429: The Core Words
430:
431: * core-idef:: Implementation Defined Options
432: * core-ambcond:: Ambiguous Conditions
433: * core-other:: Other System Documentation
434:
435: The optional Block word set
436:
437: * block-idef:: Implementation Defined Options
438: * block-ambcond:: Ambiguous Conditions
439: * block-other:: Other System Documentation
440:
441: The optional Double Number word set
442:
443: * double-ambcond:: Ambiguous Conditions
444:
445: The optional Exception word set
446:
447: * exception-idef:: Implementation Defined Options
448:
449: The optional Facility word set
450:
451: * facility-idef:: Implementation Defined Options
452: * facility-ambcond:: Ambiguous Conditions
453:
454: The optional File-Access word set
455:
456: * file-idef:: Implementation Defined Options
457: * file-ambcond:: Ambiguous Conditions
458:
459: The optional Floating-Point word set
460:
461: * floating-idef:: Implementation Defined Options
462: * floating-ambcond:: Ambiguous Conditions
463:
464: The optional Locals word set
465:
466: * locals-idef:: Implementation Defined Options
467: * locals-ambcond:: Ambiguous Conditions
468:
469: The optional Memory-Allocation word set
470:
471: * memory-idef:: Implementation Defined Options
472:
473: The optional Programming-Tools word set
474:
475: * programming-idef:: Implementation Defined Options
476: * programming-ambcond:: Ambiguous Conditions
477:
478: The optional Search-Order word set
479:
480: * search-idef:: Implementation Defined Options
481: * search-ambcond:: Ambiguous Conditions
482:
483: Emacs and Gforth
484:
485: * Installing gforth.el:: Making Emacs aware of Forth.
486: * Emacs Tags:: Viewing the source of a word in Emacs.
487: * Hilighting:: Making Forth code look prettier.
488: * Auto-Indentation:: Customizing auto-indentation.
489: * Blocks Files:: Reading and writing blocks files.
490:
491: Image Files
492:
493: * Image Licensing Issues:: Distribution terms for images.
494: * Image File Background:: Why have image files?
495: * Non-Relocatable Image Files:: don't always work.
496: * Data-Relocatable Image Files:: are better.
497: * Fully Relocatable Image Files:: better yet.
498: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
499: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
500: * Modifying the Startup Sequence:: and turnkey applications.
501:
502: Fully Relocatable Image Files
503:
504: * gforthmi:: The normal way
505: * cross.fs:: The hard way
506:
507: Engine
508:
509: * Portability::
510: * Threading::
511: * Primitives::
512: * Performance::
513:
514: Threading
515:
516: * Scheduling::
517: * Direct or Indirect Threaded?::
518: * Dynamic Superinstructions::
519: * DOES>::
520:
521: Primitives
522:
523: * Automatic Generation::
524: * TOS Optimization::
525: * Produced code::
526:
527: Cross Compiler
528:
529: * Using the Cross Compiler::
530: * How the Cross Compiler Works::
531:
532: Licenses
533:
534: * GNU Free Documentation License:: License for copying this manual.
535: * Copying:: GPL (for copying this software).
536:
537: @end detailmenu
538: @end menu
539:
540: @c ----------------------------------------------------------
541: @iftex
542: @unnumbered Preface
543: @cindex Preface
544: This manual documents Gforth. Some introductory material is provided for
545: readers who are unfamiliar with Forth or who are migrating to Gforth
546: from other Forth compilers. However, this manual is primarily a
547: reference manual.
548: @end iftex
549:
550: @comment TODO much more blurb here.
551:
552: @c ******************************************************************
553: @node Goals, Gforth Environment, Top, Top
554: @comment node-name, next, previous, up
555: @chapter Goals of Gforth
556: @cindex goals of the Gforth project
557: The goal of the Gforth Project is to develop a standard model for
558: ANS Forth. This can be split into several subgoals:
559:
560: @itemize @bullet
561: @item
562: Gforth should conform to the ANS Forth Standard.
563: @item
564: It should be a model, i.e. it should define all the
565: implementation-dependent things.
566: @item
567: It should become standard, i.e. widely accepted and used. This goal
568: is the most difficult one.
569: @end itemize
570:
571: To achieve these goals Gforth should be
572: @itemize @bullet
573: @item
574: Similar to previous models (fig-Forth, F83)
575: @item
576: Powerful. It should provide for all the things that are considered
577: necessary today and even some that are not yet considered necessary.
578: @item
579: Efficient. It should not get the reputation of being exceptionally
580: slow.
581: @item
582: Free.
583: @item
584: Available on many machines/easy to port.
585: @end itemize
586:
587: Have we achieved these goals? Gforth conforms to the ANS Forth
588: standard. It may be considered a model, but we have not yet documented
589: which parts of the model are stable and which parts we are likely to
590: change. It certainly has not yet become a de facto standard, but it
591: appears to be quite popular. It has some similarities to and some
592: differences from previous models. It has some powerful features, but not
593: yet everything that we envisioned. We certainly have achieved our
594: execution speed goals (@pxref{Performance})@footnote{However, in 1998
595: the bar was raised when the major commercial Forth vendors switched to
596: native code compilers.}. It is free and available on many machines.
597:
598: @c ******************************************************************
599: @node Gforth Environment, Tutorial, Goals, Top
600: @chapter Gforth Environment
601: @cindex Gforth environment
602:
603: Note: ultimately, the Gforth man page will be auto-generated from the
604: material in this chapter.
605:
606: @menu
607: * Invoking Gforth:: Getting in
608: * Leaving Gforth:: Getting out
609: * Command-line editing::
610: * Environment variables:: that affect how Gforth starts up
611: * Gforth Files:: What gets installed and where
612: * Gforth in pipes::
613: * Startup speed:: When 35ms is not fast enough ...
614: @end menu
615:
616: For related information about the creation of images see @ref{Image Files}.
617:
618: @comment ----------------------------------------------
619: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
620: @section Invoking Gforth
621: @cindex invoking Gforth
622: @cindex running Gforth
623: @cindex command-line options
624: @cindex options on the command line
625: @cindex flags on the command line
626:
627: Gforth is made up of two parts; an executable ``engine'' (named
628: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
629: will usually just say @code{gforth} -- this automatically loads the
630: default image file @file{gforth.fi}. In many other cases the default
631: Gforth image will be invoked like this:
632: @example
633: gforth [file | -e forth-code] ...
634: @end example
635: @noindent
636: This interprets the contents of the files and the Forth code in the order they
637: are given.
638:
639: In addition to the @command{gforth} engine, there is also an engine
640: called @command{gforth-fast}, which is faster, but gives less
641: informative error messages (@pxref{Error messages}) and may catch some
642: stack underflows later or not at all. You should use it for debugged,
643: performance-critical programs.
644:
645: Moreover, there is an engine called @command{gforth-itc}, which is
646: useful in some backwards-compatibility situations (@pxref{Direct or
647: Indirect Threaded?}).
648:
649: In general, the command line looks like this:
650:
651: @example
652: gforth[-fast] [engine options] [image options]
653: @end example
654:
655: The engine options must come before the rest of the command
656: line. They are:
657:
658: @table @code
659: @cindex -i, command-line option
660: @cindex --image-file, command-line option
661: @item --image-file @i{file}
662: @itemx -i @i{file}
663: Loads the Forth image @i{file} instead of the default
664: @file{gforth.fi} (@pxref{Image Files}).
665:
666: @cindex --appl-image, command-line option
667: @item --appl-image @i{file}
668: Loads the image @i{file} and leaves all further command-line arguments
669: to the image (instead of processing them as engine options). This is
670: useful for building executable application images on Unix, built with
671: @code{gforthmi --application ...}.
672:
673: @cindex --path, command-line option
674: @cindex -p, command-line option
675: @item --path @i{path}
676: @itemx -p @i{path}
677: Uses @i{path} for searching the image file and Forth source code files
678: instead of the default in the environment variable @code{GFORTHPATH} or
679: the path specified at installation time (e.g.,
680: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
681: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
682:
683: @cindex --dictionary-size, command-line option
684: @cindex -m, command-line option
685: @cindex @i{size} parameters for command-line options
686: @cindex size of the dictionary and the stacks
687: @item --dictionary-size @i{size}
688: @itemx -m @i{size}
689: Allocate @i{size} space for the Forth dictionary space instead of
690: using the default specified in the image (typically 256K). The
691: @i{size} specification for this and subsequent options consists of
692: an integer and a unit (e.g.,
693: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
694: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
695: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
696: @code{e} is used.
697:
698: @cindex --data-stack-size, command-line option
699: @cindex -d, command-line option
700: @item --data-stack-size @i{size}
701: @itemx -d @i{size}
702: Allocate @i{size} space for the data stack instead of using the
703: default specified in the image (typically 16K).
704:
705: @cindex --return-stack-size, command-line option
706: @cindex -r, command-line option
707: @item --return-stack-size @i{size}
708: @itemx -r @i{size}
709: Allocate @i{size} space for the return stack instead of using the
710: default specified in the image (typically 15K).
711:
712: @cindex --fp-stack-size, command-line option
713: @cindex -f, command-line option
714: @item --fp-stack-size @i{size}
715: @itemx -f @i{size}
716: Allocate @i{size} space for the floating point stack instead of
717: using the default specified in the image (typically 15.5K). In this case
718: the unit specifier @code{e} refers to floating point numbers.
719:
720: @cindex --locals-stack-size, command-line option
721: @cindex -l, command-line option
722: @item --locals-stack-size @i{size}
723: @itemx -l @i{size}
724: Allocate @i{size} space for the locals stack instead of using the
725: default specified in the image (typically 14.5K).
726:
727: @cindex -h, command-line option
728: @cindex --help, command-line option
729: @item --help
730: @itemx -h
731: Print a message about the command-line options
732:
733: @cindex -v, command-line option
734: @cindex --version, command-line option
735: @item --version
736: @itemx -v
737: Print version and exit
738:
739: @cindex --debug, command-line option
740: @item --debug
741: Print some information useful for debugging on startup.
742:
743: @cindex --offset-image, command-line option
744: @item --offset-image
745: Start the dictionary at a slightly different position than would be used
746: otherwise (useful for creating data-relocatable images,
747: @pxref{Data-Relocatable Image Files}).
748:
749: @cindex --no-offset-im, command-line option
750: @item --no-offset-im
751: Start the dictionary at the normal position.
752:
753: @cindex --clear-dictionary, command-line option
754: @item --clear-dictionary
755: Initialize all bytes in the dictionary to 0 before loading the image
756: (@pxref{Data-Relocatable Image Files}).
757:
758: @cindex --die-on-signal, command-line-option
759: @item --die-on-signal
760: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
761: or the segmentation violation SIGSEGV) by translating it into a Forth
762: @code{THROW}. With this option, Gforth exits if it receives such a
763: signal. This option is useful when the engine and/or the image might be
764: severely broken (such that it causes another signal before recovering
765: from the first); this option avoids endless loops in such cases.
766:
767: @cindex --no-dynamic, command-line option
768: @cindex --dynamic, command-line option
769: @item --no-dynamic
770: @item --dynamic
771: Disable or enable dynamic superinstructions with replication
772: (@pxref{Dynamic Superinstructions}).
773:
774: @cindex --no-super, command-line option
775: @item --no-super
776: Disable dynamic superinstructions, use just dynamic replication; this is
777: useful if you want to patch threaded code (@pxref{Dynamic
778: Superinstructions}).
779:
780: @cindex --ss-number, command-line option
781: @item --ss-number=@var{N}
782: Use only the first @var{N} static superinstructions compiled into the
783: engine (default: use them all; note that only @code{gforth-fast} has
784: any). This option is useful for measuring the performance impact of
785: static superinstructions.
786:
787: @cindex --ss-min-..., command-line options
788: @item --ss-min-codesize
789: @item --ss-min-ls
790: @item --ss-min-lsu
791: @item --ss-min-nexts
792: Use specified metric for determining the cost of a primitive or static
793: superinstruction for static superinstruction selection. @code{Codesize}
794: is the native code size of the primive or static superinstruction,
795: @code{ls} is the number of loads and stores, @code{lsu} is the number of
796: loads, stores, and updates, and @code{nexts} is the number of dispatches
797: (not taking dynamic superinstructions into account), i.e. every
798: primitive or static superinstruction has cost 1. Default:
799: @code{codesize} if you use dynamic code generation, otherwise
800: @code{nexts}.
801:
802: @cindex --ss-greedy, command-line option
803: @item --ss-greedy
804: This option is useful for measuring the performance impact of static
805: superinstructions. By default, an optimal shortest-path algorithm is
806: used for selecting static superinstructions. With @option{--ss-greedy}
807: this algorithm is modified to assume that anything after the static
808: superinstruction currently under consideration is not combined into
809: static superinstructions. With @option{--ss-min-nexts} this produces
810: the same result as a greedy algorithm that always selects the longest
811: superinstruction available at the moment. E.g., if there are
812: superinstructions AB and BCD, then for the sequence A B C D the optimal
813: algorithm will select A BCD and the greedy algorithm will select AB C D.
814:
815: @cindex --print-metrics, command-line option
816: @item --print-metrics
817: Prints some metrics used during static superinstruction selection:
818: @code{code size} is the actual size of the dynamically generated code.
819: @code{Metric codesize} is the sum of the codesize metrics as seen by
820: static superinstruction selection; there is a difference from @code{code
821: size}, because not all primitives and static superinstructions are
822: compiled into dynamically generated code, and because of markers. The
823: other metrics correspond to the @option{ss-min-...} options. This
824: option is useful for evaluating the effects of the @option{--ss-...}
825: options.
826:
827: @end table
828:
829: @cindex loading files at startup
830: @cindex executing code on startup
831: @cindex batch processing with Gforth
832: As explained above, the image-specific command-line arguments for the
833: default image @file{gforth.fi} consist of a sequence of filenames and
834: @code{-e @var{forth-code}} options that are interpreted in the sequence
835: in which they are given. The @code{-e @var{forth-code}} or
836: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
837: option takes only one argument; if you want to evaluate more Forth
838: words, you have to quote them or use @code{-e} several times. To exit
839: after processing the command line (instead of entering interactive mode)
840: append @code{-e bye} to the command line. You can also process the
841: command-line arguments with a Forth program (@pxref{OS command line
842: arguments}).
843:
844: @cindex versions, invoking other versions of Gforth
845: If you have several versions of Gforth installed, @code{gforth} will
846: invoke the version that was installed last. @code{gforth-@i{version}}
847: invokes a specific version. If your environment contains the variable
848: @code{GFORTHPATH}, you may want to override it by using the
849: @code{--path} option.
850:
851: Not yet implemented:
852: On startup the system first executes the system initialization file
853: (unless the option @code{--no-init-file} is given; note that the system
854: resulting from using this option may not be ANS Forth conformant). Then
855: the user initialization file @file{.gforth.fs} is executed, unless the
856: option @code{--no-rc} is given; this file is searched for in @file{.},
857: then in @file{~}, then in the normal path (see above).
858:
859:
860:
861: @comment ----------------------------------------------
862: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
863: @section Leaving Gforth
864: @cindex Gforth - leaving
865: @cindex leaving Gforth
866:
867: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
868: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
869: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
870: data are discarded. For ways of saving the state of the system before
871: leaving Gforth see @ref{Image Files}.
872:
873: doc-bye
874:
875:
876: @comment ----------------------------------------------
877: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
878: @section Command-line editing
879: @cindex command-line editing
880:
881: Gforth maintains a history file that records every line that you type to
882: the text interpreter. This file is preserved between sessions, and is
883: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
884: repeatedly you can recall successively older commands from this (or
885: previous) session(s). The full list of command-line editing facilities is:
886:
887: @itemize @bullet
888: @item
889: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
890: commands from the history buffer.
891: @item
892: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
893: from the history buffer.
894: @item
895: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
896: @item
897: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
898: @item
899: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
900: closing up the line.
901: @item
902: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
903: @item
904: @kbd{Ctrl-a} to move the cursor to the start of the line.
905: @item
906: @kbd{Ctrl-e} to move the cursor to the end of the line.
907: @item
908: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
909: line.
910: @item
911: @key{TAB} to step through all possible full-word completions of the word
912: currently being typed.
913: @item
914: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
915: using @code{bye}).
916: @item
917: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
918: character under the cursor.
919: @end itemize
920:
921: When editing, displayable characters are inserted to the left of the
922: cursor position; the line is always in ``insert'' (as opposed to
923: ``overstrike'') mode.
924:
925: @cindex history file
926: @cindex @file{.gforth-history}
927: On Unix systems, the history file is @file{~/.gforth-history} by
928: default@footnote{i.e. it is stored in the user's home directory.}. You
929: can find out the name and location of your history file using:
930:
931: @example
932: history-file type \ Unix-class systems
933:
934: history-file type \ Other systems
935: history-dir type
936: @end example
937:
938: If you enter long definitions by hand, you can use a text editor to
939: paste them out of the history file into a Forth source file for reuse at
940: a later time.
941:
942: Gforth never trims the size of the history file, so you should do this
943: periodically, if necessary.
944:
945: @comment this is all defined in history.fs
946: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
947: @comment chosen?
948:
949:
950: @comment ----------------------------------------------
951: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
952: @section Environment variables
953: @cindex environment variables
954:
955: Gforth uses these environment variables:
956:
957: @itemize @bullet
958: @item
959: @cindex @code{GFORTHHIST} -- environment variable
960: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
961: open/create the history file, @file{.gforth-history}. Default:
962: @code{$HOME}.
963:
964: @item
965: @cindex @code{GFORTHPATH} -- environment variable
966: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
967: for Forth source-code files.
968:
969: @item
970: @cindex @code{GFORTH} -- environment variable
971: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
972:
973: @item
974: @cindex @code{GFORTHD} -- environment variable
975: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
976:
977: @item
978: @cindex @code{TMP}, @code{TEMP} - environment variable
979: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
980: location for the history file.
981: @end itemize
982:
983: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
984: @comment mentioning these.
985:
986: All the Gforth environment variables default to sensible values if they
987: are not set.
988:
989:
990: @comment ----------------------------------------------
991: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
992: @section Gforth files
993: @cindex Gforth files
994:
995: When you install Gforth on a Unix system, it installs files in these
996: locations by default:
997:
998: @itemize @bullet
999: @item
1000: @file{/usr/local/bin/gforth}
1001: @item
1002: @file{/usr/local/bin/gforthmi}
1003: @item
1004: @file{/usr/local/man/man1/gforth.1} - man page.
1005: @item
1006: @file{/usr/local/info} - the Info version of this manual.
1007: @item
1008: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1009: @item
1010: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1011: @item
1012: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1013: @item
1014: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1015: @end itemize
1016:
1017: You can select different places for installation by using
1018: @code{configure} options (listed with @code{configure --help}).
1019:
1020: @comment ----------------------------------------------
1021: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1022: @section Gforth in pipes
1023: @cindex pipes, Gforth as part of
1024:
1025: Gforth can be used in pipes created elsewhere (described here). It can
1026: also create pipes on its own (@pxref{Pipes}).
1027:
1028: @cindex input from pipes
1029: If you pipe into Gforth, your program should read with @code{read-file}
1030: or @code{read-line} from @code{stdin} (@pxref{General files}).
1031: @code{Key} does not recognize the end of input. Words like
1032: @code{accept} echo the input and are therefore usually not useful for
1033: reading from a pipe. You have to invoke the Forth program with an OS
1034: command-line option, as you have no chance to use the Forth command line
1035: (the text interpreter would try to interpret the pipe input).
1036:
1037: @cindex output in pipes
1038: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1039:
1040: @cindex silent exiting from Gforth
1041: When you write to a pipe that has been closed at the other end, Gforth
1042: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1043: into the exception @code{broken-pipe-error}. If your application does
1044: not catch that exception, the system catches it and exits, usually
1045: silently (unless you were working on the Forth command line; then it
1046: prints an error message and exits). This is usually the desired
1047: behaviour.
1048:
1049: If you do not like this behaviour, you have to catch the exception
1050: yourself, and react to it.
1051:
1052: Here's an example of an invocation of Gforth that is usable in a pipe:
1053:
1054: @example
1055: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1056: type repeat ; foo bye"
1057: @end example
1058:
1059: This example just copies the input verbatim to the output. A very
1060: simple pipe containing this example looks like this:
1061:
1062: @example
1063: cat startup.fs |
1064: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1065: type repeat ; foo bye"|
1066: head
1067: @end example
1068:
1069: @cindex stderr and pipes
1070: Pipes involving Gforth's @code{stderr} output do not work.
1071:
1072: @comment ----------------------------------------------
1073: @node Startup speed, , Gforth in pipes, Gforth Environment
1074: @section Startup speed
1075: @cindex Startup speed
1076: @cindex speed, startup
1077:
1078: If Gforth is used for CGI scripts or in shell scripts, its startup
1079: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1080: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1081: system time.
1082:
1083: If startup speed is a problem, you may consider the following ways to
1084: improve it; or you may consider ways to reduce the number of startups
1085: (for example, by using Fast-CGI).
1086:
1087: An easy step that influences Gforth startup speed is the use of the
1088: @option{--no-dynamic} option; this decreases image loading speed, but
1089: increases compile-time and run-time.
1090:
1091: Another step to improve startup speed is to statically link Gforth, by
1092: building it with @code{XLDFLAGS=-static}. This requires more memory for
1093: the code and will therefore slow down the first invocation, but
1094: subsequent invocations avoid the dynamic linking overhead. Another
1095: disadvantage is that Gforth won't profit from library upgrades. As a
1096: result, @code{gforth-static -e bye} takes about 17.1ms user and
1097: 8.2ms system time.
1098:
1099: The next step to improve startup speed is to use a non-relocatable image
1100: (@pxref{Non-Relocatable Image Files}). You can create this image with
1101: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1102: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1103: and a part of the copy-on-write overhead. The disadvantage is that the
1104: non-relocatable image does not work if the OS gives Gforth a different
1105: address for the dictionary, for whatever reason; so you better provide a
1106: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1107: bye} takes about 15.3ms user and 7.5ms system time.
1108:
1109: The final step is to disable dictionary hashing in Gforth. Gforth
1110: builds the hash table on startup, which takes much of the startup
1111: overhead. You can do this by commenting out the @code{include hash.fs}
1112: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1113: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1114: The disadvantages are that functionality like @code{table} and
1115: @code{ekey} is missing and that text interpretation (e.g., compiling)
1116: now takes much longer. So, you should only use this method if there is
1117: no significant text interpretation to perform (the script should be
1118: compiled into the image, amongst other things). @code{gforth-static -i
1119: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1120:
1121: @c ******************************************************************
1122: @node Tutorial, Introduction, Gforth Environment, Top
1123: @chapter Forth Tutorial
1124: @cindex Tutorial
1125: @cindex Forth Tutorial
1126:
1127: @c Topics from nac's Introduction that could be mentioned:
1128: @c press <ret> after each line
1129: @c Prompt
1130: @c numbers vs. words in dictionary on text interpretation
1131: @c what happens on redefinition
1132: @c parsing words (in particular, defining words)
1133:
1134: The difference of this chapter from the Introduction
1135: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1136: be used while sitting in front of a computer, and covers much more
1137: material, but does not explain how the Forth system works.
1138:
1139: This tutorial can be used with any ANS-compliant Forth; any
1140: Gforth-specific features are marked as such and you can skip them if you
1141: work with another Forth. This tutorial does not explain all features of
1142: Forth, just enough to get you started and give you some ideas about the
1143: facilities available in Forth. Read the rest of the manual and the
1144: standard when you are through this.
1145:
1146: The intended way to use this tutorial is that you work through it while
1147: sitting in front of the console, take a look at the examples and predict
1148: what they will do, then try them out; if the outcome is not as expected,
1149: find out why (e.g., by trying out variations of the example), so you
1150: understand what's going on. There are also some assignments that you
1151: should solve.
1152:
1153: This tutorial assumes that you have programmed before and know what,
1154: e.g., a loop is.
1155:
1156: @c !! explain compat library
1157:
1158: @menu
1159: * Starting Gforth Tutorial::
1160: * Syntax Tutorial::
1161: * Crash Course Tutorial::
1162: * Stack Tutorial::
1163: * Arithmetics Tutorial::
1164: * Stack Manipulation Tutorial::
1165: * Using files for Forth code Tutorial::
1166: * Comments Tutorial::
1167: * Colon Definitions Tutorial::
1168: * Decompilation Tutorial::
1169: * Stack-Effect Comments Tutorial::
1170: * Types Tutorial::
1171: * Factoring Tutorial::
1172: * Designing the stack effect Tutorial::
1173: * Local Variables Tutorial::
1174: * Conditional execution Tutorial::
1175: * Flags and Comparisons Tutorial::
1176: * General Loops Tutorial::
1177: * Counted loops Tutorial::
1178: * Recursion Tutorial::
1179: * Leaving definitions or loops Tutorial::
1180: * Return Stack Tutorial::
1181: * Memory Tutorial::
1182: * Characters and Strings Tutorial::
1183: * Alignment Tutorial::
1184: * Files Tutorial::
1185: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1186: * Execution Tokens Tutorial::
1187: * Exceptions Tutorial::
1188: * Defining Words Tutorial::
1189: * Arrays and Records Tutorial::
1190: * POSTPONE Tutorial::
1191: * Literal Tutorial::
1192: * Advanced macros Tutorial::
1193: * Compilation Tokens Tutorial::
1194: * Wordlists and Search Order Tutorial::
1195: @end menu
1196:
1197: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1198: @section Starting Gforth
1199: @cindex starting Gforth tutorial
1200: You can start Gforth by typing its name:
1201:
1202: @example
1203: gforth
1204: @end example
1205:
1206: That puts you into interactive mode; you can leave Gforth by typing
1207: @code{bye}. While in Gforth, you can edit the command line and access
1208: the command line history with cursor keys, similar to bash.
1209:
1210:
1211: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1212: @section Syntax
1213: @cindex syntax tutorial
1214:
1215: A @dfn{word} is a sequence of arbitrary characters (expcept white
1216: space). Words are separated by white space. E.g., each of the
1217: following lines contains exactly one word:
1218:
1219: @example
1220: word
1221: !@@#$%^&*()
1222: 1234567890
1223: 5!a
1224: @end example
1225:
1226: A frequent beginner's error is to leave away necessary white space,
1227: resulting in an error like @samp{Undefined word}; so if you see such an
1228: error, check if you have put spaces wherever necessary.
1229:
1230: @example
1231: ." hello, world" \ correct
1232: ."hello, world" \ gives an "Undefined word" error
1233: @end example
1234:
1235: Gforth and most other Forth systems ignore differences in case (they are
1236: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1237: your system is case-sensitive, you may have to type all the examples
1238: given here in upper case.
1239:
1240:
1241: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1242: @section Crash Course
1243:
1244: Type
1245:
1246: @example
1247: 0 0 !
1248: here execute
1249: ' catch >body 20 erase abort
1250: ' (quit) >body 20 erase
1251: @end example
1252:
1253: The last two examples are guaranteed to destroy parts of Gforth (and
1254: most other systems), so you better leave Gforth afterwards (if it has
1255: not finished by itself). On some systems you may have to kill gforth
1256: from outside (e.g., in Unix with @code{kill}).
1257:
1258: Now that you know how to produce crashes (and that there's not much to
1259: them), let's learn how to produce meaningful programs.
1260:
1261:
1262: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1263: @section Stack
1264: @cindex stack tutorial
1265:
1266: The most obvious feature of Forth is the stack. When you type in a
1267: number, it is pushed on the stack. You can display the content of the
1268: stack with @code{.s}.
1269:
1270: @example
1271: 1 2 .s
1272: 3 .s
1273: @end example
1274:
1275: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1276: appear in @code{.s} output as they appeared in the input.
1277:
1278: You can print the top of stack element with @code{.}.
1279:
1280: @example
1281: 1 2 3 . . .
1282: @end example
1283:
1284: In general, words consume their stack arguments (@code{.s} is an
1285: exception).
1286:
1287: @assignment
1288: What does the stack contain after @code{5 6 7 .}?
1289: @endassignment
1290:
1291:
1292: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1293: @section Arithmetics
1294: @cindex arithmetics tutorial
1295:
1296: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1297: operate on the top two stack items:
1298:
1299: @example
1300: 2 2 .s
1301: + .s
1302: .
1303: 2 1 - .
1304: 7 3 mod .
1305: @end example
1306:
1307: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1308: as in the corresponding infix expression (this is generally the case in
1309: Forth).
1310:
1311: Parentheses are superfluous (and not available), because the order of
1312: the words unambiguously determines the order of evaluation and the
1313: operands:
1314:
1315: @example
1316: 3 4 + 5 * .
1317: 3 4 5 * + .
1318: @end example
1319:
1320: @assignment
1321: What are the infix expressions corresponding to the Forth code above?
1322: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1323: known as Postfix or RPN (Reverse Polish Notation).}.
1324: @endassignment
1325:
1326: To change the sign, use @code{negate}:
1327:
1328: @example
1329: 2 negate .
1330: @end example
1331:
1332: @assignment
1333: Convert -(-3)*4-5 to Forth.
1334: @endassignment
1335:
1336: @code{/mod} performs both @code{/} and @code{mod}.
1337:
1338: @example
1339: 7 3 /mod . .
1340: @end example
1341:
1342: Reference: @ref{Arithmetic}.
1343:
1344:
1345: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1346: @section Stack Manipulation
1347: @cindex stack manipulation tutorial
1348:
1349: Stack manipulation words rearrange the data on the stack.
1350:
1351: @example
1352: 1 .s drop .s
1353: 1 .s dup .s drop drop .s
1354: 1 2 .s over .s drop drop drop
1355: 1 2 .s swap .s drop drop
1356: 1 2 3 .s rot .s drop drop drop
1357: @end example
1358:
1359: These are the most important stack manipulation words. There are also
1360: variants that manipulate twice as many stack items:
1361:
1362: @example
1363: 1 2 3 4 .s 2swap .s 2drop 2drop
1364: @end example
1365:
1366: Two more stack manipulation words are:
1367:
1368: @example
1369: 1 2 .s nip .s drop
1370: 1 2 .s tuck .s 2drop drop
1371: @end example
1372:
1373: @assignment
1374: Replace @code{nip} and @code{tuck} with combinations of other stack
1375: manipulation words.
1376:
1377: @example
1378: Given: How do you get:
1379: 1 2 3 3 2 1
1380: 1 2 3 1 2 3 2
1381: 1 2 3 1 2 3 3
1382: 1 2 3 1 3 3
1383: 1 2 3 2 1 3
1384: 1 2 3 4 4 3 2 1
1385: 1 2 3 1 2 3 1 2 3
1386: 1 2 3 4 1 2 3 4 1 2
1387: 1 2 3
1388: 1 2 3 1 2 3 4
1389: 1 2 3 1 3
1390: @end example
1391: @endassignment
1392:
1393: @example
1394: 5 dup * .
1395: @end example
1396:
1397: @assignment
1398: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1399: Write a piece of Forth code that expects two numbers on the stack
1400: (@var{a} and @var{b}, with @var{b} on top) and computes
1401: @code{(a-b)(a+1)}.
1402: @endassignment
1403:
1404: Reference: @ref{Stack Manipulation}.
1405:
1406:
1407: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1408: @section Using files for Forth code
1409: @cindex loading Forth code, tutorial
1410: @cindex files containing Forth code, tutorial
1411:
1412: While working at the Forth command line is convenient for one-line
1413: examples and short one-off code, you probably want to store your source
1414: code in files for convenient editing and persistence. You can use your
1415: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1416: Gforth}) to create @var{file.fs} and use
1417:
1418: @example
1419: s" @var{file.fs}" included
1420: @end example
1421:
1422: to load it into your Forth system. The file name extension I use for
1423: Forth files is @samp{.fs}.
1424:
1425: You can easily start Gforth with some files loaded like this:
1426:
1427: @example
1428: gforth @var{file1.fs} @var{file2.fs}
1429: @end example
1430:
1431: If an error occurs during loading these files, Gforth terminates,
1432: whereas an error during @code{INCLUDED} within Gforth usually gives you
1433: a Gforth command line. Starting the Forth system every time gives you a
1434: clean start every time, without interference from the results of earlier
1435: tries.
1436:
1437: I often put all the tests in a file, then load the code and run the
1438: tests with
1439:
1440: @example
1441: gforth @var{code.fs} @var{tests.fs} -e bye
1442: @end example
1443:
1444: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1445: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1446: restart this command without ado.
1447:
1448: The advantage of this approach is that the tests can be repeated easily
1449: every time the program ist changed, making it easy to catch bugs
1450: introduced by the change.
1451:
1452: Reference: @ref{Forth source files}.
1453:
1454:
1455: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1456: @section Comments
1457: @cindex comments tutorial
1458:
1459: @example
1460: \ That's a comment; it ends at the end of the line
1461: ( Another comment; it ends here: ) .s
1462: @end example
1463:
1464: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1465: separated with white space from the following text.
1466:
1467: @example
1468: \This gives an "Undefined word" error
1469: @end example
1470:
1471: The first @code{)} ends a comment started with @code{(}, so you cannot
1472: nest @code{(}-comments; and you cannot comment out text containing a
1473: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1474: avoid @code{)} in word names.}.
1475:
1476: I use @code{\}-comments for descriptive text and for commenting out code
1477: of one or more line; I use @code{(}-comments for describing the stack
1478: effect, the stack contents, or for commenting out sub-line pieces of
1479: code.
1480:
1481: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1482: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1483: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1484: with @kbd{M-q}.
1485:
1486: Reference: @ref{Comments}.
1487:
1488:
1489: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1490: @section Colon Definitions
1491: @cindex colon definitions, tutorial
1492: @cindex definitions, tutorial
1493: @cindex procedures, tutorial
1494: @cindex functions, tutorial
1495:
1496: are similar to procedures and functions in other programming languages.
1497:
1498: @example
1499: : squared ( n -- n^2 )
1500: dup * ;
1501: 5 squared .
1502: 7 squared .
1503: @end example
1504:
1505: @code{:} starts the colon definition; its name is @code{squared}. The
1506: following comment describes its stack effect. The words @code{dup *}
1507: are not executed, but compiled into the definition. @code{;} ends the
1508: colon definition.
1509:
1510: The newly-defined word can be used like any other word, including using
1511: it in other definitions:
1512:
1513: @example
1514: : cubed ( n -- n^3 )
1515: dup squared * ;
1516: -5 cubed .
1517: : fourth-power ( n -- n^4 )
1518: squared squared ;
1519: 3 fourth-power .
1520: @end example
1521:
1522: @assignment
1523: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1524: @code{/mod} in terms of other Forth words, and check if they work (hint:
1525: test your tests on the originals first). Don't let the
1526: @samp{redefined}-Messages spook you, they are just warnings.
1527: @endassignment
1528:
1529: Reference: @ref{Colon Definitions}.
1530:
1531:
1532: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1533: @section Decompilation
1534: @cindex decompilation tutorial
1535: @cindex see tutorial
1536:
1537: You can decompile colon definitions with @code{see}:
1538:
1539: @example
1540: see squared
1541: see cubed
1542: @end example
1543:
1544: In Gforth @code{see} shows you a reconstruction of the source code from
1545: the executable code. Informations that were present in the source, but
1546: not in the executable code, are lost (e.g., comments).
1547:
1548: You can also decompile the predefined words:
1549:
1550: @example
1551: see .
1552: see +
1553: @end example
1554:
1555:
1556: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1557: @section Stack-Effect Comments
1558: @cindex stack-effect comments, tutorial
1559: @cindex --, tutorial
1560: By convention the comment after the name of a definition describes the
1561: stack effect: The part in from of the @samp{--} describes the state of
1562: the stack before the execution of the definition, i.e., the parameters
1563: that are passed into the colon definition; the part behind the @samp{--}
1564: is the state of the stack after the execution of the definition, i.e.,
1565: the results of the definition. The stack comment only shows the top
1566: stack items that the definition accesses and/or changes.
1567:
1568: You should put a correct stack effect on every definition, even if it is
1569: just @code{( -- )}. You should also add some descriptive comment to
1570: more complicated words (I usually do this in the lines following
1571: @code{:}). If you don't do this, your code becomes unreadable (because
1572: you have to work through every definition before you can understand
1573: any).
1574:
1575: @assignment
1576: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1577: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1578: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1579: are done, you can compare your stack effects to those in this manual
1580: (@pxref{Word Index}).
1581: @endassignment
1582:
1583: Sometimes programmers put comments at various places in colon
1584: definitions that describe the contents of the stack at that place (stack
1585: comments); i.e., they are like the first part of a stack-effect
1586: comment. E.g.,
1587:
1588: @example
1589: : cubed ( n -- n^3 )
1590: dup squared ( n n^2 ) * ;
1591: @end example
1592:
1593: In this case the stack comment is pretty superfluous, because the word
1594: is simple enough. If you think it would be a good idea to add such a
1595: comment to increase readability, you should also consider factoring the
1596: word into several simpler words (@pxref{Factoring Tutorial,,
1597: Factoring}), which typically eliminates the need for the stack comment;
1598: however, if you decide not to refactor it, then having such a comment is
1599: better than not having it.
1600:
1601: The names of the stack items in stack-effect and stack comments in the
1602: standard, in this manual, and in many programs specify the type through
1603: a type prefix, similar to Fortran and Hungarian notation. The most
1604: frequent prefixes are:
1605:
1606: @table @code
1607: @item n
1608: signed integer
1609: @item u
1610: unsigned integer
1611: @item c
1612: character
1613: @item f
1614: Boolean flags, i.e. @code{false} or @code{true}.
1615: @item a-addr,a-
1616: Cell-aligned address
1617: @item c-addr,c-
1618: Char-aligned address (note that a Char may have two bytes in Windows NT)
1619: @item xt
1620: Execution token, same size as Cell
1621: @item w,x
1622: Cell, can contain an integer or an address. It usually takes 32, 64 or
1623: 16 bits (depending on your platform and Forth system). A cell is more
1624: commonly known as machine word, but the term @emph{word} already means
1625: something different in Forth.
1626: @item d
1627: signed double-cell integer
1628: @item ud
1629: unsigned double-cell integer
1630: @item r
1631: Float (on the FP stack)
1632: @end table
1633:
1634: You can find a more complete list in @ref{Notation}.
1635:
1636: @assignment
1637: Write stack-effect comments for all definitions you have written up to
1638: now.
1639: @endassignment
1640:
1641:
1642: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1643: @section Types
1644: @cindex types tutorial
1645:
1646: In Forth the names of the operations are not overloaded; so similar
1647: operations on different types need different names; e.g., @code{+} adds
1648: integers, and you have to use @code{f+} to add floating-point numbers.
1649: The following prefixes are often used for related operations on
1650: different types:
1651:
1652: @table @code
1653: @item (none)
1654: signed integer
1655: @item u
1656: unsigned integer
1657: @item c
1658: character
1659: @item d
1660: signed double-cell integer
1661: @item ud, du
1662: unsigned double-cell integer
1663: @item 2
1664: two cells (not-necessarily double-cell numbers)
1665: @item m, um
1666: mixed single-cell and double-cell operations
1667: @item f
1668: floating-point (note that in stack comments @samp{f} represents flags,
1669: and @samp{r} represents FP numbers).
1670: @end table
1671:
1672: If there are no differences between the signed and the unsigned variant
1673: (e.g., for @code{+}), there is only the prefix-less variant.
1674:
1675: Forth does not perform type checking, neither at compile time, nor at
1676: run time. If you use the wrong oeration, the data are interpreted
1677: incorrectly:
1678:
1679: @example
1680: -1 u.
1681: @end example
1682:
1683: If you have only experience with type-checked languages until now, and
1684: have heard how important type-checking is, don't panic! In my
1685: experience (and that of other Forthers), type errors in Forth code are
1686: usually easy to find (once you get used to it), the increased vigilance
1687: of the programmer tends to catch some harder errors in addition to most
1688: type errors, and you never have to work around the type system, so in
1689: most situations the lack of type-checking seems to be a win (projects to
1690: add type checking to Forth have not caught on).
1691:
1692:
1693: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1694: @section Factoring
1695: @cindex factoring tutorial
1696:
1697: If you try to write longer definitions, you will soon find it hard to
1698: keep track of the stack contents. Therefore, good Forth programmers
1699: tend to write only short definitions (e.g., three lines). The art of
1700: finding meaningful short definitions is known as factoring (as in
1701: factoring polynomials).
1702:
1703: Well-factored programs offer additional advantages: smaller, more
1704: general words, are easier to test and debug and can be reused more and
1705: better than larger, specialized words.
1706:
1707: So, if you run into difficulties with stack management, when writing
1708: code, try to define meaningful factors for the word, and define the word
1709: in terms of those. Even if a factor contains only two words, it is
1710: often helpful.
1711:
1712: Good factoring is not easy, and it takes some practice to get the knack
1713: for it; but even experienced Forth programmers often don't find the
1714: right solution right away, but only when rewriting the program. So, if
1715: you don't come up with a good solution immediately, keep trying, don't
1716: despair.
1717:
1718: @c example !!
1719:
1720:
1721: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1722: @section Designing the stack effect
1723: @cindex Stack effect design, tutorial
1724: @cindex design of stack effects, tutorial
1725:
1726: In other languages you can use an arbitrary order of parameters for a
1727: function; and since there is only one result, you don't have to deal with
1728: the order of results, either.
1729:
1730: In Forth (and other stack-based languages, e.g., PostScript) the
1731: parameter and result order of a definition is important and should be
1732: designed well. The general guideline is to design the stack effect such
1733: that the word is simple to use in most cases, even if that complicates
1734: the implementation of the word. Some concrete rules are:
1735:
1736: @itemize @bullet
1737:
1738: @item
1739: Words consume all of their parameters (e.g., @code{.}).
1740:
1741: @item
1742: If there is a convention on the order of parameters (e.g., from
1743: mathematics or another programming language), stick with it (e.g.,
1744: @code{-}).
1745:
1746: @item
1747: If one parameter usually requires only a short computation (e.g., it is
1748: a constant), pass it on the top of the stack. Conversely, parameters
1749: that usually require a long sequence of code to compute should be passed
1750: as the bottom (i.e., first) parameter. This makes the code easier to
1751: read, because reader does not need to keep track of the bottom item
1752: through a long sequence of code (or, alternatively, through stack
1753: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1754: address on top of the stack because it is usually simpler to compute
1755: than the stored value (often the address is just a variable).
1756:
1757: @item
1758: Similarly, results that are usually consumed quickly should be returned
1759: on the top of stack, whereas a result that is often used in long
1760: computations should be passed as bottom result. E.g., the file words
1761: like @code{open-file} return the error code on the top of stack, because
1762: it is usually consumed quickly by @code{throw}; moreover, the error code
1763: has to be checked before doing anything with the other results.
1764:
1765: @end itemize
1766:
1767: These rules are just general guidelines, don't lose sight of the overall
1768: goal to make the words easy to use. E.g., if the convention rule
1769: conflicts with the computation-length rule, you might decide in favour
1770: of the convention if the word will be used rarely, and in favour of the
1771: computation-length rule if the word will be used frequently (because
1772: with frequent use the cost of breaking the computation-length rule would
1773: be quite high, and frequent use makes it easier to remember an
1774: unconventional order).
1775:
1776: @c example !! structure package
1777:
1778:
1779: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1780: @section Local Variables
1781: @cindex local variables, tutorial
1782:
1783: You can define local variables (@emph{locals}) in a colon definition:
1784:
1785: @example
1786: : swap @{ a b -- b a @}
1787: b a ;
1788: 1 2 swap .s 2drop
1789: @end example
1790:
1791: (If your Forth system does not support this syntax, include
1792: @file{compat/anslocals.fs} first).
1793:
1794: In this example @code{@{ a b -- b a @}} is the locals definition; it
1795: takes two cells from the stack, puts the top of stack in @code{b} and
1796: the next stack element in @code{a}. @code{--} starts a comment ending
1797: with @code{@}}. After the locals definition, using the name of the
1798: local will push its value on the stack. You can leave the comment
1799: part (@code{-- b a}) away:
1800:
1801: @example
1802: : swap ( x1 x2 -- x2 x1 )
1803: @{ a b @} b a ;
1804: @end example
1805:
1806: In Gforth you can have several locals definitions, anywhere in a colon
1807: definition; in contrast, in a standard program you can have only one
1808: locals definition per colon definition, and that locals definition must
1809: be outside any controll structure.
1810:
1811: With locals you can write slightly longer definitions without running
1812: into stack trouble. However, I recommend trying to write colon
1813: definitions without locals for exercise purposes to help you gain the
1814: essential factoring skills.
1815:
1816: @assignment
1817: Rewrite your definitions until now with locals
1818: @endassignment
1819:
1820: Reference: @ref{Locals}.
1821:
1822:
1823: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1824: @section Conditional execution
1825: @cindex conditionals, tutorial
1826: @cindex if, tutorial
1827:
1828: In Forth you can use control structures only inside colon definitions.
1829: An @code{if}-structure looks like this:
1830:
1831: @example
1832: : abs ( n1 -- +n2 )
1833: dup 0 < if
1834: negate
1835: endif ;
1836: 5 abs .
1837: -5 abs .
1838: @end example
1839:
1840: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1841: the following code is performed, otherwise execution continues after the
1842: @code{endif} (or @code{else}). @code{<} compares the top two stack
1843: elements and prioduces a flag:
1844:
1845: @example
1846: 1 2 < .
1847: 2 1 < .
1848: 1 1 < .
1849: @end example
1850:
1851: Actually the standard name for @code{endif} is @code{then}. This
1852: tutorial presents the examples using @code{endif}, because this is often
1853: less confusing for people familiar with other programming languages
1854: where @code{then} has a different meaning. If your system does not have
1855: @code{endif}, define it with
1856:
1857: @example
1858: : endif postpone then ; immediate
1859: @end example
1860:
1861: You can optionally use an @code{else}-part:
1862:
1863: @example
1864: : min ( n1 n2 -- n )
1865: 2dup < if
1866: drop
1867: else
1868: nip
1869: endif ;
1870: 2 3 min .
1871: 3 2 min .
1872: @end example
1873:
1874: @assignment
1875: Write @code{min} without @code{else}-part (hint: what's the definition
1876: of @code{nip}?).
1877: @endassignment
1878:
1879: Reference: @ref{Selection}.
1880:
1881:
1882: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1883: @section Flags and Comparisons
1884: @cindex flags tutorial
1885: @cindex comparison tutorial
1886:
1887: In a false-flag all bits are clear (0 when interpreted as integer). In
1888: a canonical true-flag all bits are set (-1 as a twos-complement signed
1889: integer); in many contexts (e.g., @code{if}) any non-zero value is
1890: treated as true flag.
1891:
1892: @example
1893: false .
1894: true .
1895: true hex u. decimal
1896: @end example
1897:
1898: Comparison words produce canonical flags:
1899:
1900: @example
1901: 1 1 = .
1902: 1 0= .
1903: 0 1 < .
1904: 0 0 < .
1905: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1906: -1 1 < .
1907: @end example
1908:
1909: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1910: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1911: these combinations are standard (for details see the standard,
1912: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1913:
1914: You can use @code{and or xor invert} can be used as operations on
1915: canonical flags. Actually they are bitwise operations:
1916:
1917: @example
1918: 1 2 and .
1919: 1 2 or .
1920: 1 3 xor .
1921: 1 invert .
1922: @end example
1923:
1924: You can convert a zero/non-zero flag into a canonical flag with
1925: @code{0<>} (and complement it on the way with @code{0=}).
1926:
1927: @example
1928: 1 0= .
1929: 1 0<> .
1930: @end example
1931:
1932: You can use the all-bits-set feature of canonical flags and the bitwise
1933: operation of the Boolean operations to avoid @code{if}s:
1934:
1935: @example
1936: : foo ( n1 -- n2 )
1937: 0= if
1938: 14
1939: else
1940: 0
1941: endif ;
1942: 0 foo .
1943: 1 foo .
1944:
1945: : foo ( n1 -- n2 )
1946: 0= 14 and ;
1947: 0 foo .
1948: 1 foo .
1949: @end example
1950:
1951: @assignment
1952: Write @code{min} without @code{if}.
1953: @endassignment
1954:
1955: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
1956: @ref{Bitwise operations}.
1957:
1958:
1959: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
1960: @section General Loops
1961: @cindex loops, indefinite, tutorial
1962:
1963: The endless loop is the most simple one:
1964:
1965: @example
1966: : endless ( -- )
1967: 0 begin
1968: dup . 1+
1969: again ;
1970: endless
1971: @end example
1972:
1973: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
1974: does nothing at run-time, @code{again} jumps back to @code{begin}.
1975:
1976: A loop with one exit at any place looks like this:
1977:
1978: @example
1979: : log2 ( +n1 -- n2 )
1980: \ logarithmus dualis of n1>0, rounded down to the next integer
1981: assert( dup 0> )
1982: 2/ 0 begin
1983: over 0> while
1984: 1+ swap 2/ swap
1985: repeat
1986: nip ;
1987: 7 log2 .
1988: 8 log2 .
1989: @end example
1990:
1991: At run-time @code{while} consumes a flag; if it is 0, execution
1992: continues behind the @code{repeat}; if the flag is non-zero, execution
1993: continues behind the @code{while}. @code{Repeat} jumps back to
1994: @code{begin}, just like @code{again}.
1995:
1996: In Forth there are many combinations/abbreviations, like @code{1+}.
1997: However, @code{2/} is not one of them; it shifts its argument right by
1998: one bit (arithmetic shift right):
1999:
2000: @example
2001: -5 2 / .
2002: -5 2/ .
2003: @end example
2004:
2005: @code{assert(} is no standard word, but you can get it on systems other
2006: then Gforth by including @file{compat/assert.fs}. You can see what it
2007: does by trying
2008:
2009: @example
2010: 0 log2 .
2011: @end example
2012:
2013: Here's a loop with an exit at the end:
2014:
2015: @example
2016: : log2 ( +n1 -- n2 )
2017: \ logarithmus dualis of n1>0, rounded down to the next integer
2018: assert( dup 0 > )
2019: -1 begin
2020: 1+ swap 2/ swap
2021: over 0 <=
2022: until
2023: nip ;
2024: @end example
2025:
2026: @code{Until} consumes a flag; if it is non-zero, execution continues at
2027: the @code{begin}, otherwise after the @code{until}.
2028:
2029: @assignment
2030: Write a definition for computing the greatest common divisor.
2031: @endassignment
2032:
2033: Reference: @ref{Simple Loops}.
2034:
2035:
2036: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2037: @section Counted loops
2038: @cindex loops, counted, tutorial
2039:
2040: @example
2041: : ^ ( n1 u -- n )
2042: \ n = the uth power of u1
2043: 1 swap 0 u+do
2044: over *
2045: loop
2046: nip ;
2047: 3 2 ^ .
2048: 4 3 ^ .
2049: @end example
2050:
2051: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2052: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2053: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2054: times (or not at all, if @code{u3-u4<0}).
2055:
2056: You can see the stack effect design rules at work in the stack effect of
2057: the loop start words: Since the start value of the loop is more
2058: frequently constant than the end value, the start value is passed on
2059: the top-of-stack.
2060:
2061: You can access the counter of a counted loop with @code{i}:
2062:
2063: @example
2064: : fac ( u -- u! )
2065: 1 swap 1+ 1 u+do
2066: i *
2067: loop ;
2068: 5 fac .
2069: 7 fac .
2070: @end example
2071:
2072: There is also @code{+do}, which expects signed numbers (important for
2073: deciding whether to enter the loop).
2074:
2075: @assignment
2076: Write a definition for computing the nth Fibonacci number.
2077: @endassignment
2078:
2079: You can also use increments other than 1:
2080:
2081: @example
2082: : up2 ( n1 n2 -- )
2083: +do
2084: i .
2085: 2 +loop ;
2086: 10 0 up2
2087:
2088: : down2 ( n1 n2 -- )
2089: -do
2090: i .
2091: 2 -loop ;
2092: 0 10 down2
2093: @end example
2094:
2095: Reference: @ref{Counted Loops}.
2096:
2097:
2098: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2099: @section Recursion
2100: @cindex recursion tutorial
2101:
2102: Usually the name of a definition is not visible in the definition; but
2103: earlier definitions are usually visible:
2104:
2105: @example
2106: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2107: : / ( n1 n2 -- n )
2108: dup 0= if
2109: -10 throw \ report division by zero
2110: endif
2111: / \ old version
2112: ;
2113: 1 0 /
2114: @end example
2115:
2116: For recursive definitions you can use @code{recursive} (non-standard) or
2117: @code{recurse}:
2118:
2119: @example
2120: : fac1 ( n -- n! ) recursive
2121: dup 0> if
2122: dup 1- fac1 *
2123: else
2124: drop 1
2125: endif ;
2126: 7 fac1 .
2127:
2128: : fac2 ( n -- n! )
2129: dup 0> if
2130: dup 1- recurse *
2131: else
2132: drop 1
2133: endif ;
2134: 8 fac2 .
2135: @end example
2136:
2137: @assignment
2138: Write a recursive definition for computing the nth Fibonacci number.
2139: @endassignment
2140:
2141: Reference (including indirect recursion): @xref{Calls and returns}.
2142:
2143:
2144: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2145: @section Leaving definitions or loops
2146: @cindex leaving definitions, tutorial
2147: @cindex leaving loops, tutorial
2148:
2149: @code{EXIT} exits the current definition right away. For every counted
2150: loop that is left in this way, an @code{UNLOOP} has to be performed
2151: before the @code{EXIT}:
2152:
2153: @c !! real examples
2154: @example
2155: : ...
2156: ... u+do
2157: ... if
2158: ... unloop exit
2159: endif
2160: ...
2161: loop
2162: ... ;
2163: @end example
2164:
2165: @code{LEAVE} leaves the innermost counted loop right away:
2166:
2167: @example
2168: : ...
2169: ... u+do
2170: ... if
2171: ... leave
2172: endif
2173: ...
2174: loop
2175: ... ;
2176: @end example
2177:
2178: @c !! example
2179:
2180: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2181:
2182:
2183: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2184: @section Return Stack
2185: @cindex return stack tutorial
2186:
2187: In addition to the data stack Forth also has a second stack, the return
2188: stack; most Forth systems store the return addresses of procedure calls
2189: there (thus its name). Programmers can also use this stack:
2190:
2191: @example
2192: : foo ( n1 n2 -- )
2193: .s
2194: >r .s
2195: r@@ .
2196: >r .s
2197: r@@ .
2198: r> .
2199: r@@ .
2200: r> . ;
2201: 1 2 foo
2202: @end example
2203:
2204: @code{>r} takes an element from the data stack and pushes it onto the
2205: return stack; conversely, @code{r>} moves an elementm from the return to
2206: the data stack; @code{r@@} pushes a copy of the top of the return stack
2207: on the return stack.
2208:
2209: Forth programmers usually use the return stack for storing data
2210: temporarily, if using the data stack alone would be too complex, and
2211: factoring and locals are not an option:
2212:
2213: @example
2214: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2215: rot >r rot r> ;
2216: @end example
2217:
2218: The return address of the definition and the loop control parameters of
2219: counted loops usually reside on the return stack, so you have to take
2220: all items, that you have pushed on the return stack in a colon
2221: definition or counted loop, from the return stack before the definition
2222: or loop ends. You cannot access items that you pushed on the return
2223: stack outside some definition or loop within the definition of loop.
2224:
2225: If you miscount the return stack items, this usually ends in a crash:
2226:
2227: @example
2228: : crash ( n -- )
2229: >r ;
2230: 5 crash
2231: @end example
2232:
2233: You cannot mix using locals and using the return stack (according to the
2234: standard; Gforth has no problem). However, they solve the same
2235: problems, so this shouldn't be an issue.
2236:
2237: @assignment
2238: Can you rewrite any of the definitions you wrote until now in a better
2239: way using the return stack?
2240: @endassignment
2241:
2242: Reference: @ref{Return stack}.
2243:
2244:
2245: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2246: @section Memory
2247: @cindex memory access/allocation tutorial
2248:
2249: You can create a global variable @code{v} with
2250:
2251: @example
2252: variable v ( -- addr )
2253: @end example
2254:
2255: @code{v} pushes the address of a cell in memory on the stack. This cell
2256: was reserved by @code{variable}. You can use @code{!} (store) to store
2257: values into this cell and @code{@@} (fetch) to load the value from the
2258: stack into memory:
2259:
2260: @example
2261: v .
2262: 5 v ! .s
2263: v @@ .
2264: @end example
2265:
2266: You can see a raw dump of memory with @code{dump}:
2267:
2268: @example
2269: v 1 cells .s dump
2270: @end example
2271:
2272: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2273: generally, address units (aus)) that @code{n1 cells} occupy. You can
2274: also reserve more memory:
2275:
2276: @example
2277: create v2 20 cells allot
2278: v2 20 cells dump
2279: @end example
2280:
2281: creates a word @code{v2} and reserves 20 uninitialized cells; the
2282: address pushed by @code{v2} points to the start of these 20 cells. You
2283: can use address arithmetic to access these cells:
2284:
2285: @example
2286: 3 v2 5 cells + !
2287: v2 20 cells dump
2288: @end example
2289:
2290: You can reserve and initialize memory with @code{,}:
2291:
2292: @example
2293: create v3
2294: 5 , 4 , 3 , 2 , 1 ,
2295: v3 @@ .
2296: v3 cell+ @@ .
2297: v3 2 cells + @@ .
2298: v3 5 cells dump
2299: @end example
2300:
2301: @assignment
2302: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2303: @code{u} cells, with the first of these cells at @code{addr}, the next
2304: one at @code{addr cell+} etc.
2305: @endassignment
2306:
2307: You can also reserve memory without creating a new word:
2308:
2309: @example
2310: here 10 cells allot .
2311: here .
2312: @end example
2313:
2314: @code{Here} pushes the start address of the memory area. You should
2315: store it somewhere, or you will have a hard time finding the memory area
2316: again.
2317:
2318: @code{Allot} manages dictionary memory. The dictionary memory contains
2319: the system's data structures for words etc. on Gforth and most other
2320: Forth systems. It is managed like a stack: You can free the memory that
2321: you have just @code{allot}ed with
2322:
2323: @example
2324: -10 cells allot
2325: here .
2326: @end example
2327:
2328: Note that you cannot do this if you have created a new word in the
2329: meantime (because then your @code{allot}ed memory is no longer on the
2330: top of the dictionary ``stack'').
2331:
2332: Alternatively, you can use @code{allocate} and @code{free} which allow
2333: freeing memory in any order:
2334:
2335: @example
2336: 10 cells allocate throw .s
2337: 20 cells allocate throw .s
2338: swap
2339: free throw
2340: free throw
2341: @end example
2342:
2343: The @code{throw}s deal with errors (e.g., out of memory).
2344:
2345: And there is also a
2346: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2347: garbage collector}, which eliminates the need to @code{free} memory
2348: explicitly.
2349:
2350: Reference: @ref{Memory}.
2351:
2352:
2353: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2354: @section Characters and Strings
2355: @cindex strings tutorial
2356: @cindex characters tutorial
2357:
2358: On the stack characters take up a cell, like numbers. In memory they
2359: have their own size (one 8-bit byte on most systems), and therefore
2360: require their own words for memory access:
2361:
2362: @example
2363: create v4
2364: 104 c, 97 c, 108 c, 108 c, 111 c,
2365: v4 4 chars + c@@ .
2366: v4 5 chars dump
2367: @end example
2368:
2369: The preferred representation of strings on the stack is @code{addr
2370: u-count}, where @code{addr} is the address of the first character and
2371: @code{u-count} is the number of characters in the string.
2372:
2373: @example
2374: v4 5 type
2375: @end example
2376:
2377: You get a string constant with
2378:
2379: @example
2380: s" hello, world" .s
2381: type
2382: @end example
2383:
2384: Make sure you have a space between @code{s"} and the string; @code{s"}
2385: is a normal Forth word and must be delimited with white space (try what
2386: happens when you remove the space).
2387:
2388: However, this interpretive use of @code{s"} is quite restricted: the
2389: string exists only until the next call of @code{s"} (some Forth systems
2390: keep more than one of these strings, but usually they still have a
2391: limited lifetime).
2392:
2393: @example
2394: s" hello," s" world" .s
2395: type
2396: type
2397: @end example
2398:
2399: You can also use @code{s"} in a definition, and the resulting
2400: strings then live forever (well, for as long as the definition):
2401:
2402: @example
2403: : foo s" hello," s" world" ;
2404: foo .s
2405: type
2406: type
2407: @end example
2408:
2409: @assignment
2410: @code{Emit ( c -- )} types @code{c} as character (not a number).
2411: Implement @code{type ( addr u -- )}.
2412: @endassignment
2413:
2414: Reference: @ref{Memory Blocks}.
2415:
2416:
2417: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
2418: @section Alignment
2419: @cindex alignment tutorial
2420: @cindex memory alignment tutorial
2421:
2422: On many processors cells have to be aligned in memory, if you want to
2423: access them with @code{@@} and @code{!} (and even if the processor does
2424: not require alignment, access to aligned cells is faster).
2425:
2426: @code{Create} aligns @code{here} (i.e., the place where the next
2427: allocation will occur, and that the @code{create}d word points to).
2428: Likewise, the memory produced by @code{allocate} starts at an aligned
2429: address. Adding a number of @code{cells} to an aligned address produces
2430: another aligned address.
2431:
2432: However, address arithmetic involving @code{char+} and @code{chars} can
2433: create an address that is not cell-aligned. @code{Aligned ( addr --
2434: a-addr )} produces the next aligned address:
2435:
2436: @example
2437: v3 char+ aligned .s @@ .
2438: v3 char+ .s @@ .
2439: @end example
2440:
2441: Similarly, @code{align} advances @code{here} to the next aligned
2442: address:
2443:
2444: @example
2445: create v5 97 c,
2446: here .
2447: align here .
2448: 1000 ,
2449: @end example
2450:
2451: Note that you should use aligned addresses even if your processor does
2452: not require them, if you want your program to be portable.
2453:
2454: Reference: @ref{Address arithmetic}.
2455:
2456:
2457: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2458: @section Files
2459: @cindex files tutorial
2460:
2461: This section gives a short introduction into how to use files inside
2462: Forth. It's broken up into five easy steps:
2463:
2464: @enumerate 1
2465: @item Opened an ASCII text file for input
2466: @item Opened a file for output
2467: @item Read input file until string matched (or some other condition matched)
2468: @item Wrote some lines from input ( modified or not) to output
2469: @item Closed the files.
2470: @end enumerate
2471:
2472: @subsection Open file for input
2473:
2474: @example
2475: s" foo.in" r/o open-file throw Value fd-in
2476: @end example
2477:
2478: @subsection Create file for output
2479:
2480: @example
2481: s" foo.out" w/o create-file throw Value fd-out
2482: @end example
2483:
2484: The available file modes are r/o for read-only access, r/w for
2485: read-write access, and w/o for write-only access. You could open both
2486: files with r/w, too, if you like. All file words return error codes; for
2487: most applications, it's best to pass there error codes with @code{throw}
2488: to the outer error handler.
2489:
2490: If you want words for opening and assigning, define them as follows:
2491:
2492: @example
2493: 0 Value fd-in
2494: 0 Value fd-out
2495: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2496: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2497: @end example
2498:
2499: Usage example:
2500:
2501: @example
2502: s" foo.in" open-input
2503: s" foo.out" open-output
2504: @end example
2505:
2506: @subsection Scan file for a particular line
2507:
2508: @example
2509: 256 Constant max-line
2510: Create line-buffer max-line 2 + allot
2511:
2512: : scan-file ( addr u -- )
2513: begin
2514: line-buffer max-line fd-in read-line throw
2515: while
2516: >r 2dup line-buffer r> compare 0=
2517: until
2518: else
2519: drop
2520: then
2521: 2drop ;
2522: @end example
2523:
2524: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
2525: the buffer at addr, and returns the number of bytes read, a flag that is
2526: false when the end of file is reached, and an error code.
2527:
2528: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2529: returns zero if both strings are equal. It returns a positive number if
2530: the first string is lexically greater, a negative if the second string
2531: is lexically greater.
2532:
2533: We haven't seen this loop here; it has two exits. Since the @code{while}
2534: exits with the number of bytes read on the stack, we have to clean up
2535: that separately; that's after the @code{else}.
2536:
2537: Usage example:
2538:
2539: @example
2540: s" The text I search is here" scan-file
2541: @end example
2542:
2543: @subsection Copy input to output
2544:
2545: @example
2546: : copy-file ( -- )
2547: begin
2548: line-buffer max-line fd-in read-line throw
2549: while
2550: line-buffer swap fd-out write-file throw
2551: repeat ;
2552: @end example
2553:
2554: @subsection Close files
2555:
2556: @example
2557: fd-in close-file throw
2558: fd-out close-file throw
2559: @end example
2560:
2561: Likewise, you can put that into definitions, too:
2562:
2563: @example
2564: : close-input ( -- ) fd-in close-file throw ;
2565: : close-output ( -- ) fd-out close-file throw ;
2566: @end example
2567:
2568: @assignment
2569: How could you modify @code{copy-file} so that it copies until a second line is
2570: matched? Can you write a program that extracts a section of a text file,
2571: given the line that starts and the line that terminates that section?
2572: @endassignment
2573:
2574: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
2575: @section Interpretation and Compilation Semantics and Immediacy
2576: @cindex semantics tutorial
2577: @cindex interpretation semantics tutorial
2578: @cindex compilation semantics tutorial
2579: @cindex immediate, tutorial
2580:
2581: When a word is compiled, it behaves differently from being interpreted.
2582: E.g., consider @code{+}:
2583:
2584: @example
2585: 1 2 + .
2586: : foo + ;
2587: @end example
2588:
2589: These two behaviours are known as compilation and interpretation
2590: semantics. For normal words (e.g., @code{+}), the compilation semantics
2591: is to append the interpretation semantics to the currently defined word
2592: (@code{foo} in the example above). I.e., when @code{foo} is executed
2593: later, the interpretation semantics of @code{+} (i.e., adding two
2594: numbers) will be performed.
2595:
2596: However, there are words with non-default compilation semantics, e.g.,
2597: the control-flow words like @code{if}. You can use @code{immediate} to
2598: change the compilation semantics of the last defined word to be equal to
2599: the interpretation semantics:
2600:
2601: @example
2602: : [FOO] ( -- )
2603: 5 . ; immediate
2604:
2605: [FOO]
2606: : bar ( -- )
2607: [FOO] ;
2608: bar
2609: see bar
2610: @end example
2611:
2612: Two conventions to mark words with non-default compilation semnatics are
2613: names with brackets (more frequently used) and to write them all in
2614: upper case (less frequently used).
2615:
2616: In Gforth (and many other systems) you can also remove the
2617: interpretation semantics with @code{compile-only} (the compilation
2618: semantics is derived from the original interpretation semantics):
2619:
2620: @example
2621: : flip ( -- )
2622: 6 . ; compile-only \ but not immediate
2623: flip
2624:
2625: : flop ( -- )
2626: flip ;
2627: flop
2628: @end example
2629:
2630: In this example the interpretation semantics of @code{flop} is equal to
2631: the original interpretation semantics of @code{flip}.
2632:
2633: The text interpreter has two states: in interpret state, it performs the
2634: interpretation semantics of words it encounters; in compile state, it
2635: performs the compilation semantics of these words.
2636:
2637: Among other things, @code{:} switches into compile state, and @code{;}
2638: switches back to interpret state. They contain the factors @code{]}
2639: (switch to compile state) and @code{[} (switch to interpret state), that
2640: do nothing but switch the state.
2641:
2642: @example
2643: : xxx ( -- )
2644: [ 5 . ]
2645: ;
2646:
2647: xxx
2648: see xxx
2649: @end example
2650:
2651: These brackets are also the source of the naming convention mentioned
2652: above.
2653:
2654: Reference: @ref{Interpretation and Compilation Semantics}.
2655:
2656:
2657: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2658: @section Execution Tokens
2659: @cindex execution tokens tutorial
2660: @cindex XT tutorial
2661:
2662: @code{' word} gives you the execution token (XT) of a word. The XT is a
2663: cell representing the interpretation semantics of a word. You can
2664: execute this semantics with @code{execute}:
2665:
2666: @example
2667: ' + .s
2668: 1 2 rot execute .
2669: @end example
2670:
2671: The XT is similar to a function pointer in C. However, parameter
2672: passing through the stack makes it a little more flexible:
2673:
2674: @example
2675: : map-array ( ... addr u xt -- ... )
2676: \ executes xt ( ... x -- ... ) for every element of the array starting
2677: \ at addr and containing u elements
2678: @{ xt @}
2679: cells over + swap ?do
2680: i @@ xt execute
2681: 1 cells +loop ;
2682:
2683: create a 3 , 4 , 2 , -1 , 4 ,
2684: a 5 ' . map-array .s
2685: 0 a 5 ' + map-array .
2686: s" max-n" environment? drop .s
2687: a 5 ' min map-array .
2688: @end example
2689:
2690: You can use map-array with the XTs of words that consume one element
2691: more than they produce. In theory you can also use it with other XTs,
2692: but the stack effect then depends on the size of the array, which is
2693: hard to understand.
2694:
2695: Since XTs are cell-sized, you can store them in memory and manipulate
2696: them on the stack like other cells. You can also compile the XT into a
2697: word with @code{compile,}:
2698:
2699: @example
2700: : foo1 ( n1 n2 -- n )
2701: [ ' + compile, ] ;
2702: see foo
2703: @end example
2704:
2705: This is non-standard, because @code{compile,} has no compilation
2706: semantics in the standard, but it works in good Forth systems. For the
2707: broken ones, use
2708:
2709: @example
2710: : [compile,] compile, ; immediate
2711:
2712: : foo1 ( n1 n2 -- n )
2713: [ ' + ] [compile,] ;
2714: see foo
2715: @end example
2716:
2717: @code{'} is a word with default compilation semantics; it parses the
2718: next word when its interpretation semantics are executed, not during
2719: compilation:
2720:
2721: @example
2722: : foo ( -- xt )
2723: ' ;
2724: see foo
2725: : bar ( ... "word" -- ... )
2726: ' execute ;
2727: see bar
2728: 1 2 bar + .
2729: @end example
2730:
2731: You often want to parse a word during compilation and compile its XT so
2732: it will be pushed on the stack at run-time. @code{[']} does this:
2733:
2734: @example
2735: : xt-+ ( -- xt )
2736: ['] + ;
2737: see xt-+
2738: 1 2 xt-+ execute .
2739: @end example
2740:
2741: Many programmers tend to see @code{'} and the word it parses as one
2742: unit, and expect it to behave like @code{[']} when compiled, and are
2743: confused by the actual behaviour. If you are, just remember that the
2744: Forth system just takes @code{'} as one unit and has no idea that it is
2745: a parsing word (attempts to convenience programmers in this issue have
2746: usually resulted in even worse pitfalls, see
2747: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2748: @code{State}-smartness---Why it is evil and How to Exorcise it}).
2749:
2750: Note that the state of the interpreter does not come into play when
2751: creating and executing XTs. I.e., even when you execute @code{'} in
2752: compile state, it still gives you the interpretation semantics. And
2753: whatever that state is, @code{execute} performs the semantics
2754: represented by the XT (i.e., for XTs produced with @code{'} the
2755: interpretation semantics).
2756:
2757: Reference: @ref{Tokens for Words}.
2758:
2759:
2760: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2761: @section Exceptions
2762: @cindex exceptions tutorial
2763:
2764: @code{throw ( n -- )} causes an exception unless n is zero.
2765:
2766: @example
2767: 100 throw .s
2768: 0 throw .s
2769: @end example
2770:
2771: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2772: it catches exceptions and pushes the number of the exception on the
2773: stack (or 0, if the xt executed without exception). If there was an
2774: exception, the stacks have the same depth as when entering @code{catch}:
2775:
2776: @example
2777: .s
2778: 3 0 ' / catch .s
2779: 3 2 ' / catch .s
2780: @end example
2781:
2782: @assignment
2783: Try the same with @code{execute} instead of @code{catch}.
2784: @endassignment
2785:
2786: @code{Throw} always jumps to the dynamically next enclosing
2787: @code{catch}, even if it has to leave several call levels to achieve
2788: this:
2789:
2790: @example
2791: : foo 100 throw ;
2792: : foo1 foo ." after foo" ;
2793: : bar ['] foo1 catch ;
2794: bar .
2795: @end example
2796:
2797: It is often important to restore a value upon leaving a definition, even
2798: if the definition is left through an exception. You can ensure this
2799: like this:
2800:
2801: @example
2802: : ...
2803: save-x
2804: ['] word-changing-x catch ( ... n )
2805: restore-x
2806: ( ... n ) throw ;
2807: @end example
2808:
2809: Gforth provides an alternative syntax in addition to @code{catch}:
2810: @code{try ... recover ... endtry}. If the code between @code{try} and
2811: @code{recover} has an exception, the stack depths are restored, the
2812: exception number is pushed on the stack, and the code between
2813: @code{recover} and @code{endtry} is performed. E.g., the definition for
2814: @code{catch} is
2815:
2816: @example
2817: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
2818: try
2819: execute 0
2820: recover
2821: nip
2822: endtry ;
2823: @end example
2824:
2825: The equivalent to the restoration code above is
2826:
2827: @example
2828: : ...
2829: save-x
2830: try
2831: word-changing-x 0
2832: recover endtry
2833: restore-x
2834: throw ;
2835: @end example
2836:
2837: This works if @code{word-changing-x} does not change the stack depth,
2838: otherwise you should add some code between @code{recover} and
2839: @code{endtry} to balance the stack.
2840:
2841: Reference: @ref{Exception Handling}.
2842:
2843:
2844: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2845: @section Defining Words
2846: @cindex defining words tutorial
2847: @cindex does> tutorial
2848: @cindex create...does> tutorial
2849:
2850: @c before semantics?
2851:
2852: @code{:}, @code{create}, and @code{variable} are definition words: They
2853: define other words. @code{Constant} is another definition word:
2854:
2855: @example
2856: 5 constant foo
2857: foo .
2858: @end example
2859:
2860: You can also use the prefixes @code{2} (double-cell) and @code{f}
2861: (floating point) with @code{variable} and @code{constant}.
2862:
2863: You can also define your own defining words. E.g.:
2864:
2865: @example
2866: : variable ( "name" -- )
2867: create 0 , ;
2868: @end example
2869:
2870: You can also define defining words that create words that do something
2871: other than just producing their address:
2872:
2873: @example
2874: : constant ( n "name" -- )
2875: create ,
2876: does> ( -- n )
2877: ( addr ) @@ ;
2878:
2879: 5 constant foo
2880: foo .
2881: @end example
2882:
2883: The definition of @code{constant} above ends at the @code{does>}; i.e.,
2884: @code{does>} replaces @code{;}, but it also does something else: It
2885: changes the last defined word such that it pushes the address of the
2886: body of the word and then performs the code after the @code{does>}
2887: whenever it is called.
2888:
2889: In the example above, @code{constant} uses @code{,} to store 5 into the
2890: body of @code{foo}. When @code{foo} executes, it pushes the address of
2891: the body onto the stack, then (in the code after the @code{does>})
2892: fetches the 5 from there.
2893:
2894: The stack comment near the @code{does>} reflects the stack effect of the
2895: defined word, not the stack effect of the code after the @code{does>}
2896: (the difference is that the code expects the address of the body that
2897: the stack comment does not show).
2898:
2899: You can use these definition words to do factoring in cases that involve
2900: (other) definition words. E.g., a field offset is always added to an
2901: address. Instead of defining
2902:
2903: @example
2904: 2 cells constant offset-field1
2905: @end example
2906:
2907: and using this like
2908:
2909: @example
2910: ( addr ) offset-field1 +
2911: @end example
2912:
2913: you can define a definition word
2914:
2915: @example
2916: : simple-field ( n "name" -- )
2917: create ,
2918: does> ( n1 -- n1+n )
2919: ( addr ) @@ + ;
2920: @end example
2921:
2922: Definition and use of field offsets now look like this:
2923:
2924: @example
2925: 2 cells simple-field field1
2926: create mystruct 4 cells allot
2927: mystruct .s field1 .s drop
2928: @end example
2929:
2930: If you want to do something with the word without performing the code
2931: after the @code{does>}, you can access the body of a @code{create}d word
2932: with @code{>body ( xt -- addr )}:
2933:
2934: @example
2935: : value ( n "name" -- )
2936: create ,
2937: does> ( -- n1 )
2938: @@ ;
2939: : to ( n "name" -- )
2940: ' >body ! ;
2941:
2942: 5 value foo
2943: foo .
2944: 7 to foo
2945: foo .
2946: @end example
2947:
2948: @assignment
2949: Define @code{defer ( "name" -- )}, which creates a word that stores an
2950: XT (at the start the XT of @code{abort}), and upon execution
2951: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
2952: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
2953: recursion is one application of @code{defer}.
2954: @endassignment
2955:
2956: Reference: @ref{User-defined Defining Words}.
2957:
2958:
2959: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
2960: @section Arrays and Records
2961: @cindex arrays tutorial
2962: @cindex records tutorial
2963: @cindex structs tutorial
2964:
2965: Forth has no standard words for defining data structures such as arrays
2966: and records (structs in C terminology), but you can build them yourself
2967: based on address arithmetic. You can also define words for defining
2968: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
2969:
2970: One of the first projects a Forth newcomer sets out upon when learning
2971: about defining words is an array defining word (possibly for
2972: n-dimensional arrays). Go ahead and do it, I did it, too; you will
2973: learn something from it. However, don't be disappointed when you later
2974: learn that you have little use for these words (inappropriate use would
2975: be even worse). I have not yet found a set of useful array words yet;
2976: the needs are just too diverse, and named, global arrays (the result of
2977: naive use of defining words) are often not flexible enough (e.g.,
2978: consider how to pass them as parameters). Another such project is a set
2979: of words to help dealing with strings.
2980:
2981: On the other hand, there is a useful set of record words, and it has
2982: been defined in @file{compat/struct.fs}; these words are predefined in
2983: Gforth. They are explained in depth elsewhere in this manual (see
2984: @pxref{Structures}). The @code{simple-field} example above is
2985: simplified variant of fields in this package.
2986:
2987:
2988: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
2989: @section @code{POSTPONE}
2990: @cindex postpone tutorial
2991:
2992: You can compile the compilation semantics (instead of compiling the
2993: interpretation semantics) of a word with @code{POSTPONE}:
2994:
2995: @example
2996: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
2997: POSTPONE + ; immediate
2998: : foo ( n1 n2 -- n )
2999: MY-+ ;
3000: 1 2 foo .
3001: see foo
3002: @end example
3003:
3004: During the definition of @code{foo} the text interpreter performs the
3005: compilation semantics of @code{MY-+}, which performs the compilation
3006: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3007:
3008: This example also displays separate stack comments for the compilation
3009: semantics and for the stack effect of the compiled code. For words with
3010: default compilation semantics these stack effects are usually not
3011: displayed; the stack effect of the compilation semantics is always
3012: @code{( -- )} for these words, the stack effect for the compiled code is
3013: the stack effect of the interpretation semantics.
3014:
3015: Note that the state of the interpreter does not come into play when
3016: performing the compilation semantics in this way. You can also perform
3017: it interpretively, e.g.:
3018:
3019: @example
3020: : foo2 ( n1 n2 -- n )
3021: [ MY-+ ] ;
3022: 1 2 foo .
3023: see foo
3024: @end example
3025:
3026: However, there are some broken Forth systems where this does not always
3027: work, and therefore this practice was been declared non-standard in
3028: 1999.
3029: @c !! repair.fs
3030:
3031: Here is another example for using @code{POSTPONE}:
3032:
3033: @example
3034: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3035: POSTPONE negate POSTPONE + ; immediate compile-only
3036: : bar ( n1 n2 -- n )
3037: MY-- ;
3038: 2 1 bar .
3039: see bar
3040: @end example
3041:
3042: You can define @code{ENDIF} in this way:
3043:
3044: @example
3045: : ENDIF ( Compilation: orig -- )
3046: POSTPONE then ; immediate
3047: @end example
3048:
3049: @assignment
3050: Write @code{MY-2DUP} that has compilation semantics equivalent to
3051: @code{2dup}, but compiles @code{over over}.
3052: @endassignment
3053:
3054: @c !! @xref{Macros} for reference
3055:
3056:
3057: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3058: @section @code{Literal}
3059: @cindex literal tutorial
3060:
3061: You cannot @code{POSTPONE} numbers:
3062:
3063: @example
3064: : [FOO] POSTPONE 500 ; immediate
3065: @end example
3066:
3067: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
3068:
3069: @example
3070: : [FOO] ( compilation: --; run-time: -- n )
3071: 500 POSTPONE literal ; immediate
3072:
3073: : flip [FOO] ;
3074: flip .
3075: see flip
3076: @end example
3077:
3078: @code{LITERAL} consumes a number at compile-time (when it's compilation
3079: semantics are executed) and pushes it at run-time (when the code it
3080: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3081: number computed at compile time into the current word:
3082:
3083: @example
3084: : bar ( -- n )
3085: [ 2 2 + ] literal ;
3086: see bar
3087: @end example
3088:
3089: @assignment
3090: Write @code{]L} which allows writing the example above as @code{: bar (
3091: -- n ) [ 2 2 + ]L ;}
3092: @endassignment
3093:
3094: @c !! @xref{Macros} for reference
3095:
3096:
3097: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3098: @section Advanced macros
3099: @cindex macros, advanced tutorial
3100: @cindex run-time code generation, tutorial
3101:
3102: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3103: Execution Tokens}. It frequently performs @code{execute}, a relatively
3104: expensive operation in some Forth implementations. You can use
3105: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3106: and produce a word that contains the word to be performed directly:
3107:
3108: @c use ]] ... [[
3109: @example
3110: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3111: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3112: \ array beginning at addr and containing u elements
3113: @{ xt @}
3114: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
3115: POSTPONE i POSTPONE @@ xt compile,
3116: 1 cells POSTPONE literal POSTPONE +loop ;
3117:
3118: : sum-array ( addr u -- n )
3119: 0 rot rot [ ' + compile-map-array ] ;
3120: see sum-array
3121: a 5 sum-array .
3122: @end example
3123:
3124: You can use the full power of Forth for generating the code; here's an
3125: example where the code is generated in a loop:
3126:
3127: @example
3128: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3129: \ n2=n1+(addr1)*n, addr2=addr1+cell
3130: POSTPONE tuck POSTPONE @@
3131: POSTPONE literal POSTPONE * POSTPONE +
3132: POSTPONE swap POSTPONE cell+ ;
3133:
3134: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
3135: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
3136: 0 postpone literal postpone swap
3137: [ ' compile-vmul-step compile-map-array ]
3138: postpone drop ;
3139: see compile-vmul
3140:
3141: : a-vmul ( addr -- n )
3142: \ n=a*v, where v is a vector that's as long as a and starts at addr
3143: [ a 5 compile-vmul ] ;
3144: see a-vmul
3145: a a-vmul .
3146: @end example
3147:
3148: This example uses @code{compile-map-array} to show off, but you could
3149: also use @code{map-array} instead (try it now!).
3150:
3151: You can use this technique for efficient multiplication of large
3152: matrices. In matrix multiplication, you multiply every line of one
3153: matrix with every column of the other matrix. You can generate the code
3154: for one line once, and use it for every column. The only downside of
3155: this technique is that it is cumbersome to recover the memory consumed
3156: by the generated code when you are done (and in more complicated cases
3157: it is not possible portably).
3158:
3159: @c !! @xref{Macros} for reference
3160:
3161:
3162: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3163: @section Compilation Tokens
3164: @cindex compilation tokens, tutorial
3165: @cindex CT, tutorial
3166:
3167: This section is Gforth-specific. You can skip it.
3168:
3169: @code{' word compile,} compiles the interpretation semantics. For words
3170: with default compilation semantics this is the same as performing the
3171: compilation semantics. To represent the compilation semantics of other
3172: words (e.g., words like @code{if} that have no interpretation
3173: semantics), Gforth has the concept of a compilation token (CT,
3174: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3175: You can perform the compilation semantics represented by a CT with
3176: @code{execute}:
3177:
3178: @example
3179: : foo2 ( n1 n2 -- n )
3180: [ comp' + execute ] ;
3181: see foo
3182: @end example
3183:
3184: You can compile the compilation semantics represented by a CT with
3185: @code{postpone,}:
3186:
3187: @example
3188: : foo3 ( -- )
3189: [ comp' + postpone, ] ;
3190: see foo3
3191: @end example
3192:
3193: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
3194: @code{comp'} is particularly useful for words that have no
3195: interpretation semantics:
3196:
3197: @example
3198: ' if
3199: comp' if .s 2drop
3200: @end example
3201:
3202: Reference: @ref{Tokens for Words}.
3203:
3204:
3205: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3206: @section Wordlists and Search Order
3207: @cindex wordlists tutorial
3208: @cindex search order, tutorial
3209:
3210: The dictionary is not just a memory area that allows you to allocate
3211: memory with @code{allot}, it also contains the Forth words, arranged in
3212: several wordlists. When searching for a word in a wordlist,
3213: conceptually you start searching at the youngest and proceed towards
3214: older words (in reality most systems nowadays use hash-tables); i.e., if
3215: you define a word with the same name as an older word, the new word
3216: shadows the older word.
3217:
3218: Which wordlists are searched in which order is determined by the search
3219: order. You can display the search order with @code{order}. It displays
3220: first the search order, starting with the wordlist searched first, then
3221: it displays the wordlist that will contain newly defined words.
3222:
3223: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
3224:
3225: @example
3226: wordlist constant mywords
3227: @end example
3228:
3229: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3230: defined words (the @emph{current} wordlist):
3231:
3232: @example
3233: mywords set-current
3234: order
3235: @end example
3236:
3237: Gforth does not display a name for the wordlist in @code{mywords}
3238: because this wordlist was created anonymously with @code{wordlist}.
3239:
3240: You can get the current wordlist with @code{get-current ( -- wid)}. If
3241: you want to put something into a specific wordlist without overall
3242: effect on the current wordlist, this typically looks like this:
3243:
3244: @example
3245: get-current mywords set-current ( wid )
3246: create someword
3247: ( wid ) set-current
3248: @end example
3249:
3250: You can write the search order with @code{set-order ( wid1 .. widn n --
3251: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3252: searched wordlist is topmost.
3253:
3254: @example
3255: get-order mywords swap 1+ set-order
3256: order
3257: @end example
3258:
3259: Yes, the order of wordlists in the output of @code{order} is reversed
3260: from stack comments and the output of @code{.s} and thus unintuitive.
3261:
3262: @assignment
3263: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3264: wordlist to the search order. Define @code{previous ( -- )}, which
3265: removes the first searched wordlist from the search order. Experiment
3266: with boundary conditions (you will see some crashes or situations that
3267: are hard or impossible to leave).
3268: @endassignment
3269:
3270: The search order is a powerful foundation for providing features similar
3271: to Modula-2 modules and C++ namespaces. However, trying to modularize
3272: programs in this way has disadvantages for debugging and reuse/factoring
3273: that overcome the advantages in my experience (I don't do huge projects,
3274: though). These disadvantages are not so clear in other
3275: languages/programming environments, because these languages are not so
3276: strong in debugging and reuse.
3277:
3278: @c !! example
3279:
3280: Reference: @ref{Word Lists}.
3281:
3282: @c ******************************************************************
3283: @node Introduction, Words, Tutorial, Top
3284: @comment node-name, next, previous, up
3285: @chapter An Introduction to ANS Forth
3286: @cindex Forth - an introduction
3287:
3288: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3289: that it is slower-paced in its examples, but uses them to dive deep into
3290: explaining Forth internals (not covered by the Tutorial). Apart from
3291: that, this chapter covers far less material. It is suitable for reading
3292: without using a computer.
3293:
3294: The primary purpose of this manual is to document Gforth. However, since
3295: Forth is not a widely-known language and there is a lack of up-to-date
3296: teaching material, it seems worthwhile to provide some introductory
3297: material. For other sources of Forth-related
3298: information, see @ref{Forth-related information}.
3299:
3300: The examples in this section should work on any ANS Forth; the
3301: output shown was produced using Gforth. Each example attempts to
3302: reproduce the exact output that Gforth produces. If you try out the
3303: examples (and you should), what you should type is shown @kbd{like this}
3304: and Gforth's response is shown @code{like this}. The single exception is
3305: that, where the example shows @key{RET} it means that you should
3306: press the ``carriage return'' key. Unfortunately, some output formats for
3307: this manual cannot show the difference between @kbd{this} and
3308: @code{this} which will make trying out the examples harder (but not
3309: impossible).
3310:
3311: Forth is an unusual language. It provides an interactive development
3312: environment which includes both an interpreter and compiler. Forth
3313: programming style encourages you to break a problem down into many
3314: @cindex factoring
3315: small fragments (@dfn{factoring}), and then to develop and test each
3316: fragment interactively. Forth advocates assert that breaking the
3317: edit-compile-test cycle used by conventional programming languages can
3318: lead to great productivity improvements.
3319:
3320: @menu
3321: * Introducing the Text Interpreter::
3322: * Stacks and Postfix notation::
3323: * Your first definition::
3324: * How does that work?::
3325: * Forth is written in Forth::
3326: * Review - elements of a Forth system::
3327: * Where to go next::
3328: * Exercises::
3329: @end menu
3330:
3331: @comment ----------------------------------------------
3332: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3333: @section Introducing the Text Interpreter
3334: @cindex text interpreter
3335: @cindex outer interpreter
3336:
3337: @c IMO this is too detailed and the pace is too slow for
3338: @c an introduction. If you know German, take a look at
3339: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3340: @c to see how I do it - anton
3341:
3342: @c nac-> Where I have accepted your comments 100% and modified the text
3343: @c accordingly, I have deleted your comments. Elsewhere I have added a
3344: @c response like this to attempt to rationalise what I have done. Of
3345: @c course, this is a very clumsy mechanism for something that would be
3346: @c done far more efficiently over a beer. Please delete any dialogue
3347: @c you consider closed.
3348:
3349: When you invoke the Forth image, you will see a startup banner printed
3350: and nothing else (if you have Gforth installed on your system, try
3351: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
3352: its command line interpreter, which is called the @dfn{Text Interpreter}
3353: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
3354: about the text interpreter as you read through this chapter, for more
3355: detail @pxref{The Text Interpreter}).
3356:
3357: Although it's not obvious, Forth is actually waiting for your
3358: input. Type a number and press the @key{RET} key:
3359:
3360: @example
3361: @kbd{45@key{RET}} ok
3362: @end example
3363:
3364: Rather than give you a prompt to invite you to input something, the text
3365: interpreter prints a status message @i{after} it has processed a line
3366: of input. The status message in this case (``@code{ ok}'' followed by
3367: carriage-return) indicates that the text interpreter was able to process
3368: all of your input successfully. Now type something illegal:
3369:
3370: @example
3371: @kbd{qwer341@key{RET}}
3372: :1: Undefined word
3373: qwer341
3374: ^^^^^^^
3375: $400D2BA8 Bounce
3376: $400DBDA8 no.extensions
3377: @end example
3378:
3379: The exact text, other than the ``Undefined word'' may differ slightly on
3380: your system, but the effect is the same; when the text interpreter
3381: detects an error, it discards any remaining text on a line, resets
3382: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
3383: messages}.
3384:
3385: The text interpreter waits for you to press carriage-return, and then
3386: processes your input line. Starting at the beginning of the line, it
3387: breaks the line into groups of characters separated by spaces. For each
3388: group of characters in turn, it makes two attempts to do something:
3389:
3390: @itemize @bullet
3391: @item
3392: @cindex name dictionary
3393: It tries to treat it as a command. It does this by searching a @dfn{name
3394: dictionary}. If the group of characters matches an entry in the name
3395: dictionary, the name dictionary provides the text interpreter with
3396: information that allows the text interpreter perform some actions. In
3397: Forth jargon, we say that the group
3398: @cindex word
3399: @cindex definition
3400: @cindex execution token
3401: @cindex xt
3402: of characters names a @dfn{word}, that the dictionary search returns an
3403: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3404: word, and that the text interpreter executes the xt. Often, the terms
3405: @dfn{word} and @dfn{definition} are used interchangeably.
3406: @item
3407: If the text interpreter fails to find a match in the name dictionary, it
3408: tries to treat the group of characters as a number in the current number
3409: base (when you start up Forth, the current number base is base 10). If
3410: the group of characters legitimately represents a number, the text
3411: interpreter pushes the number onto a stack (we'll learn more about that
3412: in the next section).
3413: @end itemize
3414:
3415: If the text interpreter is unable to do either of these things with any
3416: group of characters, it discards the group of characters and the rest of
3417: the line, then prints an error message. If the text interpreter reaches
3418: the end of the line without error, it prints the status message ``@code{ ok}''
3419: followed by carriage-return.
3420:
3421: This is the simplest command we can give to the text interpreter:
3422:
3423: @example
3424: @key{RET} ok
3425: @end example
3426:
3427: The text interpreter did everything we asked it to do (nothing) without
3428: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3429: command:
3430:
3431: @example
3432: @kbd{12 dup fred dup@key{RET}}
3433: :1: Undefined word
3434: 12 dup fred dup
3435: ^^^^
3436: $400D2BA8 Bounce
3437: $400DBDA8 no.extensions
3438: @end example
3439:
3440: When you press the carriage-return key, the text interpreter starts to
3441: work its way along the line:
3442:
3443: @itemize @bullet
3444: @item
3445: When it gets to the space after the @code{2}, it takes the group of
3446: characters @code{12} and looks them up in the name
3447: dictionary@footnote{We can't tell if it found them or not, but assume
3448: for now that it did not}. There is no match for this group of characters
3449: in the name dictionary, so it tries to treat them as a number. It is
3450: able to do this successfully, so it puts the number, 12, ``on the stack''
3451: (whatever that means).
3452: @item
3453: The text interpreter resumes scanning the line and gets the next group
3454: of characters, @code{dup}. It looks it up in the name dictionary and
3455: (you'll have to take my word for this) finds it, and executes the word
3456: @code{dup} (whatever that means).
3457: @item
3458: Once again, the text interpreter resumes scanning the line and gets the
3459: group of characters @code{fred}. It looks them up in the name
3460: dictionary, but can't find them. It tries to treat them as a number, but
3461: they don't represent any legal number.
3462: @end itemize
3463:
3464: At this point, the text interpreter gives up and prints an error
3465: message. The error message shows exactly how far the text interpreter
3466: got in processing the line. In particular, it shows that the text
3467: interpreter made no attempt to do anything with the final character
3468: group, @code{dup}, even though we have good reason to believe that the
3469: text interpreter would have no problem looking that word up and
3470: executing it a second time.
3471:
3472:
3473: @comment ----------------------------------------------
3474: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3475: @section Stacks, postfix notation and parameter passing
3476: @cindex text interpreter
3477: @cindex outer interpreter
3478:
3479: In procedural programming languages (like C and Pascal), the
3480: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3481: functions or procedures are called with @dfn{explicit parameters}. For
3482: example, in C we might write:
3483:
3484: @example
3485: total = total + new_volume(length,height,depth);
3486: @end example
3487:
3488: @noindent
3489: where new_volume is a function-call to another piece of code, and total,
3490: length, height and depth are all variables. length, height and depth are
3491: parameters to the function-call.
3492:
3493: In Forth, the equivalent of the function or procedure is the
3494: @dfn{definition} and parameters are implicitly passed between
3495: definitions using a shared stack that is visible to the
3496: programmer. Although Forth does support variables, the existence of the
3497: stack means that they are used far less often than in most other
3498: programming languages. When the text interpreter encounters a number, it
3499: will place (@dfn{push}) it on the stack. There are several stacks (the
3500: actual number is implementation-dependent ...) and the particular stack
3501: used for any operation is implied unambiguously by the operation being
3502: performed. The stack used for all integer operations is called the @dfn{data
3503: stack} and, since this is the stack used most commonly, references to
3504: ``the data stack'' are often abbreviated to ``the stack''.
3505:
3506: The stacks have a last-in, first-out (LIFO) organisation. If you type:
3507:
3508: @example
3509: @kbd{1 2 3@key{RET}} ok
3510: @end example
3511:
3512: Then this instructs the text interpreter to placed three numbers on the
3513: (data) stack. An analogy for the behaviour of the stack is to take a
3514: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3515: the table. The 3 was the last card onto the pile (``last-in'') and if
3516: you take a card off the pile then, unless you're prepared to fiddle a
3517: bit, the card that you take off will be the 3 (``first-out''). The
3518: number that will be first-out of the stack is called the @dfn{top of
3519: stack}, which
3520: @cindex TOS definition
3521: is often abbreviated to @dfn{TOS}.
3522:
3523: To understand how parameters are passed in Forth, consider the
3524: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3525: be surprised to learn that this definition performs addition. More
3526: precisely, it adds two number together and produces a result. Where does
3527: it get the two numbers from? It takes the top two numbers off the
3528: stack. Where does it place the result? On the stack. You can act-out the
3529: behaviour of @code{+} with your playing cards like this:
3530:
3531: @itemize @bullet
3532: @item
3533: Pick up two cards from the stack on the table
3534: @item
3535: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3536: numbers''
3537: @item
3538: Decide that the answer is 5
3539: @item
3540: Shuffle the two cards back into the pack and find a 5
3541: @item
3542: Put a 5 on the remaining ace that's on the table.
3543: @end itemize
3544:
3545: If you don't have a pack of cards handy but you do have Forth running,
3546: you can use the definition @code{.s} to show the current state of the stack,
3547: without affecting the stack. Type:
3548:
3549: @example
3550: @kbd{clearstacks 1 2 3@key{RET}} ok
3551: @kbd{.s@key{RET}} <3> 1 2 3 ok
3552: @end example
3553:
3554: The text interpreter looks up the word @code{clearstacks} and executes
3555: it; it tidies up the stacks and removes any entries that may have been
3556: left on it by earlier examples. The text interpreter pushes each of the
3557: three numbers in turn onto the stack. Finally, the text interpreter
3558: looks up the word @code{.s} and executes it. The effect of executing
3559: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3560: followed by a list of all the items on the stack; the item on the far
3561: right-hand side is the TOS.
3562:
3563: You can now type:
3564:
3565: @example
3566: @kbd{+ .s@key{RET}} <2> 1 5 ok
3567: @end example
3568:
3569: @noindent
3570: which is correct; there are now 2 items on the stack and the result of
3571: the addition is 5.
3572:
3573: If you're playing with cards, try doing a second addition: pick up the
3574: two cards, work out that their sum is 6, shuffle them into the pack,
3575: look for a 6 and place that on the table. You now have just one item on
3576: the stack. What happens if you try to do a third addition? Pick up the
3577: first card, pick up the second card -- ah! There is no second card. This
3578: is called a @dfn{stack underflow} and consitutes an error. If you try to
3579: do the same thing with Forth it often reports an error (probably a Stack
3580: Underflow or an Invalid Memory Address error).
3581:
3582: The opposite situation to a stack underflow is a @dfn{stack overflow},
3583: which simply accepts that there is a finite amount of storage space
3584: reserved for the stack. To stretch the playing card analogy, if you had
3585: enough packs of cards and you piled the cards up on the table, you would
3586: eventually be unable to add another card; you'd hit the ceiling. Gforth
3587: allows you to set the maximum size of the stacks. In general, the only
3588: time that you will get a stack overflow is because a definition has a
3589: bug in it and is generating data on the stack uncontrollably.
3590:
3591: There's one final use for the playing card analogy. If you model your
3592: stack using a pack of playing cards, the maximum number of items on
3593: your stack will be 52 (I assume you didn't use the Joker). The maximum
3594: @i{value} of any item on the stack is 13 (the King). In fact, the only
3595: possible numbers are positive integer numbers 1 through 13; you can't
3596: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3597: think about some of the cards, you can accommodate different
3598: numbers. For example, you could think of the Jack as representing 0,
3599: the Queen as representing -1 and the King as representing -2. Your
3600: @i{range} remains unchanged (you can still only represent a total of 13
3601: numbers) but the numbers that you can represent are -2 through 10.
3602:
3603: In that analogy, the limit was the amount of information that a single
3604: stack entry could hold, and Forth has a similar limit. In Forth, the
3605: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3606: implementation dependent and affects the maximum value that a stack
3607: entry can hold. A Standard Forth provides a cell size of at least
3608: 16-bits, and most desktop systems use a cell size of 32-bits.
3609:
3610: Forth does not do any type checking for you, so you are free to
3611: manipulate and combine stack items in any way you wish. A convenient way
3612: of treating stack items is as 2's complement signed integers, and that
3613: is what Standard words like @code{+} do. Therefore you can type:
3614:
3615: @example
3616: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
3617: @end example
3618:
3619: If you use numbers and definitions like @code{+} in order to turn Forth
3620: into a great big pocket calculator, you will realise that it's rather
3621: different from a normal calculator. Rather than typing 2 + 3 = you had
3622: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3623: result). The terminology used to describe this difference is to say that
3624: your calculator uses @dfn{Infix Notation} (parameters and operators are
3625: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3626: operators are separate), also called @dfn{Reverse Polish Notation}.
3627:
3628: Whilst postfix notation might look confusing to begin with, it has
3629: several important advantages:
3630:
3631: @itemize @bullet
3632: @item
3633: it is unambiguous
3634: @item
3635: it is more concise
3636: @item
3637: it fits naturally with a stack-based system
3638: @end itemize
3639:
3640: To examine these claims in more detail, consider these sums:
3641:
3642: @example
3643: 6 + 5 * 4 =
3644: 4 * 5 + 6 =
3645: @end example
3646:
3647: If you're just learning maths or your maths is very rusty, you will
3648: probably come up with the answer 44 for the first and 26 for the
3649: second. If you are a bit of a whizz at maths you will remember the
3650: @i{convention} that multiplication takes precendence over addition, and
3651: you'd come up with the answer 26 both times. To explain the answer 26
3652: to someone who got the answer 44, you'd probably rewrite the first sum
3653: like this:
3654:
3655: @example
3656: 6 + (5 * 4) =
3657: @end example
3658:
3659: If what you really wanted was to perform the addition before the
3660: multiplication, you would have to use parentheses to force it.
3661:
3662: If you did the first two sums on a pocket calculator you would probably
3663: get the right answers, unless you were very cautious and entered them using
3664: these keystroke sequences:
3665:
3666: 6 + 5 = * 4 =
3667: 4 * 5 = + 6 =
3668:
3669: Postfix notation is unambiguous because the order that the operators
3670: are applied is always explicit; that also means that parentheses are
3671: never required. The operators are @i{active} (the act of quoting the
3672: operator makes the operation occur) which removes the need for ``=''.
3673:
3674: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3675: equivalent ways:
3676:
3677: @example
3678: 6 5 4 * + or:
3679: 5 4 * 6 +
3680: @end example
3681:
3682: An important thing that you should notice about this notation is that
3683: the @i{order} of the numbers does not change; if you want to subtract
3684: 2 from 10 you type @code{10 2 -}.
3685:
3686: The reason that Forth uses postfix notation is very simple to explain: it
3687: makes the implementation extremely simple, and it follows naturally from
3688: using the stack as a mechanism for passing parameters. Another way of
3689: thinking about this is to realise that all Forth definitions are
3690: @i{active}; they execute as they are encountered by the text
3691: interpreter. The result of this is that the syntax of Forth is trivially
3692: simple.
3693:
3694:
3695:
3696: @comment ----------------------------------------------
3697: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3698: @section Your first Forth definition
3699: @cindex first definition
3700:
3701: Until now, the examples we've seen have been trivial; we've just been
3702: using Forth as a bigger-than-pocket calculator. Also, each calculation
3703: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3704: again@footnote{That's not quite true. If you press the up-arrow key on
3705: your keyboard you should be able to scroll back to any earlier command,
3706: edit it and re-enter it.} In this section we'll see how to add new
3707: words to Forth's vocabulary.
3708:
3709: The easiest way to create a new word is to use a @dfn{colon
3710: definition}. We'll define a few and try them out before worrying too
3711: much about how they work. Try typing in these examples; be careful to
3712: copy the spaces accurately:
3713:
3714: @example
3715: : add-two 2 + . ;
3716: : greet ." Hello and welcome" ;
3717: : demo 5 add-two ;
3718: @end example
3719:
3720: @noindent
3721: Now try them out:
3722:
3723: @example
3724: @kbd{greet@key{RET}} Hello and welcome ok
3725: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3726: @kbd{4 add-two@key{RET}} 6 ok
3727: @kbd{demo@key{RET}} 7 ok
3728: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
3729: @end example
3730:
3731: The first new thing that we've introduced here is the pair of words
3732: @code{:} and @code{;}. These are used to start and terminate a new
3733: definition, respectively. The first word after the @code{:} is the name
3734: for the new definition.
3735:
3736: As you can see from the examples, a definition is built up of words that
3737: have already been defined; Forth makes no distinction between
3738: definitions that existed when you started the system up, and those that
3739: you define yourself.
3740:
3741: The examples also introduce the words @code{.} (dot), @code{."}
3742: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3743: the stack and displays it. It's like @code{.s} except that it only
3744: displays the top item of the stack and it is destructive; after it has
3745: executed, the number is no longer on the stack. There is always one
3746: space printed after the number, and no spaces before it. Dot-quote
3747: defines a string (a sequence of characters) that will be printed when
3748: the word is executed. The string can contain any printable characters
3749: except @code{"}. A @code{"} has a special function; it is not a Forth
3750: word but it acts as a delimiter (the way that delimiters work is
3751: described in the next section). Finally, @code{dup} duplicates the value
3752: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
3753:
3754: We already know that the text interpreter searches through the
3755: dictionary to locate names. If you've followed the examples earlier, you
3756: will already have a definition called @code{add-two}. Lets try modifying
3757: it by typing in a new definition:
3758:
3759: @example
3760: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
3761: @end example
3762:
3763: Forth recognised that we were defining a word that already exists, and
3764: printed a message to warn us of that fact. Let's try out the new
3765: definition:
3766:
3767: @example
3768: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
3769: @end example
3770:
3771: @noindent
3772: All that we've actually done here, though, is to create a new
3773: definition, with a particular name. The fact that there was already a
3774: definition with the same name did not make any difference to the way
3775: that the new definition was created (except that Forth printed a warning
3776: message). The old definition of add-two still exists (try @code{demo}
3777: again to see that this is true). Any new definition will use the new
3778: definition of @code{add-two}, but old definitions continue to use the
3779: version that already existed at the time that they were @code{compiled}.
3780:
3781: Before you go on to the next section, try defining and redefining some
3782: words of your own.
3783:
3784: @comment ----------------------------------------------
3785: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3786: @section How does that work?
3787: @cindex parsing words
3788:
3789: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3790:
3791: @c Is it a good idea to talk about the interpretation semantics of a
3792: @c number? We don't have an xt to go along with it. - anton
3793:
3794: @c Now that I have eliminated execution semantics, I wonder if it would not
3795: @c be better to keep them (or add run-time semantics), to make it easier to
3796: @c explain what compilation semantics usually does. - anton
3797:
3798: @c nac-> I removed the term ``default compilation sematics'' from the
3799: @c introductory chapter. Removing ``execution semantics'' was making
3800: @c everything simpler to explain, then I think the use of this term made
3801: @c everything more complex again. I replaced it with ``default
3802: @c semantics'' (which is used elsewhere in the manual) by which I mean
3803: @c ``a definition that has neither the immediate nor the compile-only
3804: @c flag set''.
3805:
3806: @c anton: I have eliminated default semantics (except in one place where it
3807: @c means "default interpretation and compilation semantics"), because it
3808: @c makes no sense in the presence of combined words. I reverted to
3809: @c "execution semantics" where necessary.
3810:
3811: @c nac-> I reworded big chunks of the ``how does that work''
3812: @c section (and, unusually for me, I think I even made it shorter!). See
3813: @c what you think -- I know I have not addressed your primary concern
3814: @c that it is too heavy-going for an introduction. From what I understood
3815: @c of your course notes it looks as though they might be a good framework.
3816: @c Things that I've tried to capture here are some things that came as a
3817: @c great revelation here when I first understood them. Also, I like the
3818: @c fact that a very simple code example shows up almost all of the issues
3819: @c that you need to understand to see how Forth works. That's unique and
3820: @c worthwhile to emphasise.
3821:
3822: @c anton: I think it's a good idea to present the details, especially those
3823: @c that you found to be a revelation, and probably the tutorial tries to be
3824: @c too superficial and does not get some of the things across that make
3825: @c Forth special. I do believe that most of the time these things should
3826: @c be discussed at the end of a section or in separate sections instead of
3827: @c in the middle of a section (e.g., the stuff you added in "User-defined
3828: @c defining words" leads in a completely different direction from the rest
3829: @c of the section).
3830:
3831: Now we're going to take another look at the definition of @code{add-two}
3832: from the previous section. From our knowledge of the way that the text
3833: interpreter works, we would have expected this result when we tried to
3834: define @code{add-two}:
3835:
3836: @example
3837: @kbd{: add-two 2 + . ;@key{RET}}
3838: ^^^^^^^
3839: Error: Undefined word
3840: @end example
3841:
3842: The reason that this didn't happen is bound up in the way that @code{:}
3843: works. The word @code{:} does two special things. The first special
3844: thing that it does prevents the text interpreter from ever seeing the
3845: characters @code{add-two}. The text interpreter uses a variable called
3846: @cindex modifying >IN
3847: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
3848: input line. When it encounters the word @code{:} it behaves in exactly
3849: the same way as it does for any other word; it looks it up in the name
3850: dictionary, finds its xt and executes it. When @code{:} executes, it
3851: looks at the input buffer, finds the word @code{add-two} and advances the
3852: value of @code{>IN} to point past it. It then does some other stuff
3853: associated with creating the new definition (including creating an entry
3854: for @code{add-two} in the name dictionary). When the execution of @code{:}
3855: completes, control returns to the text interpreter, which is oblivious
3856: to the fact that it has been tricked into ignoring part of the input
3857: line.
3858:
3859: @cindex parsing words
3860: Words like @code{:} -- words that advance the value of @code{>IN} and so
3861: prevent the text interpreter from acting on the whole of the input line
3862: -- are called @dfn{parsing words}.
3863:
3864: @cindex @code{state} - effect on the text interpreter
3865: @cindex text interpreter - effect of state
3866: The second special thing that @code{:} does is change the value of a
3867: variable called @code{state}, which affects the way that the text
3868: interpreter behaves. When Gforth starts up, @code{state} has the value
3869: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3870: colon definition (started with @code{:}), @code{state} is set to -1 and
3871: the text interpreter is said to be @dfn{compiling}.
3872:
3873: In this example, the text interpreter is compiling when it processes the
3874: string ``@code{2 + . ;}''. It still breaks the string down into
3875: character sequences in the same way. However, instead of pushing the
3876: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
3877: into the definition of @code{add-two} that will make the number @code{2} get
3878: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
3879: the behaviours of @code{+} and @code{.} are also compiled into the
3880: definition.
3881:
3882: One category of words don't get compiled. These so-called @dfn{immediate
3883: words} get executed (performed @i{now}) regardless of whether the text
3884: interpreter is interpreting or compiling. The word @code{;} is an
3885: immediate word. Rather than being compiled into the definition, it
3886: executes. Its effect is to terminate the current definition, which
3887: includes changing the value of @code{state} back to 0.
3888:
3889: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
3890: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
3891: definition.
3892:
3893: In Forth, every word or number can be described in terms of two
3894: properties:
3895:
3896: @itemize @bullet
3897: @item
3898: @cindex interpretation semantics
3899: Its @dfn{interpretation semantics} describe how it will behave when the
3900: text interpreter encounters it in @dfn{interpret} state. The
3901: interpretation semantics of a word are represented by an @dfn{execution
3902: token}.
3903: @item
3904: @cindex compilation semantics
3905: Its @dfn{compilation semantics} describe how it will behave when the
3906: text interpreter encounters it in @dfn{compile} state. The compilation
3907: semantics of a word are represented in an implementation-dependent way;
3908: Gforth uses a @dfn{compilation token}.
3909: @end itemize
3910:
3911: @noindent
3912: Numbers are always treated in a fixed way:
3913:
3914: @itemize @bullet
3915: @item
3916: When the number is @dfn{interpreted}, its behaviour is to push the
3917: number onto the stack.
3918: @item
3919: When the number is @dfn{compiled}, a piece of code is appended to the
3920: current definition that pushes the number when it runs. (In other words,
3921: the compilation semantics of a number are to postpone its interpretation
3922: semantics until the run-time of the definition that it is being compiled
3923: into.)
3924: @end itemize
3925:
3926: Words don't behave in such a regular way, but most have @i{default
3927: semantics} which means that they behave like this:
3928:
3929: @itemize @bullet
3930: @item
3931: The @dfn{interpretation semantics} of the word are to do something useful.
3932: @item
3933: The @dfn{compilation semantics} of the word are to append its
3934: @dfn{interpretation semantics} to the current definition (so that its
3935: run-time behaviour is to do something useful).
3936: @end itemize
3937:
3938: @cindex immediate words
3939: The actual behaviour of any particular word can be controlled by using
3940: the words @code{immediate} and @code{compile-only} when the word is
3941: defined. These words set flags in the name dictionary entry of the most
3942: recently defined word, and these flags are retrieved by the text
3943: interpreter when it finds the word in the name dictionary.
3944:
3945: A word that is marked as @dfn{immediate} has compilation semantics that
3946: are identical to its interpretation semantics. In other words, it
3947: behaves like this:
3948:
3949: @itemize @bullet
3950: @item
3951: The @dfn{interpretation semantics} of the word are to do something useful.
3952: @item
3953: The @dfn{compilation semantics} of the word are to do something useful
3954: (and actually the same thing); i.e., it is executed during compilation.
3955: @end itemize
3956:
3957: Marking a word as @dfn{compile-only} prohibits the text interpreter from
3958: performing the interpretation semantics of the word directly; an attempt
3959: to do so will generate an error. It is never necessary to use
3960: @code{compile-only} (and it is not even part of ANS Forth, though it is
3961: provided by many implementations) but it is good etiquette to apply it
3962: to a word that will not behave correctly (and might have unexpected
3963: side-effects) in interpret state. For example, it is only legal to use
3964: the conditional word @code{IF} within a definition. If you forget this
3965: and try to use it elsewhere, the fact that (in Gforth) it is marked as
3966: @code{compile-only} allows the text interpreter to generate a helpful
3967: error message rather than subjecting you to the consequences of your
3968: folly.
3969:
3970: This example shows the difference between an immediate and a
3971: non-immediate word:
3972:
3973: @example
3974: : show-state state @@ . ;
3975: : show-state-now show-state ; immediate
3976: : word1 show-state ;
3977: : word2 show-state-now ;
3978: @end example
3979:
3980: The word @code{immediate} after the definition of @code{show-state-now}
3981: makes that word an immediate word. These definitions introduce a new
3982: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
3983: variable, and leaves it on the stack. Therefore, the behaviour of
3984: @code{show-state} is to print a number that represents the current value
3985: of @code{state}.
3986:
3987: When you execute @code{word1}, it prints the number 0, indicating that
3988: the system is interpreting. When the text interpreter compiled the
3989: definition of @code{word1}, it encountered @code{show-state} whose
3990: compilation semantics are to append its interpretation semantics to the
3991: current definition. When you execute @code{word1}, it performs the
3992: interpretation semantics of @code{show-state}. At the time that @code{word1}
3993: (and therefore @code{show-state}) are executed, the system is
3994: interpreting.
3995:
3996: When you pressed @key{RET} after entering the definition of @code{word2},
3997: you should have seen the number -1 printed, followed by ``@code{
3998: ok}''. When the text interpreter compiled the definition of
3999: @code{word2}, it encountered @code{show-state-now}, an immediate word,
4000: whose compilation semantics are therefore to perform its interpretation
4001: semantics. It is executed straight away (even before the text
4002: interpreter has moved on to process another group of characters; the
4003: @code{;} in this example). The effect of executing it are to display the
4004: value of @code{state} @i{at the time that the definition of}
4005: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4006: system is compiling at this time. If you execute @code{word2} it does
4007: nothing at all.
4008:
4009: @cindex @code{."}, how it works
4010: Before leaving the subject of immediate words, consider the behaviour of
4011: @code{."} in the definition of @code{greet}, in the previous
4012: section. This word is both a parsing word and an immediate word. Notice
4013: that there is a space between @code{."} and the start of the text
4014: @code{Hello and welcome}, but that there is no space between the last
4015: letter of @code{welcome} and the @code{"} character. The reason for this
4016: is that @code{."} is a Forth word; it must have a space after it so that
4017: the text interpreter can identify it. The @code{"} is not a Forth word;
4018: it is a @dfn{delimiter}. The examples earlier show that, when the string
4019: is displayed, there is neither a space before the @code{H} nor after the
4020: @code{e}. Since @code{."} is an immediate word, it executes at the time
4021: that @code{greet} is defined. When it executes, its behaviour is to
4022: search forward in the input line looking for the delimiter. When it
4023: finds the delimiter, it updates @code{>IN} to point past the
4024: delimiter. It also compiles some magic code into the definition of
4025: @code{greet}; the xt of a run-time routine that prints a text string. It
4026: compiles the string @code{Hello and welcome} into memory so that it is
4027: available to be printed later. When the text interpreter gains control,
4028: the next word it finds in the input stream is @code{;} and so it
4029: terminates the definition of @code{greet}.
4030:
4031:
4032: @comment ----------------------------------------------
4033: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4034: @section Forth is written in Forth
4035: @cindex structure of Forth programs
4036:
4037: When you start up a Forth compiler, a large number of definitions
4038: already exist. In Forth, you develop a new application using bottom-up
4039: programming techniques to create new definitions that are defined in
4040: terms of existing definitions. As you create each definition you can
4041: test and debug it interactively.
4042:
4043: If you have tried out the examples in this section, you will probably
4044: have typed them in by hand; when you leave Gforth, your definitions will
4045: be lost. You can avoid this by using a text editor to enter Forth source
4046: code into a file, and then loading code from the file using
4047: @code{include} (@pxref{Forth source files}). A Forth source file is
4048: processed by the text interpreter, just as though you had typed it in by
4049: hand@footnote{Actually, there are some subtle differences -- see
4050: @ref{The Text Interpreter}.}.
4051:
4052: Gforth also supports the traditional Forth alternative to using text
4053: files for program entry (@pxref{Blocks}).
4054:
4055: In common with many, if not most, Forth compilers, most of Gforth is
4056: actually written in Forth. All of the @file{.fs} files in the
4057: installation directory@footnote{For example,
4058: @file{/usr/local/share/gforth...}} are Forth source files, which you can
4059: study to see examples of Forth programming.
4060:
4061: Gforth maintains a history file that records every line that you type to
4062: the text interpreter. This file is preserved between sessions, and is
4063: used to provide a command-line recall facility. If you enter long
4064: definitions by hand, you can use a text editor to paste them out of the
4065: history file into a Forth source file for reuse at a later time
4066: (for more information @pxref{Command-line editing}).
4067:
4068:
4069: @comment ----------------------------------------------
4070: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4071: @section Review - elements of a Forth system
4072: @cindex elements of a Forth system
4073:
4074: To summarise this chapter:
4075:
4076: @itemize @bullet
4077: @item
4078: Forth programs use @dfn{factoring} to break a problem down into small
4079: fragments called @dfn{words} or @dfn{definitions}.
4080: @item
4081: Forth program development is an interactive process.
4082: @item
4083: The main command loop that accepts input, and controls both
4084: interpretation and compilation, is called the @dfn{text interpreter}
4085: (also known as the @dfn{outer interpreter}).
4086: @item
4087: Forth has a very simple syntax, consisting of words and numbers
4088: separated by spaces or carriage-return characters. Any additional syntax
4089: is imposed by @dfn{parsing words}.
4090: @item
4091: Forth uses a stack to pass parameters between words. As a result, it
4092: uses postfix notation.
4093: @item
4094: To use a word that has previously been defined, the text interpreter
4095: searches for the word in the @dfn{name dictionary}.
4096: @item
4097: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
4098: @item
4099: The text interpreter uses the value of @code{state} to select between
4100: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4101: semantics} of a word that it encounters.
4102: @item
4103: The relationship between the @dfn{interpretation semantics} and
4104: @dfn{compilation semantics} for a word
4105: depend upon the way in which the word was defined (for example, whether
4106: it is an @dfn{immediate} word).
4107: @item
4108: Forth definitions can be implemented in Forth (called @dfn{high-level
4109: definitions}) or in some other way (usually a lower-level language and
4110: as a result often called @dfn{low-level definitions}, @dfn{code
4111: definitions} or @dfn{primitives}).
4112: @item
4113: Many Forth systems are implemented mainly in Forth.
4114: @end itemize
4115:
4116:
4117: @comment ----------------------------------------------
4118: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
4119: @section Where To Go Next
4120: @cindex where to go next
4121:
4122: Amazing as it may seem, if you have read (and understood) this far, you
4123: know almost all the fundamentals about the inner workings of a Forth
4124: system. You certainly know enough to be able to read and understand the
4125: rest of this manual and the ANS Forth document, to learn more about the
4126: facilities that Forth in general and Gforth in particular provide. Even
4127: scarier, you know almost enough to implement your own Forth system.
4128: However, that's not a good idea just yet... better to try writing some
4129: programs in Gforth.
4130:
4131: Forth has such a rich vocabulary that it can be hard to know where to
4132: start in learning it. This section suggests a few sets of words that are
4133: enough to write small but useful programs. Use the word index in this
4134: document to learn more about each word, then try it out and try to write
4135: small definitions using it. Start by experimenting with these words:
4136:
4137: @itemize @bullet
4138: @item
4139: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4140: @item
4141: Comparison: @code{MIN MAX =}
4142: @item
4143: Logic: @code{AND OR XOR NOT}
4144: @item
4145: Stack manipulation: @code{DUP DROP SWAP OVER}
4146: @item
4147: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
4148: @item
4149: Input/Output: @code{. ." EMIT CR KEY}
4150: @item
4151: Defining words: @code{: ; CREATE}
4152: @item
4153: Memory allocation words: @code{ALLOT ,}
4154: @item
4155: Tools: @code{SEE WORDS .S MARKER}
4156: @end itemize
4157:
4158: When you have mastered those, go on to:
4159:
4160: @itemize @bullet
4161: @item
4162: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
4163: @item
4164: Memory access: @code{@@ !}
4165: @end itemize
4166:
4167: When you have mastered these, there's nothing for it but to read through
4168: the whole of this manual and find out what you've missed.
4169:
4170: @comment ----------------------------------------------
4171: @node Exercises, , Where to go next, Introduction
4172: @section Exercises
4173: @cindex exercises
4174:
4175: TODO: provide a set of programming excercises linked into the stuff done
4176: already and into other sections of the manual. Provide solutions to all
4177: the exercises in a .fs file in the distribution.
4178:
4179: @c Get some inspiration from Starting Forth and Kelly&Spies.
4180:
4181: @c excercises:
4182: @c 1. take inches and convert to feet and inches.
4183: @c 2. take temperature and convert from fahrenheight to celcius;
4184: @c may need to care about symmetric vs floored??
4185: @c 3. take input line and do character substitution
4186: @c to encipher or decipher
4187: @c 4. as above but work on a file for in and out
4188: @c 5. take input line and convert to pig-latin
4189: @c
4190: @c thing of sets of things to exercise then come up with
4191: @c problems that need those things.
4192:
4193:
4194: @c ******************************************************************
4195: @node Words, Error messages, Introduction, Top
4196: @chapter Forth Words
4197: @cindex words
4198:
4199: @menu
4200: * Notation::
4201: * Case insensitivity::
4202: * Comments::
4203: * Boolean Flags::
4204: * Arithmetic::
4205: * Stack Manipulation::
4206: * Memory::
4207: * Control Structures::
4208: * Defining Words::
4209: * Interpretation and Compilation Semantics::
4210: * Tokens for Words::
4211: * Compiling words::
4212: * The Text Interpreter::
4213: * The Input Stream::
4214: * Word Lists::
4215: * Environmental Queries::
4216: * Files::
4217: * Blocks::
4218: * Other I/O::
4219: * OS command line arguments::
4220: * Locals::
4221: * Structures::
4222: * Object-oriented Forth::
4223: * Programming Tools::
4224: * Assembler and Code Words::
4225: * Threading Words::
4226: * Passing Commands to the OS::
4227: * Keeping track of Time::
4228: * Miscellaneous Words::
4229: @end menu
4230:
4231: @node Notation, Case insensitivity, Words, Words
4232: @section Notation
4233: @cindex notation of glossary entries
4234: @cindex format of glossary entries
4235: @cindex glossary notation format
4236: @cindex word glossary entry format
4237:
4238: The Forth words are described in this section in the glossary notation
4239: that has become a de-facto standard for Forth texts:
4240:
4241: @format
4242: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
4243: @end format
4244: @i{Description}
4245:
4246: @table @var
4247: @item word
4248: The name of the word.
4249:
4250: @item Stack effect
4251: @cindex stack effect
4252: The stack effect is written in the notation @code{@i{before} --
4253: @i{after}}, where @i{before} and @i{after} describe the top of
4254: stack entries before and after the execution of the word. The rest of
4255: the stack is not touched by the word. The top of stack is rightmost,
4256: i.e., a stack sequence is written as it is typed in. Note that Gforth
4257: uses a separate floating point stack, but a unified stack
4258: notation. Also, return stack effects are not shown in @i{stack
4259: effect}, but in @i{Description}. The name of a stack item describes
4260: the type and/or the function of the item. See below for a discussion of
4261: the types.
4262:
4263: All words have two stack effects: A compile-time stack effect and a
4264: run-time stack effect. The compile-time stack-effect of most words is
4265: @i{ -- }. If the compile-time stack-effect of a word deviates from
4266: this standard behaviour, or the word does other unusual things at
4267: compile time, both stack effects are shown; otherwise only the run-time
4268: stack effect is shown.
4269:
4270: @cindex pronounciation of words
4271: @item pronunciation
4272: How the word is pronounced.
4273:
4274: @cindex wordset
4275: @cindex environment wordset
4276: @item wordset
4277: The ANS Forth standard is divided into several word sets. A standard
4278: system need not support all of them. Therefore, in theory, the fewer
4279: word sets your program uses the more portable it will be. However, we
4280: suspect that most ANS Forth systems on personal machines will feature
4281: all word sets. Words that are not defined in ANS Forth have
4282: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
4283: describes words that will work in future releases of Gforth;
4284: @code{gforth-internal} words are more volatile. Environmental query
4285: strings are also displayed like words; you can recognize them by the
4286: @code{environment} in the word set field.
4287:
4288: @item Description
4289: A description of the behaviour of the word.
4290: @end table
4291:
4292: @cindex types of stack items
4293: @cindex stack item types
4294: The type of a stack item is specified by the character(s) the name
4295: starts with:
4296:
4297: @table @code
4298: @item f
4299: @cindex @code{f}, stack item type
4300: Boolean flags, i.e. @code{false} or @code{true}.
4301: @item c
4302: @cindex @code{c}, stack item type
4303: Char
4304: @item w
4305: @cindex @code{w}, stack item type
4306: Cell, can contain an integer or an address
4307: @item n
4308: @cindex @code{n}, stack item type
4309: signed integer
4310: @item u
4311: @cindex @code{u}, stack item type
4312: unsigned integer
4313: @item d
4314: @cindex @code{d}, stack item type
4315: double sized signed integer
4316: @item ud
4317: @cindex @code{ud}, stack item type
4318: double sized unsigned integer
4319: @item r
4320: @cindex @code{r}, stack item type
4321: Float (on the FP stack)
4322: @item a-
4323: @cindex @code{a_}, stack item type
4324: Cell-aligned address
4325: @item c-
4326: @cindex @code{c_}, stack item type
4327: Char-aligned address (note that a Char may have two bytes in Windows NT)
4328: @item f-
4329: @cindex @code{f_}, stack item type
4330: Float-aligned address
4331: @item df-
4332: @cindex @code{df_}, stack item type
4333: Address aligned for IEEE double precision float
4334: @item sf-
4335: @cindex @code{sf_}, stack item type
4336: Address aligned for IEEE single precision float
4337: @item xt
4338: @cindex @code{xt}, stack item type
4339: Execution token, same size as Cell
4340: @item wid
4341: @cindex @code{wid}, stack item type
4342: Word list ID, same size as Cell
4343: @item ior, wior
4344: @cindex ior type description
4345: @cindex wior type description
4346: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
4347: @item f83name
4348: @cindex @code{f83name}, stack item type
4349: Pointer to a name structure
4350: @item "
4351: @cindex @code{"}, stack item type
4352: string in the input stream (not on the stack). The terminating character
4353: is a blank by default. If it is not a blank, it is shown in @code{<>}
4354: quotes.
4355: @end table
4356:
4357: @comment ----------------------------------------------
4358: @node Case insensitivity, Comments, Notation, Words
4359: @section Case insensitivity
4360: @cindex case sensitivity
4361: @cindex upper and lower case
4362:
4363: Gforth is case-insensitive; you can enter definitions and invoke
4364: Standard words using upper, lower or mixed case (however,
4365: @pxref{core-idef, Implementation-defined options, Implementation-defined
4366: options}).
4367:
4368: ANS Forth only @i{requires} implementations to recognise Standard words
4369: when they are typed entirely in upper case. Therefore, a Standard
4370: program must use upper case for all Standard words. You can use whatever
4371: case you like for words that you define, but in a Standard program you
4372: have to use the words in the same case that you defined them.
4373:
4374: Gforth supports case sensitivity through @code{table}s (case-sensitive
4375: wordlists, @pxref{Word Lists}).
4376:
4377: Two people have asked how to convert Gforth to be case-sensitive; while
4378: we think this is a bad idea, you can change all wordlists into tables
4379: like this:
4380:
4381: @example
4382: ' table-find forth-wordlist wordlist-map @ !
4383: @end example
4384:
4385: Note that you now have to type the predefined words in the same case
4386: that we defined them, which are varying. You may want to convert them
4387: to your favourite case before doing this operation (I won't explain how,
4388: because if you are even contemplating doing this, you'd better have
4389: enough knowledge of Forth systems to know this already).
4390:
4391: @node Comments, Boolean Flags, Case insensitivity, Words
4392: @section Comments
4393: @cindex comments
4394:
4395: Forth supports two styles of comment; the traditional @i{in-line} comment,
4396: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
4397:
4398:
4399: doc-(
4400: doc-\
4401: doc-\G
4402:
4403:
4404: @node Boolean Flags, Arithmetic, Comments, Words
4405: @section Boolean Flags
4406: @cindex Boolean flags
4407:
4408: A Boolean flag is cell-sized. A cell with all bits clear represents the
4409: flag @code{false} and a flag with all bits set represents the flag
4410: @code{true}. Words that check a flag (for example, @code{IF}) will treat
4411: a cell that has @i{any} bit set as @code{true}.
4412: @c on and off to Memory?
4413: @c true and false to "Bitwise operations" or "Numeric comparison"?
4414:
4415: doc-true
4416: doc-false
4417: doc-on
4418: doc-off
4419:
4420:
4421: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
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}).
4435: @comment TODO discuss the different division forms and the std approach
4436:
4437: @menu
4438: * Single precision::
4439: * Double precision:: Double-cell integer arithmetic
4440: * Bitwise operations::
4441: * Numeric comparison::
4442: * Mixed precision:: Operations with single and double-cell integers
4443: * Floating Point::
4444: @end menu
4445:
4446: @node Single precision, Double precision, Arithmetic, Arithmetic
4447: @subsection Single precision
4448: @cindex single precision arithmetic words
4449:
4450: @c !! cell undefined
4451:
4452: By default, numbers in Forth are single-precision integers that are one
4453: cell in size. They can be signed or unsigned, depending upon how you
4454: treat them. For the rules used by the text interpreter for recognising
4455: single-precision integers see @ref{Number Conversion}.
4456:
4457: These words are all defined for signed operands, but some of them also
4458: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4459: @code{*}.
4460:
4461: doc-+
4462: doc-1+
4463: doc--
4464: doc-1-
4465: doc-*
4466: doc-/
4467: doc-mod
4468: doc-/mod
4469: doc-negate
4470: doc-abs
4471: doc-min
4472: doc-max
4473: doc-floored
4474:
4475:
4476: @node Double precision, Bitwise operations, Single precision, Arithmetic
4477: @subsection Double precision
4478: @cindex double precision arithmetic words
4479:
4480: For the rules used by the text interpreter for
4481: recognising double-precision integers, see @ref{Number Conversion}.
4482:
4483: A double precision number is represented by a cell pair, with the most
4484: significant cell at the TOS. It is trivial to convert an unsigned single
4485: to a double: simply push a @code{0} onto the TOS. Since numbers are
4486: represented by Gforth using 2's complement arithmetic, converting a
4487: signed single to a (signed) double requires sign-extension across the
4488: most significant cell. This can be achieved using @code{s>d}. The moral
4489: of the story is that you cannot convert a number without knowing whether
4490: it represents an unsigned or a signed number.
4491:
4492: These words are all defined for signed operands, but some of them also
4493: work for unsigned numbers: @code{d+}, @code{d-}.
4494:
4495: doc-s>d
4496: doc-d>s
4497: doc-d+
4498: doc-d-
4499: doc-dnegate
4500: doc-dabs
4501: doc-dmin
4502: doc-dmax
4503:
4504:
4505: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4506: @subsection Bitwise operations
4507: @cindex bitwise operation words
4508:
4509:
4510: doc-and
4511: doc-or
4512: doc-xor
4513: doc-invert
4514: doc-lshift
4515: doc-rshift
4516: doc-2*
4517: doc-d2*
4518: doc-2/
4519: doc-d2/
4520:
4521:
4522: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
4523: @subsection Numeric comparison
4524: @cindex numeric comparison words
4525:
4526: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4527: d0= d0<>}) work for for both signed and unsigned numbers.
4528:
4529: doc-<
4530: doc-<=
4531: doc-<>
4532: doc-=
4533: doc->
4534: doc->=
4535:
4536: doc-0<
4537: doc-0<=
4538: doc-0<>
4539: doc-0=
4540: doc-0>
4541: doc-0>=
4542:
4543: doc-u<
4544: doc-u<=
4545: @c u<> and u= exist but are the same as <> and =
4546: @c doc-u<>
4547: @c doc-u=
4548: doc-u>
4549: doc-u>=
4550:
4551: doc-within
4552:
4553: doc-d<
4554: doc-d<=
4555: doc-d<>
4556: doc-d=
4557: doc-d>
4558: doc-d>=
4559:
4560: doc-d0<
4561: doc-d0<=
4562: doc-d0<>
4563: doc-d0=
4564: doc-d0>
4565: doc-d0>=
4566:
4567: doc-du<
4568: doc-du<=
4569: @c du<> and du= exist but are the same as d<> and d=
4570: @c doc-du<>
4571: @c doc-du=
4572: doc-du>
4573: doc-du>=
4574:
4575:
4576: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
4577: @subsection Mixed precision
4578: @cindex mixed precision arithmetic words
4579:
4580:
4581: doc-m+
4582: doc-*/
4583: doc-*/mod
4584: doc-m*
4585: doc-um*
4586: doc-m*/
4587: doc-um/mod
4588: doc-fm/mod
4589: doc-sm/rem
4590:
4591:
4592: @node Floating Point, , Mixed precision, Arithmetic
4593: @subsection Floating Point
4594: @cindex floating point arithmetic words
4595:
4596: For the rules used by the text interpreter for
4597: recognising floating-point numbers see @ref{Number Conversion}.
4598:
4599: Gforth has a separate floating point stack, but the documentation uses
4600: the unified notation.@footnote{It's easy to generate the separate
4601: notation from that by just separating the floating-point numbers out:
4602: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4603: r3 )}.}
4604:
4605: @cindex floating-point arithmetic, pitfalls
4606: Floating point numbers have a number of unpleasant surprises for the
4607: unwary (e.g., floating point addition is not associative) and even a few
4608: for the wary. You should not use them unless you know what you are doing
4609: or you don't care that the results you get are totally bogus. If you
4610: want to learn about the problems of floating point numbers (and how to
4611: avoid them), you might start with @cite{David Goldberg,
4612: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4613: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4614: Surveys 23(1):5@minus{}48, March 1991}.
4615:
4616:
4617: doc-d>f
4618: doc-f>d
4619: doc-f+
4620: doc-f-
4621: doc-f*
4622: doc-f/
4623: doc-fnegate
4624: doc-fabs
4625: doc-fmax
4626: doc-fmin
4627: doc-floor
4628: doc-fround
4629: doc-f**
4630: doc-fsqrt
4631: doc-fexp
4632: doc-fexpm1
4633: doc-fln
4634: doc-flnp1
4635: doc-flog
4636: doc-falog
4637: doc-f2*
4638: doc-f2/
4639: doc-1/f
4640: doc-precision
4641: doc-set-precision
4642:
4643: @cindex angles in trigonometric operations
4644: @cindex trigonometric operations
4645: Angles in floating point operations are given in radians (a full circle
4646: has 2 pi radians).
4647:
4648: doc-fsin
4649: doc-fcos
4650: doc-fsincos
4651: doc-ftan
4652: doc-fasin
4653: doc-facos
4654: doc-fatan
4655: doc-fatan2
4656: doc-fsinh
4657: doc-fcosh
4658: doc-ftanh
4659: doc-fasinh
4660: doc-facosh
4661: doc-fatanh
4662: doc-pi
4663:
4664: @cindex equality of floats
4665: @cindex floating-point comparisons
4666: One particular problem with floating-point arithmetic is that comparison
4667: for equality often fails when you would expect it to succeed. For this
4668: reason approximate equality is often preferred (but you still have to
4669: know what you are doing). Also note that IEEE NaNs may compare
4670: differently from what you might expect. The comparison words are:
4671:
4672: doc-f~rel
4673: doc-f~abs
4674: doc-f~
4675: doc-f=
4676: doc-f<>
4677:
4678: doc-f<
4679: doc-f<=
4680: doc-f>
4681: doc-f>=
4682:
4683: doc-f0<
4684: doc-f0<=
4685: doc-f0<>
4686: doc-f0=
4687: doc-f0>
4688: doc-f0>=
4689:
4690:
4691: @node Stack Manipulation, Memory, Arithmetic, Words
4692: @section Stack Manipulation
4693: @cindex stack manipulation words
4694:
4695: @cindex floating-point stack in the standard
4696: Gforth maintains a number of separate stacks:
4697:
4698: @cindex data stack
4699: @cindex parameter stack
4700: @itemize @bullet
4701: @item
4702: A data stack (also known as the @dfn{parameter stack}) -- for
4703: characters, cells, addresses, and double cells.
4704:
4705: @cindex floating-point stack
4706: @item
4707: A floating point stack -- for holding floating point (FP) numbers.
4708:
4709: @cindex return stack
4710: @item
4711: A return stack -- for holding the return addresses of colon
4712: definitions and other (non-FP) data.
4713:
4714: @cindex locals stack
4715: @item
4716: A locals stack -- for holding local variables.
4717: @end itemize
4718:
4719: @menu
4720: * Data stack::
4721: * Floating point stack::
4722: * Return stack::
4723: * Locals stack::
4724: * Stack pointer manipulation::
4725: @end menu
4726:
4727: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4728: @subsection Data stack
4729: @cindex data stack manipulation words
4730: @cindex stack manipulations words, data stack
4731:
4732:
4733: doc-drop
4734: doc-nip
4735: doc-dup
4736: doc-over
4737: doc-tuck
4738: doc-swap
4739: doc-pick
4740: doc-rot
4741: doc--rot
4742: doc-?dup
4743: doc-roll
4744: doc-2drop
4745: doc-2nip
4746: doc-2dup
4747: doc-2over
4748: doc-2tuck
4749: doc-2swap
4750: doc-2rot
4751:
4752:
4753: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4754: @subsection Floating point stack
4755: @cindex floating-point stack manipulation words
4756: @cindex stack manipulation words, floating-point stack
4757:
4758: Whilst every sane Forth has a separate floating-point stack, it is not
4759: strictly required; an ANS Forth system could theoretically keep
4760: floating-point numbers on the data stack. As an additional difficulty,
4761: you don't know how many cells a floating-point number takes. It is
4762: reportedly possible to write words in a way that they work also for a
4763: unified stack model, but we do not recommend trying it. Instead, just
4764: say that your program has an environmental dependency on a separate
4765: floating-point stack.
4766:
4767: doc-floating-stack
4768:
4769: doc-fdrop
4770: doc-fnip
4771: doc-fdup
4772: doc-fover
4773: doc-ftuck
4774: doc-fswap
4775: doc-fpick
4776: doc-frot
4777:
4778:
4779: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4780: @subsection Return stack
4781: @cindex return stack manipulation words
4782: @cindex stack manipulation words, return stack
4783:
4784: @cindex return stack and locals
4785: @cindex locals and return stack
4786: A Forth system is allowed to keep local variables on the
4787: return stack. This is reasonable, as local variables usually eliminate
4788: the need to use the return stack explicitly. So, if you want to produce
4789: a standard compliant program and you are using local variables in a
4790: word, forget about return stack manipulations in that word (refer to the
4791: standard document for the exact rules).
4792:
4793: doc->r
4794: doc-r>
4795: doc-r@
4796: doc-rdrop
4797: doc-2>r
4798: doc-2r>
4799: doc-2r@
4800: doc-2rdrop
4801:
4802:
4803: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4804: @subsection Locals stack
4805:
4806: Gforth uses an extra locals stack. It is described, along with the
4807: reasons for its existence, in @ref{Locals implementation}.
4808:
4809: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4810: @subsection Stack pointer manipulation
4811: @cindex stack pointer manipulation words
4812:
4813: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
4814: doc-sp0
4815: doc-sp@
4816: doc-sp!
4817: doc-fp0
4818: doc-fp@
4819: doc-fp!
4820: doc-rp0
4821: doc-rp@
4822: doc-rp!
4823: doc-lp0
4824: doc-lp@
4825: doc-lp!
4826:
4827:
4828: @node Memory, Control Structures, Stack Manipulation, Words
4829: @section Memory
4830: @cindex memory words
4831:
4832: @menu
4833: * Memory model::
4834: * Dictionary allocation::
4835: * Heap Allocation::
4836: * Memory Access::
4837: * Address arithmetic::
4838: * Memory Blocks::
4839: @end menu
4840:
4841: In addition to the standard Forth memory allocation words, there is also
4842: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4843: garbage collector}.
4844:
4845: @node Memory model, Dictionary allocation, Memory, Memory
4846: @subsection ANS Forth and Gforth memory models
4847:
4848: @c The ANS Forth description is a mess (e.g., is the heap part of
4849: @c the dictionary?), so let's not stick to closely with it.
4850:
4851: ANS Forth considers a Forth system as consisting of several address
4852: spaces, of which only @dfn{data space} is managed and accessible with
4853: the memory words. Memory not necessarily in data space includes the
4854: stacks, the code (called code space) and the headers (called name
4855: space). In Gforth everything is in data space, but the code for the
4856: primitives is usually read-only.
4857:
4858: Data space is divided into a number of areas: The (data space portion of
4859: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4860: refer to the search data structure embodied in word lists and headers,
4861: because it is used for looking up names, just as you would in a
4862: conventional dictionary.}, the heap, and a number of system-allocated
4863: buffers.
4864:
4865: @cindex address arithmetic restrictions, ANS vs. Gforth
4866: @cindex contiguous regions, ANS vs. Gforth
4867: In ANS Forth data space is also divided into contiguous regions. You
4868: can only use address arithmetic within a contiguous region, not between
4869: them. Usually each allocation gives you one contiguous region, but the
4870: dictionary allocation words have additional rules (@pxref{Dictionary
4871: allocation}).
4872:
4873: Gforth provides one big address space, and address arithmetic can be
4874: performed between any addresses. However, in the dictionary headers or
4875: code are interleaved with data, so almost the only contiguous data space
4876: regions there are those described by ANS Forth as contiguous; but you
4877: can be sure that the dictionary is allocated towards increasing
4878: addresses even between contiguous regions. The memory order of
4879: allocations in the heap is platform-dependent (and possibly different
4880: from one run to the next).
4881:
4882:
4883: @node Dictionary allocation, Heap Allocation, Memory model, Memory
4884: @subsection Dictionary allocation
4885: @cindex reserving data space
4886: @cindex data space - reserving some
4887:
4888: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
4889: you want to deallocate X, you also deallocate everything
4890: allocated after X.
4891:
4892: @cindex contiguous regions in dictionary allocation
4893: The allocations using the words below are contiguous and grow the region
4894: towards increasing addresses. Other words that allocate dictionary
4895: memory of any kind (i.e., defining words including @code{:noname}) end
4896: the contiguous region and start a new one.
4897:
4898: In ANS Forth only @code{create}d words are guaranteed to produce an
4899: address that is the start of the following contiguous region. In
4900: particular, the cell allocated by @code{variable} is not guaranteed to
4901: be contiguous with following @code{allot}ed memory.
4902:
4903: You can deallocate memory by using @code{allot} with a negative argument
4904: (with some restrictions, see @code{allot}). For larger deallocations use
4905: @code{marker}.
4906:
4907:
4908: doc-here
4909: doc-unused
4910: doc-allot
4911: doc-c,
4912: doc-f,
4913: doc-,
4914: doc-2,
4915:
4916: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
4917: course you should allocate memory in an aligned way, too. I.e., before
4918: allocating allocating a cell, @code{here} must be cell-aligned, etc.
4919: The words below align @code{here} if it is not already. Basically it is
4920: only already aligned for a type, if the last allocation was a multiple
4921: of the size of this type and if @code{here} was aligned for this type
4922: before.
4923:
4924: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
4925: ANS Forth (@code{maxalign}ed in Gforth).
4926:
4927: doc-align
4928: doc-falign
4929: doc-sfalign
4930: doc-dfalign
4931: doc-maxalign
4932: doc-cfalign
4933:
4934:
4935: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
4936: @subsection Heap allocation
4937: @cindex heap allocation
4938: @cindex dynamic allocation of memory
4939: @cindex memory-allocation word set
4940:
4941: @cindex contiguous regions and heap allocation
4942: Heap allocation supports deallocation of allocated memory in any
4943: order. Dictionary allocation is not affected by it (i.e., it does not
4944: end a contiguous region). In Gforth, these words are implemented using
4945: the standard C library calls malloc(), free() and resize().
4946:
4947: The memory region produced by one invocation of @code{allocate} or
4948: @code{resize} is internally contiguous. There is no contiguity between
4949: such a region and any other region (including others allocated from the
4950: heap).
4951:
4952: doc-allocate
4953: doc-free
4954: doc-resize
4955:
4956:
4957: @node Memory Access, Address arithmetic, Heap Allocation, Memory
4958: @subsection Memory Access
4959: @cindex memory access words
4960:
4961: doc-@
4962: doc-!
4963: doc-+!
4964: doc-c@
4965: doc-c!
4966: doc-2@
4967: doc-2!
4968: doc-f@
4969: doc-f!
4970: doc-sf@
4971: doc-sf!
4972: doc-df@
4973: doc-df!
4974:
4975:
4976: @node Address arithmetic, Memory Blocks, Memory Access, Memory
4977: @subsection Address arithmetic
4978: @cindex address arithmetic words
4979:
4980: Address arithmetic is the foundation on which you can build data
4981: structures like arrays, records (@pxref{Structures}) and objects
4982: (@pxref{Object-oriented Forth}).
4983:
4984: @cindex address unit
4985: @cindex au (address unit)
4986: ANS Forth does not specify the sizes of the data types. Instead, it
4987: offers a number of words for computing sizes and doing address
4988: arithmetic. Address arithmetic is performed in terms of address units
4989: (aus); on most systems the address unit is one byte. Note that a
4990: character may have more than one au, so @code{chars} is no noop (on
4991: platforms where it is a noop, it compiles to nothing).
4992:
4993: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
4994: you have the address of a cell, perform @code{1 cells +}, and you will
4995: have the address of the next cell.
4996:
4997: @cindex contiguous regions and address arithmetic
4998: In ANS Forth you can perform address arithmetic only within a contiguous
4999: region, i.e., if you have an address into one region, you can only add
5000: and subtract such that the result is still within the region; you can
5001: only subtract or compare addresses from within the same contiguous
5002: region. Reasons: several contiguous regions can be arranged in memory
5003: in any way; on segmented systems addresses may have unusual
5004: representations, such that address arithmetic only works within a
5005: region. Gforth provides a few more guarantees (linear address space,
5006: dictionary grows upwards), but in general I have found it easy to stay
5007: within contiguous regions (exception: computing and comparing to the
5008: address just beyond the end of an array).
5009:
5010: @cindex alignment of addresses for types
5011: ANS Forth also defines words for aligning addresses for specific
5012: types. Many computers require that accesses to specific data types
5013: must only occur at specific addresses; e.g., that cells may only be
5014: accessed at addresses divisible by 4. Even if a machine allows unaligned
5015: accesses, it can usually perform aligned accesses faster.
5016:
5017: For the performance-conscious: alignment operations are usually only
5018: necessary during the definition of a data structure, not during the
5019: (more frequent) accesses to it.
5020:
5021: ANS Forth defines no words for character-aligning addresses. This is not
5022: an oversight, but reflects the fact that addresses that are not
5023: char-aligned have no use in the standard and therefore will not be
5024: created.
5025:
5026: @cindex @code{CREATE} and alignment
5027: ANS Forth guarantees that addresses returned by @code{CREATE}d words
5028: are cell-aligned; in addition, Gforth guarantees that these addresses
5029: are aligned for all purposes.
5030:
5031: Note that the ANS Forth word @code{char} has nothing to do with address
5032: arithmetic.
5033:
5034:
5035: doc-chars
5036: doc-char+
5037: doc-cells
5038: doc-cell+
5039: doc-cell
5040: doc-aligned
5041: doc-floats
5042: doc-float+
5043: doc-float
5044: doc-faligned
5045: doc-sfloats
5046: doc-sfloat+
5047: doc-sfaligned
5048: doc-dfloats
5049: doc-dfloat+
5050: doc-dfaligned
5051: doc-maxaligned
5052: doc-cfaligned
5053: doc-address-unit-bits
5054:
5055:
5056: @node Memory Blocks, , Address arithmetic, Memory
5057: @subsection Memory Blocks
5058: @cindex memory block words
5059: @cindex character strings - moving and copying
5060:
5061: Memory blocks often represent character strings; For ways of storing
5062: character strings in memory see @ref{String Formats}. For other
5063: string-processing words see @ref{Displaying characters and strings}.
5064:
5065: A few of these words work on address unit blocks. In that case, you
5066: usually have to insert @code{CHARS} before the word when working on
5067: character strings. Most words work on character blocks, and expect a
5068: char-aligned address.
5069:
5070: When copying characters between overlapping memory regions, use
5071: @code{chars move} or choose carefully between @code{cmove} and
5072: @code{cmove>}.
5073:
5074: doc-move
5075: doc-erase
5076: doc-cmove
5077: doc-cmove>
5078: doc-fill
5079: doc-blank
5080: doc-compare
5081: doc-str=
5082: doc-str<
5083: doc-string-prefix?
5084: doc-search
5085: doc--trailing
5086: doc-/string
5087: doc-bounds
5088:
5089:
5090: @comment TODO examples
5091:
5092:
5093: @node Control Structures, Defining Words, Memory, Words
5094: @section Control Structures
5095: @cindex control structures
5096:
5097: Control structures in Forth cannot be used interpretively, only in a
5098: colon definition@footnote{To be precise, they have no interpretation
5099: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5100: not like this limitation, but have not seen a satisfying way around it
5101: yet, although many schemes have been proposed.
5102:
5103: @menu
5104: * Selection:: IF ... ELSE ... ENDIF
5105: * Simple Loops:: BEGIN ...
5106: * Counted Loops:: DO
5107: * Arbitrary control structures::
5108: * Calls and returns::
5109: * Exception Handling::
5110: @end menu
5111:
5112: @node Selection, Simple Loops, Control Structures, Control Structures
5113: @subsection Selection
5114: @cindex selection control structures
5115: @cindex control structures for selection
5116:
5117: @cindex @code{IF} control structure
5118: @example
5119: @i{flag}
5120: IF
5121: @i{code}
5122: ENDIF
5123: @end example
5124: @noindent
5125:
5126: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5127: with any bit set represents truth) @i{code} is executed.
5128:
5129: @example
5130: @i{flag}
5131: IF
5132: @i{code1}
5133: ELSE
5134: @i{code2}
5135: ENDIF
5136: @end example
5137:
5138: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5139: executed.
5140:
5141: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5142: standard, and @code{ENDIF} is not, although it is quite popular. We
5143: recommend using @code{ENDIF}, because it is less confusing for people
5144: who also know other languages (and is not prone to reinforcing negative
5145: prejudices against Forth in these people). Adding @code{ENDIF} to a
5146: system that only supplies @code{THEN} is simple:
5147: @example
5148: : ENDIF POSTPONE then ; immediate
5149: @end example
5150:
5151: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5152: (adv.)} has the following meanings:
5153: @quotation
5154: ... 2b: following next after in order ... 3d: as a necessary consequence
5155: (if you were there, then you saw them).
5156: @end quotation
5157: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5158: and many other programming languages has the meaning 3d.]
5159:
5160: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
5161: you can avoid using @code{?dup}. Using these alternatives is also more
5162: efficient than using @code{?dup}. Definitions in ANS Forth
5163: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5164: @file{compat/control.fs}.
5165:
5166: @cindex @code{CASE} control structure
5167: @example
5168: @i{n}
5169: CASE
5170: @i{n1} OF @i{code1} ENDOF
5171: @i{n2} OF @i{code2} ENDOF
5172: @dots{}
5173: ( n ) @i{default-code} ( n )
5174: ENDCASE
5175: @end example
5176:
5177: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If no
5178: @i{ni} matches, the optional @i{default-code} is executed. The optional
5179: default case can be added by simply writing the code after the last
5180: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
5181: not consume it.
5182:
5183: @progstyle
5184: To keep the code understandable, you should ensure that on all paths
5185: through a selection construct the stack is changed in the same way
5186: (wrt. number and types of stack items consumed and pushed).
5187:
5188: @node Simple Loops, Counted Loops, Selection, Control Structures
5189: @subsection Simple Loops
5190: @cindex simple loops
5191: @cindex loops without count
5192:
5193: @cindex @code{WHILE} loop
5194: @example
5195: BEGIN
5196: @i{code1}
5197: @i{flag}
5198: WHILE
5199: @i{code2}
5200: REPEAT
5201: @end example
5202:
5203: @i{code1} is executed and @i{flag} is computed. If it is true,
5204: @i{code2} is executed and the loop is restarted; If @i{flag} is
5205: false, execution continues after the @code{REPEAT}.
5206:
5207: @cindex @code{UNTIL} loop
5208: @example
5209: BEGIN
5210: @i{code}
5211: @i{flag}
5212: UNTIL
5213: @end example
5214:
5215: @i{code} is executed. The loop is restarted if @code{flag} is false.
5216:
5217: @progstyle
5218: To keep the code understandable, a complete iteration of the loop should
5219: not change the number and types of the items on the stacks.
5220:
5221: @cindex endless loop
5222: @cindex loops, endless
5223: @example
5224: BEGIN
5225: @i{code}
5226: AGAIN
5227: @end example
5228:
5229: This is an endless loop.
5230:
5231: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5232: @subsection Counted Loops
5233: @cindex counted loops
5234: @cindex loops, counted
5235: @cindex @code{DO} loops
5236:
5237: The basic counted loop is:
5238: @example
5239: @i{limit} @i{start}
5240: ?DO
5241: @i{body}
5242: LOOP
5243: @end example
5244:
5245: This performs one iteration for every integer, starting from @i{start}
5246: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
5247: accessed with @code{i}. For example, the loop:
5248: @example
5249: 10 0 ?DO
5250: i .
5251: LOOP
5252: @end example
5253: @noindent
5254: prints @code{0 1 2 3 4 5 6 7 8 9}
5255:
5256: The index of the innermost loop can be accessed with @code{i}, the index
5257: of the next loop with @code{j}, and the index of the third loop with
5258: @code{k}.
5259:
5260:
5261: doc-i
5262: doc-j
5263: doc-k
5264:
5265:
5266: The loop control data are kept on the return stack, so there are some
5267: restrictions on mixing return stack accesses and counted loop words. In
5268: particuler, if you put values on the return stack outside the loop, you
5269: cannot read them inside the loop@footnote{well, not in a way that is
5270: portable.}. If you put values on the return stack within a loop, you
5271: have to remove them before the end of the loop and before accessing the
5272: index of the loop.
5273:
5274: There are several variations on the counted loop:
5275:
5276: @itemize @bullet
5277: @item
5278: @code{LEAVE} leaves the innermost counted loop immediately; execution
5279: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5280:
5281: @example
5282: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5283: @end example
5284: prints @code{0 1 2 3}
5285:
5286:
5287: @item
5288: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5289: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5290: return stack so @code{EXIT} can get to its return address. For example:
5291:
5292: @example
5293: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5294: @end example
5295: prints @code{0 1 2 3}
5296:
5297:
5298: @item
5299: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
5300: (and @code{LOOP} iterates until they become equal by wrap-around
5301: arithmetic). This behaviour is usually not what you want. Therefore,
5302: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
5303: @code{?DO}), which do not enter the loop if @i{start} is greater than
5304: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
5305: unsigned loop parameters.
5306:
5307: @item
5308: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5309: the loop, independent of the loop parameters. Do not use @code{DO}, even
5310: if you know that the loop is entered in any case. Such knowledge tends
5311: to become invalid during maintenance of a program, and then the
5312: @code{DO} will make trouble.
5313:
5314: @item
5315: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5316: index by @i{n} instead of by 1. The loop is terminated when the border
5317: between @i{limit-1} and @i{limit} is crossed. E.g.:
5318:
5319: @example
5320: 4 0 +DO i . 2 +LOOP
5321: @end example
5322: @noindent
5323: prints @code{0 2}
5324:
5325: @example
5326: 4 1 +DO i . 2 +LOOP
5327: @end example
5328: @noindent
5329: prints @code{1 3}
5330:
5331: @item
5332: @cindex negative increment for counted loops
5333: @cindex counted loops with negative increment
5334: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
5335:
5336: @example
5337: -1 0 ?DO i . -1 +LOOP
5338: @end example
5339: @noindent
5340: prints @code{0 -1}
5341:
5342: @example
5343: 0 0 ?DO i . -1 +LOOP
5344: @end example
5345: prints nothing.
5346:
5347: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5348: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5349: index by @i{u} each iteration. The loop is terminated when the border
5350: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
5351: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5352:
5353: @example
5354: -2 0 -DO i . 1 -LOOP
5355: @end example
5356: @noindent
5357: prints @code{0 -1}
5358:
5359: @example
5360: -1 0 -DO i . 1 -LOOP
5361: @end example
5362: @noindent
5363: prints @code{0}
5364:
5365: @example
5366: 0 0 -DO i . 1 -LOOP
5367: @end example
5368: @noindent
5369: prints nothing.
5370:
5371: @end itemize
5372:
5373: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
5374: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5375: for these words that uses only standard words is provided in
5376: @file{compat/loops.fs}.
5377:
5378:
5379: @cindex @code{FOR} loops
5380: Another counted loop is:
5381: @example
5382: @i{n}
5383: FOR
5384: @i{body}
5385: NEXT
5386: @end example
5387: This is the preferred loop of native code compiler writers who are too
5388: lazy to optimize @code{?DO} loops properly. This loop structure is not
5389: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5390: @code{i} produces values starting with @i{n} and ending with 0. Other
5391: Forth systems may behave differently, even if they support @code{FOR}
5392: loops. To avoid problems, don't use @code{FOR} loops.
5393:
5394: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5395: @subsection Arbitrary control structures
5396: @cindex control structures, user-defined
5397:
5398: @cindex control-flow stack
5399: ANS Forth permits and supports using control structures in a non-nested
5400: way. Information about incomplete control structures is stored on the
5401: control-flow stack. This stack may be implemented on the Forth data
5402: stack, and this is what we have done in Gforth.
5403:
5404: @cindex @code{orig}, control-flow stack item
5405: @cindex @code{dest}, control-flow stack item
5406: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5407: entry represents a backward branch target. A few words are the basis for
5408: building any control structure possible (except control structures that
5409: need storage, like calls, coroutines, and backtracking).
5410:
5411:
5412: doc-if
5413: doc-ahead
5414: doc-then
5415: doc-begin
5416: doc-until
5417: doc-again
5418: doc-cs-pick
5419: doc-cs-roll
5420:
5421:
5422: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5423: manipulate the control-flow stack in a portable way. Without them, you
5424: would need to know how many stack items are occupied by a control-flow
5425: entry (many systems use one cell. In Gforth they currently take three,
5426: but this may change in the future).
5427:
5428: Some standard control structure words are built from these words:
5429:
5430:
5431: doc-else
5432: doc-while
5433: doc-repeat
5434:
5435:
5436: @noindent
5437: Gforth adds some more control-structure words:
5438:
5439:
5440: doc-endif
5441: doc-?dup-if
5442: doc-?dup-0=-if
5443:
5444:
5445: @noindent
5446: Counted loop words constitute a separate group of words:
5447:
5448:
5449: doc-?do
5450: doc-+do
5451: doc-u+do
5452: doc--do
5453: doc-u-do
5454: doc-do
5455: doc-for
5456: doc-loop
5457: doc-+loop
5458: doc--loop
5459: doc-next
5460: doc-leave
5461: doc-?leave
5462: doc-unloop
5463: doc-done
5464:
5465:
5466: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5467: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
5468: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5469: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5470: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5471: resolved (by using one of the loop-ending words or @code{DONE}).
5472:
5473: @noindent
5474: Another group of control structure words are:
5475:
5476:
5477: doc-case
5478: doc-endcase
5479: doc-of
5480: doc-endof
5481:
5482:
5483: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5484: @code{CS-ROLL}.
5485:
5486: @subsubsection Programming Style
5487: @cindex control structures programming style
5488: @cindex programming style, arbitrary control structures
5489:
5490: In order to ensure readability we recommend that you do not create
5491: arbitrary control structures directly, but define new control structure
5492: words for the control structure you want and use these words in your
5493: program. For example, instead of writing:
5494:
5495: @example
5496: BEGIN
5497: ...
5498: IF [ 1 CS-ROLL ]
5499: ...
5500: AGAIN THEN
5501: @end example
5502:
5503: @noindent
5504: we recommend defining control structure words, e.g.,
5505:
5506: @example
5507: : WHILE ( DEST -- ORIG DEST )
5508: POSTPONE IF
5509: 1 CS-ROLL ; immediate
5510:
5511: : REPEAT ( orig dest -- )
5512: POSTPONE AGAIN
5513: POSTPONE THEN ; immediate
5514: @end example
5515:
5516: @noindent
5517: and then using these to create the control structure:
5518:
5519: @example
5520: BEGIN
5521: ...
5522: WHILE
5523: ...
5524: REPEAT
5525: @end example
5526:
5527: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5528: @code{WHILE} are predefined, so in this example it would not be
5529: necessary to define them.
5530:
5531: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5532: @subsection Calls and returns
5533: @cindex calling a definition
5534: @cindex returning from a definition
5535:
5536: @cindex recursive definitions
5537: A definition can be called simply be writing the name of the definition
5538: to be called. Normally a definition is invisible during its own
5539: definition. If you want to write a directly recursive definition, you
5540: can use @code{recursive} to make the current definition visible, or
5541: @code{recurse} to call the current definition directly.
5542:
5543:
5544: doc-recursive
5545: doc-recurse
5546:
5547:
5548: @comment TODO add example of the two recursion methods
5549: @quotation
5550: @progstyle
5551: I prefer using @code{recursive} to @code{recurse}, because calling the
5552: definition by name is more descriptive (if the name is well-chosen) than
5553: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5554: implementation, it is much better to read (and think) ``now sort the
5555: partitions'' than to read ``now do a recursive call''.
5556: @end quotation
5557:
5558: For mutual recursion, use @code{Defer}red words, like this:
5559:
5560: @example
5561: Defer foo
5562:
5563: : bar ( ... -- ... )
5564: ... foo ... ;
5565:
5566: :noname ( ... -- ... )
5567: ... bar ... ;
5568: IS foo
5569: @end example
5570:
5571: Deferred words are discussed in more detail in @ref{Deferred words}.
5572:
5573: The current definition returns control to the calling definition when
5574: the end of the definition is reached or @code{EXIT} is encountered.
5575:
5576: doc-exit
5577: doc-;s
5578:
5579:
5580: @node Exception Handling, , Calls and returns, Control Structures
5581: @subsection Exception Handling
5582: @cindex exceptions
5583:
5584: @c quit is a very bad idea for error handling,
5585: @c because it does not translate into a THROW
5586: @c it also does not belong into this chapter
5587:
5588: If a word detects an error condition that it cannot handle, it can
5589: @code{throw} an exception. In the simplest case, this will terminate
5590: your program, and report an appropriate error.
5591:
5592: doc-throw
5593:
5594: @code{Throw} consumes a cell-sized error number on the stack. There are
5595: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5596: Gforth (and most other systems) you can use the iors produced by various
5597: words as error numbers (e.g., a typical use of @code{allocate} is
5598: @code{allocate throw}). Gforth also provides the word @code{exception}
5599: to define your own error numbers (with decent error reporting); an ANS
5600: Forth version of this word (but without the error messages) is available
5601: in @code{compat/except.fs}. And finally, you can use your own error
5602: numbers (anything outside the range -4095..0), but won't get nice error
5603: messages, only numbers. For example, try:
5604:
5605: @example
5606: -10 throw \ ANS defined
5607: -267 throw \ system defined
5608: s" my error" exception throw \ user defined
5609: 7 throw \ arbitrary number
5610: @end example
5611:
5612: doc---exception-exception
5613:
5614: A common idiom to @code{THROW} a specific error if a flag is true is
5615: this:
5616:
5617: @example
5618: @code{( flag ) 0<> @i{errno} and throw}
5619: @end example
5620:
5621: Your program can provide exception handlers to catch exceptions. An
5622: exception handler can be used to correct the problem, or to clean up
5623: some data structures and just throw the exception to the next exception
5624: handler. Note that @code{throw} jumps to the dynamically innermost
5625: exception handler. The system's exception handler is outermost, and just
5626: prints an error and restarts command-line interpretation (or, in batch
5627: mode (i.e., while processing the shell command line), leaves Gforth).
5628:
5629: The ANS Forth way to catch exceptions is @code{catch}:
5630:
5631: doc-catch
5632:
5633: The most common use of exception handlers is to clean up the state when
5634: an error happens. E.g.,
5635:
5636: @example
5637: base @ >r hex \ actually the hex should be inside foo, or we h
5638: ['] foo catch ( nerror|0 )
5639: r> base !
5640: ( nerror|0 ) throw \ pass it on
5641: @end example
5642:
5643: A use of @code{catch} for handling the error @code{myerror} might look
5644: like this:
5645:
5646: @example
5647: ['] foo catch
5648: CASE
5649: myerror OF ... ( do something about it ) ENDOF
5650: dup throw \ default: pass other errors on, do nothing on non-errors
5651: ENDCASE
5652: @end example
5653:
5654: Having to wrap the code into a separate word is often cumbersome,
5655: therefore Gforth provides an alternative syntax:
5656:
5657: @example
5658: TRY
5659: @i{code1}
5660: RECOVER \ optional
5661: @i{code2} \ optional
5662: ENDTRY
5663: @end example
5664:
5665: This performs @i{Code1}. If @i{code1} completes normally, execution
5666: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5667: reset to the state during @code{try}, the throw value is pushed on the
5668: data stack, and execution constinues at @i{code2}, and finally falls
5669: through the @code{endtry} into the following code.
5670:
5671: doc-try
5672: doc-recover
5673: doc-endtry
5674:
5675: The cleanup example from above in this syntax:
5676:
5677: @example
5678: base @ >r TRY
5679: hex foo \ now the hex is placed correctly
5680: 0 \ value for throw
5681: RECOVER ENDTRY
5682: r> base ! throw
5683: @end example
5684:
5685: And here's the error handling example:
5686:
5687: @example
5688: TRY
5689: foo
5690: RECOVER
5691: CASE
5692: myerror OF ... ( do something about it ) ENDOF
5693: throw \ pass other errors on
5694: ENDCASE
5695: ENDTRY
5696: @end example
5697:
5698: @progstyle
5699: As usual, you should ensure that the stack depth is statically known at
5700: the end: either after the @code{throw} for passing on errors, or after
5701: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5702: selection construct for handling the error).
5703:
5704: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5705: and you can provide an error message. @code{Abort} just produces an
5706: ``Aborted'' error.
5707:
5708: The problem with these words is that exception handlers cannot
5709: differentiate between different @code{abort"}s; they just look like
5710: @code{-2 throw} to them (the error message cannot be accessed by
5711: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5712: exception handlers.
5713:
5714: doc-abort"
5715: doc-abort
5716:
5717:
5718:
5719: @c -------------------------------------------------------------
5720: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
5721: @section Defining Words
5722: @cindex defining words
5723:
5724: Defining words are used to extend Forth by creating new entries in the dictionary.
5725:
5726: @menu
5727: * CREATE::
5728: * Variables:: Variables and user variables
5729: * Constants::
5730: * Values:: Initialised variables
5731: * Colon Definitions::
5732: * Anonymous Definitions:: Definitions without names
5733: * Supplying names:: Passing definition names as strings
5734: * User-defined Defining Words::
5735: * Deferred words:: Allow forward references
5736: * Aliases::
5737: @end menu
5738:
5739: @node CREATE, Variables, Defining Words, Defining Words
5740: @subsection @code{CREATE}
5741: @cindex simple defining words
5742: @cindex defining words, simple
5743:
5744: Defining words are used to create new entries in the dictionary. The
5745: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5746: this:
5747:
5748: @example
5749: CREATE new-word1
5750: @end example
5751:
5752: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5753: input stream (@code{new-word1} in our example). It generates a
5754: dictionary entry for @code{new-word1}. When @code{new-word1} is
5755: executed, all that it does is leave an address on the stack. The address
5756: represents the value of the data space pointer (@code{HERE}) at the time
5757: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5758: associating a name with the address of a region of memory.
5759:
5760: doc-create
5761:
5762: Note that in ANS Forth guarantees only for @code{create} that its body
5763: is in dictionary data space (i.e., where @code{here}, @code{allot}
5764: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5765: @code{create}d words can be modified with @code{does>}
5766: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5767: can only be applied to @code{create}d words.
5768:
5769: By extending this example to reserve some memory in data space, we end
5770: up with something like a @i{variable}. Here are two different ways to do
5771: it:
5772:
5773: @example
5774: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5775: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5776: @end example
5777:
5778: The variable can be examined and modified using @code{@@} (``fetch'') and
5779: @code{!} (``store'') like this:
5780:
5781: @example
5782: new-word2 @@ . \ get address, fetch from it and display
5783: 1234 new-word2 ! \ new value, get address, store to it
5784: @end example
5785:
5786: @cindex arrays
5787: A similar mechanism can be used to create arrays. For example, an
5788: 80-character text input buffer:
5789:
5790: @example
5791: CREATE text-buf 80 chars allot
5792:
5793: text-buf 0 chars c@@ \ the 1st character (offset 0)
5794: text-buf 3 chars c@@ \ the 4th character (offset 3)
5795: @end example
5796:
5797: You can build arbitrarily complex data structures by allocating
5798: appropriate areas of memory. For further discussions of this, and to
5799: learn about some Gforth tools that make it easier,
5800: @xref{Structures}.
5801:
5802:
5803: @node Variables, Constants, CREATE, Defining Words
5804: @subsection Variables
5805: @cindex variables
5806:
5807: The previous section showed how a sequence of commands could be used to
5808: generate a variable. As a final refinement, the whole code sequence can
5809: be wrapped up in a defining word (pre-empting the subject of the next
5810: section), making it easier to create new variables:
5811:
5812: @example
5813: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5814: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5815:
5816: myvariableX foo \ variable foo starts off with an unknown value
5817: myvariable0 joe \ whilst joe is initialised to 0
5818:
5819: 45 3 * foo ! \ set foo to 135
5820: 1234 joe ! \ set joe to 1234
5821: 3 joe +! \ increment joe by 3.. to 1237
5822: @end example
5823:
5824: Not surprisingly, there is no need to define @code{myvariable}, since
5825: Forth already has a definition @code{Variable}. ANS Forth does not
5826: guarantee that a @code{Variable} is initialised when it is created
5827: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5828: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5829: like @code{myvariable0}). Forth also provides @code{2Variable} and
5830: @code{fvariable} for double and floating-point variables, respectively
5831: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
5832: store a boolean, you can use @code{on} and @code{off} to toggle its
5833: state.
5834:
5835: doc-variable
5836: doc-2variable
5837: doc-fvariable
5838:
5839: @cindex user variables
5840: @cindex user space
5841: The defining word @code{User} behaves in the same way as @code{Variable}.
5842: The difference is that it reserves space in @i{user (data) space} rather
5843: than normal data space. In a Forth system that has a multi-tasker, each
5844: task has its own set of user variables.
5845:
5846: doc-user
5847: @c doc-udp
5848: @c doc-uallot
5849:
5850: @comment TODO is that stuff about user variables strictly correct? Is it
5851: @comment just terminal tasks that have user variables?
5852: @comment should document tasker.fs (with some examples) elsewhere
5853: @comment in this manual, then expand on user space and user variables.
5854:
5855: @node Constants, Values, Variables, Defining Words
5856: @subsection Constants
5857: @cindex constants
5858:
5859: @code{Constant} allows you to declare a fixed value and refer to it by
5860: name. For example:
5861:
5862: @example
5863: 12 Constant INCHES-PER-FOOT
5864: 3E+08 fconstant SPEED-O-LIGHT
5865: @end example
5866:
5867: A @code{Variable} can be both read and written, so its run-time
5868: behaviour is to supply an address through which its current value can be
5869: manipulated. In contrast, the value of a @code{Constant} cannot be
5870: changed once it has been declared@footnote{Well, often it can be -- but
5871: not in a Standard, portable way. It's safer to use a @code{Value} (read
5872: on).} so it's not necessary to supply the address -- it is more
5873: efficient to return the value of the constant directly. That's exactly
5874: what happens; the run-time effect of a constant is to put its value on
5875: the top of the stack (You can find one
5876: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
5877:
5878: Forth also provides @code{2Constant} and @code{fconstant} for defining
5879: double and floating-point constants, respectively.
5880:
5881: doc-constant
5882: doc-2constant
5883: doc-fconstant
5884:
5885: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
5886: @c nac-> How could that not be true in an ANS Forth? You can't define a
5887: @c constant, use it and then delete the definition of the constant..
5888:
5889: @c anton->An ANS Forth system can compile a constant to a literal; On
5890: @c decompilation you would see only the number, just as if it had been used
5891: @c in the first place. The word will stay, of course, but it will only be
5892: @c used by the text interpreter (no run-time duties, except when it is
5893: @c POSTPONEd or somesuch).
5894:
5895: @c nac:
5896: @c I agree that it's rather deep, but IMO it is an important difference
5897: @c relative to other programming languages.. often it's annoying: it
5898: @c certainly changes my programming style relative to C.
5899:
5900: @c anton: In what way?
5901:
5902: Constants in Forth behave differently from their equivalents in other
5903: programming languages. In other languages, a constant (such as an EQU in
5904: assembler or a #define in C) only exists at compile-time; in the
5905: executable program the constant has been translated into an absolute
5906: number and, unless you are using a symbolic debugger, it's impossible to
5907: know what abstract thing that number represents. In Forth a constant has
5908: an entry in the header space and remains there after the code that uses
5909: it has been defined. In fact, it must remain in the dictionary since it
5910: has run-time duties to perform. For example:
5911:
5912: @example
5913: 12 Constant INCHES-PER-FOOT
5914: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
5915: @end example
5916:
5917: @cindex in-lining of constants
5918: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
5919: associated with the constant @code{INCHES-PER-FOOT}. If you use
5920: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
5921: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
5922: attempt to optimise constants by in-lining them where they are used. You
5923: can force Gforth to in-line a constant like this:
5924:
5925: @example
5926: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
5927: @end example
5928:
5929: If you use @code{see} to decompile @i{this} version of
5930: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
5931: longer present. To understand how this works, read
5932: @ref{Interpret/Compile states}, and @ref{Literals}.
5933:
5934: In-lining constants in this way might improve execution time
5935: fractionally, and can ensure that a constant is now only referenced at
5936: compile-time. However, the definition of the constant still remains in
5937: the dictionary. Some Forth compilers provide a mechanism for controlling
5938: a second dictionary for holding transient words such that this second
5939: dictionary can be deleted later in order to recover memory
5940: space. However, there is no standard way of doing this.
5941:
5942:
5943: @node Values, Colon Definitions, Constants, Defining Words
5944: @subsection Values
5945: @cindex values
5946:
5947: A @code{Value} behaves like a @code{Constant}, but it can be changed.
5948: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
5949: (not in ANS Forth) you can access (and change) a @code{value} also with
5950: @code{>body}.
5951:
5952: Here are some
5953: examples:
5954:
5955: @example
5956: 12 Value APPLES \ Define APPLES with an initial value of 12
5957: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
5958: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
5959: APPLES \ puts 35 on the top of the stack.
5960: @end example
5961:
5962: doc-value
5963: doc-to
5964:
5965:
5966:
5967: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
5968: @subsection Colon Definitions
5969: @cindex colon definitions
5970:
5971: @example
5972: : name ( ... -- ... )
5973: word1 word2 word3 ;
5974: @end example
5975:
5976: @noindent
5977: Creates a word called @code{name} that, upon execution, executes
5978: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
5979:
5980: The explanation above is somewhat superficial. For simple examples of
5981: colon definitions see @ref{Your first definition}. For an in-depth
5982: discussion of some of the issues involved, @xref{Interpretation and
5983: Compilation Semantics}.
5984:
5985: doc-:
5986: doc-;
5987:
5988:
5989: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
5990: @subsection Anonymous Definitions
5991: @cindex colon definitions
5992: @cindex defining words without name
5993:
5994: Sometimes you want to define an @dfn{anonymous word}; a word without a
5995: name. You can do this with:
5996:
5997: doc-:noname
5998:
5999: This leaves the execution token for the word on the stack after the
6000: closing @code{;}. Here's an example in which a deferred word is
6001: initialised with an @code{xt} from an anonymous colon definition:
6002:
6003: @example
6004: Defer deferred
6005: :noname ( ... -- ... )
6006: ... ;
6007: IS deferred
6008: @end example
6009:
6010: @noindent
6011: Gforth provides an alternative way of doing this, using two separate
6012: words:
6013:
6014: doc-noname
6015: @cindex execution token of last defined word
6016: doc-latestxt
6017:
6018: @noindent
6019: The previous example can be rewritten using @code{noname} and
6020: @code{latestxt}:
6021:
6022: @example
6023: Defer deferred
6024: noname : ( ... -- ... )
6025: ... ;
6026: latestxt IS deferred
6027: @end example
6028:
6029: @noindent
6030: @code{noname} works with any defining word, not just @code{:}.
6031:
6032: @code{latestxt} also works when the last word was not defined as
6033: @code{noname}. It does not work for combined words, though. It also has
6034: the useful property that is is valid as soon as the header for a
6035: definition has been built. Thus:
6036:
6037: @example
6038: latestxt . : foo [ latestxt . ] ; ' foo .
6039: @end example
6040:
6041: @noindent
6042: prints 3 numbers; the last two are the same.
6043:
6044: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6045: @subsection Supplying the name of a defined word
6046: @cindex names for defined words
6047: @cindex defining words, name given in a string
6048:
6049: By default, a defining word takes the name for the defined word from the
6050: input stream. Sometimes you want to supply the name from a string. You
6051: can do this with:
6052:
6053: doc-nextname
6054:
6055: For example:
6056:
6057: @example
6058: s" foo" nextname create
6059: @end example
6060:
6061: @noindent
6062: is equivalent to:
6063:
6064: @example
6065: create foo
6066: @end example
6067:
6068: @noindent
6069: @code{nextname} works with any defining word.
6070:
6071:
6072: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
6073: @subsection User-defined Defining Words
6074: @cindex user-defined defining words
6075: @cindex defining words, user-defined
6076:
6077: You can create a new defining word by wrapping defining-time code around
6078: an existing defining word and putting the sequence in a colon
6079: definition.
6080:
6081: @c anton: This example is very complex and leads in a quite different
6082: @c direction from the CREATE-DOES> stuff that follows. It should probably
6083: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6084: @c subsection of Defining Words)
6085:
6086: For example, suppose that you have a word @code{stats} that
6087: gathers statistics about colon definitions given the @i{xt} of the
6088: definition, and you want every colon definition in your application to
6089: make a call to @code{stats}. You can define and use a new version of
6090: @code{:} like this:
6091:
6092: @example
6093: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6094: ... ; \ other code
6095:
6096: : my: : latestxt postpone literal ['] stats compile, ;
6097:
6098: my: foo + - ;
6099: @end example
6100:
6101: When @code{foo} is defined using @code{my:} these steps occur:
6102:
6103: @itemize @bullet
6104: @item
6105: @code{my:} is executed.
6106: @item
6107: The @code{:} within the definition (the one between @code{my:} and
6108: @code{latestxt}) is executed, and does just what it always does; it parses
6109: the input stream for a name, builds a dictionary header for the name
6110: @code{foo} and switches @code{state} from interpret to compile.
6111: @item
6112: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
6113: being defined -- @code{foo} -- onto the stack.
6114: @item
6115: The code that was produced by @code{postpone literal} is executed; this
6116: causes the value on the stack to be compiled as a literal in the code
6117: area of @code{foo}.
6118: @item
6119: The code @code{['] stats} compiles a literal into the definition of
6120: @code{my:}. When @code{compile,} is executed, that literal -- the
6121: execution token for @code{stats} -- is layed down in the code area of
6122: @code{foo} , following the literal@footnote{Strictly speaking, the
6123: mechanism that @code{compile,} uses to convert an @i{xt} into something
6124: in the code area is implementation-dependent. A threaded implementation
6125: might spit out the execution token directly whilst another
6126: implementation might spit out a native code sequence.}.
6127: @item
6128: At this point, the execution of @code{my:} is complete, and control
6129: returns to the text interpreter. The text interpreter is in compile
6130: state, so subsequent text @code{+ -} is compiled into the definition of
6131: @code{foo} and the @code{;} terminates the definition as always.
6132: @end itemize
6133:
6134: You can use @code{see} to decompile a word that was defined using
6135: @code{my:} and see how it is different from a normal @code{:}
6136: definition. For example:
6137:
6138: @example
6139: : bar + - ; \ like foo but using : rather than my:
6140: see bar
6141: : bar
6142: + - ;
6143: see foo
6144: : foo
6145: 107645672 stats + - ;
6146:
6147: \ use ' stats . to show that 107645672 is the xt for stats
6148: @end example
6149:
6150: You can use techniques like this to make new defining words in terms of
6151: @i{any} existing defining word.
6152:
6153:
6154: @cindex defining defining words
6155: @cindex @code{CREATE} ... @code{DOES>}
6156: If you want the words defined with your defining words to behave
6157: differently from words defined with standard defining words, you can
6158: write your defining word like this:
6159:
6160: @example
6161: : def-word ( "name" -- )
6162: CREATE @i{code1}
6163: DOES> ( ... -- ... )
6164: @i{code2} ;
6165:
6166: def-word name
6167: @end example
6168:
6169: @cindex child words
6170: This fragment defines a @dfn{defining word} @code{def-word} and then
6171: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6172: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6173: is not executed at this time. The word @code{name} is sometimes called a
6174: @dfn{child} of @code{def-word}.
6175:
6176: When you execute @code{name}, the address of the body of @code{name} is
6177: put on the data stack and @i{code2} is executed (the address of the body
6178: of @code{name} is the address @code{HERE} returns immediately after the
6179: @code{CREATE}, i.e., the address a @code{create}d word returns by
6180: default).
6181:
6182: @c anton:
6183: @c www.dictionary.com says:
6184: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6185: @c several generations of absence, usually caused by the chance
6186: @c recombination of genes. 2.An individual or a part that exhibits
6187: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6188: @c of previous behavior after a period of absence.
6189: @c
6190: @c Doesn't seem to fit.
6191:
6192: @c @cindex atavism in child words
6193: You can use @code{def-word} to define a set of child words that behave
6194: similarly; they all have a common run-time behaviour determined by
6195: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6196: body of the child word. The structure of the data is common to all
6197: children of @code{def-word}, but the data values are specific -- and
6198: private -- to each child word. When a child word is executed, the
6199: address of its private data area is passed as a parameter on TOS to be
6200: used and manipulated@footnote{It is legitimate both to read and write to
6201: 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:
6205:
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:
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:
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:
6228: @noindent
6229: Then using @code{name1 action1} is equivalent to using @code{name}.
6230:
6231: The classic example is that you can define @code{CONSTANT} in this way:
6232:
6233: @example
6234: : CONSTANT ( w "name" -- )
6235: CREATE ,
6236: DOES> ( -- w )
6237: @@ ;
6238: @end example
6239:
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
6247: @code{,}. When @code{five} is executed, the address of the body is put on
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> ( -- )
6264: @@ . ;
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}.
6280:
6281: @cindex stack effect of @code{DOES>}-parts
6282: @cindex @code{DOES>}-parts, stack effect
6283: In the examples above the stack comment after the @code{DOES>} specifies
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).
6289:
6290: @menu
6291: * CREATE..DOES> applications::
6292: * CREATE..DOES> details::
6293: * Advanced does> usage example::
6294: * @code{Const-does>}::
6295: @end menu
6296:
6297: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
6298: @subsubsection Applications of @code{CREATE..DOES>}
6299: @cindex @code{CREATE} ... @code{DOES>}, applications
6300:
6301: You may wonder how to use this feature. Here are some usage patterns:
6302:
6303: @cindex factoring similar colon definitions
6304: When you see a sequence of code occurring several times, and you can
6305: identify a meaning, you will factor it out as a colon definition. When
6306: you see similar colon definitions, you can factor them using
6307: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6308: that look very similar:
6309: @example
6310: : ori, ( reg-target reg-source n -- )
6311: 0 asm-reg-reg-imm ;
6312: : andi, ( reg-target reg-source n -- )
6313: 1 asm-reg-reg-imm ;
6314: @end example
6315:
6316: @noindent
6317: This could be factored with:
6318: @example
6319: : reg-reg-imm ( op-code -- )
6320: CREATE ,
6321: DOES> ( reg-target reg-source n -- )
6322: @@ asm-reg-reg-imm ;
6323:
6324: 0 reg-reg-imm ori,
6325: 1 reg-reg-imm andi,
6326: @end example
6327:
6328: @cindex currying
6329: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6330: supply a part of the parameters for a word (known as @dfn{currying} in
6331: the functional language community). E.g., @code{+} needs two
6332: parameters. Creating versions of @code{+} with one parameter fixed can
6333: be done like this:
6334:
6335: @example
6336: : curry+ ( n1 "name" -- )
6337: CREATE ,
6338: DOES> ( n2 -- n1+n2 )
6339: @@ + ;
6340:
6341: 3 curry+ 3+
6342: -2 curry+ 2-
6343: @end example
6344:
6345:
6346: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
6347: @subsubsection The gory details of @code{CREATE..DOES>}
6348: @cindex @code{CREATE} ... @code{DOES>}, details
6349:
6350: doc-does>
6351:
6352: @cindex @code{DOES>} in a separate definition
6353: This means that you need not use @code{CREATE} and @code{DOES>} in the
6354: same definition; you can put the @code{DOES>}-part in a separate
6355: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
6356: @example
6357: : does1
6358: DOES> ( ... -- ... )
6359: ... ;
6360:
6361: : does2
6362: DOES> ( ... -- ... )
6363: ... ;
6364:
6365: : def-word ( ... -- ... )
6366: create ...
6367: IF
6368: does1
6369: ELSE
6370: does2
6371: ENDIF ;
6372: @end example
6373:
6374: In this example, the selection of whether to use @code{does1} or
6375: @code{does2} is made at definition-time; at the time that the child word is
6376: @code{CREATE}d.
6377:
6378: @cindex @code{DOES>} in interpretation state
6379: In a standard program you can apply a @code{DOES>}-part only if the last
6380: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6381: will override the behaviour of the last word defined in any case. In a
6382: standard program, you can use @code{DOES>} only in a colon
6383: definition. In Gforth, you can also use it in interpretation state, in a
6384: kind of one-shot mode; for example:
6385: @example
6386: CREATE name ( ... -- ... )
6387: @i{initialization}
6388: DOES>
6389: @i{code} ;
6390: @end example
6391:
6392: @noindent
6393: is equivalent to the standard:
6394: @example
6395: :noname
6396: DOES>
6397: @i{code} ;
6398: CREATE name EXECUTE ( ... -- ... )
6399: @i{initialization}
6400: @end example
6401:
6402: doc->body
6403:
6404: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
6405: @subsubsection Advanced does> usage example
6406:
6407: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6408: for disassembling instructions, that follow a very repetetive scheme:
6409:
6410: @example
6411: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6412: @var{entry-num} cells @var{table} + !
6413: @end example
6414:
6415: Of course, this inspires the idea to factor out the commonalities to
6416: allow a definition like
6417:
6418: @example
6419: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6420: @end example
6421:
6422: The parameters @var{disasm-operands} and @var{table} are usually
6423: correlated. Moreover, before I wrote the disassembler, there already
6424: existed code that defines instructions like this:
6425:
6426: @example
6427: @var{entry-num} @var{inst-format} @var{inst-name}
6428: @end example
6429:
6430: This code comes from the assembler and resides in
6431: @file{arch/mips/insts.fs}.
6432:
6433: So I had to define the @var{inst-format} words that performed the scheme
6434: above when executed. At first I chose to use run-time code-generation:
6435:
6436: @example
6437: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6438: :noname Postpone @var{disasm-operands}
6439: name Postpone sliteral Postpone type Postpone ;
6440: swap cells @var{table} + ! ;
6441: @end example
6442:
6443: Note that this supplies the other two parameters of the scheme above.
6444:
6445: An alternative would have been to write this using
6446: @code{create}/@code{does>}:
6447:
6448: @example
6449: : @var{inst-format} ( entry-num "name" -- )
6450: here name string, ( entry-num c-addr ) \ parse and save "name"
6451: noname create , ( entry-num )
6452: latestxt swap cells @var{table} + !
6453: does> ( addr w -- )
6454: \ disassemble instruction w at addr
6455: @@ >r
6456: @var{disasm-operands}
6457: r> count type ;
6458: @end example
6459:
6460: Somehow the first solution is simpler, mainly because it's simpler to
6461: shift a string from definition-time to use-time with @code{sliteral}
6462: than with @code{string,} and friends.
6463:
6464: I wrote a lot of words following this scheme and soon thought about
6465: factoring out the commonalities among them. Note that this uses a
6466: two-level defining word, i.e., a word that defines ordinary defining
6467: words.
6468:
6469: This time a solution involving @code{postpone} and friends seemed more
6470: difficult (try it as an exercise), so I decided to use a
6471: @code{create}/@code{does>} word; since I was already at it, I also used
6472: @code{create}/@code{does>} for the lower level (try using
6473: @code{postpone} etc. as an exercise), resulting in the following
6474: definition:
6475:
6476: @example
6477: : define-format ( disasm-xt table-xt -- )
6478: \ define an instruction format that uses disasm-xt for
6479: \ disassembling and enters the defined instructions into table
6480: \ table-xt
6481: create 2,
6482: does> ( u "inst" -- )
6483: \ defines an anonymous word for disassembling instruction inst,
6484: \ and enters it as u-th entry into table-xt
6485: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6486: noname create 2, \ define anonymous word
6487: execute latestxt swap ! \ enter xt of defined word into table-xt
6488: does> ( addr w -- )
6489: \ disassemble instruction w at addr
6490: 2@@ >r ( addr w disasm-xt R: c-addr )
6491: execute ( R: c-addr ) \ disassemble operands
6492: r> count type ; \ print name
6493: @end example
6494:
6495: Note that the tables here (in contrast to above) do the @code{cells +}
6496: by themselves (that's why you have to pass an xt). This word is used in
6497: the following way:
6498:
6499: @example
6500: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6501: @end example
6502:
6503: As shown above, the defined instruction format is then used like this:
6504:
6505: @example
6506: @var{entry-num} @var{inst-format} @var{inst-name}
6507: @end example
6508:
6509: In terms of currying, this kind of two-level defining word provides the
6510: parameters in three stages: first @var{disasm-operands} and @var{table},
6511: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6512: the instruction to be disassembled.
6513:
6514: Of course this did not quite fit all the instruction format names used
6515: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6516: the parameters into the right form.
6517:
6518: If you have trouble following this section, don't worry. First, this is
6519: involved and takes time (and probably some playing around) to
6520: understand; second, this is the first two-level
6521: @code{create}/@code{does>} word I have written in seventeen years of
6522: Forth; and if I did not have @file{insts.fs} to start with, I may well
6523: have elected to use just a one-level defining word (with some repeating
6524: of parameters when using the defining word). So it is not necessary to
6525: understand this, but it may improve your understanding of Forth.
6526:
6527:
6528: @node @code{Const-does>}, , Advanced does> usage example, User-defined Defining Words
6529: @subsubsection @code{Const-does>}
6530:
6531: A frequent use of @code{create}...@code{does>} is for transferring some
6532: values from definition-time to run-time. Gforth supports this use with
6533:
6534: doc-const-does>
6535:
6536: A typical use of this word is:
6537:
6538: @example
6539: : curry+ ( n1 "name" -- )
6540: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6541: + ;
6542:
6543: 3 curry+ 3+
6544: @end example
6545:
6546: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6547: definition to run-time.
6548:
6549: The advantages of using @code{const-does>} are:
6550:
6551: @itemize
6552:
6553: @item
6554: You don't have to deal with storing and retrieving the values, i.e.,
6555: your program becomes more writable and readable.
6556:
6557: @item
6558: When using @code{does>}, you have to introduce a @code{@@} that cannot
6559: be optimized away (because you could change the data using
6560: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6561:
6562: @end itemize
6563:
6564: An ANS Forth implementation of @code{const-does>} is available in
6565: @file{compat/const-does.fs}.
6566:
6567:
6568: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6569: @subsection Deferred words
6570: @cindex deferred words
6571:
6572: The defining word @code{Defer} allows you to define a word by name
6573: without defining its behaviour; the definition of its behaviour is
6574: deferred. Here are two situation where this can be useful:
6575:
6576: @itemize @bullet
6577: @item
6578: Where you want to allow the behaviour of a word to be altered later, and
6579: for all precompiled references to the word to change when its behaviour
6580: is changed.
6581: @item
6582: For mutual recursion; @xref{Calls and returns}.
6583: @end itemize
6584:
6585: In the following example, @code{foo} always invokes the version of
6586: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6587: always invokes the version that prints ``@code{Hello}''. There is no way
6588: of getting @code{foo} to use the later version without re-ordering the
6589: source code and recompiling it.
6590:
6591: @example
6592: : greet ." Good morning" ;
6593: : foo ... greet ... ;
6594: : greet ." Hello" ;
6595: : bar ... greet ... ;
6596: @end example
6597:
6598: This problem can be solved by defining @code{greet} as a @code{Defer}red
6599: word. The behaviour of a @code{Defer}red word can be defined and
6600: redefined at any time by using @code{IS} to associate the xt of a
6601: previously-defined word with it. The previous example becomes:
6602:
6603: @example
6604: Defer greet ( -- )
6605: : foo ... greet ... ;
6606: : bar ... greet ... ;
6607: : greet1 ( -- ) ." Good morning" ;
6608: : greet2 ( -- ) ." Hello" ;
6609: ' greet2 <IS> greet \ make greet behave like greet2
6610: @end example
6611:
6612: @progstyle
6613: You should write a stack comment for every deferred word, and put only
6614: XTs into deferred words that conform to this stack effect. Otherwise
6615: it's too difficult to use the deferred word.
6616:
6617: A deferred word can be used to improve the statistics-gathering example
6618: from @ref{User-defined Defining Words}; rather than edit the
6619: application's source code to change every @code{:} to a @code{my:}, do
6620: this:
6621:
6622: @example
6623: : real: : ; \ retain access to the original
6624: defer : \ redefine as a deferred word
6625: ' my: <IS> : \ use special version of :
6626: \
6627: \ load application here
6628: \
6629: ' real: <IS> : \ go back to the original
6630: @end example
6631:
6632:
6633: One thing to note is that @code{<IS>} consumes its name when it is
6634: executed. If you want to specify the name at compile time, use
6635: @code{[IS]}:
6636:
6637: @example
6638: : set-greet ( xt -- )
6639: [IS] greet ;
6640:
6641: ' greet1 set-greet
6642: @end example
6643:
6644: A deferred word can only inherit execution semantics from the xt
6645: (because that is all that an xt can represent -- for more discussion of
6646: this @pxref{Tokens for Words}); by default it will have default
6647: interpretation and compilation semantics deriving from this execution
6648: semantics. However, you can change the interpretation and compilation
6649: semantics of the deferred word in the usual ways:
6650:
6651: @example
6652: : bar .... ; compile-only
6653: Defer fred immediate
6654: Defer jim
6655:
6656: ' bar <IS> jim \ jim has default semantics
6657: ' bar <IS> fred \ fred is immediate
6658: @end example
6659:
6660: doc-defer
6661: doc-<is>
6662: doc-[is]
6663: doc-is
6664: @comment TODO document these: what's defers [is]
6665: doc-what's
6666: doc-defers
6667:
6668: @c Use @code{words-deferred} to see a list of deferred words.
6669:
6670: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
6671: are provided in @file{compat/defer.fs}.
6672:
6673:
6674: @node Aliases, , Deferred words, Defining Words
6675: @subsection Aliases
6676: @cindex aliases
6677:
6678: The defining word @code{Alias} allows you to define a word by name that
6679: has the same behaviour as some other word. Here are two situation where
6680: this can be useful:
6681:
6682: @itemize @bullet
6683: @item
6684: When you want access to a word's definition from a different word list
6685: (for an example of this, see the definition of the @code{Root} word list
6686: in the Gforth source).
6687: @item
6688: When you want to create a synonym; a definition that can be known by
6689: either of two names (for example, @code{THEN} and @code{ENDIF} are
6690: aliases).
6691: @end itemize
6692:
6693: Like deferred words, an alias has default compilation and interpretation
6694: semantics at the beginning (not the modifications of the other word),
6695: but you can change them in the usual ways (@code{immediate},
6696: @code{compile-only}). For example:
6697:
6698: @example
6699: : foo ... ; immediate
6700:
6701: ' foo Alias bar \ bar is not an immediate word
6702: ' foo Alias fooby immediate \ fooby is an immediate word
6703: @end example
6704:
6705: Words that are aliases have the same xt, different headers in the
6706: dictionary, and consequently different name tokens (@pxref{Tokens for
6707: Words}) and possibly different immediate flags. An alias can only have
6708: default or immediate compilation semantics; you can define aliases for
6709: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
6710:
6711: doc-alias
6712:
6713:
6714: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6715: @section Interpretation and Compilation Semantics
6716: @cindex semantics, interpretation and compilation
6717:
6718: @c !! state and ' are used without explanation
6719: @c example for immediate/compile-only? or is the tutorial enough
6720:
6721: @cindex interpretation semantics
6722: The @dfn{interpretation semantics} of a (named) word are what the text
6723: interpreter does when it encounters the word in interpret state. It also
6724: appears in some other contexts, e.g., the execution token returned by
6725: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6726: (in other words, @code{' @i{word} execute} is equivalent to
6727: interpret-state text interpretation of @code{@i{word}}).
6728:
6729: @cindex compilation semantics
6730: The @dfn{compilation semantics} of a (named) word are what the text
6731: interpreter does when it encounters the word in compile state. It also
6732: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6733: compiles@footnote{In standard terminology, ``appends to the current
6734: definition''.} the compilation semantics of @i{word}.
6735:
6736: @cindex execution semantics
6737: The standard also talks about @dfn{execution semantics}. They are used
6738: only for defining the interpretation and compilation semantics of many
6739: words. By default, the interpretation semantics of a word are to
6740: @code{execute} its execution semantics, and the compilation semantics of
6741: a word are to @code{compile,} its execution semantics.@footnote{In
6742: standard terminology: The default interpretation semantics are its
6743: execution semantics; the default compilation semantics are to append its
6744: execution semantics to the execution semantics of the current
6745: definition.}
6746:
6747: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6748: the text interpreter, ticked, or @code{postpone}d, so they have no
6749: interpretation or compilation semantics. Their behaviour is represented
6750: by their XT (@pxref{Tokens for Words}), and we call it execution
6751: semantics, too.
6752:
6753: @comment TODO expand, make it co-operate with new sections on text interpreter.
6754:
6755: @cindex immediate words
6756: @cindex compile-only words
6757: You can change the semantics of the most-recently defined word:
6758:
6759:
6760: doc-immediate
6761: doc-compile-only
6762: doc-restrict
6763:
6764: By convention, words with non-default compilation semantics (e.g.,
6765: immediate words) often have names surrounded with brackets (e.g.,
6766: @code{[']}, @pxref{Execution token}).
6767:
6768: Note that ticking (@code{'}) a compile-only word gives an error
6769: (``Interpreting a compile-only word'').
6770:
6771: @menu
6772: * Combined words::
6773: @end menu
6774:
6775:
6776: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
6777: @subsection Combined Words
6778: @cindex combined words
6779:
6780: Gforth allows you to define @dfn{combined words} -- words that have an
6781: arbitrary combination of interpretation and compilation semantics.
6782:
6783: doc-interpret/compile:
6784:
6785: This feature was introduced for implementing @code{TO} and @code{S"}. I
6786: recommend that you do not define such words, as cute as they may be:
6787: they make it hard to get at both parts of the word in some contexts.
6788: E.g., assume you want to get an execution token for the compilation
6789: part. Instead, define two words, one that embodies the interpretation
6790: part, and one that embodies the compilation part. Once you have done
6791: that, you can define a combined word with @code{interpret/compile:} for
6792: the convenience of your users.
6793:
6794: You might try to use this feature to provide an optimizing
6795: implementation of the default compilation semantics of a word. For
6796: example, by defining:
6797: @example
6798: :noname
6799: foo bar ;
6800: :noname
6801: POSTPONE foo POSTPONE bar ;
6802: interpret/compile: opti-foobar
6803: @end example
6804:
6805: @noindent
6806: as an optimizing version of:
6807:
6808: @example
6809: : foobar
6810: foo bar ;
6811: @end example
6812:
6813: Unfortunately, this does not work correctly with @code{[compile]},
6814: because @code{[compile]} assumes that the compilation semantics of all
6815: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
6816: opti-foobar} would compile compilation semantics, whereas
6817: @code{[compile] foobar} would compile interpretation semantics.
6818:
6819: @cindex state-smart words (are a bad idea)
6820: @anchor{state-smartness}
6821: Some people try to use @dfn{state-smart} words to emulate the feature provided
6822: by @code{interpret/compile:} (words are state-smart if they check
6823: @code{STATE} during execution). E.g., they would try to code
6824: @code{foobar} like this:
6825:
6826: @example
6827: : foobar
6828: STATE @@
6829: IF ( compilation state )
6830: POSTPONE foo POSTPONE bar
6831: ELSE
6832: foo bar
6833: ENDIF ; immediate
6834: @end example
6835:
6836: Although this works if @code{foobar} is only processed by the text
6837: interpreter, it does not work in other contexts (like @code{'} or
6838: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6839: for a state-smart word, not for the interpretation semantics of the
6840: original @code{foobar}; when you execute this execution token (directly
6841: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6842: state, the result will not be what you expected (i.e., it will not
6843: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6844: write them@footnote{For a more detailed discussion of this topic, see
6845: M. Anton Ertl,
6846: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6847: it is Evil and How to Exorcise it}}, EuroForth '98.}!
6848:
6849: @cindex defining words with arbitrary semantics combinations
6850: It is also possible to write defining words that define words with
6851: arbitrary combinations of interpretation and compilation semantics. In
6852: general, they look like this:
6853:
6854: @example
6855: : def-word
6856: create-interpret/compile
6857: @i{code1}
6858: interpretation>
6859: @i{code2}
6860: <interpretation
6861: compilation>
6862: @i{code3}
6863: <compilation ;
6864: @end example
6865:
6866: For a @i{word} defined with @code{def-word}, the interpretation
6867: semantics are to push the address of the body of @i{word} and perform
6868: @i{code2}, and the compilation semantics are to push the address of
6869: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
6870: can also be defined like this (except that the defined constants don't
6871: behave correctly when @code{[compile]}d):
6872:
6873: @example
6874: : constant ( n "name" -- )
6875: create-interpret/compile
6876: ,
6877: interpretation> ( -- n )
6878: @@
6879: <interpretation
6880: compilation> ( compilation. -- ; run-time. -- n )
6881: @@ postpone literal
6882: <compilation ;
6883: @end example
6884:
6885:
6886: doc-create-interpret/compile
6887: doc-interpretation>
6888: doc-<interpretation
6889: doc-compilation>
6890: doc-<compilation
6891:
6892:
6893: Words defined with @code{interpret/compile:} and
6894: @code{create-interpret/compile} have an extended header structure that
6895: differs from other words; however, unless you try to access them with
6896: plain address arithmetic, you should not notice this. Words for
6897: accessing the header structure usually know how to deal with this; e.g.,
6898: @code{'} @i{word} @code{>body} also gives you the body of a word created
6899: with @code{create-interpret/compile}.
6900:
6901:
6902: @c -------------------------------------------------------------
6903: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
6904: @section Tokens for Words
6905: @cindex tokens for words
6906:
6907: This section describes the creation and use of tokens that represent
6908: words.
6909:
6910: @menu
6911: * Execution token:: represents execution/interpretation semantics
6912: * Compilation token:: represents compilation semantics
6913: * Name token:: represents named words
6914: @end menu
6915:
6916: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
6917: @subsection Execution token
6918:
6919: @cindex xt
6920: @cindex execution token
6921: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
6922: You can use @code{execute} to invoke this behaviour.
6923:
6924: @cindex tick (')
6925: You can use @code{'} to get an execution token that represents the
6926: interpretation semantics of a named word:
6927:
6928: @example
6929: 5 ' . ( n xt )
6930: execute ( ) \ execute the xt (i.e., ".")
6931: @end example
6932:
6933: doc-'
6934:
6935: @code{'} parses at run-time; there is also a word @code{[']} that parses
6936: when it is compiled, and compiles the resulting XT:
6937:
6938: @example
6939: : foo ['] . execute ;
6940: 5 foo
6941: : bar ' execute ; \ by contrast,
6942: 5 bar . \ ' parses "." when bar executes
6943: @end example
6944:
6945: doc-[']
6946:
6947: If you want the execution token of @i{word}, write @code{['] @i{word}}
6948: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
6949: @code{'} and @code{[']} behave somewhat unusually by complaining about
6950: compile-only words (because these words have no interpretation
6951: semantics). You might get what you want by using @code{COMP' @i{word}
6952: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
6953: token}).
6954:
6955: Another way to get an XT is @code{:noname} or @code{latestxt}
6956: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
6957: for the only behaviour the word has (the execution semantics). For
6958: named words, @code{latestxt} produces an XT for the same behaviour it
6959: would produce if the word was defined anonymously.
6960:
6961: @example
6962: :noname ." hello" ;
6963: execute
6964: @end example
6965:
6966: An XT occupies one cell and can be manipulated like any other cell.
6967:
6968: @cindex code field address
6969: @cindex CFA
6970: In ANS Forth the XT is just an abstract data type (i.e., defined by the
6971: operations that produce or consume it). For old hands: In Gforth, the
6972: XT is implemented as a code field address (CFA).
6973:
6974: doc-execute
6975: doc-perform
6976:
6977: @node Compilation token, Name token, Execution token, Tokens for Words
6978: @subsection Compilation token
6979:
6980: @cindex compilation token
6981: @cindex CT (compilation token)
6982: Gforth represents the compilation semantics of a named word by a
6983: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
6984: @i{xt} is an execution token. The compilation semantics represented by
6985: the compilation token can be performed with @code{execute}, which
6986: consumes the whole compilation token, with an additional stack effect
6987: determined by the represented compilation semantics.
6988:
6989: At present, the @i{w} part of a compilation token is an execution token,
6990: and the @i{xt} part represents either @code{execute} or
6991: @code{compile,}@footnote{Depending upon the compilation semantics of the
6992: word. If the word has default compilation semantics, the @i{xt} will
6993: represent @code{compile,}. Otherwise (e.g., for immediate words), the
6994: @i{xt} will represent @code{execute}.}. However, don't rely on that
6995: knowledge, unless necessary; future versions of Gforth may introduce
6996: unusual compilation tokens (e.g., a compilation token that represents
6997: the compilation semantics of a literal).
6998:
6999: You can perform the compilation semantics represented by the compilation
7000: token with @code{execute}. You can compile the compilation semantics
7001: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7002: equivalent to @code{postpone @i{word}}.
7003:
7004: doc-[comp']
7005: doc-comp'
7006: doc-postpone,
7007:
7008: @node Name token, , Compilation token, Tokens for Words
7009: @subsection Name token
7010:
7011: @cindex name token
7012: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7013: token is an abstract data type that occurs as argument or result of the
7014: words below.
7015:
7016: @c !! put this elswhere?
7017: @cindex name field address
7018: @cindex NFA
7019: The closest thing to the nt in older Forth systems is the name field
7020: address (NFA), but there are significant differences: in older Forth
7021: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7022: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7023: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7024: is a link field in the structure identified by the name token, but
7025: searching usually uses a hash table external to these structures; the
7026: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7027: implemented as the address of that count field.
7028:
7029: doc-find-name
7030: doc-latest
7031: doc->name
7032: doc-name>int
7033: doc-name?int
7034: doc-name>comp
7035: doc-name>string
7036: doc-id.
7037: doc-.name
7038: doc-.id
7039:
7040: @c ----------------------------------------------------------
7041: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7042: @section Compiling words
7043: @cindex compiling words
7044: @cindex macros
7045:
7046: In contrast to most other languages, Forth has no strict boundary
7047: between compilation and run-time. E.g., you can run arbitrary code
7048: between defining words (or for computing data used by defining words
7049: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7050: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7051: running arbitrary code while compiling a colon definition (exception:
7052: you must not allot dictionary space).
7053:
7054: @menu
7055: * Literals:: Compiling data values
7056: * Macros:: Compiling words
7057: @end menu
7058:
7059: @node Literals, Macros, Compiling words, Compiling words
7060: @subsection Literals
7061: @cindex Literals
7062:
7063: The simplest and most frequent example is to compute a literal during
7064: compilation. E.g., the following definition prints an array of strings,
7065: one string per line:
7066:
7067: @example
7068: : .strings ( addr u -- ) \ gforth
7069: 2* cells bounds U+DO
7070: cr i 2@@ type
7071: 2 cells +LOOP ;
7072: @end example
7073:
7074: With a simple-minded compiler like Gforth's, this computes @code{2
7075: cells} on every loop iteration. You can compute this value once and for
7076: all at compile time and compile it into the definition like this:
7077:
7078: @example
7079: : .strings ( addr u -- ) \ gforth
7080: 2* cells bounds U+DO
7081: cr i 2@@ type
7082: [ 2 cells ] literal +LOOP ;
7083: @end example
7084:
7085: @code{[} switches the text interpreter to interpret state (you will get
7086: an @code{ok} prompt if you type this example interactively and insert a
7087: newline between @code{[} and @code{]}), so it performs the
7088: interpretation semantics of @code{2 cells}; this computes a number.
7089: @code{]} switches the text interpreter back into compile state. It then
7090: performs @code{Literal}'s compilation semantics, which are to compile
7091: this number into the current word. You can decompile the word with
7092: @code{see .strings} to see the effect on the compiled code.
7093:
7094: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7095: *} in this way.
7096:
7097: doc-[
7098: doc-]
7099: doc-literal
7100: doc-]L
7101:
7102: There are also words for compiling other data types than single cells as
7103: literals:
7104:
7105: doc-2literal
7106: doc-fliteral
7107: doc-sliteral
7108:
7109: @cindex colon-sys, passing data across @code{:}
7110: @cindex @code{:}, passing data across
7111: You might be tempted to pass data from outside a colon definition to the
7112: inside on the data stack. This does not work, because @code{:} puhes a
7113: colon-sys, making stuff below unaccessible. E.g., this does not work:
7114:
7115: @example
7116: 5 : foo literal ; \ error: "unstructured"
7117: @end example
7118:
7119: Instead, you have to pass the value in some other way, e.g., through a
7120: variable:
7121:
7122: @example
7123: variable temp
7124: 5 temp !
7125: : foo [ temp @@ ] literal ;
7126: @end example
7127:
7128:
7129: @node Macros, , Literals, Compiling words
7130: @subsection Macros
7131: @cindex Macros
7132: @cindex compiling compilation semantics
7133:
7134: @code{Literal} and friends compile data values into the current
7135: definition. You can also write words that compile other words into the
7136: current definition. E.g.,
7137:
7138: @example
7139: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7140: POSTPONE + ;
7141:
7142: : foo ( n1 n2 -- n )
7143: [ compile-+ ] ;
7144: 1 2 foo .
7145: @end example
7146:
7147: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7148: What happens in this example? @code{Postpone} compiles the compilation
7149: semantics of @code{+} into @code{compile-+}; later the text interpreter
7150: executes @code{compile-+} and thus the compilation semantics of +, which
7151: compile (the execution semantics of) @code{+} into
7152: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7153: should only be executed in compile state, so this example is not
7154: guaranteed to work on all standard systems, but on any decent system it
7155: will work.}
7156:
7157: doc-postpone
7158: doc-[compile]
7159:
7160: Compiling words like @code{compile-+} are usually immediate (or similar)
7161: so you do not have to switch to interpret state to execute them;
7162: mopifying the last example accordingly produces:
7163:
7164: @example
7165: : [compile-+] ( compilation: --; interpretation: -- )
7166: \ compiled code: ( n1 n2 -- n )
7167: POSTPONE + ; immediate
7168:
7169: : foo ( n1 n2 -- n )
7170: [compile-+] ;
7171: 1 2 foo .
7172: @end example
7173:
7174: Immediate compiling words are similar to macros in other languages (in
7175: particular, Lisp). The important differences to macros in, e.g., C are:
7176:
7177: @itemize @bullet
7178:
7179: @item
7180: You use the same language for defining and processing macros, not a
7181: separate preprocessing language and processor.
7182:
7183: @item
7184: Consequently, the full power of Forth is available in macro definitions.
7185: E.g., you can perform arbitrarily complex computations, or generate
7186: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7187: Tutorial}). This power is very useful when writing a parser generators
7188: or other code-generating software.
7189:
7190: @item
7191: Macros defined using @code{postpone} etc. deal with the language at a
7192: higher level than strings; name binding happens at macro definition
7193: time, so you can avoid the pitfalls of name collisions that can happen
7194: in C macros. Of course, Forth is a liberal language and also allows to
7195: shoot yourself in the foot with text-interpreted macros like
7196:
7197: @example
7198: : [compile-+] s" +" evaluate ; immediate
7199: @end example
7200:
7201: Apart from binding the name at macro use time, using @code{evaluate}
7202: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7203: @end itemize
7204:
7205: You may want the macro to compile a number into a word. The word to do
7206: it is @code{literal}, but you have to @code{postpone} it, so its
7207: compilation semantics take effect when the macro is executed, not when
7208: it is compiled:
7209:
7210: @example
7211: : [compile-5] ( -- ) \ compiled code: ( -- n )
7212: 5 POSTPONE literal ; immediate
7213:
7214: : foo [compile-5] ;
7215: foo .
7216: @end example
7217:
7218: You may want to pass parameters to a macro, that the macro should
7219: compile into the current definition. If the parameter is a number, then
7220: you can use @code{postpone literal} (similar for other values).
7221:
7222: If you want to pass a word that is to be compiled, the usual way is to
7223: pass an execution token and @code{compile,} it:
7224:
7225: @example
7226: : twice1 ( xt -- ) \ compiled code: ... -- ...
7227: dup compile, compile, ;
7228:
7229: : 2+ ( n1 -- n2 )
7230: [ ' 1+ twice1 ] ;
7231: @end example
7232:
7233: doc-compile,
7234:
7235: An alternative available in Gforth, that allows you to pass compile-only
7236: words as parameters is to use the compilation token (@pxref{Compilation
7237: token}). The same example in this technique:
7238:
7239: @example
7240: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7241: 2dup 2>r execute 2r> execute ;
7242:
7243: : 2+ ( n1 -- n2 )
7244: [ comp' 1+ twice ] ;
7245: @end example
7246:
7247: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7248: works even if the executed compilation semantics has an effect on the
7249: data stack.
7250:
7251: You can also define complete definitions with these words; this provides
7252: an alternative to using @code{does>} (@pxref{User-defined Defining
7253: Words}). E.g., instead of
7254:
7255: @example
7256: : curry+ ( n1 "name" -- )
7257: CREATE ,
7258: DOES> ( n2 -- n1+n2 )
7259: @@ + ;
7260: @end example
7261:
7262: you could define
7263:
7264: @example
7265: : curry+ ( n1 "name" -- )
7266: \ name execution: ( n2 -- n1+n2 )
7267: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
7268:
7269: -3 curry+ 3-
7270: see 3-
7271: @end example
7272:
7273: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7274: colon-sys on the data stack that makes everything below it unaccessible.
7275:
7276: This way of writing defining words is sometimes more, sometimes less
7277: convenient than using @code{does>} (@pxref{Advanced does> usage
7278: example}). One advantage of this method is that it can be optimized
7279: better, because the compiler knows that the value compiled with
7280: @code{literal} is fixed, whereas the data associated with a
7281: @code{create}d word can be changed.
7282:
7283: @c ----------------------------------------------------------
7284: @node The Text Interpreter, The Input Stream, Compiling words, Words
7285: @section The Text Interpreter
7286: @cindex interpreter - outer
7287: @cindex text interpreter
7288: @cindex outer interpreter
7289:
7290: @c Should we really describe all these ugly details? IMO the text
7291: @c interpreter should be much cleaner, but that may not be possible within
7292: @c ANS Forth. - anton
7293: @c nac-> I wanted to explain how it works to show how you can exploit
7294: @c it in your own programs. When I was writing a cross-compiler, figuring out
7295: @c some of these gory details was very helpful to me. None of the textbooks
7296: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7297: @c seems to positively avoid going into too much detail for some of
7298: @c the internals.
7299:
7300: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7301: @c it is; for the ugly details, I would prefer another place. I wonder
7302: @c whether we should have a chapter before "Words" that describes some
7303: @c basic concepts referred to in words, and a chapter after "Words" that
7304: @c describes implementation details.
7305:
7306: The text interpreter@footnote{This is an expanded version of the
7307: material in @ref{Introducing the Text Interpreter}.} is an endless loop
7308: that processes input from the current input device. It is also called
7309: the outer interpreter, in contrast to the inner interpreter
7310: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7311: implementations.
7312:
7313: @cindex interpret state
7314: @cindex compile state
7315: The text interpreter operates in one of two states: @dfn{interpret
7316: state} and @dfn{compile state}. The current state is defined by the
7317: aptly-named variable @code{state}.
7318:
7319: This section starts by describing how the text interpreter behaves when
7320: it is in interpret state, processing input from the user input device --
7321: the keyboard. This is the mode that a Forth system is in after it starts
7322: up.
7323:
7324: @cindex input buffer
7325: @cindex terminal input buffer
7326: The text interpreter works from an area of memory called the @dfn{input
7327: buffer}@footnote{When the text interpreter is processing input from the
7328: keyboard, this area of memory is called the @dfn{terminal input buffer}
7329: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7330: @code{#TIB}.}, which stores your keyboard input when you press the
7331: @key{RET} key. Starting at the beginning of the input buffer, it skips
7332: leading spaces (called @dfn{delimiters}) then parses a string (a
7333: sequence of non-space characters) until it reaches either a space
7334: character or the end of the buffer. Having parsed a string, it makes two
7335: attempts to process it:
7336:
7337: @cindex dictionary
7338: @itemize @bullet
7339: @item
7340: It looks for the string in a @dfn{dictionary} of definitions. If the
7341: string is found, the string names a @dfn{definition} (also known as a
7342: @dfn{word}) and the dictionary search returns information that allows
7343: the text interpreter to perform the word's @dfn{interpretation
7344: semantics}. In most cases, this simply means that the word will be
7345: executed.
7346: @item
7347: If the string is not found in the dictionary, the text interpreter
7348: attempts to treat it as a number, using the rules described in
7349: @ref{Number Conversion}. If the string represents a legal number in the
7350: current radix, the number is pushed onto a parameter stack (the data
7351: stack for integers, the floating-point stack for floating-point
7352: numbers).
7353: @end itemize
7354:
7355: If both attempts fail, or if the word is found in the dictionary but has
7356: no interpretation semantics@footnote{This happens if the word was
7357: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7358: remainder of the input buffer, issues an error message and waits for
7359: more input. If one of the attempts succeeds, the text interpreter
7360: repeats the parsing process until the whole of the input buffer has been
7361: processed, at which point it prints the status message ``@code{ ok}''
7362: and waits for more input.
7363:
7364: @c anton: this should be in the input stream subsection (or below it)
7365:
7366: @cindex parse area
7367: The text interpreter keeps track of its position in the input buffer by
7368: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7369: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7370: of the input buffer. The region from offset @code{>IN @@} to the end of
7371: the input buffer is called the @dfn{parse area}@footnote{In other words,
7372: the text interpreter processes the contents of the input buffer by
7373: parsing strings from the parse area until the parse area is empty.}.
7374: This example shows how @code{>IN} changes as the text interpreter parses
7375: the input buffer:
7376:
7377: @example
7378: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7379: CR ." ->" TYPE ." <-" ; IMMEDIATE
7380:
7381: 1 2 3 remaining + remaining .
7382:
7383: : foo 1 2 3 remaining SWAP remaining ;
7384: @end example
7385:
7386: @noindent
7387: The result is:
7388:
7389: @example
7390: ->+ remaining .<-
7391: ->.<-5 ok
7392:
7393: ->SWAP remaining ;-<
7394: ->;<- ok
7395: @end example
7396:
7397: @cindex parsing words
7398: The value of @code{>IN} can also be modified by a word in the input
7399: buffer that is executed by the text interpreter. This means that a word
7400: can ``trick'' the text interpreter into either skipping a section of the
7401: input buffer@footnote{This is how parsing words work.} or into parsing a
7402: section twice. For example:
7403:
7404: @example
7405: : lat ." <<foo>>" ;
7406: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
7407: @end example
7408:
7409: @noindent
7410: When @code{flat} is executed, this output is produced@footnote{Exercise
7411: for the reader: what would happen if the @code{3} were replaced with
7412: @code{4}?}:
7413:
7414: @example
7415: <<bar>><<foo>>
7416: @end example
7417:
7418: This technique can be used to work around some of the interoperability
7419: problems of parsing words. Of course, it's better to avoid parsing
7420: words where possible.
7421:
7422: @noindent
7423: Two important notes about the behaviour of the text interpreter:
7424:
7425: @itemize @bullet
7426: @item
7427: It processes each input string to completion before parsing additional
7428: characters from the input buffer.
7429: @item
7430: It treats the input buffer as a read-only region (and so must your code).
7431: @end itemize
7432:
7433: @noindent
7434: When the text interpreter is in compile state, its behaviour changes in
7435: these ways:
7436:
7437: @itemize @bullet
7438: @item
7439: If a parsed string is found in the dictionary, the text interpreter will
7440: perform the word's @dfn{compilation semantics}. In most cases, this
7441: simply means that the execution semantics of the word will be appended
7442: to the current definition.
7443: @item
7444: When a number is encountered, it is compiled into the current definition
7445: (as a literal) rather than being pushed onto a parameter stack.
7446: @item
7447: If an error occurs, @code{state} is modified to put the text interpreter
7448: back into interpret state.
7449: @item
7450: Each time a line is entered from the keyboard, Gforth prints
7451: ``@code{ compiled}'' rather than `` @code{ok}''.
7452: @end itemize
7453:
7454: @cindex text interpreter - input sources
7455: When the text interpreter is using an input device other than the
7456: keyboard, its behaviour changes in these ways:
7457:
7458: @itemize @bullet
7459: @item
7460: When the parse area is empty, the text interpreter attempts to refill
7461: the input buffer from the input source. When the input source is
7462: exhausted, the input source is set back to the previous input source.
7463: @item
7464: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7465: time the parse area is emptied.
7466: @item
7467: If an error occurs, the input source is set back to the user input
7468: device.
7469: @end itemize
7470:
7471: You can read about this in more detail in @ref{Input Sources}.
7472:
7473: doc->in
7474: doc-source
7475:
7476: doc-tib
7477: doc-#tib
7478:
7479:
7480: @menu
7481: * Input Sources::
7482: * Number Conversion::
7483: * Interpret/Compile states::
7484: * Interpreter Directives::
7485: @end menu
7486:
7487: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7488: @subsection Input Sources
7489: @cindex input sources
7490: @cindex text interpreter - input sources
7491:
7492: By default, the text interpreter processes input from the user input
7493: device (the keyboard) when Forth starts up. The text interpreter can
7494: process input from any of these sources:
7495:
7496: @itemize @bullet
7497: @item
7498: The user input device -- the keyboard.
7499: @item
7500: A file, using the words described in @ref{Forth source files}.
7501: @item
7502: A block, using the words described in @ref{Blocks}.
7503: @item
7504: A text string, using @code{evaluate}.
7505: @end itemize
7506:
7507: A program can identify the current input device from the values of
7508: @code{source-id} and @code{blk}.
7509:
7510:
7511: doc-source-id
7512: doc-blk
7513:
7514: doc-save-input
7515: doc-restore-input
7516:
7517: doc-evaluate
7518: doc-query
7519:
7520:
7521:
7522: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
7523: @subsection Number Conversion
7524: @cindex number conversion
7525: @cindex double-cell numbers, input format
7526: @cindex input format for double-cell numbers
7527: @cindex single-cell numbers, input format
7528: @cindex input format for single-cell numbers
7529: @cindex floating-point numbers, input format
7530: @cindex input format for floating-point numbers
7531:
7532: This section describes the rules that the text interpreter uses when it
7533: tries to convert a string into a number.
7534:
7535: Let <digit> represent any character that is a legal digit in the current
7536: number base@footnote{For example, 0-9 when the number base is decimal or
7537: 0-9, A-F when the number base is hexadecimal.}.
7538:
7539: Let <decimal digit> represent any character in the range 0-9.
7540:
7541: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7542: in the braces (@i{a} or @i{b} or neither).
7543:
7544: Let * represent any number of instances of the previous character
7545: (including none).
7546:
7547: Let any other character represent itself.
7548:
7549: @noindent
7550: Now, the conversion rules are:
7551:
7552: @itemize @bullet
7553: @item
7554: A string of the form <digit><digit>* is treated as a single-precision
7555: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
7556: @item
7557: A string of the form -<digit><digit>* is treated as a single-precision
7558: (cell-sized) negative integer, and is represented using 2's-complement
7559: arithmetic. Examples are -45 -5681 -0
7560: @item
7561: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
7562: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7563: (all three of these represent the same number).
7564: @item
7565: A string of the form -<digit><digit>*.<digit>* is treated as a
7566: double-precision (double-cell-sized) negative integer, and is
7567: represented using 2's-complement arithmetic. Examples are -3465. -3.465
7568: -34.65 (all three of these represent the same number).
7569: @item
7570: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7571: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
7572: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
7573: number) +12.E-4
7574: @end itemize
7575:
7576: By default, the number base used for integer number conversion is given
7577: by the contents of the variable @code{base}. Note that a lot of
7578: confusion can result from unexpected values of @code{base}. If you
7579: change @code{base} anywhere, make sure to save the old value and restore
7580: it afterwards. In general I recommend keeping @code{base} decimal, and
7581: using the prefixes described below for the popular non-decimal bases.
7582:
7583: doc-dpl
7584: doc-base
7585: doc-hex
7586: doc-decimal
7587:
7588:
7589: @cindex '-prefix for character strings
7590: @cindex &-prefix for decimal numbers
7591: @cindex %-prefix for binary numbers
7592: @cindex $-prefix for hexadecimal numbers
7593: Gforth allows you to override the value of @code{base} by using a
7594: prefix@footnote{Some Forth implementations provide a similar scheme by
7595: implementing @code{$} etc. as parsing words that process the subsequent
7596: number in the input stream and push it onto the stack. For example, see
7597: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7598: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7599: is required between the prefix and the number.} before the first digit
7600: of an (integer) number. Four prefixes are supported:
7601:
7602: @itemize @bullet
7603: @item
7604: @code{&} -- decimal
7605: @item
7606: @code{%} -- binary
7607: @item
7608: @code{$} -- hexadecimal
7609: @item
7610: @code{'} -- base @code{max-char+1}
7611: @end itemize
7612:
7613: Here are some examples, with the equivalent decimal number shown after
7614: in braces:
7615:
7616: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
7617: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
7618: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
7619: &905 (905), $abc (2478), $ABC (2478).
7620:
7621: @cindex number conversion - traps for the unwary
7622: @noindent
7623: Number conversion has a number of traps for the unwary:
7624:
7625: @itemize @bullet
7626: @item
7627: You cannot determine the current number base using the code sequence
7628: @code{base @@ .} -- the number base is always 10 in the current number
7629: base. Instead, use something like @code{base @@ dec.}
7630: @item
7631: If the number base is set to a value greater than 14 (for example,
7632: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7633: it to be intepreted as either a single-precision integer or a
7634: floating-point number (Gforth treats it as an integer). The ambiguity
7635: can be resolved by explicitly stating the sign of the mantissa and/or
7636: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7637: ambiguity arises; either representation will be treated as a
7638: floating-point number.
7639: @item
7640: There is a word @code{bin} but it does @i{not} set the number base!
7641: It is used to specify file types.
7642: @item
7643: ANS Forth requires the @code{.} of a double-precision number to be the
7644: final character in the string. Gforth allows the @code{.} to be
7645: anywhere after the first digit.
7646: @item
7647: The number conversion process does not check for overflow.
7648: @item
7649: In an ANS Forth program @code{base} is required to be decimal when
7650: converting floating-point numbers. In Gforth, number conversion to
7651: floating-point numbers always uses base &10, irrespective of the value
7652: of @code{base}.
7653: @end itemize
7654:
7655: You can read numbers into your programs with the words described in
7656: @ref{Input}.
7657:
7658: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
7659: @subsection Interpret/Compile states
7660: @cindex Interpret/Compile states
7661:
7662: A standard program is not permitted to change @code{state}
7663: explicitly. However, it can change @code{state} implicitly, using the
7664: words @code{[} and @code{]}. When @code{[} is executed it switches
7665: @code{state} to interpret state, and therefore the text interpreter
7666: starts interpreting. When @code{]} is executed it switches @code{state}
7667: to compile state and therefore the text interpreter starts
7668: compiling. The most common usage for these words is for switching into
7669: interpret state and back from within a colon definition; this technique
7670: can be used to compile a literal (for an example, @pxref{Literals}) or
7671: for conditional compilation (for an example, @pxref{Interpreter
7672: Directives}).
7673:
7674:
7675: @c This is a bad example: It's non-standard, and it's not necessary.
7676: @c However, I can't think of a good example for switching into compile
7677: @c state when there is no current word (@code{state}-smart words are not a
7678: @c good reason). So maybe we should use an example for switching into
7679: @c interpret @code{state} in a colon def. - anton
7680: @c nac-> I agree. I started out by putting in the example, then realised
7681: @c that it was non-ANS, so wrote more words around it. I hope this
7682: @c re-written version is acceptable to you. I do want to keep the example
7683: @c as it is helpful for showing what is and what is not portable, particularly
7684: @c where it outlaws a style in common use.
7685:
7686: @c anton: it's more important to show what's portable. After we have done
7687: @c that, we can also show what's not. In any case, I have written a
7688: @c section Compiling Words which also deals with [ ].
7689:
7690: @c !! The following example does not work in Gforth 0.5.9 or later.
7691:
7692: @c @code{[} and @code{]} also give you the ability to switch into compile
7693: @c state and back, but we cannot think of any useful Standard application
7694: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7695:
7696: @c @example
7697: @c : AA ." this is A" ;
7698: @c : BB ." this is B" ;
7699: @c : CC ." this is C" ;
7700:
7701: @c create table ] aa bb cc [
7702:
7703: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7704: @c cells table + @@ execute ;
7705: @c @end example
7706:
7707: @c This example builds a jump table; @code{0 go} will display ``@code{this
7708: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7709: @c defining @code{table} like this:
7710:
7711: @c @example
7712: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7713: @c @end example
7714:
7715: @c The problem with this code is that the definition of @code{table} is not
7716: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7717: @c @i{may} work on systems where code space and data space co-incide, the
7718: @c Standard only allows data space to be assigned for a @code{CREATE}d
7719: @c word. In addition, the Standard only allows @code{@@} to access data
7720: @c space, whilst this example is using it to access code space. The only
7721: @c portable, Standard way to build this table is to build it in data space,
7722: @c like this:
7723:
7724: @c @example
7725: @c create table ' aa , ' bb , ' cc ,
7726: @c @end example
7727:
7728: @c doc-state
7729:
7730:
7731: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
7732: @subsection Interpreter Directives
7733: @cindex interpreter directives
7734: @cindex conditional compilation
7735:
7736: These words are usually used in interpret state; typically to control
7737: which parts of a source file are processed by the text
7738: interpreter. There are only a few ANS Forth Standard words, but Gforth
7739: supplements these with a rich set of immediate control structure words
7740: to compensate for the fact that the non-immediate versions can only be
7741: used in compile state (@pxref{Control Structures}). Typical usages:
7742:
7743: @example
7744: FALSE Constant HAVE-ASSEMBLER
7745: .
7746: .
7747: HAVE-ASSEMBLER [IF]
7748: : ASSEMBLER-FEATURE
7749: ...
7750: ;
7751: [ENDIF]
7752: .
7753: .
7754: : SEE
7755: ... \ general-purpose SEE code
7756: [ HAVE-ASSEMBLER [IF] ]
7757: ... \ assembler-specific SEE code
7758: [ [ENDIF] ]
7759: ;
7760: @end example
7761:
7762:
7763: doc-[IF]
7764: doc-[ELSE]
7765: doc-[THEN]
7766: doc-[ENDIF]
7767:
7768: doc-[IFDEF]
7769: doc-[IFUNDEF]
7770:
7771: doc-[?DO]
7772: doc-[DO]
7773: doc-[FOR]
7774: doc-[LOOP]
7775: doc-[+LOOP]
7776: doc-[NEXT]
7777:
7778: doc-[BEGIN]
7779: doc-[UNTIL]
7780: doc-[AGAIN]
7781: doc-[WHILE]
7782: doc-[REPEAT]
7783:
7784:
7785: @c -------------------------------------------------------------
7786: @node The Input Stream, Word Lists, The Text Interpreter, Words
7787: @section The Input Stream
7788: @cindex input stream
7789:
7790: @c !! integrate this better with the "Text Interpreter" section
7791: The text interpreter reads from the input stream, which can come from
7792: several sources (@pxref{Input Sources}). Some words, in particular
7793: defining words, but also words like @code{'}, read parameters from the
7794: input stream instead of from the stack.
7795:
7796: Such words are called parsing words, because they parse the input
7797: stream. Parsing words are hard to use in other words, because it is
7798: hard to pass program-generated parameters through the input stream.
7799: They also usually have an unintuitive combination of interpretation and
7800: compilation semantics when implemented naively, leading to various
7801: approaches that try to produce a more intuitive behaviour
7802: (@pxref{Combined words}).
7803:
7804: It should be obvious by now that parsing words are a bad idea. If you
7805: want to implement a parsing word for convenience, also provide a factor
7806: of the word that does not parse, but takes the parameters on the stack.
7807: To implement the parsing word on top if it, you can use the following
7808: words:
7809:
7810: @c anton: these belong in the input stream section
7811: doc-parse
7812: doc-parse-word
7813: doc-name
7814: doc-word
7815: doc-\"-parse
7816: doc-refill
7817:
7818: Conversely, if you have the bad luck (or lack of foresight) to have to
7819: deal with parsing words without having such factors, how do you pass a
7820: string that is not in the input stream to it?
7821:
7822: doc-execute-parsing
7823:
7824: If you want to run a parsing word on a file, the following word should
7825: help:
7826:
7827: doc-execute-parsing-file
7828:
7829: @c -------------------------------------------------------------
7830: @node Word Lists, Environmental Queries, The Input Stream, Words
7831: @section Word Lists
7832: @cindex word lists
7833: @cindex header space
7834:
7835: A wordlist is a list of named words; you can add new words and look up
7836: words by name (and you can remove words in a restricted way with
7837: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7838:
7839: @cindex search order stack
7840: The text interpreter searches the wordlists present in the search order
7841: (a stack of wordlists), from the top to the bottom. Within each
7842: wordlist, the search starts conceptually at the newest word; i.e., if
7843: two words in a wordlist have the same name, the newer word is found.
7844:
7845: @cindex compilation word list
7846: New words are added to the @dfn{compilation wordlist} (aka current
7847: wordlist).
7848:
7849: @cindex wid
7850: A word list is identified by a cell-sized word list identifier (@i{wid})
7851: in much the same way as a file is identified by a file handle. The
7852: numerical value of the wid has no (portable) meaning, and might change
7853: from session to session.
7854:
7855: The ANS Forth ``Search order'' word set is intended to provide a set of
7856: low-level tools that allow various different schemes to be
7857: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
7858: word. @file{compat/vocabulary.fs} provides an implementation in ANS
7859: Forth.
7860:
7861: @comment TODO: locals section refers to here, saying that every word list (aka
7862: @comment vocabulary) has its own methods for searching etc. Need to document that.
7863: @c anton: but better in a separate subsection on wordlist internals
7864:
7865: @comment TODO: document markers, reveal, tables, mappedwordlist
7866:
7867: @comment the gforthman- prefix is used to pick out the true definition of a
7868: @comment word from the source files, rather than some alias.
7869:
7870: doc-forth-wordlist
7871: doc-definitions
7872: doc-get-current
7873: doc-set-current
7874: doc-get-order
7875: doc---gforthman-set-order
7876: doc-wordlist
7877: doc-table
7878: doc->order
7879: doc-previous
7880: doc-also
7881: doc---gforthman-forth
7882: doc-only
7883: doc---gforthman-order
7884:
7885: doc-find
7886: doc-search-wordlist
7887:
7888: doc-words
7889: doc-vlist
7890: @c doc-words-deferred
7891:
7892: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
7893: doc-root
7894: doc-vocabulary
7895: doc-seal
7896: doc-vocs
7897: doc-current
7898: doc-context
7899:
7900:
7901: @menu
7902: * Vocabularies::
7903: * Why use word lists?::
7904: * Word list example::
7905: @end menu
7906:
7907: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
7908: @subsection Vocabularies
7909: @cindex Vocabularies, detailed explanation
7910:
7911: Here is an example of creating and using a new wordlist using ANS
7912: Forth words:
7913:
7914: @example
7915: wordlist constant my-new-words-wordlist
7916: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
7917:
7918: \ add it to the search order
7919: also my-new-words
7920:
7921: \ alternatively, add it to the search order and make it
7922: \ the compilation word list
7923: also my-new-words definitions
7924: \ type "order" to see the problem
7925: @end example
7926:
7927: The problem with this example is that @code{order} has no way to
7928: associate the name @code{my-new-words} with the wid of the word list (in
7929: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7930: that has no associated name). There is no Standard way of associating a
7931: name with a wid.
7932:
7933: In Gforth, this example can be re-coded using @code{vocabulary}, which
7934: associates a name with a wid:
7935:
7936: @example
7937: vocabulary my-new-words
7938:
7939: \ add it to the search order
7940: also my-new-words
7941:
7942: \ alternatively, add it to the search order and make it
7943: \ the compilation word list
7944: my-new-words definitions
7945: \ type "order" to see that the problem is solved
7946: @end example
7947:
7948:
7949: @node Why use word lists?, Word list example, Vocabularies, Word Lists
7950: @subsection Why use word lists?
7951: @cindex word lists - why use them?
7952:
7953: Here are some reasons why people use wordlists:
7954:
7955: @itemize @bullet
7956:
7957: @c anton: Gforth's hashing implementation makes the search speed
7958: @c independent from the number of words. But it is linear with the number
7959: @c of wordlists that have to be searched, so in effect using more wordlists
7960: @c actually slows down compilation.
7961:
7962: @c @item
7963: @c To improve compilation speed by reducing the number of header space
7964: @c entries that must be searched. This is achieved by creating a new
7965: @c word list that contains all of the definitions that are used in the
7966: @c definition of a Forth system but which would not usually be used by
7967: @c programs running on that system. That word list would be on the search
7968: @c list when the Forth system was compiled but would be removed from the
7969: @c search list for normal operation. This can be a useful technique for
7970: @c low-performance systems (for example, 8-bit processors in embedded
7971: @c systems) but is unlikely to be necessary in high-performance desktop
7972: @c systems.
7973:
7974: @item
7975: To prevent a set of words from being used outside the context in which
7976: they are valid. Two classic examples of this are an integrated editor
7977: (all of the edit commands are defined in a separate word list; the
7978: search order is set to the editor word list when the editor is invoked;
7979: the old search order is restored when the editor is terminated) and an
7980: integrated assembler (the op-codes for the machine are defined in a
7981: separate word list which is used when a @code{CODE} word is defined).
7982:
7983: @item
7984: To organize the words of an application or library into a user-visible
7985: set (in @code{forth-wordlist} or some other common wordlist) and a set
7986: of helper words used just for the implementation (hidden in a separate
7987: wordlist). This keeps @code{words}' output smaller, separates
7988: implementation and interface, and reduces the chance of name conflicts
7989: within the common wordlist.
7990:
7991: @item
7992: To prevent a name-space clash between multiple definitions with the same
7993: name. For example, when building a cross-compiler you might have a word
7994: @code{IF} that generates conditional code for your target system. By
7995: placing this definition in a different word list you can control whether
7996: the host system's @code{IF} or the target system's @code{IF} get used in
7997: any particular context by controlling the order of the word lists on the
7998: search order stack.
7999:
8000: @end itemize
8001:
8002: The downsides of using wordlists are:
8003:
8004: @itemize
8005:
8006: @item
8007: Debugging becomes more cumbersome.
8008:
8009: @item
8010: Name conflicts worked around with wordlists are still there, and you
8011: have to arrange the search order carefully to get the desired results;
8012: if you forget to do that, you get hard-to-find errors (as in any case
8013: where you read the code differently from the compiler; @code{see} can
8014: help seeing which of several possible words the name resolves to in such
8015: cases). @code{See} displays just the name of the words, not what
8016: wordlist they belong to, so it might be misleading. Using unique names
8017: is a better approach to avoid name conflicts.
8018:
8019: @item
8020: You have to explicitly undo any changes to the search order. In many
8021: cases it would be more convenient if this happened implicitly. Gforth
8022: currently does not provide such a feature, but it may do so in the
8023: future.
8024: @end itemize
8025:
8026:
8027: @node Word list example, , Why use word lists?, Word Lists
8028: @subsection Word list example
8029: @cindex word lists - example
8030:
8031: The following example is from the
8032: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8033: garbage collector} and uses wordlists to separate public words from
8034: helper words:
8035:
8036: @example
8037: get-current ( wid )
8038: vocabulary garbage-collector also garbage-collector definitions
8039: ... \ define helper words
8040: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8041: ... \ define the public (i.e., API) words
8042: \ they can refer to the helper words
8043: previous \ restore original search order (helper words become invisible)
8044: @end example
8045:
8046: @c -------------------------------------------------------------
8047: @node Environmental Queries, Files, Word Lists, Words
8048: @section Environmental Queries
8049: @cindex environmental queries
8050:
8051: ANS Forth introduced the idea of ``environmental queries'' as a way
8052: for a program running on a system to determine certain characteristics of the system.
8053: The Standard specifies a number of strings that might be recognised by a system.
8054:
8055: The Standard requires that the header space used for environmental queries
8056: be distinct from the header space used for definitions.
8057:
8058: Typically, environmental queries are supported by creating a set of
8059: definitions in a word list that is @i{only} used during environmental
8060: queries; that is what Gforth does. There is no Standard way of adding
8061: definitions to the set of recognised environmental queries, but any
8062: implementation that supports the loading of optional word sets must have
8063: some mechanism for doing this (after loading the word set, the
8064: associated environmental query string must return @code{true}). In
8065: Gforth, the word list used to honour environmental queries can be
8066: manipulated just like any other word list.
8067:
8068:
8069: doc-environment?
8070: doc-environment-wordlist
8071:
8072: doc-gforth
8073: doc-os-class
8074:
8075:
8076: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8077: returning two items on the stack, querying it using @code{environment?}
8078: will return an additional item; the @code{true} flag that shows that the
8079: string was recognised.
8080:
8081: @comment TODO Document the standard strings or note where they are documented herein
8082:
8083: Here are some examples of using environmental queries:
8084:
8085: @example
8086: s" address-unit-bits" environment? 0=
8087: [IF]
8088: cr .( environmental attribute address-units-bits unknown... ) cr
8089: [ELSE]
8090: drop \ ensure balanced stack effect
8091: [THEN]
8092:
8093: \ this might occur in the prelude of a standard program that uses THROW
8094: s" exception" environment? [IF]
8095: 0= [IF]
8096: : throw abort" exception thrown" ;
8097: [THEN]
8098: [ELSE] \ we don't know, so make sure
8099: : throw abort" exception thrown" ;
8100: [THEN]
8101:
8102: s" gforth" environment? [IF] .( Gforth version ) TYPE
8103: [ELSE] .( Not Gforth..) [THEN]
8104:
8105: \ a program using v*
8106: s" gforth" environment? [IF]
8107: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8108: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8109: >r swap 2swap swap 0e r> 0 ?DO
8110: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8111: LOOP
8112: 2drop 2drop ;
8113: [THEN]
8114: [ELSE] \
8115: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8116: ...
8117: [THEN]
8118: @end example
8119:
8120: Here is an example of adding a definition to the environment word list:
8121:
8122: @example
8123: get-current environment-wordlist set-current
8124: true constant block
8125: true constant block-ext
8126: set-current
8127: @end example
8128:
8129: You can see what definitions are in the environment word list like this:
8130:
8131: @example
8132: environment-wordlist >order words previous
8133: @end example
8134:
8135:
8136: @c -------------------------------------------------------------
8137: @node Files, Blocks, Environmental Queries, Words
8138: @section Files
8139: @cindex files
8140: @cindex I/O - file-handling
8141:
8142: Gforth provides facilities for accessing files that are stored in the
8143: host operating system's file-system. Files that are processed by Gforth
8144: can be divided into two categories:
8145:
8146: @itemize @bullet
8147: @item
8148: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
8149: @item
8150: Files that are processed by some other program (@dfn{general files}).
8151: @end itemize
8152:
8153: @menu
8154: * Forth source files::
8155: * General files::
8156: * Search Paths::
8157: @end menu
8158:
8159: @c -------------------------------------------------------------
8160: @node Forth source files, General files, Files, Files
8161: @subsection Forth source files
8162: @cindex including files
8163: @cindex Forth source files
8164:
8165: The simplest way to interpret the contents of a file is to use one of
8166: these two formats:
8167:
8168: @example
8169: include mysource.fs
8170: s" mysource.fs" included
8171: @end example
8172:
8173: You usually want to include a file only if it is not included already
8174: (by, say, another source file). In that case, you can use one of these
8175: three formats:
8176:
8177: @example
8178: require mysource.fs
8179: needs mysource.fs
8180: s" mysource.fs" required
8181: @end example
8182:
8183: @cindex stack effect of included files
8184: @cindex including files, stack effect
8185: It is good practice to write your source files such that interpreting them
8186: does not change the stack. Source files designed in this way can be used with
8187: @code{required} and friends without complications. For example:
8188:
8189: @example
8190: 1024 require foo.fs drop
8191: @end example
8192:
8193: Here you want to pass the argument 1024 (e.g., a buffer size) to
8194: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8195: ), which allows its use with @code{require}. Of course with such
8196: parameters to required files, you have to ensure that the first
8197: @code{require} fits for all uses (i.e., @code{require} it early in the
8198: master load file).
8199:
8200: doc-include-file
8201: doc-included
8202: doc-included?
8203: doc-include
8204: doc-required
8205: doc-require
8206: doc-needs
8207: @c doc-init-included-files @c internal
8208: doc-sourcefilename
8209: doc-sourceline#
8210:
8211: A definition in ANS Forth for @code{required} is provided in
8212: @file{compat/required.fs}.
8213:
8214: @c -------------------------------------------------------------
8215: @node General files, Search Paths, Forth source files, Files
8216: @subsection General files
8217: @cindex general files
8218: @cindex file-handling
8219:
8220: Files are opened/created by name and type. The following file access
8221: methods (FAMs) are recognised:
8222:
8223: @cindex fam (file access method)
8224: doc-r/o
8225: doc-r/w
8226: doc-w/o
8227: doc-bin
8228:
8229:
8230: When a file is opened/created, it returns a file identifier,
8231: @i{wfileid} that is used for all other file commands. All file
8232: commands also return a status value, @i{wior}, that is 0 for a
8233: successful operation and an implementation-defined non-zero value in the
8234: case of an error.
8235:
8236:
8237: doc-open-file
8238: doc-create-file
8239:
8240: doc-close-file
8241: doc-delete-file
8242: doc-rename-file
8243: doc-read-file
8244: doc-read-line
8245: doc-write-file
8246: doc-write-line
8247: doc-emit-file
8248: doc-flush-file
8249:
8250: doc-file-status
8251: doc-file-position
8252: doc-reposition-file
8253: doc-file-size
8254: doc-resize-file
8255:
8256: doc-slurp-file
8257: doc-slurp-fid
8258: doc-stdin
8259: doc-stdout
8260: doc-stderr
8261:
8262: @c ---------------------------------------------------------
8263: @node Search Paths, , General files, Files
8264: @subsection Search Paths
8265: @cindex path for @code{included}
8266: @cindex file search path
8267: @cindex @code{include} search path
8268: @cindex search path for files
8269:
8270: If you specify an absolute filename (i.e., a filename starting with
8271: @file{/} or @file{~}, or with @file{:} in the second position (as in
8272: @samp{C:...})) for @code{included} and friends, that file is included
8273: just as you would expect.
8274:
8275: If the filename starts with @file{./}, this refers to the directory that
8276: the present file was @code{included} from. This allows files to include
8277: other files relative to their own position (irrespective of the current
8278: working directory or the absolute position). This feature is essential
8279: for libraries consisting of several files, where a file may include
8280: other files from the library. It corresponds to @code{#include "..."}
8281: in C. If the current input source is not a file, @file{.} refers to the
8282: directory of the innermost file being included, or, if there is no file
8283: being included, to the current working directory.
8284:
8285: For relative filenames (not starting with @file{./}), Gforth uses a
8286: search path similar to Forth's search order (@pxref{Word Lists}). It
8287: tries to find the given filename in the directories present in the path,
8288: and includes the first one it finds. There are separate search paths for
8289: Forth source files and general files. If the search path contains the
8290: directory @file{.}, this refers to the directory of the current file, or
8291: the working directory, as if the file had been specified with @file{./}.
8292:
8293: Use @file{~+} to refer to the current working directory (as in the
8294: @code{bash}).
8295:
8296: @c anton: fold the following subsubsections into this subsection?
8297:
8298: @menu
8299: * Source Search Paths::
8300: * General Search Paths::
8301: @end menu
8302:
8303: @c ---------------------------------------------------------
8304: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8305: @subsubsection Source Search Paths
8306: @cindex search path control, source files
8307:
8308: The search path is initialized when you start Gforth (@pxref{Invoking
8309: Gforth}). You can display it and change it using @code{fpath} in
8310: combination with the general path handling words.
8311:
8312: doc-fpath
8313: @c the functionality of the following words is easily available through
8314: @c fpath and the general path words. The may go away.
8315: @c doc-.fpath
8316: @c doc-fpath+
8317: @c doc-fpath=
8318: @c doc-open-fpath-file
8319:
8320: @noindent
8321: Here is an example of using @code{fpath} and @code{require}:
8322:
8323: @example
8324: fpath path= /usr/lib/forth/|./
8325: require timer.fs
8326: @end example
8327:
8328:
8329: @c ---------------------------------------------------------
8330: @node General Search Paths, , Source Search Paths, Search Paths
8331: @subsubsection General Search Paths
8332: @cindex search path control, source files
8333:
8334: Your application may need to search files in several directories, like
8335: @code{included} does. To facilitate this, Gforth allows you to define
8336: and use your own search paths, by providing generic equivalents of the
8337: Forth search path words:
8338:
8339: doc-open-path-file
8340: doc-path-allot
8341: doc-clear-path
8342: doc-also-path
8343: doc-.path
8344: doc-path+
8345: doc-path=
8346:
8347: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
8348:
8349: Here's an example of creating an empty search path:
8350: @c
8351: @example
8352: create mypath 500 path-allot \ maximum length 500 chars (is checked)
8353: @end example
8354:
8355: @c -------------------------------------------------------------
8356: @node Blocks, Other I/O, Files, Words
8357: @section Blocks
8358: @cindex I/O - blocks
8359: @cindex blocks
8360:
8361: When you run Gforth on a modern desk-top computer, it runs under the
8362: control of an operating system which provides certain services. One of
8363: these services is @var{file services}, which allows Forth source code
8364: and data to be stored in files and read into Gforth (@pxref{Files}).
8365:
8366: Traditionally, Forth has been an important programming language on
8367: systems where it has interfaced directly to the underlying hardware with
8368: no intervening operating system. Forth provides a mechanism, called
8369: @dfn{blocks}, for accessing mass storage on such systems.
8370:
8371: A block is a 1024-byte data area, which can be used to hold data or
8372: Forth source code. No structure is imposed on the contents of the
8373: block. A block is identified by its number; blocks are numbered
8374: contiguously from 1 to an implementation-defined maximum.
8375:
8376: A typical system that used blocks but no operating system might use a
8377: single floppy-disk drive for mass storage, with the disks formatted to
8378: provide 256-byte sectors. Blocks would be implemented by assigning the
8379: first four sectors of the disk to block 1, the second four sectors to
8380: block 2 and so on, up to the limit of the capacity of the disk. The disk
8381: would not contain any file system information, just the set of blocks.
8382:
8383: @cindex blocks file
8384: On systems that do provide file services, blocks are typically
8385: implemented by storing a sequence of blocks within a single @dfn{blocks
8386: file}. The size of the blocks file will be an exact multiple of 1024
8387: bytes, corresponding to the number of blocks it contains. This is the
8388: mechanism that Gforth uses.
8389:
8390: @cindex @file{blocks.fb}
8391: Only one blocks file can be open at a time. If you use block words without
8392: having specified a blocks file, Gforth defaults to the blocks file
8393: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
8394: locate a blocks file (@pxref{Source Search Paths}).
8395:
8396: @cindex block buffers
8397: When you read and write blocks under program control, Gforth uses a
8398: number of @dfn{block buffers} as intermediate storage. These buffers are
8399: not used when you use @code{load} to interpret the contents of a block.
8400:
8401: The behaviour of the block buffers is analagous to that of a cache.
8402: Each block buffer has three states:
8403:
8404: @itemize @bullet
8405: @item
8406: Unassigned
8407: @item
8408: Assigned-clean
8409: @item
8410: Assigned-dirty
8411: @end itemize
8412:
8413: Initially, all block buffers are @i{unassigned}. In order to access a
8414: block, the block (specified by its block number) must be assigned to a
8415: block buffer.
8416:
8417: The assignment of a block to a block buffer is performed by @code{block}
8418: or @code{buffer}. Use @code{block} when you wish to modify the existing
8419: contents of a block. Use @code{buffer} when you don't care about the
8420: existing contents of the block@footnote{The ANS Forth definition of
8421: @code{buffer} is intended not to cause disk I/O; if the data associated
8422: with the particular block is already stored in a block buffer due to an
8423: earlier @code{block} command, @code{buffer} will return that block
8424: buffer and the existing contents of the block will be
8425: available. Otherwise, @code{buffer} will simply assign a new, empty
8426: block buffer for the block.}.
8427:
8428: Once a block has been assigned to a block buffer using @code{block} or
8429: @code{buffer}, that block buffer becomes the @i{current block
8430: buffer}. Data may only be manipulated (read or written) within the
8431: current block buffer.
8432:
8433: When the contents of the current block buffer has been modified it is
8434: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
8435: either abandon the changes (by doing nothing) or mark the block as
8436: changed (assigned-dirty), using @code{update}. Using @code{update} does
8437: not change the blocks file; it simply changes a block buffer's state to
8438: @i{assigned-dirty}. The block will be written implicitly when it's
8439: buffer is needed for another block, or explicitly by @code{flush} or
8440: @code{save-buffers}.
8441:
8442: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8443: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8444: @code{flush}.
8445:
8446: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
8447: algorithm to assign a block buffer to a block. That means that any
8448: particular block can only be assigned to one specific block buffer,
8449: called (for the particular operation) the @i{victim buffer}. If the
8450: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8451: the new block immediately. If it is @i{assigned-dirty} its current
8452: contents are written back to the blocks file on disk before it is
8453: allocated to the new block.
8454:
8455: Although no structure is imposed on the contents of a block, it is
8456: traditional to display the contents as 16 lines each of 64 characters. A
8457: block provides a single, continuous stream of input (for example, it
8458: acts as a single parse area) -- there are no end-of-line characters
8459: within a block, and no end-of-file character at the end of a
8460: block. There are two consequences of this:
8461:
8462: @itemize @bullet
8463: @item
8464: The last character of one line wraps straight into the first character
8465: of the following line
8466: @item
8467: The word @code{\} -- comment to end of line -- requires special
8468: treatment; in the context of a block it causes all characters until the
8469: end of the current 64-character ``line'' to be ignored.
8470: @end itemize
8471:
8472: In Gforth, when you use @code{block} with a non-existent block number,
8473: the current blocks file will be extended to the appropriate size and the
8474: block buffer will be initialised with spaces.
8475:
8476: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8477: for details) but doesn't encourage the use of blocks; the mechanism is
8478: only provided for backward compatibility -- ANS Forth requires blocks to
8479: be available when files are.
8480:
8481: Common techniques that are used when working with blocks include:
8482:
8483: @itemize @bullet
8484: @item
8485: A screen editor that allows you to edit blocks without leaving the Forth
8486: environment.
8487: @item
8488: Shadow screens; where every code block has an associated block
8489: containing comments (for example: code in odd block numbers, comments in
8490: even block numbers). Typically, the block editor provides a convenient
8491: mechanism to toggle between code and comments.
8492: @item
8493: Load blocks; a single block (typically block 1) contains a number of
8494: @code{thru} commands which @code{load} the whole of the application.
8495: @end itemize
8496:
8497: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8498: integrated into a Forth programming environment.
8499:
8500: @comment TODO what about errors on open-blocks?
8501:
8502: doc-open-blocks
8503: doc-use
8504: doc-block-offset
8505: doc-get-block-fid
8506: doc-block-position
8507:
8508: doc-list
8509: doc-scr
8510:
8511: doc---gforthman-block
8512: doc-buffer
8513:
8514: doc-empty-buffers
8515: doc-empty-buffer
8516: doc-update
8517: doc-updated?
8518: doc-save-buffers
8519: doc-save-buffer
8520: doc-flush
8521:
8522: doc-load
8523: doc-thru
8524: doc-+load
8525: doc-+thru
8526: doc---gforthman--->
8527: doc-block-included
8528:
8529:
8530: @c -------------------------------------------------------------
8531: @node Other I/O, Locals, Blocks, Words
8532: @section Other I/O
8533: @cindex I/O - keyboard and display
8534:
8535: @menu
8536: * Simple numeric output:: Predefined formats
8537: * Formatted numeric output:: Formatted (pictured) output
8538: * String Formats:: How Forth stores strings in memory
8539: * Displaying characters and strings:: Other stuff
8540: * Input:: Input
8541: * Pipes:: How to create your own pipes
8542: @end menu
8543:
8544: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8545: @subsection Simple numeric output
8546: @cindex numeric output - simple/free-format
8547:
8548: The simplest output functions are those that display numbers from the
8549: data or floating-point stacks. Floating-point output is always displayed
8550: using base 10. Numbers displayed from the data stack use the value stored
8551: in @code{base}.
8552:
8553:
8554: doc-.
8555: doc-dec.
8556: doc-hex.
8557: doc-u.
8558: doc-.r
8559: doc-u.r
8560: doc-d.
8561: doc-ud.
8562: doc-d.r
8563: doc-ud.r
8564: doc-f.
8565: doc-fe.
8566: doc-fs.
8567: doc-f.rdp
8568:
8569: Examples of printing the number 1234.5678E23 in the different floating-point output
8570: formats are shown below:
8571:
8572: @example
8573: f. 123456779999999000000000000.
8574: fe. 123.456779999999E24
8575: fs. 1.23456779999999E26
8576: @end example
8577:
8578:
8579: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8580: @subsection Formatted numeric output
8581: @cindex formatted numeric output
8582: @cindex pictured numeric output
8583: @cindex numeric output - formatted
8584:
8585: Forth traditionally uses a technique called @dfn{pictured numeric
8586: output} for formatted printing of integers. In this technique, digits
8587: are extracted from the number (using the current output radix defined by
8588: @code{base}), converted to ASCII codes and appended to a string that is
8589: built in a scratch-pad area of memory (@pxref{core-idef,
8590: Implementation-defined options, Implementation-defined
8591: options}). Arbitrary characters can be appended to the string during the
8592: extraction process. The completed string is specified by an address
8593: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8594: under program control.
8595:
8596: All of the integer output words described in the previous section
8597: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8598: numeric output.
8599:
8600: Three important things to remember about pictured numeric output:
8601:
8602: @itemize @bullet
8603: @item
8604: It always operates on double-precision numbers; to display a
8605: single-precision number, convert it first (for ways of doing this
8606: @pxref{Double precision}).
8607: @item
8608: It always treats the double-precision number as though it were
8609: unsigned. The examples below show ways of printing signed numbers.
8610: @item
8611: The string is built up from right to left; least significant digit first.
8612: @end itemize
8613:
8614:
8615: doc-<#
8616: doc-<<#
8617: doc-#
8618: doc-#s
8619: doc-hold
8620: doc-sign
8621: doc-#>
8622: doc-#>>
8623:
8624: doc-represent
8625: doc-f>str-rdp
8626: doc-f>buf-rdp
8627:
8628:
8629: @noindent
8630: Here are some examples of using pictured numeric output:
8631:
8632: @example
8633: : my-u. ( u -- )
8634: \ Simplest use of pns.. behaves like Standard u.
8635: 0 \ convert to unsigned double
8636: <<# \ start conversion
8637: #s \ convert all digits
8638: #> \ complete conversion
8639: TYPE SPACE \ display, with trailing space
8640: #>> ; \ release hold area
8641:
8642: : cents-only ( u -- )
8643: 0 \ convert to unsigned double
8644: <<# \ start conversion
8645: # # \ convert two least-significant digits
8646: #> \ complete conversion, discard other digits
8647: TYPE SPACE \ display, with trailing space
8648: #>> ; \ release hold area
8649:
8650: : dollars-and-cents ( u -- )
8651: 0 \ convert to unsigned double
8652: <<# \ start conversion
8653: # # \ convert two least-significant digits
8654: [char] . hold \ insert decimal point
8655: #s \ convert remaining digits
8656: [char] $ hold \ append currency symbol
8657: #> \ complete conversion
8658: TYPE SPACE \ display, with trailing space
8659: #>> ; \ release hold area
8660:
8661: : my-. ( n -- )
8662: \ handling negatives.. behaves like Standard .
8663: s>d \ convert to signed double
8664: swap over dabs \ leave sign byte followed by unsigned double
8665: <<# \ start conversion
8666: #s \ convert all digits
8667: rot sign \ get at sign byte, append "-" if needed
8668: #> \ complete conversion
8669: TYPE SPACE \ display, with trailing space
8670: #>> ; \ release hold area
8671:
8672: : account. ( n -- )
8673: \ accountants don't like minus signs, they use parentheses
8674: \ for negative numbers
8675: s>d \ convert to signed double
8676: swap over dabs \ leave sign byte followed by unsigned double
8677: <<# \ start conversion
8678: 2 pick \ get copy of sign byte
8679: 0< IF [char] ) hold THEN \ right-most character of output
8680: #s \ convert all digits
8681: rot \ get at sign byte
8682: 0< IF [char] ( hold THEN
8683: #> \ complete conversion
8684: TYPE SPACE \ display, with trailing space
8685: #>> ; \ release hold area
8686:
8687: @end example
8688:
8689: Here are some examples of using these words:
8690:
8691: @example
8692: 1 my-u. 1
8693: hex -1 my-u. decimal FFFFFFFF
8694: 1 cents-only 01
8695: 1234 cents-only 34
8696: 2 dollars-and-cents $0.02
8697: 1234 dollars-and-cents $12.34
8698: 123 my-. 123
8699: -123 my. -123
8700: 123 account. 123
8701: -456 account. (456)
8702: @end example
8703:
8704:
8705: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8706: @subsection String Formats
8707: @cindex strings - see character strings
8708: @cindex character strings - formats
8709: @cindex I/O - see character strings
8710: @cindex counted strings
8711:
8712: @c anton: this does not really belong here; maybe the memory section,
8713: @c or the principles chapter
8714:
8715: Forth commonly uses two different methods for representing character
8716: strings:
8717:
8718: @itemize @bullet
8719: @item
8720: @cindex address of counted string
8721: @cindex counted string
8722: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8723: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8724: string and the string occupies the subsequent @i{n} char addresses in
8725: memory.
8726: @item
8727: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8728: of the string in characters, and @i{c-addr} is the address of the
8729: first byte of the string.
8730: @end itemize
8731:
8732: ANS Forth encourages the use of the second format when representing
8733: strings.
8734:
8735:
8736: doc-count
8737:
8738:
8739: For words that move, copy and search for strings see @ref{Memory
8740: Blocks}. For words that display characters and strings see
8741: @ref{Displaying characters and strings}.
8742:
8743: @node Displaying characters and strings, Input, String Formats, Other I/O
8744: @subsection Displaying characters and strings
8745: @cindex characters - compiling and displaying
8746: @cindex character strings - compiling and displaying
8747:
8748: This section starts with a glossary of Forth words and ends with a set
8749: of examples.
8750:
8751:
8752: doc-bl
8753: doc-space
8754: doc-spaces
8755: doc-emit
8756: doc-toupper
8757: doc-."
8758: doc-.(
8759: doc-.\"
8760: doc-type
8761: doc-typewhite
8762: doc-cr
8763: @cindex cursor control
8764: doc-at-xy
8765: doc-page
8766: doc-s"
8767: doc-s\"
8768: doc-c"
8769: doc-char
8770: doc-[char]
8771:
8772:
8773: @noindent
8774: As an example, consider the following text, stored in a file @file{test.fs}:
8775:
8776: @example
8777: .( text-1)
8778: : my-word
8779: ." text-2" cr
8780: .( text-3)
8781: ;
8782:
8783: ." text-4"
8784:
8785: : my-char
8786: [char] ALPHABET emit
8787: char emit
8788: ;
8789: @end example
8790:
8791: When you load this code into Gforth, the following output is generated:
8792:
8793: @example
8794: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
8795: @end example
8796:
8797: @itemize @bullet
8798: @item
8799: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8800: is an immediate word; it behaves in the same way whether it is used inside
8801: or outside a colon definition.
8802: @item
8803: Message @code{text-4} is displayed because of Gforth's added interpretation
8804: semantics for @code{."}.
8805: @item
8806: Message @code{text-2} is @i{not} displayed, because the text interpreter
8807: performs the compilation semantics for @code{."} within the definition of
8808: @code{my-word}.
8809: @end itemize
8810:
8811: Here are some examples of executing @code{my-word} and @code{my-char}:
8812:
8813: @example
8814: @kbd{my-word @key{RET}} text-2
8815: ok
8816: @kbd{my-char fred @key{RET}} Af ok
8817: @kbd{my-char jim @key{RET}} Aj ok
8818: @end example
8819:
8820: @itemize @bullet
8821: @item
8822: Message @code{text-2} is displayed because of the run-time behaviour of
8823: @code{."}.
8824: @item
8825: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8826: on the stack at run-time. @code{emit} always displays the character
8827: when @code{my-char} is executed.
8828: @item
8829: @code{char} parses a string at run-time and the second @code{emit} displays
8830: the first character of the string.
8831: @item
8832: If you type @code{see my-char} you can see that @code{[char]} discarded
8833: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8834: definition of @code{my-char}.
8835: @end itemize
8836:
8837:
8838:
8839: @node Input, Pipes, Displaying characters and strings, Other I/O
8840: @subsection Input
8841: @cindex input
8842: @cindex I/O - see input
8843: @cindex parsing a string
8844:
8845: For ways of storing character strings in memory see @ref{String Formats}.
8846:
8847: @comment TODO examples for >number >float accept key key? pad parse word refill
8848: @comment then index them
8849:
8850:
8851: doc-key
8852: doc-key?
8853: doc-ekey
8854: doc-ekey?
8855: doc-ekey>char
8856: doc->number
8857: doc->float
8858: doc-accept
8859: doc-edit-line
8860: doc-pad
8861: @comment obsolescent words..
8862: doc-convert
8863: doc-expect
8864: doc-span
8865:
8866:
8867: @node Pipes, , Input, Other I/O
8868: @subsection Pipes
8869: @cindex pipes, creating your own
8870:
8871: In addition to using Gforth in pipes created by other processes
8872: (@pxref{Gforth in pipes}), you can create your own pipe with
8873: @code{open-pipe}, and read from or write to it.
8874:
8875: doc-open-pipe
8876: doc-close-pipe
8877:
8878: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
8879: you don't catch this exception, Gforth will catch it and exit, usually
8880: silently (@pxref{Gforth in pipes}). Since you probably do not want
8881: this, you should wrap a @code{catch} or @code{try} block around the code
8882: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
8883: problem yourself, and then return to regular processing.
8884:
8885: doc-broken-pipe-error
8886:
8887:
8888: @node OS command line arguments, Locals, Other I/O, Words
8889: @section OS command line arguments
8890: @cindex OS command line arguments
8891: @cindex command line arguments, OS
8892: @cindex arguments, OS command line
8893:
8894: The usual way to pass arguments to Gforth programs on the command line
8895: is via the @option{-e} option, e.g.
8896:
8897: @example
8898: gforth -e "123 456" foo.fs -e bye
8899: @end example
8900:
8901: However, you may want to interpret the command-line arguments directly.
8902: In that case, you can access the (image-specific) command-line arguments
8903: through @code{next-arg}:
8904:
8905: doc-next-arg
8906:
8907: Here's an example program @file{echo.fs} for @code{next-arg}:
8908:
8909: @example
8910: : echo ( -- )
8911: begin
8912: next-arg 2dup 0 0 d<> while
8913: type space
8914: repeat
8915: 2drop ;
8916:
8917: echo cr bye
8918: @end example
8919:
8920: This can be invoked with
8921:
8922: @example
8923: gforth echo.fs hello world
8924: @end example
8925:
8926: and it will print
8927:
8928: @example
8929: hello world
8930: @end example
8931:
8932: The next lower level of dealing with the OS command line are the
8933: following words:
8934:
8935: doc-arg
8936: doc-shift-args
8937:
8938: Finally, at the lowest level Gforth provides the following words:
8939:
8940: doc-argc
8941: doc-argv
8942:
8943: @c -------------------------------------------------------------
8944: @node Locals, Structures, Other I/O, Words
8945: @section Locals
8946: @cindex locals
8947:
8948: Local variables can make Forth programming more enjoyable and Forth
8949: programs easier to read. Unfortunately, the locals of ANS Forth are
8950: laden with restrictions. Therefore, we provide not only the ANS Forth
8951: locals wordset, but also our own, more powerful locals wordset (we
8952: implemented the ANS Forth locals wordset through our locals wordset).
8953:
8954: The ideas in this section have also been published in M. Anton Ertl,
8955: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
8956: Automatic Scoping of Local Variables}}, EuroForth '94.
8957:
8958: @menu
8959: * Gforth locals::
8960: * ANS Forth locals::
8961: @end menu
8962:
8963: @node Gforth locals, ANS Forth locals, Locals, Locals
8964: @subsection Gforth locals
8965: @cindex Gforth locals
8966: @cindex locals, Gforth style
8967:
8968: Locals can be defined with
8969:
8970: @example
8971: @{ local1 local2 ... -- comment @}
8972: @end example
8973: or
8974: @example
8975: @{ local1 local2 ... @}
8976: @end example
8977:
8978: E.g.,
8979: @example
8980: : max @{ n1 n2 -- n3 @}
8981: n1 n2 > if
8982: n1
8983: else
8984: n2
8985: endif ;
8986: @end example
8987:
8988: The similarity of locals definitions with stack comments is intended. A
8989: locals definition often replaces the stack comment of a word. The order
8990: of the locals corresponds to the order in a stack comment and everything
8991: after the @code{--} is really a comment.
8992:
8993: This similarity has one disadvantage: It is too easy to confuse locals
8994: declarations with stack comments, causing bugs and making them hard to
8995: find. However, this problem can be avoided by appropriate coding
8996: conventions: Do not use both notations in the same program. If you do,
8997: they should be distinguished using additional means, e.g. by position.
8998:
8999: @cindex types of locals
9000: @cindex locals types
9001: The name of the local may be preceded by a type specifier, e.g.,
9002: @code{F:} for a floating point value:
9003:
9004: @example
9005: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9006: \ complex multiplication
9007: Ar Br f* Ai Bi f* f-
9008: Ar Bi f* Ai Br f* f+ ;
9009: @end example
9010:
9011: @cindex flavours of locals
9012: @cindex locals flavours
9013: @cindex value-flavoured locals
9014: @cindex variable-flavoured locals
9015: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9016: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9017: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9018: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9019: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9020: produces its address (which becomes invalid when the variable's scope is
9021: left). E.g., the standard word @code{emit} can be defined in terms of
9022: @code{type} like this:
9023:
9024: @example
9025: : emit @{ C^ char* -- @}
9026: char* 1 type ;
9027: @end example
9028:
9029: @cindex default type of locals
9030: @cindex locals, default type
9031: A local without type specifier is a @code{W:} local. Both flavours of
9032: locals are initialized with values from the data or FP stack.
9033:
9034: Currently there is no way to define locals with user-defined data
9035: structures, but we are working on it.
9036:
9037: Gforth allows defining locals everywhere in a colon definition. This
9038: poses the following questions:
9039:
9040: @menu
9041: * Where are locals visible by name?::
9042: * How long do locals live?::
9043: * Locals programming style::
9044: * Locals implementation::
9045: @end menu
9046:
9047: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9048: @subsubsection Where are locals visible by name?
9049: @cindex locals visibility
9050: @cindex visibility of locals
9051: @cindex scope of locals
9052:
9053: Basically, the answer is that locals are visible where you would expect
9054: it in block-structured languages, and sometimes a little longer. If you
9055: want to restrict the scope of a local, enclose its definition in
9056: @code{SCOPE}...@code{ENDSCOPE}.
9057:
9058:
9059: doc-scope
9060: doc-endscope
9061:
9062:
9063: These words behave like control structure words, so you can use them
9064: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9065: arbitrary ways.
9066:
9067: If you want a more exact answer to the visibility question, here's the
9068: basic principle: A local is visible in all places that can only be
9069: reached through the definition of the local@footnote{In compiler
9070: construction terminology, all places dominated by the definition of the
9071: local.}. In other words, it is not visible in places that can be reached
9072: without going through the definition of the local. E.g., locals defined
9073: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9074: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9075: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
9076:
9077: The reasoning behind this solution is: We want to have the locals
9078: visible as long as it is meaningful. The user can always make the
9079: visibility shorter by using explicit scoping. In a place that can
9080: only be reached through the definition of a local, the meaning of a
9081: local name is clear. In other places it is not: How is the local
9082: initialized at the control flow path that does not contain the
9083: definition? Which local is meant, if the same name is defined twice in
9084: two independent control flow paths?
9085:
9086: This should be enough detail for nearly all users, so you can skip the
9087: rest of this section. If you really must know all the gory details and
9088: options, read on.
9089:
9090: In order to implement this rule, the compiler has to know which places
9091: are unreachable. It knows this automatically after @code{AHEAD},
9092: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9093: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9094: compiler that the control flow never reaches that place. If
9095: @code{UNREACHABLE} is not used where it could, the only consequence is
9096: that the visibility of some locals is more limited than the rule above
9097: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9098: lie to the compiler), buggy code will be produced.
9099:
9100:
9101: doc-unreachable
9102:
9103:
9104: Another problem with this rule is that at @code{BEGIN}, the compiler
9105: does not know which locals will be visible on the incoming
9106: back-edge. All problems discussed in the following are due to this
9107: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9108: loops as examples; the discussion also applies to @code{?DO} and other
9109: loops). Perhaps the most insidious example is:
9110: @example
9111: AHEAD
9112: BEGIN
9113: x
9114: [ 1 CS-ROLL ] THEN
9115: @{ x @}
9116: ...
9117: UNTIL
9118: @end example
9119:
9120: This should be legal according to the visibility rule. The use of
9121: @code{x} can only be reached through the definition; but that appears
9122: textually below the use.
9123:
9124: From this example it is clear that the visibility rules cannot be fully
9125: implemented without major headaches. Our implementation treats common
9126: cases as advertised and the exceptions are treated in a safe way: The
9127: compiler makes a reasonable guess about the locals visible after a
9128: @code{BEGIN}; if it is too pessimistic, the
9129: user will get a spurious error about the local not being defined; if the
9130: compiler is too optimistic, it will notice this later and issue a
9131: warning. In the case above the compiler would complain about @code{x}
9132: being undefined at its use. You can see from the obscure examples in
9133: this section that it takes quite unusual control structures to get the
9134: compiler into trouble, and even then it will often do fine.
9135:
9136: If the @code{BEGIN} is reachable from above, the most optimistic guess
9137: is that all locals visible before the @code{BEGIN} will also be
9138: visible after the @code{BEGIN}. This guess is valid for all loops that
9139: are entered only through the @code{BEGIN}, in particular, for normal
9140: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9141: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9142: compiler. When the branch to the @code{BEGIN} is finally generated by
9143: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9144: warns the user if it was too optimistic:
9145: @example
9146: IF
9147: @{ x @}
9148: BEGIN
9149: \ x ?
9150: [ 1 cs-roll ] THEN
9151: ...
9152: UNTIL
9153: @end example
9154:
9155: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9156: optimistically assumes that it lives until the @code{THEN}. It notices
9157: this difference when it compiles the @code{UNTIL} and issues a
9158: warning. The user can avoid the warning, and make sure that @code{x}
9159: is not used in the wrong area by using explicit scoping:
9160: @example
9161: IF
9162: SCOPE
9163: @{ x @}
9164: ENDSCOPE
9165: BEGIN
9166: [ 1 cs-roll ] THEN
9167: ...
9168: UNTIL
9169: @end example
9170:
9171: Since the guess is optimistic, there will be no spurious error messages
9172: about undefined locals.
9173:
9174: If the @code{BEGIN} is not reachable from above (e.g., after
9175: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9176: optimistic guess, as the locals visible after the @code{BEGIN} may be
9177: defined later. Therefore, the compiler assumes that no locals are
9178: visible after the @code{BEGIN}. However, the user can use
9179: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9180: visible at the BEGIN as at the point where the top control-flow stack
9181: item was created.
9182:
9183:
9184: doc-assume-live
9185:
9186:
9187: @noindent
9188: E.g.,
9189: @example
9190: @{ x @}
9191: AHEAD
9192: ASSUME-LIVE
9193: BEGIN
9194: x
9195: [ 1 CS-ROLL ] THEN
9196: ...
9197: UNTIL
9198: @end example
9199:
9200: Other cases where the locals are defined before the @code{BEGIN} can be
9201: handled by inserting an appropriate @code{CS-ROLL} before the
9202: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9203: behind the @code{ASSUME-LIVE}).
9204:
9205: Cases where locals are defined after the @code{BEGIN} (but should be
9206: visible immediately after the @code{BEGIN}) can only be handled by
9207: rearranging the loop. E.g., the ``most insidious'' example above can be
9208: arranged into:
9209: @example
9210: BEGIN
9211: @{ x @}
9212: ... 0=
9213: WHILE
9214: x
9215: REPEAT
9216: @end example
9217:
9218: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9219: @subsubsection How long do locals live?
9220: @cindex locals lifetime
9221: @cindex lifetime of locals
9222:
9223: The right answer for the lifetime question would be: A local lives at
9224: least as long as it can be accessed. For a value-flavoured local this
9225: means: until the end of its visibility. However, a variable-flavoured
9226: local could be accessed through its address far beyond its visibility
9227: scope. Ultimately, this would mean that such locals would have to be
9228: garbage collected. Since this entails un-Forth-like implementation
9229: complexities, I adopted the same cowardly solution as some other
9230: languages (e.g., C): The local lives only as long as it is visible;
9231: afterwards its address is invalid (and programs that access it
9232: afterwards are erroneous).
9233:
9234: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9235: @subsubsection Locals programming style
9236: @cindex locals programming style
9237: @cindex programming style, locals
9238:
9239: The freedom to define locals anywhere has the potential to change
9240: programming styles dramatically. In particular, the need to use the
9241: return stack for intermediate storage vanishes. Moreover, all stack
9242: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9243: determined arguments) can be eliminated: If the stack items are in the
9244: wrong order, just write a locals definition for all of them; then
9245: write the items in the order you want.
9246:
9247: This seems a little far-fetched and eliminating stack manipulations is
9248: unlikely to become a conscious programming objective. Still, the number
9249: of stack manipulations will be reduced dramatically if local variables
9250: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9251: a traditional implementation of @code{max}).
9252:
9253: This shows one potential benefit of locals: making Forth programs more
9254: readable. Of course, this benefit will only be realized if the
9255: programmers continue to honour the principle of factoring instead of
9256: using the added latitude to make the words longer.
9257:
9258: @cindex single-assignment style for locals
9259: Using @code{TO} can and should be avoided. Without @code{TO},
9260: every value-flavoured local has only a single assignment and many
9261: advantages of functional languages apply to Forth. I.e., programs are
9262: easier to analyse, to optimize and to read: It is clear from the
9263: definition what the local stands for, it does not turn into something
9264: different later.
9265:
9266: E.g., a definition using @code{TO} might look like this:
9267: @example
9268: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9269: u1 u2 min 0
9270: ?do
9271: addr1 c@@ addr2 c@@ -
9272: ?dup-if
9273: unloop exit
9274: then
9275: addr1 char+ TO addr1
9276: addr2 char+ TO addr2
9277: loop
9278: u1 u2 - ;
9279: @end example
9280: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9281: every loop iteration. @code{strcmp} is a typical example of the
9282: readability problems of using @code{TO}. When you start reading
9283: @code{strcmp}, you think that @code{addr1} refers to the start of the
9284: string. Only near the end of the loop you realize that it is something
9285: else.
9286:
9287: This can be avoided by defining two locals at the start of the loop that
9288: are initialized with the right value for the current iteration.
9289: @example
9290: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9291: addr1 addr2
9292: u1 u2 min 0
9293: ?do @{ s1 s2 @}
9294: s1 c@@ s2 c@@ -
9295: ?dup-if
9296: unloop exit
9297: then
9298: s1 char+ s2 char+
9299: loop
9300: 2drop
9301: u1 u2 - ;
9302: @end example
9303: Here it is clear from the start that @code{s1} has a different value
9304: in every loop iteration.
9305:
9306: @node Locals implementation, , Locals programming style, Gforth locals
9307: @subsubsection Locals implementation
9308: @cindex locals implementation
9309: @cindex implementation of locals
9310:
9311: @cindex locals stack
9312: Gforth uses an extra locals stack. The most compelling reason for
9313: this is that the return stack is not float-aligned; using an extra stack
9314: also eliminates the problems and restrictions of using the return stack
9315: as locals stack. Like the other stacks, the locals stack grows toward
9316: lower addresses. A few primitives allow an efficient implementation:
9317:
9318:
9319: doc-@local#
9320: doc-f@local#
9321: doc-laddr#
9322: doc-lp+!#
9323: doc-lp!
9324: doc->l
9325: doc-f>l
9326:
9327:
9328: In addition to these primitives, some specializations of these
9329: primitives for commonly occurring inline arguments are provided for
9330: efficiency reasons, e.g., @code{@@local0} as specialization of
9331: @code{@@local#} for the inline argument 0. The following compiling words
9332: compile the right specialized version, or the general version, as
9333: appropriate:
9334:
9335:
9336: @c doc-compile-@local
9337: @c doc-compile-f@local
9338: doc-compile-lp+!
9339:
9340:
9341: Combinations of conditional branches and @code{lp+!#} like
9342: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9343: is taken) are provided for efficiency and correctness in loops.
9344:
9345: A special area in the dictionary space is reserved for keeping the
9346: local variable names. @code{@{} switches the dictionary pointer to this
9347: area and @code{@}} switches it back and generates the locals
9348: initializing code. @code{W:} etc.@ are normal defining words. This
9349: special area is cleared at the start of every colon definition.
9350:
9351: @cindex word list for defining locals
9352: A special feature of Gforth's dictionary is used to implement the
9353: definition of locals without type specifiers: every word list (aka
9354: vocabulary) has its own methods for searching
9355: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9356: with a special search method: When it is searched for a word, it
9357: actually creates that word using @code{W:}. @code{@{} changes the search
9358: order to first search the word list containing @code{@}}, @code{W:} etc.,
9359: and then the word list for defining locals without type specifiers.
9360:
9361: The lifetime rules support a stack discipline within a colon
9362: definition: The lifetime of a local is either nested with other locals
9363: lifetimes or it does not overlap them.
9364:
9365: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9366: pointer manipulation is generated. Between control structure words
9367: locals definitions can push locals onto the locals stack. @code{AGAIN}
9368: is the simplest of the other three control flow words. It has to
9369: restore the locals stack depth of the corresponding @code{BEGIN}
9370: before branching. The code looks like this:
9371: @format
9372: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9373: @code{branch} <begin>
9374: @end format
9375:
9376: @code{UNTIL} is a little more complicated: If it branches back, it
9377: must adjust the stack just like @code{AGAIN}. But if it falls through,
9378: the locals stack must not be changed. The compiler generates the
9379: following code:
9380: @format
9381: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9382: @end format
9383: The locals stack pointer is only adjusted if the branch is taken.
9384:
9385: @code{THEN} can produce somewhat inefficient code:
9386: @format
9387: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9388: <orig target>:
9389: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9390: @end format
9391: The second @code{lp+!#} adjusts the locals stack pointer from the
9392: level at the @i{orig} point to the level after the @code{THEN}. The
9393: first @code{lp+!#} adjusts the locals stack pointer from the current
9394: level to the level at the orig point, so the complete effect is an
9395: adjustment from the current level to the right level after the
9396: @code{THEN}.
9397:
9398: @cindex locals information on the control-flow stack
9399: @cindex control-flow stack items, locals information
9400: In a conventional Forth implementation a dest control-flow stack entry
9401: is just the target address and an orig entry is just the address to be
9402: patched. Our locals implementation adds a word list to every orig or dest
9403: item. It is the list of locals visible (or assumed visible) at the point
9404: described by the entry. Our implementation also adds a tag to identify
9405: the kind of entry, in particular to differentiate between live and dead
9406: (reachable and unreachable) orig entries.
9407:
9408: A few unusual operations have to be performed on locals word lists:
9409:
9410:
9411: doc-common-list
9412: doc-sub-list?
9413: doc-list-size
9414:
9415:
9416: Several features of our locals word list implementation make these
9417: operations easy to implement: The locals word lists are organised as
9418: linked lists; the tails of these lists are shared, if the lists
9419: contain some of the same locals; and the address of a name is greater
9420: than the address of the names behind it in the list.
9421:
9422: Another important implementation detail is the variable
9423: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9424: determine if they can be reached directly or only through the branch
9425: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9426: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9427: definition, by @code{BEGIN} and usually by @code{THEN}.
9428:
9429: Counted loops are similar to other loops in most respects, but
9430: @code{LEAVE} requires special attention: It performs basically the same
9431: service as @code{AHEAD}, but it does not create a control-flow stack
9432: entry. Therefore the information has to be stored elsewhere;
9433: traditionally, the information was stored in the target fields of the
9434: branches created by the @code{LEAVE}s, by organizing these fields into a
9435: linked list. Unfortunately, this clever trick does not provide enough
9436: space for storing our extended control flow information. Therefore, we
9437: introduce another stack, the leave stack. It contains the control-flow
9438: stack entries for all unresolved @code{LEAVE}s.
9439:
9440: Local names are kept until the end of the colon definition, even if
9441: they are no longer visible in any control-flow path. In a few cases
9442: this may lead to increased space needs for the locals name area, but
9443: usually less than reclaiming this space would cost in code size.
9444:
9445:
9446: @node ANS Forth locals, , Gforth locals, Locals
9447: @subsection ANS Forth locals
9448: @cindex locals, ANS Forth style
9449:
9450: The ANS Forth locals wordset does not define a syntax for locals, but
9451: words that make it possible to define various syntaxes. One of the
9452: possible syntaxes is a subset of the syntax we used in the Gforth locals
9453: wordset, i.e.:
9454:
9455: @example
9456: @{ local1 local2 ... -- comment @}
9457: @end example
9458: @noindent
9459: or
9460: @example
9461: @{ local1 local2 ... @}
9462: @end example
9463:
9464: The order of the locals corresponds to the order in a stack comment. The
9465: restrictions are:
9466:
9467: @itemize @bullet
9468: @item
9469: Locals can only be cell-sized values (no type specifiers are allowed).
9470: @item
9471: Locals can be defined only outside control structures.
9472: @item
9473: Locals can interfere with explicit usage of the return stack. For the
9474: exact (and long) rules, see the standard. If you don't use return stack
9475: accessing words in a definition using locals, you will be all right. The
9476: purpose of this rule is to make locals implementation on the return
9477: stack easier.
9478: @item
9479: The whole definition must be in one line.
9480: @end itemize
9481:
9482: Locals defined in ANS Forth behave like @code{VALUE}s
9483: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9484: name produces their value. Their value can be changed using @code{TO}.
9485:
9486: Since the syntax above is supported by Gforth directly, you need not do
9487: anything to use it. If you want to port a program using this syntax to
9488: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9489: syntax on the other system.
9490:
9491: Note that a syntax shown in the standard, section A.13 looks
9492: similar, but is quite different in having the order of locals
9493: reversed. Beware!
9494:
9495: The ANS Forth locals wordset itself consists of one word:
9496:
9497: doc-(local)
9498:
9499: The ANS Forth locals extension wordset defines a syntax using
9500: @code{locals|}, but it is so awful that we strongly recommend not to use
9501: it. We have implemented this syntax to make porting to Gforth easy, but
9502: do not document it here. The problem with this syntax is that the locals
9503: are defined in an order reversed with respect to the standard stack
9504: comment notation, making programs harder to read, and easier to misread
9505: and miswrite. The only merit of this syntax is that it is easy to
9506: implement using the ANS Forth locals wordset.
9507:
9508:
9509: @c ----------------------------------------------------------
9510: @node Structures, Object-oriented Forth, Locals, Words
9511: @section Structures
9512: @cindex structures
9513: @cindex records
9514:
9515: This section presents the structure package that comes with Gforth. A
9516: version of the package implemented in ANS Forth is available in
9517: @file{compat/struct.fs}. This package was inspired by a posting on
9518: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9519: possibly John Hayes). A version of this section has been published in
9520: M. Anton Ertl,
9521: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9522: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9523: 13--16. Marcel Hendrix provided helpful comments.
9524:
9525: @menu
9526: * Why explicit structure support?::
9527: * Structure Usage::
9528: * Structure Naming Convention::
9529: * Structure Implementation::
9530: * Structure Glossary::
9531: @end menu
9532:
9533: @node Why explicit structure support?, Structure Usage, Structures, Structures
9534: @subsection Why explicit structure support?
9535:
9536: @cindex address arithmetic for structures
9537: @cindex structures using address arithmetic
9538: If we want to use a structure containing several fields, we could simply
9539: reserve memory for it, and access the fields using address arithmetic
9540: (@pxref{Address arithmetic}). As an example, consider a structure with
9541: the following fields
9542:
9543: @table @code
9544: @item a
9545: is a float
9546: @item b
9547: is a cell
9548: @item c
9549: is a float
9550: @end table
9551:
9552: Given the (float-aligned) base address of the structure we get the
9553: address of the field
9554:
9555: @table @code
9556: @item a
9557: without doing anything further.
9558: @item b
9559: with @code{float+}
9560: @item c
9561: with @code{float+ cell+ faligned}
9562: @end table
9563:
9564: It is easy to see that this can become quite tiring.
9565:
9566: Moreover, it is not very readable, because seeing a
9567: @code{cell+} tells us neither which kind of structure is
9568: accessed nor what field is accessed; we have to somehow infer the kind
9569: of structure, and then look up in the documentation, which field of
9570: that structure corresponds to that offset.
9571:
9572: Finally, this kind of address arithmetic also causes maintenance
9573: troubles: If you add or delete a field somewhere in the middle of the
9574: structure, you have to find and change all computations for the fields
9575: afterwards.
9576:
9577: So, instead of using @code{cell+} and friends directly, how
9578: about storing the offsets in constants:
9579:
9580: @example
9581: 0 constant a-offset
9582: 0 float+ constant b-offset
9583: 0 float+ cell+ faligned c-offset
9584: @end example
9585:
9586: Now we can get the address of field @code{x} with @code{x-offset
9587: +}. This is much better in all respects. Of course, you still
9588: have to change all later offset definitions if you add a field. You can
9589: fix this by declaring the offsets in the following way:
9590:
9591: @example
9592: 0 constant a-offset
9593: a-offset float+ constant b-offset
9594: b-offset cell+ faligned constant c-offset
9595: @end example
9596:
9597: Since we always use the offsets with @code{+}, we could use a defining
9598: word @code{cfield} that includes the @code{+} in the action of the
9599: defined word:
9600:
9601: @example
9602: : cfield ( n "name" -- )
9603: create ,
9604: does> ( name execution: addr1 -- addr2 )
9605: @@ + ;
9606:
9607: 0 cfield a
9608: 0 a float+ cfield b
9609: 0 b cell+ faligned cfield c
9610: @end example
9611:
9612: Instead of @code{x-offset +}, we now simply write @code{x}.
9613:
9614: The structure field words now can be used quite nicely. However,
9615: their definition is still a bit cumbersome: We have to repeat the
9616: name, the information about size and alignment is distributed before
9617: and after the field definitions etc. The structure package presented
9618: here addresses these problems.
9619:
9620: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9621: @subsection Structure Usage
9622: @cindex structure usage
9623:
9624: @cindex @code{field} usage
9625: @cindex @code{struct} usage
9626: @cindex @code{end-struct} usage
9627: You can define a structure for a (data-less) linked list with:
9628: @example
9629: struct
9630: cell% field list-next
9631: end-struct list%
9632: @end example
9633:
9634: With the address of the list node on the stack, you can compute the
9635: address of the field that contains the address of the next node with
9636: @code{list-next}. E.g., you can determine the length of a list
9637: with:
9638:
9639: @example
9640: : list-length ( list -- n )
9641: \ "list" is a pointer to the first element of a linked list
9642: \ "n" is the length of the list
9643: 0 BEGIN ( list1 n1 )
9644: over
9645: WHILE ( list1 n1 )
9646: 1+ swap list-next @@ swap
9647: REPEAT
9648: nip ;
9649: @end example
9650:
9651: You can reserve memory for a list node in the dictionary with
9652: @code{list% %allot}, which leaves the address of the list node on the
9653: stack. For the equivalent allocation on the heap you can use @code{list%
9654: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9655: use @code{list% %allocate}). You can get the the size of a list
9656: node with @code{list% %size} and its alignment with @code{list%
9657: %alignment}.
9658:
9659: Note that in ANS Forth the body of a @code{create}d word is
9660: @code{aligned} but not necessarily @code{faligned};
9661: therefore, if you do a:
9662:
9663: @example
9664: create @emph{name} foo% %allot drop
9665: @end example
9666:
9667: @noindent
9668: then the memory alloted for @code{foo%} is guaranteed to start at the
9669: body of @code{@emph{name}} only if @code{foo%} contains only character,
9670: cell and double fields. Therefore, if your structure contains floats,
9671: better use
9672:
9673: @example
9674: foo% %allot constant @emph{name}
9675: @end example
9676:
9677: @cindex structures containing structures
9678: You can include a structure @code{foo%} as a field of
9679: another structure, like this:
9680: @example
9681: struct
9682: ...
9683: foo% field ...
9684: ...
9685: end-struct ...
9686: @end example
9687:
9688: @cindex structure extension
9689: @cindex extended records
9690: Instead of starting with an empty structure, you can extend an
9691: existing structure. E.g., a plain linked list without data, as defined
9692: above, is hardly useful; You can extend it to a linked list of integers,
9693: like this:@footnote{This feature is also known as @emph{extended
9694: records}. It is the main innovation in the Oberon language; in other
9695: words, adding this feature to Modula-2 led Wirth to create a new
9696: language, write a new compiler etc. Adding this feature to Forth just
9697: required a few lines of code.}
9698:
9699: @example
9700: list%
9701: cell% field intlist-int
9702: end-struct intlist%
9703: @end example
9704:
9705: @code{intlist%} is a structure with two fields:
9706: @code{list-next} and @code{intlist-int}.
9707:
9708: @cindex structures containing arrays
9709: You can specify an array type containing @emph{n} elements of
9710: type @code{foo%} like this:
9711:
9712: @example
9713: foo% @emph{n} *
9714: @end example
9715:
9716: You can use this array type in any place where you can use a normal
9717: type, e.g., when defining a @code{field}, or with
9718: @code{%allot}.
9719:
9720: @cindex first field optimization
9721: The first field is at the base address of a structure and the word for
9722: this field (e.g., @code{list-next}) actually does not change the address
9723: on the stack. You may be tempted to leave it away in the interest of
9724: run-time and space efficiency. This is not necessary, because the
9725: structure package optimizes this case: If you compile a first-field
9726: words, no code is generated. So, in the interest of readability and
9727: maintainability you should include the word for the field when accessing
9728: the field.
9729:
9730:
9731: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9732: @subsection Structure Naming Convention
9733: @cindex structure naming convention
9734:
9735: The field names that come to (my) mind are often quite generic, and,
9736: if used, would cause frequent name clashes. E.g., many structures
9737: probably contain a @code{counter} field. The structure names
9738: that come to (my) mind are often also the logical choice for the names
9739: of words that create such a structure.
9740:
9741: Therefore, I have adopted the following naming conventions:
9742:
9743: @itemize @bullet
9744: @cindex field naming convention
9745: @item
9746: The names of fields are of the form
9747: @code{@emph{struct}-@emph{field}}, where
9748: @code{@emph{struct}} is the basic name of the structure, and
9749: @code{@emph{field}} is the basic name of the field. You can
9750: think of field words as converting the (address of the)
9751: structure into the (address of the) field.
9752:
9753: @cindex structure naming convention
9754: @item
9755: The names of structures are of the form
9756: @code{@emph{struct}%}, where
9757: @code{@emph{struct}} is the basic name of the structure.
9758: @end itemize
9759:
9760: This naming convention does not work that well for fields of extended
9761: structures; e.g., the integer list structure has a field
9762: @code{intlist-int}, but has @code{list-next}, not
9763: @code{intlist-next}.
9764:
9765: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9766: @subsection Structure Implementation
9767: @cindex structure implementation
9768: @cindex implementation of structures
9769:
9770: The central idea in the implementation is to pass the data about the
9771: structure being built on the stack, not in some global
9772: variable. Everything else falls into place naturally once this design
9773: decision is made.
9774:
9775: The type description on the stack is of the form @emph{align
9776: size}. Keeping the size on the top-of-stack makes dealing with arrays
9777: very simple.
9778:
9779: @code{field} is a defining word that uses @code{Create}
9780: and @code{DOES>}. The body of the field contains the offset
9781: of the field, and the normal @code{DOES>} action is simply:
9782:
9783: @example
9784: @@ +
9785: @end example
9786:
9787: @noindent
9788: i.e., add the offset to the address, giving the stack effect
9789: @i{addr1 -- addr2} for a field.
9790:
9791: @cindex first field optimization, implementation
9792: This simple structure is slightly complicated by the optimization
9793: for fields with offset 0, which requires a different
9794: @code{DOES>}-part (because we cannot rely on there being
9795: something on the stack if such a field is invoked during
9796: compilation). Therefore, we put the different @code{DOES>}-parts
9797: in separate words, and decide which one to invoke based on the
9798: offset. For a zero offset, the field is basically a noop; it is
9799: immediate, and therefore no code is generated when it is compiled.
9800:
9801: @node Structure Glossary, , Structure Implementation, Structures
9802: @subsection Structure Glossary
9803: @cindex structure glossary
9804:
9805:
9806: doc-%align
9807: doc-%alignment
9808: doc-%alloc
9809: doc-%allocate
9810: doc-%allot
9811: doc-cell%
9812: doc-char%
9813: doc-dfloat%
9814: doc-double%
9815: doc-end-struct
9816: doc-field
9817: doc-float%
9818: doc-naligned
9819: doc-sfloat%
9820: doc-%size
9821: doc-struct
9822:
9823:
9824: @c -------------------------------------------------------------
9825: @node Object-oriented Forth, Programming Tools, Structures, Words
9826: @section Object-oriented Forth
9827:
9828: Gforth comes with three packages for object-oriented programming:
9829: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9830: is preloaded, so you have to @code{include} them before use. The most
9831: important differences between these packages (and others) are discussed
9832: in @ref{Comparison with other object models}. All packages are written
9833: in ANS Forth and can be used with any other ANS Forth.
9834:
9835: @menu
9836: * Why object-oriented programming?::
9837: * Object-Oriented Terminology::
9838: * Objects::
9839: * OOF::
9840: * Mini-OOF::
9841: * Comparison with other object models::
9842: @end menu
9843:
9844: @c ----------------------------------------------------------------
9845: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9846: @subsection Why object-oriented programming?
9847: @cindex object-oriented programming motivation
9848: @cindex motivation for object-oriented programming
9849:
9850: Often we have to deal with several data structures (@emph{objects}),
9851: that have to be treated similarly in some respects, but differently in
9852: others. Graphical objects are the textbook example: circles, triangles,
9853: dinosaurs, icons, and others, and we may want to add more during program
9854: development. We want to apply some operations to any graphical object,
9855: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9856: has to do something different for every kind of object.
9857: @comment TODO add some other operations eg perimeter, area
9858: @comment and tie in to concrete examples later..
9859:
9860: We could implement @code{draw} as a big @code{CASE}
9861: control structure that executes the appropriate code depending on the
9862: kind of object to be drawn. This would be not be very elegant, and,
9863: moreover, we would have to change @code{draw} every time we add
9864: a new kind of graphical object (say, a spaceship).
9865:
9866: What we would rather do is: When defining spaceships, we would tell
9867: the system: ``Here's how you @code{draw} a spaceship; you figure
9868: out the rest''.
9869:
9870: This is the problem that all systems solve that (rightfully) call
9871: themselves object-oriented; the object-oriented packages presented here
9872: solve this problem (and not much else).
9873: @comment TODO ?list properties of oo systems.. oo vs o-based?
9874:
9875: @c ------------------------------------------------------------------------
9876: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
9877: @subsection Object-Oriented Terminology
9878: @cindex object-oriented terminology
9879: @cindex terminology for object-oriented programming
9880:
9881: This section is mainly for reference, so you don't have to understand
9882: all of it right away. The terminology is mainly Smalltalk-inspired. In
9883: short:
9884:
9885: @table @emph
9886: @cindex class
9887: @item class
9888: a data structure definition with some extras.
9889:
9890: @cindex object
9891: @item object
9892: an instance of the data structure described by the class definition.
9893:
9894: @cindex instance variables
9895: @item instance variables
9896: fields of the data structure.
9897:
9898: @cindex selector
9899: @cindex method selector
9900: @cindex virtual function
9901: @item selector
9902: (or @emph{method selector}) a word (e.g.,
9903: @code{draw}) that performs an operation on a variety of data
9904: structures (classes). A selector describes @emph{what} operation to
9905: perform. In C++ terminology: a (pure) virtual function.
9906:
9907: @cindex method
9908: @item method
9909: the concrete definition that performs the operation
9910: described by the selector for a specific class. A method specifies
9911: @emph{how} the operation is performed for a specific class.
9912:
9913: @cindex selector invocation
9914: @cindex message send
9915: @cindex invoking a selector
9916: @item selector invocation
9917: a call of a selector. One argument of the call (the TOS (top-of-stack))
9918: is used for determining which method is used. In Smalltalk terminology:
9919: a message (consisting of the selector and the other arguments) is sent
9920: to the object.
9921:
9922: @cindex receiving object
9923: @item receiving object
9924: the object used for determining the method executed by a selector
9925: invocation. In the @file{objects.fs} model, it is the object that is on
9926: the TOS when the selector is invoked. (@emph{Receiving} comes from
9927: the Smalltalk @emph{message} terminology.)
9928:
9929: @cindex child class
9930: @cindex parent class
9931: @cindex inheritance
9932: @item child class
9933: a class that has (@emph{inherits}) all properties (instance variables,
9934: selectors, methods) from a @emph{parent class}. In Smalltalk
9935: terminology: The subclass inherits from the superclass. In C++
9936: terminology: The derived class inherits from the base class.
9937:
9938: @end table
9939:
9940: @c If you wonder about the message sending terminology, it comes from
9941: @c a time when each object had it's own task and objects communicated via
9942: @c message passing; eventually the Smalltalk developers realized that
9943: @c they can do most things through simple (indirect) calls. They kept the
9944: @c terminology.
9945:
9946: @c --------------------------------------------------------------
9947: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
9948: @subsection The @file{objects.fs} model
9949: @cindex objects
9950: @cindex object-oriented programming
9951:
9952: @cindex @file{objects.fs}
9953: @cindex @file{oof.fs}
9954:
9955: This section describes the @file{objects.fs} package. This material also
9956: has been published in M. Anton Ertl,
9957: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
9958: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
9959: 37--43.
9960: @c McKewan's and Zsoter's packages
9961:
9962: This section assumes that you have read @ref{Structures}.
9963:
9964: The techniques on which this model is based have been used to implement
9965: the parser generator, Gray, and have also been used in Gforth for
9966: implementing the various flavours of word lists (hashed or not,
9967: case-sensitive or not, special-purpose word lists for locals etc.).
9968:
9969:
9970: @menu
9971: * Properties of the Objects model::
9972: * Basic Objects Usage::
9973: * The Objects base class::
9974: * Creating objects::
9975: * Object-Oriented Programming Style::
9976: * Class Binding::
9977: * Method conveniences::
9978: * Classes and Scoping::
9979: * Dividing classes::
9980: * Object Interfaces::
9981: * Objects Implementation::
9982: * Objects Glossary::
9983: @end menu
9984:
9985: Marcel Hendrix provided helpful comments on this section.
9986:
9987: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
9988: @subsubsection Properties of the @file{objects.fs} model
9989: @cindex @file{objects.fs} properties
9990:
9991: @itemize @bullet
9992: @item
9993: It is straightforward to pass objects on the stack. Passing
9994: selectors on the stack is a little less convenient, but possible.
9995:
9996: @item
9997: Objects are just data structures in memory, and are referenced by their
9998: address. You can create words for objects with normal defining words
9999: like @code{constant}. Likewise, there is no difference between instance
10000: variables that contain objects and those that contain other data.
10001:
10002: @item
10003: Late binding is efficient and easy to use.
10004:
10005: @item
10006: It avoids parsing, and thus avoids problems with state-smartness
10007: and reduced extensibility; for convenience there are a few parsing
10008: words, but they have non-parsing counterparts. There are also a few
10009: defining words that parse. This is hard to avoid, because all standard
10010: defining words parse (except @code{:noname}); however, such
10011: words are not as bad as many other parsing words, because they are not
10012: state-smart.
10013:
10014: @item
10015: It does not try to incorporate everything. It does a few things and does
10016: them well (IMO). In particular, this model was not designed to support
10017: information hiding (although it has features that may help); you can use
10018: a separate package for achieving this.
10019:
10020: @item
10021: It is layered; you don't have to learn and use all features to use this
10022: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10023: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10024: are optional and independent of each other.
10025:
10026: @item
10027: An implementation in ANS Forth is available.
10028:
10029: @end itemize
10030:
10031:
10032: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10033: @subsubsection Basic @file{objects.fs} Usage
10034: @cindex basic objects usage
10035: @cindex objects, basic usage
10036:
10037: You can define a class for graphical objects like this:
10038:
10039: @cindex @code{class} usage
10040: @cindex @code{end-class} usage
10041: @cindex @code{selector} usage
10042: @example
10043: object class \ "object" is the parent class
10044: selector draw ( x y graphical -- )
10045: end-class graphical
10046: @end example
10047:
10048: This code defines a class @code{graphical} with an
10049: operation @code{draw}. We can perform the operation
10050: @code{draw} on any @code{graphical} object, e.g.:
10051:
10052: @example
10053: 100 100 t-rex draw
10054: @end example
10055:
10056: @noindent
10057: where @code{t-rex} is a word (say, a constant) that produces a
10058: graphical object.
10059:
10060: @comment TODO add a 2nd operation eg perimeter.. and use for
10061: @comment a concrete example
10062:
10063: @cindex abstract class
10064: How do we create a graphical object? With the present definitions,
10065: we cannot create a useful graphical object. The class
10066: @code{graphical} describes graphical objects in general, but not
10067: any concrete graphical object type (C++ users would call it an
10068: @emph{abstract class}); e.g., there is no method for the selector
10069: @code{draw} in the class @code{graphical}.
10070:
10071: For concrete graphical objects, we define child classes of the
10072: class @code{graphical}, e.g.:
10073:
10074: @cindex @code{overrides} usage
10075: @cindex @code{field} usage in class definition
10076: @example
10077: graphical class \ "graphical" is the parent class
10078: cell% field circle-radius
10079:
10080: :noname ( x y circle -- )
10081: circle-radius @@ draw-circle ;
10082: overrides draw
10083:
10084: :noname ( n-radius circle -- )
10085: circle-radius ! ;
10086: overrides construct
10087:
10088: end-class circle
10089: @end example
10090:
10091: Here we define a class @code{circle} as a child of @code{graphical},
10092: with field @code{circle-radius} (which behaves just like a field
10093: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10094: for the selectors @code{draw} and @code{construct} (@code{construct} is
10095: defined in @code{object}, the parent class of @code{graphical}).
10096:
10097: Now we can create a circle on the heap (i.e.,
10098: @code{allocate}d memory) with:
10099:
10100: @cindex @code{heap-new} usage
10101: @example
10102: 50 circle heap-new constant my-circle
10103: @end example
10104:
10105: @noindent
10106: @code{heap-new} invokes @code{construct}, thus
10107: initializing the field @code{circle-radius} with 50. We can draw
10108: this new circle at (100,100) with:
10109:
10110: @example
10111: 100 100 my-circle draw
10112: @end example
10113:
10114: @cindex selector invocation, restrictions
10115: @cindex class definition, restrictions
10116: Note: You can only invoke a selector if the object on the TOS
10117: (the receiving object) belongs to the class where the selector was
10118: defined or one of its descendents; e.g., you can invoke
10119: @code{draw} only for objects belonging to @code{graphical}
10120: or its descendents (e.g., @code{circle}). Immediately before
10121: @code{end-class}, the search order has to be the same as
10122: immediately after @code{class}.
10123:
10124: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10125: @subsubsection The @file{object.fs} base class
10126: @cindex @code{object} class
10127:
10128: When you define a class, you have to specify a parent class. So how do
10129: you start defining classes? There is one class available from the start:
10130: @code{object}. It is ancestor for all classes and so is the
10131: only class that has no parent. It has two selectors: @code{construct}
10132: and @code{print}.
10133:
10134: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10135: @subsubsection Creating objects
10136: @cindex creating objects
10137: @cindex object creation
10138: @cindex object allocation options
10139:
10140: @cindex @code{heap-new} discussion
10141: @cindex @code{dict-new} discussion
10142: @cindex @code{construct} discussion
10143: You can create and initialize an object of a class on the heap with
10144: @code{heap-new} ( ... class -- object ) and in the dictionary
10145: (allocation with @code{allot}) with @code{dict-new} (
10146: ... class -- object ). Both words invoke @code{construct}, which
10147: consumes the stack items indicated by "..." above.
10148:
10149: @cindex @code{init-object} discussion
10150: @cindex @code{class-inst-size} discussion
10151: If you want to allocate memory for an object yourself, you can get its
10152: alignment and size with @code{class-inst-size 2@@} ( class --
10153: align size ). Once you have memory for an object, you can initialize
10154: it with @code{init-object} ( ... class object -- );
10155: @code{construct} does only a part of the necessary work.
10156:
10157: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10158: @subsubsection Object-Oriented Programming Style
10159: @cindex object-oriented programming style
10160: @cindex programming style, object-oriented
10161:
10162: This section is not exhaustive.
10163:
10164: @cindex stack effects of selectors
10165: @cindex selectors and stack effects
10166: In general, it is a good idea to ensure that all methods for the
10167: same selector have the same stack effect: when you invoke a selector,
10168: you often have no idea which method will be invoked, so, unless all
10169: methods have the same stack effect, you will not know the stack effect
10170: of the selector invocation.
10171:
10172: One exception to this rule is methods for the selector
10173: @code{construct}. We know which method is invoked, because we
10174: specify the class to be constructed at the same place. Actually, I
10175: defined @code{construct} as a selector only to give the users a
10176: convenient way to specify initialization. The way it is used, a
10177: mechanism different from selector invocation would be more natural
10178: (but probably would take more code and more space to explain).
10179:
10180: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10181: @subsubsection Class Binding
10182: @cindex class binding
10183: @cindex early binding
10184:
10185: @cindex late binding
10186: Normal selector invocations determine the method at run-time depending
10187: on the class of the receiving object. This run-time selection is called
10188: @i{late binding}.
10189:
10190: Sometimes it's preferable to invoke a different method. For example,
10191: you might want to use the simple method for @code{print}ing
10192: @code{object}s instead of the possibly long-winded @code{print} method
10193: of the receiver class. You can achieve this by replacing the invocation
10194: of @code{print} with:
10195:
10196: @cindex @code{[bind]} usage
10197: @example
10198: [bind] object print
10199: @end example
10200:
10201: @noindent
10202: in compiled code or:
10203:
10204: @cindex @code{bind} usage
10205: @example
10206: bind object print
10207: @end example
10208:
10209: @cindex class binding, alternative to
10210: @noindent
10211: in interpreted code. Alternatively, you can define the method with a
10212: name (e.g., @code{print-object}), and then invoke it through the
10213: name. Class binding is just a (often more convenient) way to achieve
10214: the same effect; it avoids name clutter and allows you to invoke
10215: methods directly without naming them first.
10216:
10217: @cindex superclass binding
10218: @cindex parent class binding
10219: A frequent use of class binding is this: When we define a method
10220: for a selector, we often want the method to do what the selector does
10221: in the parent class, and a little more. There is a special word for
10222: this purpose: @code{[parent]}; @code{[parent]
10223: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10224: selector}}, where @code{@emph{parent}} is the parent
10225: class of the current class. E.g., a method definition might look like:
10226:
10227: @cindex @code{[parent]} usage
10228: @example
10229: :noname
10230: dup [parent] foo \ do parent's foo on the receiving object
10231: ... \ do some more
10232: ; overrides foo
10233: @end example
10234:
10235: @cindex class binding as optimization
10236: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10237: March 1997), Andrew McKewan presents class binding as an optimization
10238: technique. I recommend not using it for this purpose unless you are in
10239: an emergency. Late binding is pretty fast with this model anyway, so the
10240: benefit of using class binding is small; the cost of using class binding
10241: where it is not appropriate is reduced maintainability.
10242:
10243: While we are at programming style questions: You should bind
10244: selectors only to ancestor classes of the receiving object. E.g., say,
10245: you know that the receiving object is of class @code{foo} or its
10246: descendents; then you should bind only to @code{foo} and its
10247: ancestors.
10248:
10249: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10250: @subsubsection Method conveniences
10251: @cindex method conveniences
10252:
10253: In a method you usually access the receiving object pretty often. If
10254: you define the method as a plain colon definition (e.g., with
10255: @code{:noname}), you may have to do a lot of stack
10256: gymnastics. To avoid this, you can define the method with @code{m:
10257: ... ;m}. E.g., you could define the method for
10258: @code{draw}ing a @code{circle} with
10259:
10260: @cindex @code{this} usage
10261: @cindex @code{m:} usage
10262: @cindex @code{;m} usage
10263: @example
10264: m: ( x y circle -- )
10265: ( x y ) this circle-radius @@ draw-circle ;m
10266: @end example
10267:
10268: @cindex @code{exit} in @code{m: ... ;m}
10269: @cindex @code{exitm} discussion
10270: @cindex @code{catch} in @code{m: ... ;m}
10271: When this method is executed, the receiver object is removed from the
10272: stack; you can access it with @code{this} (admittedly, in this
10273: example the use of @code{m: ... ;m} offers no advantage). Note
10274: that I specify the stack effect for the whole method (i.e. including
10275: the receiver object), not just for the code between @code{m:}
10276: and @code{;m}. You cannot use @code{exit} in
10277: @code{m:...;m}; instead, use
10278: @code{exitm}.@footnote{Moreover, for any word that calls
10279: @code{catch} and was defined before loading
10280: @code{objects.fs}, you have to redefine it like I redefined
10281: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10282:
10283: @cindex @code{inst-var} usage
10284: You will frequently use sequences of the form @code{this
10285: @emph{field}} (in the example above: @code{this
10286: circle-radius}). If you use the field only in this way, you can
10287: define it with @code{inst-var} and eliminate the
10288: @code{this} before the field name. E.g., the @code{circle}
10289: class above could also be defined with:
10290:
10291: @example
10292: graphical class
10293: cell% inst-var radius
10294:
10295: m: ( x y circle -- )
10296: radius @@ draw-circle ;m
10297: overrides draw
10298:
10299: m: ( n-radius circle -- )
10300: radius ! ;m
10301: overrides construct
10302:
10303: end-class circle
10304: @end example
10305:
10306: @code{radius} can only be used in @code{circle} and its
10307: descendent classes and inside @code{m:...;m}.
10308:
10309: @cindex @code{inst-value} usage
10310: You can also define fields with @code{inst-value}, which is
10311: to @code{inst-var} what @code{value} is to
10312: @code{variable}. You can change the value of such a field with
10313: @code{[to-inst]}. E.g., we could also define the class
10314: @code{circle} like this:
10315:
10316: @example
10317: graphical class
10318: inst-value radius
10319:
10320: m: ( x y circle -- )
10321: radius draw-circle ;m
10322: overrides draw
10323:
10324: m: ( n-radius circle -- )
10325: [to-inst] radius ;m
10326: overrides construct
10327:
10328: end-class circle
10329: @end example
10330:
10331: @c !! :m is easy to confuse with m:. Another name would be better.
10332:
10333: @c Finally, you can define named methods with @code{:m}. One use of this
10334: @c feature is the definition of words that occur only in one class and are
10335: @c not intended to be overridden, but which still need method context
10336: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10337: @c would be bound frequently, if defined anonymously.
10338:
10339:
10340: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10341: @subsubsection Classes and Scoping
10342: @cindex classes and scoping
10343: @cindex scoping and classes
10344:
10345: Inheritance is frequent, unlike structure extension. This exacerbates
10346: the problem with the field name convention (@pxref{Structure Naming
10347: Convention}): One always has to remember in which class the field was
10348: originally defined; changing a part of the class structure would require
10349: changes for renaming in otherwise unaffected code.
10350:
10351: @cindex @code{inst-var} visibility
10352: @cindex @code{inst-value} visibility
10353: To solve this problem, I added a scoping mechanism (which was not in my
10354: original charter): A field defined with @code{inst-var} (or
10355: @code{inst-value}) is visible only in the class where it is defined and in
10356: the descendent classes of this class. Using such fields only makes
10357: sense in @code{m:}-defined methods in these classes anyway.
10358:
10359: This scoping mechanism allows us to use the unadorned field name,
10360: because name clashes with unrelated words become much less likely.
10361:
10362: @cindex @code{protected} discussion
10363: @cindex @code{private} discussion
10364: Once we have this mechanism, we can also use it for controlling the
10365: visibility of other words: All words defined after
10366: @code{protected} are visible only in the current class and its
10367: descendents. @code{public} restores the compilation
10368: (i.e. @code{current}) word list that was in effect before. If you
10369: have several @code{protected}s without an intervening
10370: @code{public} or @code{set-current}, @code{public}
10371: will restore the compilation word list in effect before the first of
10372: these @code{protected}s.
10373:
10374: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10375: @subsubsection Dividing classes
10376: @cindex Dividing classes
10377: @cindex @code{methods}...@code{end-methods}
10378:
10379: You may want to do the definition of methods separate from the
10380: definition of the class, its selectors, fields, and instance variables,
10381: i.e., separate the implementation from the definition. You can do this
10382: in the following way:
10383:
10384: @example
10385: graphical class
10386: inst-value radius
10387: end-class circle
10388:
10389: ... \ do some other stuff
10390:
10391: circle methods \ now we are ready
10392:
10393: m: ( x y circle -- )
10394: radius draw-circle ;m
10395: overrides draw
10396:
10397: m: ( n-radius circle -- )
10398: [to-inst] radius ;m
10399: overrides construct
10400:
10401: end-methods
10402: @end example
10403:
10404: You can use several @code{methods}...@code{end-methods} sections. The
10405: only things you can do to the class in these sections are: defining
10406: methods, and overriding the class's selectors. You must not define new
10407: selectors or fields.
10408:
10409: Note that you often have to override a selector before using it. In
10410: particular, you usually have to override @code{construct} with a new
10411: method before you can invoke @code{heap-new} and friends. E.g., you
10412: must not create a circle before the @code{overrides construct} sequence
10413: in the example above.
10414:
10415: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10416: @subsubsection Object Interfaces
10417: @cindex object interfaces
10418: @cindex interfaces for objects
10419:
10420: In this model you can only call selectors defined in the class of the
10421: receiving objects or in one of its ancestors. If you call a selector
10422: with a receiving object that is not in one of these classes, the
10423: result is undefined; if you are lucky, the program crashes
10424: immediately.
10425:
10426: @cindex selectors common to hardly-related classes
10427: Now consider the case when you want to have a selector (or several)
10428: available in two classes: You would have to add the selector to a
10429: common ancestor class, in the worst case to @code{object}. You
10430: may not want to do this, e.g., because someone else is responsible for
10431: this ancestor class.
10432:
10433: The solution for this problem is interfaces. An interface is a
10434: collection of selectors. If a class implements an interface, the
10435: selectors become available to the class and its descendents. A class
10436: can implement an unlimited number of interfaces. For the problem
10437: discussed above, we would define an interface for the selector(s), and
10438: both classes would implement the interface.
10439:
10440: As an example, consider an interface @code{storage} for
10441: writing objects to disk and getting them back, and a class
10442: @code{foo} that implements it. The code would look like this:
10443:
10444: @cindex @code{interface} usage
10445: @cindex @code{end-interface} usage
10446: @cindex @code{implementation} usage
10447: @example
10448: interface
10449: selector write ( file object -- )
10450: selector read1 ( file object -- )
10451: end-interface storage
10452:
10453: bar class
10454: storage implementation
10455:
10456: ... overrides write
10457: ... overrides read1
10458: ...
10459: end-class foo
10460: @end example
10461:
10462: @noindent
10463: (I would add a word @code{read} @i{( file -- object )} that uses
10464: @code{read1} internally, but that's beyond the point illustrated
10465: here.)
10466:
10467: Note that you cannot use @code{protected} in an interface; and
10468: of course you cannot define fields.
10469:
10470: In the Neon model, all selectors are available for all classes;
10471: therefore it does not need interfaces. The price you pay in this model
10472: is slower late binding, and therefore, added complexity to avoid late
10473: binding.
10474:
10475: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10476: @subsubsection @file{objects.fs} Implementation
10477: @cindex @file{objects.fs} implementation
10478:
10479: @cindex @code{object-map} discussion
10480: An object is a piece of memory, like one of the data structures
10481: described with @code{struct...end-struct}. It has a field
10482: @code{object-map} that points to the method map for the object's
10483: class.
10484:
10485: @cindex method map
10486: @cindex virtual function table
10487: The @emph{method map}@footnote{This is Self terminology; in C++
10488: terminology: virtual function table.} is an array that contains the
10489: execution tokens (@i{xt}s) of the methods for the object's class. Each
10490: selector contains an offset into a method map.
10491:
10492: @cindex @code{selector} implementation, class
10493: @code{selector} is a defining word that uses
10494: @code{CREATE} and @code{DOES>}. The body of the
10495: selector contains the offset; the @code{DOES>} action for a
10496: class selector is, basically:
10497:
10498: @example
10499: ( object addr ) @@ over object-map @@ + @@ execute
10500: @end example
10501:
10502: Since @code{object-map} is the first field of the object, it
10503: does not generate any code. As you can see, calling a selector has a
10504: small, constant cost.
10505:
10506: @cindex @code{current-interface} discussion
10507: @cindex class implementation and representation
10508: A class is basically a @code{struct} combined with a method
10509: map. During the class definition the alignment and size of the class
10510: are passed on the stack, just as with @code{struct}s, so
10511: @code{field} can also be used for defining class
10512: fields. However, passing more items on the stack would be
10513: inconvenient, so @code{class} builds a data structure in memory,
10514: which is accessed through the variable
10515: @code{current-interface}. After its definition is complete, the
10516: class is represented on the stack by a pointer (e.g., as parameter for
10517: a child class definition).
10518:
10519: A new class starts off with the alignment and size of its parent,
10520: and a copy of the parent's method map. Defining new fields extends the
10521: size and alignment; likewise, defining new selectors extends the
10522: method map. @code{overrides} just stores a new @i{xt} in the method
10523: map at the offset given by the selector.
10524:
10525: @cindex class binding, implementation
10526: Class binding just gets the @i{xt} at the offset given by the selector
10527: from the class's method map and @code{compile,}s (in the case of
10528: @code{[bind]}) it.
10529:
10530: @cindex @code{this} implementation
10531: @cindex @code{catch} and @code{this}
10532: @cindex @code{this} and @code{catch}
10533: I implemented @code{this} as a @code{value}. At the
10534: start of an @code{m:...;m} method the old @code{this} is
10535: stored to the return stack and restored at the end; and the object on
10536: the TOS is stored @code{TO this}. This technique has one
10537: disadvantage: If the user does not leave the method via
10538: @code{;m}, but via @code{throw} or @code{exit},
10539: @code{this} is not restored (and @code{exit} may
10540: crash). To deal with the @code{throw} problem, I have redefined
10541: @code{catch} to save and restore @code{this}; the same
10542: should be done with any word that can catch an exception. As for
10543: @code{exit}, I simply forbid it (as a replacement, there is
10544: @code{exitm}).
10545:
10546: @cindex @code{inst-var} implementation
10547: @code{inst-var} is just the same as @code{field}, with
10548: a different @code{DOES>} action:
10549: @example
10550: @@ this +
10551: @end example
10552: Similar for @code{inst-value}.
10553:
10554: @cindex class scoping implementation
10555: Each class also has a word list that contains the words defined with
10556: @code{inst-var} and @code{inst-value}, and its protected
10557: words. It also has a pointer to its parent. @code{class} pushes
10558: the word lists of the class and all its ancestors onto the search order stack,
10559: and @code{end-class} drops them.
10560:
10561: @cindex interface implementation
10562: An interface is like a class without fields, parent and protected
10563: words; i.e., it just has a method map. If a class implements an
10564: interface, its method map contains a pointer to the method map of the
10565: interface. The positive offsets in the map are reserved for class
10566: methods, therefore interface map pointers have negative
10567: offsets. Interfaces have offsets that are unique throughout the
10568: system, unlike class selectors, whose offsets are only unique for the
10569: classes where the selector is available (invokable).
10570:
10571: This structure means that interface selectors have to perform one
10572: indirection more than class selectors to find their method. Their body
10573: contains the interface map pointer offset in the class method map, and
10574: the method offset in the interface method map. The
10575: @code{does>} action for an interface selector is, basically:
10576:
10577: @example
10578: ( object selector-body )
10579: 2dup selector-interface @@ ( object selector-body object interface-offset )
10580: swap object-map @@ + @@ ( object selector-body map )
10581: swap selector-offset @@ + @@ execute
10582: @end example
10583:
10584: where @code{object-map} and @code{selector-offset} are
10585: first fields and generate no code.
10586:
10587: As a concrete example, consider the following code:
10588:
10589: @example
10590: interface
10591: selector if1sel1
10592: selector if1sel2
10593: end-interface if1
10594:
10595: object class
10596: if1 implementation
10597: selector cl1sel1
10598: cell% inst-var cl1iv1
10599:
10600: ' m1 overrides construct
10601: ' m2 overrides if1sel1
10602: ' m3 overrides if1sel2
10603: ' m4 overrides cl1sel2
10604: end-class cl1
10605:
10606: create obj1 object dict-new drop
10607: create obj2 cl1 dict-new drop
10608: @end example
10609:
10610: The data structure created by this code (including the data structure
10611: for @code{object}) is shown in the
10612: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10613: @comment TODO add this diagram..
10614:
10615: @node Objects Glossary, , Objects Implementation, Objects
10616: @subsubsection @file{objects.fs} Glossary
10617: @cindex @file{objects.fs} Glossary
10618:
10619:
10620: doc---objects-bind
10621: doc---objects-<bind>
10622: doc---objects-bind'
10623: doc---objects-[bind]
10624: doc---objects-class
10625: doc---objects-class->map
10626: doc---objects-class-inst-size
10627: doc---objects-class-override!
10628: doc---objects-class-previous
10629: doc---objects-class>order
10630: doc---objects-construct
10631: doc---objects-current'
10632: doc---objects-[current]
10633: doc---objects-current-interface
10634: doc---objects-dict-new
10635: doc---objects-end-class
10636: doc---objects-end-class-noname
10637: doc---objects-end-interface
10638: doc---objects-end-interface-noname
10639: doc---objects-end-methods
10640: doc---objects-exitm
10641: doc---objects-heap-new
10642: doc---objects-implementation
10643: doc---objects-init-object
10644: doc---objects-inst-value
10645: doc---objects-inst-var
10646: doc---objects-interface
10647: doc---objects-m:
10648: doc---objects-:m
10649: doc---objects-;m
10650: doc---objects-method
10651: doc---objects-methods
10652: doc---objects-object
10653: doc---objects-overrides
10654: doc---objects-[parent]
10655: doc---objects-print
10656: doc---objects-protected
10657: doc---objects-public
10658: doc---objects-selector
10659: doc---objects-this
10660: doc---objects-<to-inst>
10661: doc---objects-[to-inst]
10662: doc---objects-to-this
10663: doc---objects-xt-new
10664:
10665:
10666: @c -------------------------------------------------------------
10667: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10668: @subsection The @file{oof.fs} model
10669: @cindex oof
10670: @cindex object-oriented programming
10671:
10672: @cindex @file{objects.fs}
10673: @cindex @file{oof.fs}
10674:
10675: This section describes the @file{oof.fs} package.
10676:
10677: The package described in this section has been used in bigFORTH since 1991, and
10678: used for two large applications: a chromatographic system used to
10679: create new medicaments, and a graphic user interface library (MINOS).
10680:
10681: You can find a description (in German) of @file{oof.fs} in @cite{Object
10682: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10683: 10(2), 1994.
10684:
10685: @menu
10686: * Properties of the OOF model::
10687: * Basic OOF Usage::
10688: * The OOF base class::
10689: * Class Declaration::
10690: * Class Implementation::
10691: @end menu
10692:
10693: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10694: @subsubsection Properties of the @file{oof.fs} model
10695: @cindex @file{oof.fs} properties
10696:
10697: @itemize @bullet
10698: @item
10699: This model combines object oriented programming with information
10700: hiding. It helps you writing large application, where scoping is
10701: necessary, because it provides class-oriented scoping.
10702:
10703: @item
10704: Named objects, object pointers, and object arrays can be created,
10705: selector invocation uses the ``object selector'' syntax. Selector invocation
10706: to objects and/or selectors on the stack is a bit less convenient, but
10707: possible.
10708:
10709: @item
10710: Selector invocation and instance variable usage of the active object is
10711: straightforward, since both make use of the active object.
10712:
10713: @item
10714: Late binding is efficient and easy to use.
10715:
10716: @item
10717: State-smart objects parse selectors. However, extensibility is provided
10718: using a (parsing) selector @code{postpone} and a selector @code{'}.
10719:
10720: @item
10721: An implementation in ANS Forth is available.
10722:
10723: @end itemize
10724:
10725:
10726: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10727: @subsubsection Basic @file{oof.fs} Usage
10728: @cindex @file{oof.fs} usage
10729:
10730: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
10731:
10732: You can define a class for graphical objects like this:
10733:
10734: @cindex @code{class} usage
10735: @cindex @code{class;} usage
10736: @cindex @code{method} usage
10737: @example
10738: object class graphical \ "object" is the parent class
10739: method draw ( x y graphical -- )
10740: class;
10741: @end example
10742:
10743: This code defines a class @code{graphical} with an
10744: operation @code{draw}. We can perform the operation
10745: @code{draw} on any @code{graphical} object, e.g.:
10746:
10747: @example
10748: 100 100 t-rex draw
10749: @end example
10750:
10751: @noindent
10752: where @code{t-rex} is an object or object pointer, created with e.g.
10753: @code{graphical : t-rex}.
10754:
10755: @cindex abstract class
10756: How do we create a graphical object? With the present definitions,
10757: we cannot create a useful graphical object. The class
10758: @code{graphical} describes graphical objects in general, but not
10759: any concrete graphical object type (C++ users would call it an
10760: @emph{abstract class}); e.g., there is no method for the selector
10761: @code{draw} in the class @code{graphical}.
10762:
10763: For concrete graphical objects, we define child classes of the
10764: class @code{graphical}, e.g.:
10765:
10766: @example
10767: graphical class circle \ "graphical" is the parent class
10768: cell var circle-radius
10769: how:
10770: : draw ( x y -- )
10771: circle-radius @@ draw-circle ;
10772:
10773: : init ( n-radius -- (
10774: circle-radius ! ;
10775: class;
10776: @end example
10777:
10778: Here we define a class @code{circle} as a child of @code{graphical},
10779: with a field @code{circle-radius}; it defines new methods for the
10780: selectors @code{draw} and @code{init} (@code{init} is defined in
10781: @code{object}, the parent class of @code{graphical}).
10782:
10783: Now we can create a circle in the dictionary with:
10784:
10785: @example
10786: 50 circle : my-circle
10787: @end example
10788:
10789: @noindent
10790: @code{:} invokes @code{init}, thus initializing the field
10791: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10792: with:
10793:
10794: @example
10795: 100 100 my-circle draw
10796: @end example
10797:
10798: @cindex selector invocation, restrictions
10799: @cindex class definition, restrictions
10800: Note: You can only invoke a selector if the receiving object belongs to
10801: the class where the selector was defined or one of its descendents;
10802: e.g., you can invoke @code{draw} only for objects belonging to
10803: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10804: mechanism will check if you try to invoke a selector that is not
10805: defined in this class hierarchy, so you'll get an error at compilation
10806: time.
10807:
10808:
10809: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10810: @subsubsection The @file{oof.fs} base class
10811: @cindex @file{oof.fs} base class
10812:
10813: When you define a class, you have to specify a parent class. So how do
10814: you start defining classes? There is one class available from the start:
10815: @code{object}. You have to use it as ancestor for all classes. It is the
10816: only class that has no parent. Classes are also objects, except that
10817: they don't have instance variables; class manipulation such as
10818: inheritance or changing definitions of a class is handled through
10819: selectors of the class @code{object}.
10820:
10821: @code{object} provides a number of selectors:
10822:
10823: @itemize @bullet
10824: @item
10825: @code{class} for subclassing, @code{definitions} to add definitions
10826: later on, and @code{class?} to get type informations (is the class a
10827: subclass of the class passed on the stack?).
10828:
10829: doc---object-class
10830: doc---object-definitions
10831: doc---object-class?
10832:
10833:
10834: @item
10835: @code{init} and @code{dispose} as constructor and destructor of the
10836: object. @code{init} is invocated after the object's memory is allocated,
10837: while @code{dispose} also handles deallocation. Thus if you redefine
10838: @code{dispose}, you have to call the parent's dispose with @code{super
10839: dispose}, too.
10840:
10841: doc---object-init
10842: doc---object-dispose
10843:
10844:
10845: @item
10846: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10847: @code{[]} to create named and unnamed objects and object arrays or
10848: object pointers.
10849:
10850: doc---object-new
10851: doc---object-new[]
10852: doc---object-:
10853: doc---object-ptr
10854: doc---object-asptr
10855: doc---object-[]
10856:
10857:
10858: @item
10859: @code{::} and @code{super} for explicit scoping. You should use explicit
10860: scoping only for super classes or classes with the same set of instance
10861: variables. Explicitly-scoped selectors use early binding.
10862:
10863: doc---object-::
10864: doc---object-super
10865:
10866:
10867: @item
10868: @code{self} to get the address of the object
10869:
10870: doc---object-self
10871:
10872:
10873: @item
10874: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10875: pointers and instance defers.
10876:
10877: doc---object-bind
10878: doc---object-bound
10879: doc---object-link
10880: doc---object-is
10881:
10882:
10883: @item
10884: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10885: form the stack, and @code{postpone} to generate selector invocation code.
10886:
10887: doc---object-'
10888: doc---object-postpone
10889:
10890:
10891: @item
10892: @code{with} and @code{endwith} to select the active object from the
10893: stack, and enable its scope. Using @code{with} and @code{endwith}
10894: also allows you to create code using selector @code{postpone} without being
10895: trapped by the state-smart objects.
10896:
10897: doc---object-with
10898: doc---object-endwith
10899:
10900:
10901: @end itemize
10902:
10903: @node Class Declaration, Class Implementation, The OOF base class, OOF
10904: @subsubsection Class Declaration
10905: @cindex class declaration
10906:
10907: @itemize @bullet
10908: @item
10909: Instance variables
10910:
10911: doc---oof-var
10912:
10913:
10914: @item
10915: Object pointers
10916:
10917: doc---oof-ptr
10918: doc---oof-asptr
10919:
10920:
10921: @item
10922: Instance defers
10923:
10924: doc---oof-defer
10925:
10926:
10927: @item
10928: Method selectors
10929:
10930: doc---oof-early
10931: doc---oof-method
10932:
10933:
10934: @item
10935: Class-wide variables
10936:
10937: doc---oof-static
10938:
10939:
10940: @item
10941: End declaration
10942:
10943: doc---oof-how:
10944: doc---oof-class;
10945:
10946:
10947: @end itemize
10948:
10949: @c -------------------------------------------------------------
10950: @node Class Implementation, , Class Declaration, OOF
10951: @subsubsection Class Implementation
10952: @cindex class implementation
10953:
10954: @c -------------------------------------------------------------
10955: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
10956: @subsection The @file{mini-oof.fs} model
10957: @cindex mini-oof
10958:
10959: Gforth's third object oriented Forth package is a 12-liner. It uses a
10960: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
10961: and reduces to the bare minimum of features. This is based on a posting
10962: of Bernd Paysan in comp.lang.forth.
10963:
10964: @menu
10965: * Basic Mini-OOF Usage::
10966: * Mini-OOF Example::
10967: * Mini-OOF Implementation::
10968: @end menu
10969:
10970: @c -------------------------------------------------------------
10971: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
10972: @subsubsection Basic @file{mini-oof.fs} Usage
10973: @cindex mini-oof usage
10974:
10975: There is a base class (@code{class}, which allocates one cell for the
10976: object pointer) plus seven other words: to define a method, a variable,
10977: a class; to end a class, to resolve binding, to allocate an object and
10978: to compile a class method.
10979: @comment TODO better description of the last one
10980:
10981:
10982: doc-object
10983: doc-method
10984: doc-var
10985: doc-class
10986: doc-end-class
10987: doc-defines
10988: doc-new
10989: doc-::
10990:
10991:
10992:
10993: @c -------------------------------------------------------------
10994: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
10995: @subsubsection Mini-OOF Example
10996: @cindex mini-oof example
10997:
10998: A short example shows how to use this package. This example, in slightly
10999: extended form, is supplied as @file{moof-exm.fs}
11000: @comment TODO could flesh this out with some comments from the Forthwrite article
11001:
11002: @example
11003: object class
11004: method init
11005: method draw
11006: end-class graphical
11007: @end example
11008:
11009: This code defines a class @code{graphical} with an
11010: operation @code{draw}. We can perform the operation
11011: @code{draw} on any @code{graphical} object, e.g.:
11012:
11013: @example
11014: 100 100 t-rex draw
11015: @end example
11016:
11017: where @code{t-rex} is an object or object pointer, created with e.g.
11018: @code{graphical new Constant t-rex}.
11019:
11020: For concrete graphical objects, we define child classes of the
11021: class @code{graphical}, e.g.:
11022:
11023: @example
11024: graphical class
11025: cell var circle-radius
11026: end-class circle \ "graphical" is the parent class
11027:
11028: :noname ( x y -- )
11029: circle-radius @@ draw-circle ; circle defines draw
11030: :noname ( r -- )
11031: circle-radius ! ; circle defines init
11032: @end example
11033:
11034: There is no implicit init method, so we have to define one. The creation
11035: code of the object now has to call init explicitely.
11036:
11037: @example
11038: circle new Constant my-circle
11039: 50 my-circle init
11040: @end example
11041:
11042: It is also possible to add a function to create named objects with
11043: automatic call of @code{init}, given that all objects have @code{init}
11044: on the same place:
11045:
11046: @example
11047: : new: ( .. o "name" -- )
11048: new dup Constant init ;
11049: 80 circle new: large-circle
11050: @end example
11051:
11052: We can draw this new circle at (100,100) with:
11053:
11054: @example
11055: 100 100 my-circle draw
11056: @end example
11057:
11058: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11059: @subsubsection @file{mini-oof.fs} Implementation
11060:
11061: Object-oriented systems with late binding typically use a
11062: ``vtable''-approach: the first variable in each object is a pointer to a
11063: table, which contains the methods as function pointers. The vtable
11064: may also contain other information.
11065:
11066: So first, let's declare selectors:
11067:
11068: @example
11069: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
11070: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11071: @end example
11072:
11073: During selector declaration, the number of selectors and instance
11074: variables is on the stack (in address units). @code{method} creates one
11075: selector and increments the selector number. To execute a selector, it
11076: takes the object, fetches the vtable pointer, adds the offset, and
11077: executes the method @i{xt} stored there. Each selector takes the object
11078: it is invoked with as top of stack parameter; it passes the parameters
11079: (including the object) unchanged to the appropriate method which should
11080: consume that object.
11081:
11082: Now, we also have to declare instance variables
11083:
11084: @example
11085: : var ( m v size "name" -- m v' ) Create over , +
11086: DOES> ( o -- addr ) @@ + ;
11087: @end example
11088:
11089: As before, a word is created with the current offset. Instance
11090: variables can have different sizes (cells, floats, doubles, chars), so
11091: all we do is take the size and add it to the offset. If your machine
11092: has alignment restrictions, put the proper @code{aligned} or
11093: @code{faligned} before the variable, to adjust the variable
11094: offset. That's why it is on the top of stack.
11095:
11096: We need a starting point (the base object) and some syntactic sugar:
11097:
11098: @example
11099: Create object 1 cells , 2 cells ,
11100: : class ( class -- class selectors vars ) dup 2@@ ;
11101: @end example
11102:
11103: For inheritance, the vtable of the parent object has to be
11104: copied when a new, derived class is declared. This gives all the
11105: methods of the parent class, which can be overridden, though.
11106:
11107: @example
11108: : end-class ( class selectors vars "name" -- )
11109: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11110: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11111: @end example
11112:
11113: The first line creates the vtable, initialized with
11114: @code{noop}s. The second line is the inheritance mechanism, it
11115: copies the xts from the parent vtable.
11116:
11117: We still have no way to define new methods, let's do that now:
11118:
11119: @example
11120: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11121: @end example
11122:
11123: To allocate a new object, we need a word, too:
11124:
11125: @example
11126: : new ( class -- o ) here over @@ allot swap over ! ;
11127: @end example
11128:
11129: Sometimes derived classes want to access the method of the
11130: parent object. There are two ways to achieve this with Mini-OOF:
11131: first, you could use named words, and second, you could look up the
11132: vtable of the parent object.
11133:
11134: @example
11135: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11136: @end example
11137:
11138:
11139: Nothing can be more confusing than a good example, so here is
11140: one. First let's declare a text object (called
11141: @code{button}), that stores text and position:
11142:
11143: @example
11144: object class
11145: cell var text
11146: cell var len
11147: cell var x
11148: cell var y
11149: method init
11150: method draw
11151: end-class button
11152: @end example
11153:
11154: @noindent
11155: Now, implement the two methods, @code{draw} and @code{init}:
11156:
11157: @example
11158: :noname ( o -- )
11159: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11160: button defines draw
11161: :noname ( addr u o -- )
11162: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11163: button defines init
11164: @end example
11165:
11166: @noindent
11167: To demonstrate inheritance, we define a class @code{bold-button}, with no
11168: new data and no new selectors:
11169:
11170: @example
11171: button class
11172: end-class bold-button
11173:
11174: : bold 27 emit ." [1m" ;
11175: : normal 27 emit ." [0m" ;
11176: @end example
11177:
11178: @noindent
11179: The class @code{bold-button} has a different draw method to
11180: @code{button}, but the new method is defined in terms of the draw method
11181: for @code{button}:
11182:
11183: @example
11184: :noname bold [ button :: draw ] normal ; bold-button defines draw
11185: @end example
11186:
11187: @noindent
11188: Finally, create two objects and apply selectors:
11189:
11190: @example
11191: button new Constant foo
11192: s" thin foo" foo init
11193: page
11194: foo draw
11195: bold-button new Constant bar
11196: s" fat bar" bar init
11197: 1 bar y !
11198: bar draw
11199: @end example
11200:
11201:
11202: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11203: @subsection Comparison with other object models
11204: @cindex comparison of object models
11205: @cindex object models, comparison
11206:
11207: Many object-oriented Forth extensions have been proposed (@cite{A survey
11208: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11209: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11210: relation of the object models described here to two well-known and two
11211: closely-related (by the use of method maps) models. Andras Zsoter
11212: helped us with this section.
11213:
11214: @cindex Neon model
11215: The most popular model currently seems to be the Neon model (see
11216: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11217: 1997) by Andrew McKewan) but this model has a number of limitations
11218: @footnote{A longer version of this critique can be
11219: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11220: Dimensions, May 1997) by Anton Ertl.}:
11221:
11222: @itemize @bullet
11223: @item
11224: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11225: to pass objects on the stack.
11226:
11227: @item
11228: It requires that the selector parses the input stream (at
11229: compile time); this leads to reduced extensibility and to bugs that are
11230: hard to find.
11231:
11232: @item
11233: It allows using every selector on every object; this eliminates the
11234: need for interfaces, but makes it harder to create efficient
11235: implementations.
11236: @end itemize
11237:
11238: @cindex Pountain's object-oriented model
11239: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11240: Press, London, 1987) by Dick Pountain. However, it is not really about
11241: object-oriented programming, because it hardly deals with late
11242: binding. Instead, it focuses on features like information hiding and
11243: overloading that are characteristic of modular languages like Ada (83).
11244:
11245: @cindex Zsoter's object-oriented model
11246: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11247: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11248: describes a model that makes heavy use of an active object (like
11249: @code{this} in @file{objects.fs}): The active object is not only used
11250: for accessing all fields, but also specifies the receiving object of
11251: every selector invocation; you have to change the active object
11252: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11253: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11254: the method entry point is unnecessary with Zsoter's model, because the
11255: receiving object is the active object already. On the other hand, the
11256: explicit change is absolutely necessary in that model, because otherwise
11257: no one could ever change the active object. An ANS Forth implementation
11258: of this model is available through
11259: @uref{http://www.forth.org/oopf.html}.
11260:
11261: @cindex @file{oof.fs}, differences to other models
11262: The @file{oof.fs} model combines information hiding and overloading
11263: resolution (by keeping names in various word lists) with object-oriented
11264: programming. It sets the active object implicitly on method entry, but
11265: also allows explicit changing (with @code{>o...o>} or with
11266: @code{with...endwith}). It uses parsing and state-smart objects and
11267: classes for resolving overloading and for early binding: the object or
11268: class parses the selector and determines the method from this. If the
11269: selector is not parsed by an object or class, it performs a call to the
11270: selector for the active object (late binding), like Zsoter's model.
11271: Fields are always accessed through the active object. The big
11272: disadvantage of this model is the parsing and the state-smartness, which
11273: reduces extensibility and increases the opportunities for subtle bugs;
11274: essentially, you are only safe if you never tick or @code{postpone} an
11275: object or class (Bernd disagrees, but I (Anton) am not convinced).
11276:
11277: @cindex @file{mini-oof.fs}, differences to other models
11278: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11279: version of the @file{objects.fs} model, but syntactically it is a
11280: mixture of the @file{objects.fs} and @file{oof.fs} models.
11281:
11282:
11283: @c -------------------------------------------------------------
11284: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11285: @section Programming Tools
11286: @cindex programming tools
11287:
11288: @c !! move this and assembler down below OO stuff.
11289:
11290: @menu
11291: * Examining::
11292: * Forgetting words::
11293: * Debugging:: Simple and quick.
11294: * Assertions:: Making your programs self-checking.
11295: * Singlestep Debugger:: Executing your program word by word.
11296: @end menu
11297:
11298: @node Examining, Forgetting words, Programming Tools, Programming Tools
11299: @subsection Examining data and code
11300: @cindex examining data and code
11301: @cindex data examination
11302: @cindex code examination
11303:
11304: The following words inspect the stack non-destructively:
11305:
11306: doc-.s
11307: doc-f.s
11308:
11309: There is a word @code{.r} but it does @i{not} display the return stack!
11310: It is used for formatted numeric output (@pxref{Simple numeric output}).
11311:
11312: doc-depth
11313: doc-fdepth
11314: doc-clearstack
11315: doc-clearstacks
11316:
11317: The following words inspect memory.
11318:
11319: doc-?
11320: doc-dump
11321:
11322: And finally, @code{see} allows to inspect code:
11323:
11324: doc-see
11325: doc-xt-see
11326: doc-simple-see
11327: doc-simple-see-range
11328:
11329: @node Forgetting words, Debugging, Examining, Programming Tools
11330: @subsection Forgetting words
11331: @cindex words, forgetting
11332: @cindex forgeting words
11333:
11334: @c anton: other, maybe better places for this subsection: Defining Words;
11335: @c Dictionary allocation. At least a reference should be there.
11336:
11337: Forth allows you to forget words (and everything that was alloted in the
11338: dictonary after them) in a LIFO manner.
11339:
11340: doc-marker
11341:
11342: The most common use of this feature is during progam development: when
11343: you change a source file, forget all the words it defined and load it
11344: again (since you also forget everything defined after the source file
11345: was loaded, you have to reload that, too). Note that effects like
11346: storing to variables and destroyed system words are not undone when you
11347: forget words. With a system like Gforth, that is fast enough at
11348: starting up and compiling, I find it more convenient to exit and restart
11349: Gforth, as this gives me a clean slate.
11350:
11351: Here's an example of using @code{marker} at the start of a source file
11352: that you are debugging; it ensures that you only ever have one copy of
11353: the file's definitions compiled at any time:
11354:
11355: @example
11356: [IFDEF] my-code
11357: my-code
11358: [ENDIF]
11359:
11360: marker my-code
11361: init-included-files
11362:
11363: \ .. definitions start here
11364: \ .
11365: \ .
11366: \ end
11367: @end example
11368:
11369:
11370: @node Debugging, Assertions, Forgetting words, Programming Tools
11371: @subsection Debugging
11372: @cindex debugging
11373:
11374: Languages with a slow edit/compile/link/test development loop tend to
11375: require sophisticated tracing/stepping debuggers to facilate debugging.
11376:
11377: A much better (faster) way in fast-compiling languages is to add
11378: printing code at well-selected places, let the program run, look at
11379: the output, see where things went wrong, add more printing code, etc.,
11380: until the bug is found.
11381:
11382: The simple debugging aids provided in @file{debugs.fs}
11383: are meant to support this style of debugging.
11384:
11385: The word @code{~~} prints debugging information (by default the source
11386: location and the stack contents). It is easy to insert. If you use Emacs
11387: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11388: query-replace them with nothing). The deferred words
11389: @code{printdebugdata} and @code{.debugline} control the output of
11390: @code{~~}. The default source location output format works well with
11391: Emacs' compilation mode, so you can step through the program at the
11392: source level using @kbd{C-x `} (the advantage over a stepping debugger
11393: is that you can step in any direction and you know where the crash has
11394: happened or where the strange data has occurred).
11395:
11396: doc-~~
11397: doc-printdebugdata
11398: doc-.debugline
11399:
11400: @cindex filenames in @code{~~} output
11401: @code{~~} (and assertions) will usually print the wrong file name if a
11402: marker is executed in the same file after their occurance. They will
11403: print @samp{*somewhere*} as file name if a marker is executed in the
11404: same file before their occurance.
11405:
11406:
11407: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11408: @subsection Assertions
11409: @cindex assertions
11410:
11411: It is a good idea to make your programs self-checking, especially if you
11412: make an assumption that may become invalid during maintenance (for
11413: example, that a certain field of a data structure is never zero). Gforth
11414: supports @dfn{assertions} for this purpose. They are used like this:
11415:
11416: @example
11417: assert( @i{flag} )
11418: @end example
11419:
11420: The code between @code{assert(} and @code{)} should compute a flag, that
11421: should be true if everything is alright and false otherwise. It should
11422: not change anything else on the stack. The overall stack effect of the
11423: assertion is @code{( -- )}. E.g.
11424:
11425: @example
11426: assert( 1 1 + 2 = ) \ what we learn in school
11427: assert( dup 0<> ) \ assert that the top of stack is not zero
11428: assert( false ) \ this code should not be reached
11429: @end example
11430:
11431: The need for assertions is different at different times. During
11432: debugging, we want more checking, in production we sometimes care more
11433: for speed. Therefore, assertions can be turned off, i.e., the assertion
11434: becomes a comment. Depending on the importance of an assertion and the
11435: time it takes to check it, you may want to turn off some assertions and
11436: keep others turned on. Gforth provides several levels of assertions for
11437: this purpose:
11438:
11439:
11440: doc-assert0(
11441: doc-assert1(
11442: doc-assert2(
11443: doc-assert3(
11444: doc-assert(
11445: doc-)
11446:
11447:
11448: The variable @code{assert-level} specifies the highest assertions that
11449: are turned on. I.e., at the default @code{assert-level} of one,
11450: @code{assert0(} and @code{assert1(} assertions perform checking, while
11451: @code{assert2(} and @code{assert3(} assertions are treated as comments.
11452:
11453: The value of @code{assert-level} is evaluated at compile-time, not at
11454: run-time. Therefore you cannot turn assertions on or off at run-time;
11455: you have to set the @code{assert-level} appropriately before compiling a
11456: piece of code. You can compile different pieces of code at different
11457: @code{assert-level}s (e.g., a trusted library at level 1 and
11458: newly-written code at level 3).
11459:
11460:
11461: doc-assert-level
11462:
11463:
11464: If an assertion fails, a message compatible with Emacs' compilation mode
11465: is produced and the execution is aborted (currently with @code{ABORT"}.
11466: If there is interest, we will introduce a special throw code. But if you
11467: intend to @code{catch} a specific condition, using @code{throw} is
11468: probably more appropriate than an assertion).
11469:
11470: @cindex filenames in assertion output
11471: Assertions (and @code{~~}) will usually print the wrong file name if a
11472: marker is executed in the same file after their occurance. They will
11473: print @samp{*somewhere*} as file name if a marker is executed in the
11474: same file before their occurance.
11475:
11476: Definitions in ANS Forth for these assertion words are provided
11477: in @file{compat/assert.fs}.
11478:
11479:
11480: @node Singlestep Debugger, , Assertions, Programming Tools
11481: @subsection Singlestep Debugger
11482: @cindex singlestep Debugger
11483: @cindex debugging Singlestep
11484:
11485: The singlestep debugger does not work in this release.
11486:
11487: When you create a new word there's often the need to check whether it
11488: behaves correctly or not. You can do this by typing @code{dbg
11489: badword}. A debug session might look like this:
11490:
11491: @example
11492: : badword 0 DO i . LOOP ; ok
11493: 2 dbg badword
11494: : badword
11495: Scanning code...
11496:
11497: Nesting debugger ready!
11498:
11499: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11500: 400D4740 8049F68 DO -> [ 0 ]
11501: 400D4744 804A0C8 i -> [ 1 ] 00000
11502: 400D4748 400C5E60 . -> 0 [ 0 ]
11503: 400D474C 8049D0C LOOP -> [ 0 ]
11504: 400D4744 804A0C8 i -> [ 1 ] 00001
11505: 400D4748 400C5E60 . -> 1 [ 0 ]
11506: 400D474C 8049D0C LOOP -> [ 0 ]
11507: 400D4758 804B384 ; -> ok
11508: @end example
11509:
11510: Each line displayed is one step. You always have to hit return to
11511: execute the next word that is displayed. If you don't want to execute
11512: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11513: an overview what keys are available:
11514:
11515: @table @i
11516:
11517: @item @key{RET}
11518: Next; Execute the next word.
11519:
11520: @item n
11521: Nest; Single step through next word.
11522:
11523: @item u
11524: Unnest; Stop debugging and execute rest of word. If we got to this word
11525: with nest, continue debugging with the calling word.
11526:
11527: @item d
11528: Done; Stop debugging and execute rest.
11529:
11530: @item s
11531: Stop; Abort immediately.
11532:
11533: @end table
11534:
11535: Debugging large application with this mechanism is very difficult, because
11536: you have to nest very deeply into the program before the interesting part
11537: begins. This takes a lot of time.
11538:
11539: To do it more directly put a @code{BREAK:} command into your source code.
11540: When program execution reaches @code{BREAK:} the single step debugger is
11541: invoked and you have all the features described above.
11542:
11543: If you have more than one part to debug it is useful to know where the
11544: program has stopped at the moment. You can do this by the
11545: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11546: string is typed out when the ``breakpoint'' is reached.
11547:
11548:
11549: doc-dbg
11550: doc-break:
11551: doc-break"
11552:
11553:
11554:
11555: @c -------------------------------------------------------------
11556: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11557: @section Assembler and Code Words
11558: @cindex assembler
11559: @cindex code words
11560:
11561: @menu
11562: * Code and ;code::
11563: * Common Assembler:: Assembler Syntax
11564: * Common Disassembler::
11565: * 386 Assembler:: Deviations and special cases
11566: * Alpha Assembler:: Deviations and special cases
11567: * MIPS assembler:: Deviations and special cases
11568: * Other assemblers:: How to write them
11569: @end menu
11570:
11571: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11572: @subsection @code{Code} and @code{;code}
11573:
11574: Gforth provides some words for defining primitives (words written in
11575: machine code), and for defining the machine-code equivalent of
11576: @code{DOES>}-based defining words. However, the machine-independent
11577: nature of Gforth poses a few problems: First of all, Gforth runs on
11578: several architectures, so it can provide no standard assembler. What's
11579: worse is that the register allocation not only depends on the processor,
11580: but also on the @code{gcc} version and options used.
11581:
11582: The words that Gforth offers encapsulate some system dependences (e.g.,
11583: the header structure), so a system-independent assembler may be used in
11584: Gforth. If you do not have an assembler, you can compile machine code
11585: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11586: because these words emit stuff in @i{data} space; it works because
11587: Gforth has unified code/data spaces. Assembler isn't likely to be
11588: portable anyway.}.
11589:
11590:
11591: doc-assembler
11592: doc-init-asm
11593: doc-code
11594: doc-end-code
11595: doc-;code
11596: doc-flush-icache
11597:
11598:
11599: If @code{flush-icache} does not work correctly, @code{code} words
11600: etc. will not work (reliably), either.
11601:
11602: The typical usage of these @code{code} words can be shown most easily by
11603: analogy to the equivalent high-level defining words:
11604:
11605: @example
11606: : foo code foo
11607: <high-level Forth words> <assembler>
11608: ; end-code
11609:
11610: : bar : bar
11611: <high-level Forth words> <high-level Forth words>
11612: CREATE CREATE
11613: <high-level Forth words> <high-level Forth words>
11614: DOES> ;code
11615: <high-level Forth words> <assembler>
11616: ; end-code
11617: @end example
11618:
11619: @c anton: the following stuff is also in "Common Assembler", in less detail.
11620:
11621: @cindex registers of the inner interpreter
11622: In the assembly code you will want to refer to the inner interpreter's
11623: registers (e.g., the data stack pointer) and you may want to use other
11624: registers for temporary storage. Unfortunately, the register allocation
11625: is installation-dependent.
11626:
11627: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
11628: (return stack pointer) may be in different places in @code{gforth} and
11629: @code{gforth-fast}, or different installations. This means that you
11630: cannot write a @code{NEXT} routine that works reliably on both versions
11631: or different installations; so for doing @code{NEXT}, I recommend
11632: jumping to @code{' noop >code-address}, which contains nothing but a
11633: @code{NEXT}.
11634:
11635: For general accesses to the inner interpreter's registers, the easiest
11636: solution is to use explicit register declarations (@pxref{Explicit Reg
11637: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11638: all of the inner interpreter's registers: You have to compile Gforth
11639: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11640: the appropriate declarations must be present in the @code{machine.h}
11641: file (see @code{mips.h} for an example; you can find a full list of all
11642: declarable register symbols with @code{grep register engine.c}). If you
11643: give explicit registers to all variables that are declared at the
11644: beginning of @code{engine()}, you should be able to use the other
11645: caller-saved registers for temporary storage. Alternatively, you can use
11646: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11647: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11648: reserve a register (however, this restriction on register allocation may
11649: slow Gforth significantly).
11650:
11651: If this solution is not viable (e.g., because @code{gcc} does not allow
11652: you to explicitly declare all the registers you need), you have to find
11653: out by looking at the code where the inner interpreter's registers
11654: reside and which registers can be used for temporary storage. You can
11655: get an assembly listing of the engine's code with @code{make engine.s}.
11656:
11657: In any case, it is good practice to abstract your assembly code from the
11658: actual register allocation. E.g., if the data stack pointer resides in
11659: register @code{$17}, create an alias for this register called @code{sp},
11660: and use that in your assembly code.
11661:
11662: @cindex code words, portable
11663: Another option for implementing normal and defining words efficiently
11664: is to add the desired functionality to the source of Gforth. For normal
11665: words you just have to edit @file{primitives} (@pxref{Automatic
11666: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11667: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11668: @file{prims2x.fs}, and possibly @file{cross.fs}.
11669:
11670: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11671: @subsection Common Assembler
11672:
11673: The assemblers in Gforth generally use a postfix syntax, i.e., the
11674: instruction name follows the operands.
11675:
11676: The operands are passed in the usual order (the same that is used in the
11677: manual of the architecture). Since they all are Forth words, they have
11678: to be separated by spaces; you can also use Forth words to compute the
11679: operands.
11680:
11681: The instruction names usually end with a @code{,}. This makes it easier
11682: to visually separate instructions if you put several of them on one
11683: line; it also avoids shadowing other Forth words (e.g., @code{and}).
11684:
11685: Registers are usually specified by number; e.g., (decimal) @code{11}
11686: specifies registers R11 and F11 on the Alpha architecture (which one,
11687: depends on the instruction). The usual names are also available, e.g.,
11688: @code{s2} for R11 on Alpha.
11689:
11690: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11691: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11692: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11693: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
11694: conditions are specified in a way specific to each assembler.
11695:
11696: Note that the register assignments of the Gforth engine can change
11697: between Gforth versions, or even between different compilations of the
11698: same Gforth version (e.g., if you use a different GCC version). So if
11699: you want to refer to Gforth's registers (e.g., the stack pointer or
11700: TOS), I recommend defining your own words for refering to these
11701: registers, and using them later on; then you can easily adapt to a
11702: changed register assignment. The stability of the register assignment
11703: is usually better if you build Gforth with @code{--enable-force-reg}.
11704:
11705: The most common use of these registers is to dispatch to the next word
11706: (the @code{next} routine). A portable way to do this is to jump to
11707: @code{' noop >code-address} (of course, this is less efficient than
11708: integrating the @code{next} code and scheduling it well).
11709:
11710: Another difference between Gforth version is that the top of stack is
11711: kept in memory in @code{gforth} and, on most platforms, in a register in
11712: @code{gforth-fast}.
11713:
11714: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11715: @subsection Common Disassembler
11716:
11717: You can disassemble a @code{code} word with @code{see}
11718: (@pxref{Debugging}). You can disassemble a section of memory with
11719:
11720: doc-disasm
11721:
11722: The disassembler generally produces output that can be fed into the
11723: assembler (i.e., same syntax, etc.). It also includes additional
11724: information in comments. In particular, the address of the instruction
11725: is given in a comment before the instruction.
11726:
11727: @code{See} may display more or less than the actual code of the word,
11728: because the recognition of the end of the code is unreliable. You can
11729: use @code{disasm} if it did not display enough. It may display more, if
11730: the code word is not immediately followed by a named word. If you have
11731: something else there, you can follow the word with @code{align latest ,}
11732: to ensure that the end is recognized.
11733:
11734: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11735: @subsection 386 Assembler
11736:
11737: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11738: available under GPL, and originally part of bigFORTH.
11739:
11740: The 386 disassembler included in Gforth was written by Andrew McKewan
11741: and is in the public domain.
11742:
11743: The disassembler displays code in an Intel-like prefix syntax.
11744:
11745: The assembler uses a postfix syntax with reversed parameters.
11746:
11747: The assembler includes all instruction of the Athlon, i.e. 486 core
11748: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11749: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11750: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
11751:
11752: There are several prefixes to switch between different operation sizes,
11753: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11754: double-word accesses. Addressing modes can be switched with @code{.wa}
11755: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11756: need a prefix for byte register names (@code{AL} et al).
11757:
11758: For floating point operations, the prefixes are @code{.fs} (IEEE
11759: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11760: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
11761:
11762: The MMX opcodes don't have size prefixes, they are spelled out like in
11763: the Intel assembler. Instead of move from and to memory, there are
11764: PLDQ/PLDD and PSTQ/PSTD.
11765:
11766: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11767: ax. Immediate values are indicated by postfixing them with @code{#},
11768: e.g., @code{3 #}. Here are some examples of addressing modes in various
11769: syntaxes:
11770:
11771: @example
11772: Gforth Intel (NASM) AT&T (gas) Name
11773: .w ax ax %ax register (16 bit)
11774: ax eax %eax register (32 bit)
11775: 3 # offset 3 $3 immediate
11776: 1000 #) byte ptr 1000 1000 displacement
11777: bx ) [ebx] (%ebx) base
11778: 100 di d) 100[edi] 100(%edi) base+displacement
11779: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
11780: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
11781: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
11782: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
11783: @end example
11784:
11785: You can use @code{L)} and @code{LI)} instead of @code{D)} and
11786: @code{DI)} to enforce 32-bit displacement fields (useful for
11787: later patching).
11788:
11789: Some example of instructions are:
11790:
11791: @example
11792: ax bx mov \ move ebx,eax
11793: 3 # ax mov \ mov eax,3
11794: 100 di ) ax mov \ mov eax,100[edi]
11795: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
11796: .w ax bx mov \ mov bx,ax
11797: @end example
11798:
11799: The following forms are supported for binary instructions:
11800:
11801: @example
11802: <reg> <reg> <inst>
11803: <n> # <reg> <inst>
11804: <mem> <reg> <inst>
11805: <reg> <mem> <inst>
11806: @end example
11807:
11808: Immediate to memory is not supported. The shift/rotate syntax is:
11809:
11810: @example
11811: <reg/mem> 1 # shl \ shortens to shift without immediate
11812: <reg/mem> 4 # shl
11813: <reg/mem> cl shl
11814: @end example
11815:
11816: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11817: the byte version.
11818:
11819: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11820: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11821: pc < >= <= >}. (Note that most of these words shadow some Forth words
11822: when @code{assembler} is in front of @code{forth} in the search path,
11823: e.g., in @code{code} words). Currently the control structure words use
11824: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11825: to shuffle them (you can also use @code{swap} etc.).
11826:
11827: Here is an example of a @code{code} word (assumes that the stack pointer
11828: is in esi and the TOS is in ebx):
11829:
11830: @example
11831: code my+ ( n1 n2 -- n )
11832: 4 si D) bx add
11833: 4 # si add
11834: Next
11835: end-code
11836: @end example
11837:
11838: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11839: @subsection Alpha Assembler
11840:
11841: The Alpha assembler and disassembler were originally written by Bernd
11842: Thallner.
11843:
11844: The register names @code{a0}--@code{a5} are not available to avoid
11845: shadowing hex numbers.
11846:
11847: Immediate forms of arithmetic instructions are distinguished by a
11848: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11849: does not count as arithmetic instruction).
11850:
11851: You have to specify all operands to an instruction, even those that
11852: other assemblers consider optional, e.g., the destination register for
11853: @code{br,}, or the destination register and hint for @code{jmp,}.
11854:
11855: You can specify conditions for @code{if,} by removing the first @code{b}
11856: and the trailing @code{,} from a branch with a corresponding name; e.g.,
11857:
11858: @example
11859: 11 fgt if, \ if F11>0e
11860: ...
11861: endif,
11862: @end example
11863:
11864: @code{fbgt,} gives @code{fgt}.
11865:
11866: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11867: @subsection MIPS assembler
11868:
11869: The MIPS assembler was originally written by Christian Pirker.
11870:
11871: Currently the assembler and disassembler only cover the MIPS-I
11872: architecture (R3000), and don't support FP instructions.
11873:
11874: The register names @code{$a0}--@code{$a3} are not available to avoid
11875: shadowing hex numbers.
11876:
11877: Because there is no way to distinguish registers from immediate values,
11878: you have to explicitly use the immediate forms of instructions, i.e.,
11879: @code{addiu,}, not just @code{addu,} (@command{as} does this
11880: implicitly).
11881:
11882: If the architecture manual specifies several formats for the instruction
11883: (e.g., for @code{jalr,}), you usually have to use the one with more
11884: arguments (i.e., two for @code{jalr,}). When in doubt, see
11885: @code{arch/mips/testasm.fs} for an example of correct use.
11886:
11887: Branches and jumps in the MIPS architecture have a delay slot. You have
11888: to fill it yourself (the simplest way is to use @code{nop,}), the
11889: assembler does not do it for you (unlike @command{as}). Even
11890: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
11891: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
11892: and @code{then,} just specify branch targets, they are not affected.
11893:
11894: Note that you must not put branches, jumps, or @code{li,} into the delay
11895: slot: @code{li,} may expand to several instructions, and control flow
11896: instructions may not be put into the branch delay slot in any case.
11897:
11898: For branches the argument specifying the target is a relative address;
11899: You have to add the address of the delay slot to get the absolute
11900: address.
11901:
11902: The MIPS architecture also has load delay slots and restrictions on
11903: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
11904: yourself to satisfy these restrictions, the assembler does not do it for
11905: you.
11906:
11907: You can specify the conditions for @code{if,} etc. by taking a
11908: conditional branch and leaving away the @code{b} at the start and the
11909: @code{,} at the end. E.g.,
11910:
11911: @example
11912: 4 5 eq if,
11913: ... \ do something if $4 equals $5
11914: then,
11915: @end example
11916:
11917: @node Other assemblers, , MIPS assembler, Assembler and Code Words
11918: @subsection Other assemblers
11919:
11920: If you want to contribute another assembler/disassembler, please contact
11921: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
11922: an assembler already. If you are writing them from scratch, please use
11923: a similar syntax style as the one we use (i.e., postfix, commas at the
11924: end of the instruction names, @pxref{Common Assembler}); make the output
11925: of the disassembler be valid input for the assembler, and keep the style
11926: similar to the style we used.
11927:
11928: Hints on implementation: The most important part is to have a good test
11929: suite that contains all instructions. Once you have that, the rest is
11930: easy. For actual coding you can take a look at
11931: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
11932: the assembler and disassembler, avoiding redundancy and some potential
11933: bugs. You can also look at that file (and @pxref{Advanced does> usage
11934: example}) to get ideas how to factor a disassembler.
11935:
11936: Start with the disassembler, because it's easier to reuse data from the
11937: disassembler for the assembler than the other way round.
11938:
11939: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
11940: how simple it can be.
11941:
11942: @c -------------------------------------------------------------
11943: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
11944: @section Threading Words
11945: @cindex threading words
11946:
11947: @cindex code address
11948: These words provide access to code addresses and other threading stuff
11949: in Gforth (and, possibly, other interpretive Forths). It more or less
11950: abstracts away the differences between direct and indirect threading
11951: (and, for direct threading, the machine dependences). However, at
11952: present this wordset is still incomplete. It is also pretty low-level;
11953: some day it will hopefully be made unnecessary by an internals wordset
11954: that abstracts implementation details away completely.
11955:
11956: The terminology used here stems from indirect threaded Forth systems; in
11957: such a system, the XT of a word is represented by the CFA (code field
11958: address) of a word; the CFA points to a cell that contains the code
11959: address. The code address is the address of some machine code that
11960: performs the run-time action of invoking the word (e.g., the
11961: @code{dovar:} routine pushes the address of the body of the word (a
11962: variable) on the stack
11963: ).
11964:
11965: @cindex code address
11966: @cindex code field address
11967: In an indirect threaded Forth, you can get the code address of @i{name}
11968: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
11969: >code-address}, independent of the threading method.
11970:
11971: doc-threading-method
11972: doc->code-address
11973: doc-code-address!
11974:
11975: @cindex @code{does>}-handler
11976: @cindex @code{does>}-code
11977: For a word defined with @code{DOES>}, the code address usually points to
11978: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
11979: routine (in Gforth on some platforms, it can also point to the dodoes
11980: routine itself). What you are typically interested in, though, is
11981: whether a word is a @code{DOES>}-defined word, and what Forth code it
11982: executes; @code{>does-code} tells you that.
11983:
11984: doc->does-code
11985:
11986: To create a @code{DOES>}-defined word with the following basic words,
11987: you have to set up a @code{DOES>}-handler with @code{does-handler!};
11988: @code{/does-handler} aus behind you have to place your executable Forth
11989: code. Finally you have to create a word and modify its behaviour with
11990: @code{does-handler!}.
11991:
11992: doc-does-code!
11993: doc-does-handler!
11994: doc-/does-handler
11995:
11996: The code addresses produced by various defining words are produced by
11997: the following words:
11998:
11999: doc-docol:
12000: doc-docon:
12001: doc-dovar:
12002: doc-douser:
12003: doc-dodefer:
12004: doc-dofield:
12005:
12006: @cindex definer
12007: The following two words generalize @code{>code-address},
12008: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12009:
12010: doc->definer
12011: doc-definer!
12012:
12013: @c -------------------------------------------------------------
12014: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
12015: @section Passing Commands to the Operating System
12016: @cindex operating system - passing commands
12017: @cindex shell commands
12018:
12019: Gforth allows you to pass an arbitrary string to the host operating
12020: system shell (if such a thing exists) for execution.
12021:
12022:
12023: doc-sh
12024: doc-system
12025: doc-$?
12026: doc-getenv
12027:
12028:
12029: @c -------------------------------------------------------------
12030: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12031: @section Keeping track of Time
12032: @cindex time-related words
12033:
12034: doc-ms
12035: doc-time&date
12036: doc-utime
12037: doc-cputime
12038:
12039:
12040: @c -------------------------------------------------------------
12041: @node Miscellaneous Words, , Keeping track of Time, Words
12042: @section Miscellaneous Words
12043: @cindex miscellaneous words
12044:
12045: @comment TODO find homes for these
12046:
12047: These section lists the ANS Forth words that are not documented
12048: elsewhere in this manual. Ultimately, they all need proper homes.
12049:
12050: doc-quit
12051:
12052: The following ANS Forth words are not currently supported by Gforth
12053: (@pxref{ANS conformance}):
12054:
12055: @code{EDITOR}
12056: @code{EMIT?}
12057: @code{FORGET}
12058:
12059: @c ******************************************************************
12060: @node Error messages, Tools, Words, Top
12061: @chapter Error messages
12062: @cindex error messages
12063: @cindex backtrace
12064:
12065: A typical Gforth error message looks like this:
12066:
12067: @example
12068: in file included from \evaluated string/:-1
12069: in file included from ./yyy.fs:1
12070: ./xxx.fs:4: Invalid memory address
12071: bar
12072: ^^^
12073: Backtrace:
12074: $400E664C @@
12075: $400E6664 foo
12076: @end example
12077:
12078: The message identifying the error is @code{Invalid memory address}. The
12079: error happened when text-interpreting line 4 of the file
12080: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12081: word on the line where the error happened, is pointed out (with
12082: @code{^^^}).
12083:
12084: The file containing the error was included in line 1 of @file{./yyy.fs},
12085: and @file{yyy.fs} was included from a non-file (in this case, by giving
12086: @file{yyy.fs} as command-line parameter to Gforth).
12087:
12088: At the end of the error message you find a return stack dump that can be
12089: interpreted as a backtrace (possibly empty). On top you find the top of
12090: the return stack when the @code{throw} happened, and at the bottom you
12091: find the return stack entry just above the return stack of the topmost
12092: text interpreter.
12093:
12094: To the right of most return stack entries you see a guess for the word
12095: that pushed that return stack entry as its return address. This gives a
12096: backtrace. In our case we see that @code{bar} called @code{foo}, and
12097: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12098: address} exception).
12099:
12100: Note that the backtrace is not perfect: We don't know which return stack
12101: entries are return addresses (so we may get false positives); and in
12102: some cases (e.g., for @code{abort"}) we cannot determine from the return
12103: address the word that pushed the return address, so for some return
12104: addresses you see no names in the return stack dump.
12105:
12106: @cindex @code{catch} and backtraces
12107: The return stack dump represents the return stack at the time when a
12108: specific @code{throw} was executed. In programs that make use of
12109: @code{catch}, it is not necessarily clear which @code{throw} should be
12110: used for the return stack dump (e.g., consider one @code{throw} that
12111: indicates an error, which is caught, and during recovery another error
12112: happens; which @code{throw} should be used for the stack dump?). Gforth
12113: presents the return stack dump for the first @code{throw} after the last
12114: executed (not returned-to) @code{catch}; this works well in the usual
12115: case.
12116:
12117: @cindex @code{gforth-fast} and backtraces
12118: @cindex @code{gforth-fast}, difference from @code{gforth}
12119: @cindex backtraces with @code{gforth-fast}
12120: @cindex return stack dump with @code{gforth-fast}
12121: @code{Gforth} is able to do a return stack dump for throws generated
12122: from primitives (e.g., invalid memory address, stack empty etc.);
12123: @code{gforth-fast} is only able to do a return stack dump from a
12124: directly called @code{throw} (including @code{abort} etc.). Given an
12125: exception caused by a primitive in @code{gforth-fast}, you will
12126: typically see no return stack dump at all; however, if the exception is
12127: caught by @code{catch} (e.g., for restoring some state), and then
12128: @code{throw}n again, the return stack dump will be for the first such
12129: @code{throw}.
12130:
12131: @c ******************************************************************
12132: @node Tools, ANS conformance, Error messages, Top
12133: @chapter Tools
12134:
12135: @menu
12136: * ANS Report:: Report the words used, sorted by wordset.
12137: @end menu
12138:
12139: See also @ref{Emacs and Gforth}.
12140:
12141: @node ANS Report, , Tools, Tools
12142: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12143: @cindex @file{ans-report.fs}
12144: @cindex report the words used in your program
12145: @cindex words used in your program
12146:
12147: If you want to label a Forth program as ANS Forth Program, you must
12148: document which wordsets the program uses; for extension wordsets, it is
12149: helpful to list the words the program requires from these wordsets
12150: (because Forth systems are allowed to provide only some words of them).
12151:
12152: The @file{ans-report.fs} tool makes it easy for you to determine which
12153: words from which wordset and which non-ANS words your application
12154: uses. You simply have to include @file{ans-report.fs} before loading the
12155: program you want to check. After loading your program, you can get the
12156: report with @code{print-ans-report}. A typical use is to run this as
12157: batch job like this:
12158: @example
12159: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12160: @end example
12161:
12162: The output looks like this (for @file{compat/control.fs}):
12163: @example
12164: The program uses the following words
12165: from CORE :
12166: : POSTPONE THEN ; immediate ?dup IF 0=
12167: from BLOCK-EXT :
12168: \
12169: from FILE :
12170: (
12171: @end example
12172:
12173: @subsection Caveats
12174:
12175: Note that @file{ans-report.fs} just checks which words are used, not whether
12176: they are used in an ANS Forth conforming way!
12177:
12178: Some words are defined in several wordsets in the
12179: standard. @file{ans-report.fs} reports them for only one of the
12180: wordsets, and not necessarily the one you expect. It depends on usage
12181: which wordset is the right one to specify. E.g., if you only use the
12182: compilation semantics of @code{S"}, it is a Core word; if you also use
12183: its interpretation semantics, it is a File word.
12184:
12185:
12186: @node Stack depth changes
12187: @section Stack depth changes during interpretation
12188: @cindex @file{depth-changes.fs}
12189: @cindex depth changes during interpretation
12190: @cindex stack depth changes during interpretation
12191: @cindex items on the stack after interpretation
12192:
12193: Sometimes you notice that, after loading a file, there are items left
12194: on the stack. The tool @file{depth-changes.fs} helps you find out
12195: quickly where in the file these stack items are coming from.
12196:
12197: The simplest way of using @file{depth-changes.fs} is to include it
12198: before the file(s) you want to check, e.g.:
12199:
12200: @example
12201: gforth depth-changes.fs my-file.fs
12202: @end example
12203:
12204: This will compare the stack depths of the data and FP stack at every
12205: empty line (in interpretation state) against these depths at the last
12206: empty line (in interpretation state). If the depths are not equal,
12207: the position in the file and the stack contents are printed with
12208: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
12209: change has occured in the paragraph of non-empty lines before the
12210: indicated line. It is a good idea to leave an empty line at the end
12211: of the file, so the last paragraph is checked, too.
12212:
12213: Checking only at empty lines usually works well, but sometimes you
12214: have big blocks of non-empty lines (e.g., when building a big table),
12215: and you want to know where in this block the stack depth changed. You
12216: can check all interpreted lines with
12217:
12218: @example
12219: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12220: @end example
12221:
12222: This checks the stack depth at every end-of-line. So the depth change
12223: occured in the line reported by the @code{~~} (not in the line
12224: before).
12225:
12226: Note that, while this offers better accuracy in indicating where the
12227: stack depth changes, it will often report many intentional stack depth
12228: changes (e.g., when an interpreted computation stretches across
12229: several lines). You can suppress the checking of some lines by
12230: putting backslashes at the end of these lines (not followed by white
12231: space), and using
12232:
12233: @example
12234: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12235: @end example
12236:
12237: @c ******************************************************************
12238: @node ANS conformance, Standard vs Extensions, Tools, Top
12239: @chapter ANS conformance
12240: @cindex ANS conformance of Gforth
12241:
12242: To the best of our knowledge, Gforth is an
12243:
12244: ANS Forth System
12245: @itemize @bullet
12246: @item providing the Core Extensions word set
12247: @item providing the Block word set
12248: @item providing the Block Extensions word set
12249: @item providing the Double-Number word set
12250: @item providing the Double-Number Extensions word set
12251: @item providing the Exception word set
12252: @item providing the Exception Extensions word set
12253: @item providing the Facility word set
12254: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
12255: @item providing the File Access word set
12256: @item providing the File Access Extensions word set
12257: @item providing the Floating-Point word set
12258: @item providing the Floating-Point Extensions word set
12259: @item providing the Locals word set
12260: @item providing the Locals Extensions word set
12261: @item providing the Memory-Allocation word set
12262: @item providing the Memory-Allocation Extensions word set (that one's easy)
12263: @item providing the Programming-Tools word set
12264: @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
12265: @item providing the Search-Order word set
12266: @item providing the Search-Order Extensions word set
12267: @item providing the String word set
12268: @item providing the String Extensions word set (another easy one)
12269: @end itemize
12270:
12271: Gforth has the following environmental restrictions:
12272:
12273: @cindex environmental restrictions
12274: @itemize @bullet
12275: @item
12276: While processing the OS command line, if an exception is not caught,
12277: Gforth exits with a non-zero exit code instyead of performing QUIT.
12278:
12279: @item
12280: When an @code{throw} is performed after a @code{query}, Gforth does not
12281: allways restore the input source specification in effect at the
12282: corresponding catch.
12283:
12284: @end itemize
12285:
12286:
12287: @cindex system documentation
12288: In addition, ANS Forth systems are required to document certain
12289: implementation choices. This chapter tries to meet these
12290: requirements. In many cases it gives a way to ask the system for the
12291: information instead of providing the information directly, in
12292: particular, if the information depends on the processor, the operating
12293: system or the installation options chosen, or if they are likely to
12294: change during the maintenance of Gforth.
12295:
12296: @comment The framework for the rest has been taken from pfe.
12297:
12298: @menu
12299: * The Core Words::
12300: * The optional Block word set::
12301: * The optional Double Number word set::
12302: * The optional Exception word set::
12303: * The optional Facility word set::
12304: * The optional File-Access word set::
12305: * The optional Floating-Point word set::
12306: * The optional Locals word set::
12307: * The optional Memory-Allocation word set::
12308: * The optional Programming-Tools word set::
12309: * The optional Search-Order word set::
12310: @end menu
12311:
12312:
12313: @c =====================================================================
12314: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12315: @comment node-name, next, previous, up
12316: @section The Core Words
12317: @c =====================================================================
12318: @cindex core words, system documentation
12319: @cindex system documentation, core words
12320:
12321: @menu
12322: * core-idef:: Implementation Defined Options
12323: * core-ambcond:: Ambiguous Conditions
12324: * core-other:: Other System Documentation
12325: @end menu
12326:
12327: @c ---------------------------------------------------------------------
12328: @node core-idef, core-ambcond, The Core Words, The Core Words
12329: @subsection Implementation Defined Options
12330: @c ---------------------------------------------------------------------
12331: @cindex core words, implementation-defined options
12332: @cindex implementation-defined options, core words
12333:
12334:
12335: @table @i
12336: @item (Cell) aligned addresses:
12337: @cindex cell-aligned addresses
12338: @cindex aligned addresses
12339: processor-dependent. Gforth's alignment words perform natural alignment
12340: (e.g., an address aligned for a datum of size 8 is divisible by
12341: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12342:
12343: @item @code{EMIT} and non-graphic characters:
12344: @cindex @code{EMIT} and non-graphic characters
12345: @cindex non-graphic characters and @code{EMIT}
12346: The character is output using the C library function (actually, macro)
12347: @code{putc}.
12348:
12349: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12350: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12351: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12352: @cindex @code{ACCEPT}, editing
12353: @cindex @code{EXPECT}, editing
12354: This is modeled on the GNU readline library (@pxref{Readline
12355: Interaction, , Command Line Editing, readline, The GNU Readline
12356: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12357: producing a full word completion every time you type it (instead of
12358: producing the common prefix of all completions). @xref{Command-line editing}.
12359:
12360: @item character set:
12361: @cindex character set
12362: The character set of your computer and display device. Gforth is
12363: 8-bit-clean (but some other component in your system may make trouble).
12364:
12365: @item Character-aligned address requirements:
12366: @cindex character-aligned address requirements
12367: installation-dependent. Currently a character is represented by a C
12368: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12369: (Comments on that requested).
12370:
12371: @item character-set extensions and matching of names:
12372: @cindex character-set extensions and matching of names
12373: @cindex case-sensitivity for name lookup
12374: @cindex name lookup, case-sensitivity
12375: @cindex locale and case-sensitivity
12376: Any character except the ASCII NUL character can be used in a
12377: name. Matching is case-insensitive (except in @code{TABLE}s). The
12378: matching is performed using the C library function @code{strncasecmp}, whose
12379: function is probably influenced by the locale. E.g., the @code{C} locale
12380: does not know about accents and umlauts, so they are matched
12381: case-sensitively in that locale. For portability reasons it is best to
12382: write programs such that they work in the @code{C} locale. Then one can
12383: use libraries written by a Polish programmer (who might use words
12384: containing ISO Latin-2 encoded characters) and by a French programmer
12385: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12386: funny results for some of the words (which ones, depends on the font you
12387: are using)). Also, the locale you prefer may not be available in other
12388: operating systems. Hopefully, Unicode will solve these problems one day.
12389:
12390: @item conditions under which control characters match a space delimiter:
12391: @cindex space delimiters
12392: @cindex control characters as delimiters
12393: If @code{word} is called with the space character as a delimiter, all
12394: white-space characters (as identified by the C macro @code{isspace()})
12395: are delimiters. @code{Parse}, on the other hand, treats space like other
12396: delimiters. @code{Parse-word}, which is used by the outer
12397: interpreter (aka text interpreter) by default, treats all white-space
12398: characters as delimiters.
12399:
12400: @item format of the control-flow stack:
12401: @cindex control-flow stack, format
12402: The data stack is used as control-flow stack. The size of a control-flow
12403: stack item in cells is given by the constant @code{cs-item-size}. At the
12404: time of this writing, an item consists of a (pointer to a) locals list
12405: (third), an address in the code (second), and a tag for identifying the
12406: item (TOS). The following tags are used: @code{defstart},
12407: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12408: @code{scopestart}.
12409:
12410: @item conversion of digits > 35
12411: @cindex digits > 35
12412: The characters @code{[\]^_'} are the digits with the decimal value
12413: 36@minus{}41. There is no way to input many of the larger digits.
12414:
12415: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12416: @cindex @code{EXPECT}, display after end of input
12417: @cindex @code{ACCEPT}, display after end of input
12418: The cursor is moved to the end of the entered string. If the input is
12419: terminated using the @kbd{Return} key, a space is typed.
12420:
12421: @item exception abort sequence of @code{ABORT"}:
12422: @cindex exception abort sequence of @code{ABORT"}
12423: @cindex @code{ABORT"}, exception abort sequence
12424: The error string is stored into the variable @code{"error} and a
12425: @code{-2 throw} is performed.
12426:
12427: @item input line terminator:
12428: @cindex input line terminator
12429: @cindex line terminator on input
12430: @cindex newline character on input
12431: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12432: lines. One of these characters is typically produced when you type the
12433: @kbd{Enter} or @kbd{Return} key.
12434:
12435: @item maximum size of a counted string:
12436: @cindex maximum size of a counted string
12437: @cindex counted string, maximum size
12438: @code{s" /counted-string" environment? drop .}. Currently 255 characters
12439: on all platforms, but this may change.
12440:
12441: @item maximum size of a parsed string:
12442: @cindex maximum size of a parsed string
12443: @cindex parsed string, maximum size
12444: Given by the constant @code{/line}. Currently 255 characters.
12445:
12446: @item maximum size of a definition name, in characters:
12447: @cindex maximum size of a definition name, in characters
12448: @cindex name, maximum length
12449: MAXU/8
12450:
12451: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12452: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12453: @cindex @code{ENVIRONMENT?} string length, maximum
12454: MAXU/8
12455:
12456: @item method of selecting the user input device:
12457: @cindex user input device, method of selecting
12458: The user input device is the standard input. There is currently no way to
12459: change it from within Gforth. However, the input can typically be
12460: redirected in the command line that starts Gforth.
12461:
12462: @item method of selecting the user output device:
12463: @cindex user output device, method of selecting
12464: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
12465: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12466: output when the user output device is a terminal, otherwise the output
12467: is buffered.
12468:
12469: @item methods of dictionary compilation:
12470: What are we expected to document here?
12471:
12472: @item number of bits in one address unit:
12473: @cindex number of bits in one address unit
12474: @cindex address unit, size in bits
12475: @code{s" address-units-bits" environment? drop .}. 8 in all current
12476: platforms.
12477:
12478: @item number representation and arithmetic:
12479: @cindex number representation and arithmetic
12480: Processor-dependent. Binary two's complement on all current platforms.
12481:
12482: @item ranges for integer types:
12483: @cindex ranges for integer types
12484: @cindex integer types, ranges
12485: Installation-dependent. Make environmental queries for @code{MAX-N},
12486: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12487: unsigned (and positive) types is 0. The lower bound for signed types on
12488: two's complement and one's complement machines machines can be computed
12489: by adding 1 to the upper bound.
12490:
12491: @item read-only data space regions:
12492: @cindex read-only data space regions
12493: @cindex data-space, read-only regions
12494: The whole Forth data space is writable.
12495:
12496: @item size of buffer at @code{WORD}:
12497: @cindex size of buffer at @code{WORD}
12498: @cindex @code{WORD} buffer size
12499: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12500: shared with the pictured numeric output string. If overwriting
12501: @code{PAD} is acceptable, it is as large as the remaining dictionary
12502: space, although only as much can be sensibly used as fits in a counted
12503: string.
12504:
12505: @item size of one cell in address units:
12506: @cindex cell size
12507: @code{1 cells .}.
12508:
12509: @item size of one character in address units:
12510: @cindex char size
12511: @code{1 chars .}. 1 on all current platforms.
12512:
12513: @item size of the keyboard terminal buffer:
12514: @cindex size of the keyboard terminal buffer
12515: @cindex terminal buffer, size
12516: Varies. You can determine the size at a specific time using @code{lp@@
12517: tib - .}. It is shared with the locals stack and TIBs of files that
12518: include the current file. You can change the amount of space for TIBs
12519: and locals stack at Gforth startup with the command line option
12520: @code{-l}.
12521:
12522: @item size of the pictured numeric output buffer:
12523: @cindex size of the pictured numeric output buffer
12524: @cindex pictured numeric output buffer, size
12525: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12526: shared with @code{WORD}.
12527:
12528: @item size of the scratch area returned by @code{PAD}:
12529: @cindex size of the scratch area returned by @code{PAD}
12530: @cindex @code{PAD} size
12531: The remainder of dictionary space. @code{unused pad here - - .}.
12532:
12533: @item system case-sensitivity characteristics:
12534: @cindex case-sensitivity characteristics
12535: Dictionary searches are case-insensitive (except in
12536: @code{TABLE}s). However, as explained above under @i{character-set
12537: extensions}, the matching for non-ASCII characters is determined by the
12538: locale you are using. In the default @code{C} locale all non-ASCII
12539: characters are matched case-sensitively.
12540:
12541: @item system prompt:
12542: @cindex system prompt
12543: @cindex prompt
12544: @code{ ok} in interpret state, @code{ compiled} in compile state.
12545:
12546: @item division rounding:
12547: @cindex division rounding
12548: installation dependent. @code{s" floored" environment? drop .}. We leave
12549: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12550: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12551:
12552: @item values of @code{STATE} when true:
12553: @cindex @code{STATE} values
12554: -1.
12555:
12556: @item values returned after arithmetic overflow:
12557: On two's complement machines, arithmetic is performed modulo
12558: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12559: arithmetic (with appropriate mapping for signed types). Division by zero
12560: typically results in a @code{-55 throw} (Floating-point unidentified
12561: fault) or @code{-10 throw} (divide by zero).
12562:
12563: @item whether the current definition can be found after @t{DOES>}:
12564: @cindex @t{DOES>}, visibility of current definition
12565: No.
12566:
12567: @end table
12568:
12569: @c ---------------------------------------------------------------------
12570: @node core-ambcond, core-other, core-idef, The Core Words
12571: @subsection Ambiguous conditions
12572: @c ---------------------------------------------------------------------
12573: @cindex core words, ambiguous conditions
12574: @cindex ambiguous conditions, core words
12575:
12576: @table @i
12577:
12578: @item a name is neither a word nor a number:
12579: @cindex name not found
12580: @cindex undefined word
12581: @code{-13 throw} (Undefined word).
12582:
12583: @item a definition name exceeds the maximum length allowed:
12584: @cindex word name too long
12585: @code{-19 throw} (Word name too long)
12586:
12587: @item addressing a region not inside the various data spaces of the forth system:
12588: @cindex Invalid memory address
12589: The stacks, code space and header space are accessible. Machine code space is
12590: typically readable. Accessing other addresses gives results dependent on
12591: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12592: address).
12593:
12594: @item argument type incompatible with parameter:
12595: @cindex argument type mismatch
12596: This is usually not caught. Some words perform checks, e.g., the control
12597: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12598: mismatch).
12599:
12600: @item attempting to obtain the execution token of a word with undefined execution semantics:
12601: @cindex Interpreting a compile-only word, for @code{'} etc.
12602: @cindex execution token of words with undefined execution semantics
12603: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12604: get an execution token for @code{compile-only-error} (which performs a
12605: @code{-14 throw} when executed).
12606:
12607: @item dividing by zero:
12608: @cindex dividing by zero
12609: @cindex floating point unidentified fault, integer division
12610: On some platforms, this produces a @code{-10 throw} (Division by
12611: zero); on other systems, this typically results in a @code{-55 throw}
12612: (Floating-point unidentified fault).
12613:
12614: @item insufficient data stack or return stack space:
12615: @cindex insufficient data stack or return stack space
12616: @cindex stack overflow
12617: @cindex address alignment exception, stack overflow
12618: @cindex Invalid memory address, stack overflow
12619: Depending on the operating system, the installation, and the invocation
12620: of Gforth, this is either checked by the memory management hardware, or
12621: it is not checked. If it is checked, you typically get a @code{-3 throw}
12622: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12623: throw} (Invalid memory address) (depending on the platform and how you
12624: achieved the overflow) as soon as the overflow happens. If it is not
12625: checked, overflows typically result in mysterious illegal memory
12626: accesses, producing @code{-9 throw} (Invalid memory address) or
12627: @code{-23 throw} (Address alignment exception); they might also destroy
12628: the internal data structure of @code{ALLOCATE} and friends, resulting in
12629: various errors in these words.
12630:
12631: @item insufficient space for loop control parameters:
12632: @cindex insufficient space for loop control parameters
12633: Like other return stack overflows.
12634:
12635: @item insufficient space in the dictionary:
12636: @cindex insufficient space in the dictionary
12637: @cindex dictionary overflow
12638: If you try to allot (either directly with @code{allot}, or indirectly
12639: with @code{,}, @code{create} etc.) more memory than available in the
12640: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12641: to access memory beyond the end of the dictionary, the results are
12642: similar to stack overflows.
12643:
12644: @item interpreting a word with undefined interpretation semantics:
12645: @cindex interpreting a word with undefined interpretation semantics
12646: @cindex Interpreting a compile-only word
12647: For some words, we have defined interpretation semantics. For the
12648: others: @code{-14 throw} (Interpreting a compile-only word).
12649:
12650: @item modifying the contents of the input buffer or a string literal:
12651: @cindex modifying the contents of the input buffer or a string literal
12652: These are located in writable memory and can be modified.
12653:
12654: @item overflow of the pictured numeric output string:
12655: @cindex overflow of the pictured numeric output string
12656: @cindex pictured numeric output string, overflow
12657: @code{-17 throw} (Pictured numeric ouput string overflow).
12658:
12659: @item parsed string overflow:
12660: @cindex parsed string overflow
12661: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12662:
12663: @item producing a result out of range:
12664: @cindex result out of range
12665: On two's complement machines, arithmetic is performed modulo
12666: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12667: arithmetic (with appropriate mapping for signed types). Division by zero
12668: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12669: throw} (floating point unidentified fault). @code{convert} and
12670: @code{>number} currently overflow silently.
12671:
12672: @item reading from an empty data or return stack:
12673: @cindex stack empty
12674: @cindex stack underflow
12675: @cindex return stack underflow
12676: The data stack is checked by the outer (aka text) interpreter after
12677: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12678: underflow) is performed. Apart from that, stacks may be checked or not,
12679: depending on operating system, installation, and invocation. If they are
12680: caught by a check, they typically result in @code{-4 throw} (Stack
12681: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12682: (Invalid memory address), depending on the platform and which stack
12683: underflows and by how much. Note that even if the system uses checking
12684: (through the MMU), your program may have to underflow by a significant
12685: number of stack items to trigger the reaction (the reason for this is
12686: that the MMU, and therefore the checking, works with a page-size
12687: granularity). If there is no checking, the symptoms resulting from an
12688: underflow are similar to those from an overflow. Unbalanced return
12689: stack errors can result in a variety of symptoms, including @code{-9 throw}
12690: (Invalid memory address) and Illegal Instruction (typically @code{-260
12691: throw}).
12692:
12693: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12694: @cindex unexpected end of the input buffer
12695: @cindex zero-length string as a name
12696: @cindex Attempt to use zero-length string as a name
12697: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12698: use zero-length string as a name). Words like @code{'} probably will not
12699: find what they search. Note that it is possible to create zero-length
12700: names with @code{nextname} (should it not?).
12701:
12702: @item @code{>IN} greater than input buffer:
12703: @cindex @code{>IN} greater than input buffer
12704: The next invocation of a parsing word returns a string with length 0.
12705:
12706: @item @code{RECURSE} appears after @code{DOES>}:
12707: @cindex @code{RECURSE} appears after @code{DOES>}
12708: Compiles a recursive call to the defining word, not to the defined word.
12709:
12710: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12711: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
12712: @cindex argument type mismatch, @code{RESTORE-INPUT}
12713: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12714: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12715: the end of the file was reached), its source-id may be
12716: reused. Therefore, restoring an input source specification referencing a
12717: closed file may lead to unpredictable results instead of a @code{-12
12718: THROW}.
12719:
12720: In the future, Gforth may be able to restore input source specifications
12721: from other than the current input source.
12722:
12723: @item data space containing definitions gets de-allocated:
12724: @cindex data space containing definitions gets de-allocated
12725: Deallocation with @code{allot} is not checked. This typically results in
12726: memory access faults or execution of illegal instructions.
12727:
12728: @item data space read/write with incorrect alignment:
12729: @cindex data space read/write with incorrect alignment
12730: @cindex alignment faults
12731: @cindex address alignment exception
12732: Processor-dependent. Typically results in a @code{-23 throw} (Address
12733: alignment exception). Under Linux-Intel on a 486 or later processor with
12734: alignment turned on, incorrect alignment results in a @code{-9 throw}
12735: (Invalid memory address). There are reportedly some processors with
12736: alignment restrictions that do not report violations.
12737:
12738: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12739: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12740: Like other alignment errors.
12741:
12742: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12743: Like other stack underflows.
12744:
12745: @item loop control parameters not available:
12746: @cindex loop control parameters not available
12747: Not checked. The counted loop words simply assume that the top of return
12748: stack items are loop control parameters and behave accordingly.
12749:
12750: @item most recent definition does not have a name (@code{IMMEDIATE}):
12751: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12752: @cindex last word was headerless
12753: @code{abort" last word was headerless"}.
12754:
12755: @item name not defined by @code{VALUE} used by @code{TO}:
12756: @cindex name not defined by @code{VALUE} used by @code{TO}
12757: @cindex @code{TO} on non-@code{VALUE}s
12758: @cindex Invalid name argument, @code{TO}
12759: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12760: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12761:
12762: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12763: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
12764: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
12765: @code{-13 throw} (Undefined word)
12766:
12767: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12768: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12769: Gforth behaves as if they were of the same type. I.e., you can predict
12770: the behaviour by interpreting all parameters as, e.g., signed.
12771:
12772: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12773: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12774: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12775: compilation semantics of @code{TO}.
12776:
12777: @item String longer than a counted string returned by @code{WORD}:
12778: @cindex string longer than a counted string returned by @code{WORD}
12779: @cindex @code{WORD}, string overflow
12780: Not checked. The string will be ok, but the count will, of course,
12781: contain only the least significant bits of the length.
12782:
12783: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12784: @cindex @code{LSHIFT}, large shift counts
12785: @cindex @code{RSHIFT}, large shift counts
12786: Processor-dependent. Typical behaviours are returning 0 and using only
12787: the low bits of the shift count.
12788:
12789: @item word not defined via @code{CREATE}:
12790: @cindex @code{>BODY} of non-@code{CREATE}d words
12791: @code{>BODY} produces the PFA of the word no matter how it was defined.
12792:
12793: @cindex @code{DOES>} of non-@code{CREATE}d words
12794: @code{DOES>} changes the execution semantics of the last defined word no
12795: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12796: @code{CREATE , DOES>}.
12797:
12798: @item words improperly used outside @code{<#} and @code{#>}:
12799: Not checked. As usual, you can expect memory faults.
12800:
12801: @end table
12802:
12803:
12804: @c ---------------------------------------------------------------------
12805: @node core-other, , core-ambcond, The Core Words
12806: @subsection Other system documentation
12807: @c ---------------------------------------------------------------------
12808: @cindex other system documentation, core words
12809: @cindex core words, other system documentation
12810:
12811: @table @i
12812: @item nonstandard words using @code{PAD}:
12813: @cindex @code{PAD} use by nonstandard words
12814: None.
12815:
12816: @item operator's terminal facilities available:
12817: @cindex operator's terminal facilities available
12818: After processing the OS's command line, Gforth goes into interactive mode,
12819: and you can give commands to Gforth interactively. The actual facilities
12820: available depend on how you invoke Gforth.
12821:
12822: @item program data space available:
12823: @cindex program data space available
12824: @cindex data space available
12825: @code{UNUSED .} gives the remaining dictionary space. The total
12826: dictionary space can be specified with the @code{-m} switch
12827: (@pxref{Invoking Gforth}) when Gforth starts up.
12828:
12829: @item return stack space available:
12830: @cindex return stack space available
12831: You can compute the total return stack space in cells with
12832: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12833: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12834:
12835: @item stack space available:
12836: @cindex stack space available
12837: You can compute the total data stack space in cells with
12838: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12839: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12840:
12841: @item system dictionary space required, in address units:
12842: @cindex system dictionary space required, in address units
12843: Type @code{here forthstart - .} after startup. At the time of this
12844: writing, this gives 80080 (bytes) on a 32-bit system.
12845: @end table
12846:
12847:
12848: @c =====================================================================
12849: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12850: @section The optional Block word set
12851: @c =====================================================================
12852: @cindex system documentation, block words
12853: @cindex block words, system documentation
12854:
12855: @menu
12856: * block-idef:: Implementation Defined Options
12857: * block-ambcond:: Ambiguous Conditions
12858: * block-other:: Other System Documentation
12859: @end menu
12860:
12861:
12862: @c ---------------------------------------------------------------------
12863: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12864: @subsection Implementation Defined Options
12865: @c ---------------------------------------------------------------------
12866: @cindex implementation-defined options, block words
12867: @cindex block words, implementation-defined options
12868:
12869: @table @i
12870: @item the format for display by @code{LIST}:
12871: @cindex @code{LIST} display format
12872: First the screen number is displayed, then 16 lines of 64 characters,
12873: each line preceded by the line number.
12874:
12875: @item the length of a line affected by @code{\}:
12876: @cindex length of a line affected by @code{\}
12877: @cindex @code{\}, line length in blocks
12878: 64 characters.
12879: @end table
12880:
12881:
12882: @c ---------------------------------------------------------------------
12883: @node block-ambcond, block-other, block-idef, The optional Block word set
12884: @subsection Ambiguous conditions
12885: @c ---------------------------------------------------------------------
12886: @cindex block words, ambiguous conditions
12887: @cindex ambiguous conditions, block words
12888:
12889: @table @i
12890: @item correct block read was not possible:
12891: @cindex block read not possible
12892: Typically results in a @code{throw} of some OS-derived value (between
12893: -512 and -2048). If the blocks file was just not long enough, blanks are
12894: supplied for the missing portion.
12895:
12896: @item I/O exception in block transfer:
12897: @cindex I/O exception in block transfer
12898: @cindex block transfer, I/O exception
12899: Typically results in a @code{throw} of some OS-derived value (between
12900: -512 and -2048).
12901:
12902: @item invalid block number:
12903: @cindex invalid block number
12904: @cindex block number invalid
12905: @code{-35 throw} (Invalid block number)
12906:
12907: @item a program directly alters the contents of @code{BLK}:
12908: @cindex @code{BLK}, altering @code{BLK}
12909: The input stream is switched to that other block, at the same
12910: position. If the storing to @code{BLK} happens when interpreting
12911: non-block input, the system will get quite confused when the block ends.
12912:
12913: @item no current block buffer for @code{UPDATE}:
12914: @cindex @code{UPDATE}, no current block buffer
12915: @code{UPDATE} has no effect.
12916:
12917: @end table
12918:
12919: @c ---------------------------------------------------------------------
12920: @node block-other, , block-ambcond, The optional Block word set
12921: @subsection Other system documentation
12922: @c ---------------------------------------------------------------------
12923: @cindex other system documentation, block words
12924: @cindex block words, other system documentation
12925:
12926: @table @i
12927: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12928: No restrictions (yet).
12929:
12930: @item the number of blocks available for source and data:
12931: depends on your disk space.
12932:
12933: @end table
12934:
12935:
12936: @c =====================================================================
12937: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12938: @section The optional Double Number word set
12939: @c =====================================================================
12940: @cindex system documentation, double words
12941: @cindex double words, system documentation
12942:
12943: @menu
12944: * double-ambcond:: Ambiguous Conditions
12945: @end menu
12946:
12947:
12948: @c ---------------------------------------------------------------------
12949: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
12950: @subsection Ambiguous conditions
12951: @c ---------------------------------------------------------------------
12952: @cindex double words, ambiguous conditions
12953: @cindex ambiguous conditions, double words
12954:
12955: @table @i
12956: @item @i{d} outside of range of @i{n} in @code{D>S}:
12957: @cindex @code{D>S}, @i{d} out of range of @i{n}
12958: The least significant cell of @i{d} is produced.
12959:
12960: @end table
12961:
12962:
12963: @c =====================================================================
12964: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
12965: @section The optional Exception word set
12966: @c =====================================================================
12967: @cindex system documentation, exception words
12968: @cindex exception words, system documentation
12969:
12970: @menu
12971: * exception-idef:: Implementation Defined Options
12972: @end menu
12973:
12974:
12975: @c ---------------------------------------------------------------------
12976: @node exception-idef, , The optional Exception word set, The optional Exception word set
12977: @subsection Implementation Defined Options
12978: @c ---------------------------------------------------------------------
12979: @cindex implementation-defined options, exception words
12980: @cindex exception words, implementation-defined options
12981:
12982: @table @i
12983: @item @code{THROW}-codes used in the system:
12984: @cindex @code{THROW}-codes used in the system
12985: The codes -256@minus{}-511 are used for reporting signals. The mapping
12986: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
12987: codes -512@minus{}-2047 are used for OS errors (for file and memory
12988: allocation operations). The mapping from OS error numbers to throw codes
12989: is -512@minus{}@code{errno}. One side effect of this mapping is that
12990: undefined OS errors produce a message with a strange number; e.g.,
12991: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
12992: @end table
12993:
12994: @c =====================================================================
12995: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
12996: @section The optional Facility word set
12997: @c =====================================================================
12998: @cindex system documentation, facility words
12999: @cindex facility words, system documentation
13000:
13001: @menu
13002: * facility-idef:: Implementation Defined Options
13003: * facility-ambcond:: Ambiguous Conditions
13004: @end menu
13005:
13006:
13007: @c ---------------------------------------------------------------------
13008: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13009: @subsection Implementation Defined Options
13010: @c ---------------------------------------------------------------------
13011: @cindex implementation-defined options, facility words
13012: @cindex facility words, implementation-defined options
13013:
13014: @table @i
13015: @item encoding of keyboard events (@code{EKEY}):
13016: @cindex keyboard events, encoding in @code{EKEY}
13017: @cindex @code{EKEY}, encoding of keyboard events
13018: Keys corresponding to ASCII characters are encoded as ASCII characters.
13019: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13020: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13021: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13022: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
13023:
13024:
13025: @item duration of a system clock tick:
13026: @cindex duration of a system clock tick
13027: @cindex clock tick duration
13028: System dependent. With respect to @code{MS}, the time is specified in
13029: microseconds. How well the OS and the hardware implement this, is
13030: another question.
13031:
13032: @item repeatability to be expected from the execution of @code{MS}:
13033: @cindex repeatability to be expected from the execution of @code{MS}
13034: @cindex @code{MS}, repeatability to be expected
13035: System dependent. On Unix, a lot depends on load. If the system is
13036: lightly loaded, and the delay is short enough that Gforth does not get
13037: swapped out, the performance should be acceptable. Under MS-DOS and
13038: other single-tasking systems, it should be good.
13039:
13040: @end table
13041:
13042:
13043: @c ---------------------------------------------------------------------
13044: @node facility-ambcond, , facility-idef, The optional Facility word set
13045: @subsection Ambiguous conditions
13046: @c ---------------------------------------------------------------------
13047: @cindex facility words, ambiguous conditions
13048: @cindex ambiguous conditions, facility words
13049:
13050: @table @i
13051: @item @code{AT-XY} can't be performed on user output device:
13052: @cindex @code{AT-XY} can't be performed on user output device
13053: Largely terminal dependent. No range checks are done on the arguments.
13054: No errors are reported. You may see some garbage appearing, you may see
13055: simply nothing happen.
13056:
13057: @end table
13058:
13059:
13060: @c =====================================================================
13061: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13062: @section The optional File-Access word set
13063: @c =====================================================================
13064: @cindex system documentation, file words
13065: @cindex file words, system documentation
13066:
13067: @menu
13068: * file-idef:: Implementation Defined Options
13069: * file-ambcond:: Ambiguous Conditions
13070: @end menu
13071:
13072: @c ---------------------------------------------------------------------
13073: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13074: @subsection Implementation Defined Options
13075: @c ---------------------------------------------------------------------
13076: @cindex implementation-defined options, file words
13077: @cindex file words, implementation-defined options
13078:
13079: @table @i
13080: @item file access methods used:
13081: @cindex file access methods used
13082: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13083: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13084: @code{wb}): The file is cleared, if it exists, and created, if it does
13085: not (with both @code{open-file} and @code{create-file}). Under Unix
13086: @code{create-file} creates a file with 666 permissions modified by your
13087: umask.
13088:
13089: @item file exceptions:
13090: @cindex file exceptions
13091: The file words do not raise exceptions (except, perhaps, memory access
13092: faults when you pass illegal addresses or file-ids).
13093:
13094: @item file line terminator:
13095: @cindex file line terminator
13096: System-dependent. Gforth uses C's newline character as line
13097: terminator. What the actual character code(s) of this are is
13098: system-dependent.
13099:
13100: @item file name format:
13101: @cindex file name format
13102: System dependent. Gforth just uses the file name format of your OS.
13103:
13104: @item information returned by @code{FILE-STATUS}:
13105: @cindex @code{FILE-STATUS}, returned information
13106: @code{FILE-STATUS} returns the most powerful file access mode allowed
13107: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13108: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13109: along with the returned mode.
13110:
13111: @item input file state after an exception when including source:
13112: @cindex exception when including source
13113: All files that are left via the exception are closed.
13114:
13115: @item @i{ior} values and meaning:
13116: @cindex @i{ior} values and meaning
13117: @cindex @i{wior} values and meaning
13118: The @i{ior}s returned by the file and memory allocation words are
13119: intended as throw codes. They typically are in the range
13120: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
13121: @i{ior}s is -512@minus{}@i{errno}.
13122:
13123: @item maximum depth of file input nesting:
13124: @cindex maximum depth of file input nesting
13125: @cindex file input nesting, maximum depth
13126: limited by the amount of return stack, locals/TIB stack, and the number
13127: of open files available. This should not give you troubles.
13128:
13129: @item maximum size of input line:
13130: @cindex maximum size of input line
13131: @cindex input line size, maximum
13132: @code{/line}. Currently 255.
13133:
13134: @item methods of mapping block ranges to files:
13135: @cindex mapping block ranges to files
13136: @cindex files containing blocks
13137: @cindex blocks in files
13138: By default, blocks are accessed in the file @file{blocks.fb} in the
13139: current working directory. The file can be switched with @code{USE}.
13140:
13141: @item number of string buffers provided by @code{S"}:
13142: @cindex @code{S"}, number of string buffers
13143: 1
13144:
13145: @item size of string buffer used by @code{S"}:
13146: @cindex @code{S"}, size of string buffer
13147: @code{/line}. currently 255.
13148:
13149: @end table
13150:
13151: @c ---------------------------------------------------------------------
13152: @node file-ambcond, , file-idef, The optional File-Access word set
13153: @subsection Ambiguous conditions
13154: @c ---------------------------------------------------------------------
13155: @cindex file words, ambiguous conditions
13156: @cindex ambiguous conditions, file words
13157:
13158: @table @i
13159: @item attempting to position a file outside its boundaries:
13160: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13161: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13162: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13163:
13164: @item attempting to read from file positions not yet written:
13165: @cindex reading from file positions not yet written
13166: End-of-file, i.e., zero characters are read and no error is reported.
13167:
13168: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13169: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
13170: An appropriate exception may be thrown, but a memory fault or other
13171: problem is more probable.
13172:
13173: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13174: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13175: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13176: The @i{ior} produced by the operation, that discovered the problem, is
13177: thrown.
13178:
13179: @item named file cannot be opened (@code{INCLUDED}):
13180: @cindex @code{INCLUDED}, named file cannot be opened
13181: The @i{ior} produced by @code{open-file} is thrown.
13182:
13183: @item requesting an unmapped block number:
13184: @cindex unmapped block numbers
13185: There are no unmapped legal block numbers. On some operating systems,
13186: writing a block with a large number may overflow the file system and
13187: have an error message as consequence.
13188:
13189: @item using @code{source-id} when @code{blk} is non-zero:
13190: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13191: @code{source-id} performs its function. Typically it will give the id of
13192: the source which loaded the block. (Better ideas?)
13193:
13194: @end table
13195:
13196:
13197: @c =====================================================================
13198: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13199: @section The optional Floating-Point word set
13200: @c =====================================================================
13201: @cindex system documentation, floating-point words
13202: @cindex floating-point words, system documentation
13203:
13204: @menu
13205: * floating-idef:: Implementation Defined Options
13206: * floating-ambcond:: Ambiguous Conditions
13207: @end menu
13208:
13209:
13210: @c ---------------------------------------------------------------------
13211: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13212: @subsection Implementation Defined Options
13213: @c ---------------------------------------------------------------------
13214: @cindex implementation-defined options, floating-point words
13215: @cindex floating-point words, implementation-defined options
13216:
13217: @table @i
13218: @item format and range of floating point numbers:
13219: @cindex format and range of floating point numbers
13220: @cindex floating point numbers, format and range
13221: System-dependent; the @code{double} type of C.
13222:
13223: @item results of @code{REPRESENT} when @i{float} is out of range:
13224: @cindex @code{REPRESENT}, results when @i{float} is out of range
13225: System dependent; @code{REPRESENT} is implemented using the C library
13226: function @code{ecvt()} and inherits its behaviour in this respect.
13227:
13228: @item rounding or truncation of floating-point numbers:
13229: @cindex rounding of floating-point numbers
13230: @cindex truncation of floating-point numbers
13231: @cindex floating-point numbers, rounding or truncation
13232: System dependent; the rounding behaviour is inherited from the hosting C
13233: compiler. IEEE-FP-based (i.e., most) systems by default round to
13234: nearest, and break ties by rounding to even (i.e., such that the last
13235: bit of the mantissa is 0).
13236:
13237: @item size of floating-point stack:
13238: @cindex floating-point stack size
13239: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13240: the floating-point stack (in floats). You can specify this on startup
13241: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13242:
13243: @item width of floating-point stack:
13244: @cindex floating-point stack width
13245: @code{1 floats}.
13246:
13247: @end table
13248:
13249:
13250: @c ---------------------------------------------------------------------
13251: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13252: @subsection Ambiguous conditions
13253: @c ---------------------------------------------------------------------
13254: @cindex floating-point words, ambiguous conditions
13255: @cindex ambiguous conditions, floating-point words
13256:
13257: @table @i
13258: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13259: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13260: System-dependent. Typically results in a @code{-23 THROW} like other
13261: alignment violations.
13262:
13263: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13264: @cindex @code{f@@} used with an address that is not float aligned
13265: @cindex @code{f!} used with an address that is not float aligned
13266: System-dependent. Typically results in a @code{-23 THROW} like other
13267: alignment violations.
13268:
13269: @item floating-point result out of range:
13270: @cindex floating-point result out of range
13271: System-dependent. Can result in a @code{-43 throw} (floating point
13272: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13273: (floating point inexact result), @code{-55 THROW} (Floating-point
13274: unidentified fault), or can produce a special value representing, e.g.,
13275: Infinity.
13276:
13277: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13278: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13279: System-dependent. Typically results in an alignment fault like other
13280: alignment violations.
13281:
13282: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13283: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
13284: The floating-point number is converted into decimal nonetheless.
13285:
13286: @item Both arguments are equal to zero (@code{FATAN2}):
13287: @cindex @code{FATAN2}, both arguments are equal to zero
13288: System-dependent. @code{FATAN2} is implemented using the C library
13289: function @code{atan2()}.
13290:
13291: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13292: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13293: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
13294: because of small errors and the tan will be a very large (or very small)
13295: but finite number.
13296:
13297: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13298: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
13299: The result is rounded to the nearest float.
13300:
13301: @item dividing by zero:
13302: @cindex dividing by zero, floating-point
13303: @cindex floating-point dividing by zero
13304: @cindex floating-point unidentified fault, FP divide-by-zero
13305: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13306: (floating point divide by zero) or @code{-55 throw} (Floating-point
13307: unidentified fault).
13308:
13309: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13310: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13311: System dependent. On IEEE-FP based systems the number is converted into
13312: an infinity.
13313:
13314: @item @i{float}<1 (@code{FACOSH}):
13315: @cindex @code{FACOSH}, @i{float}<1
13316: @cindex floating-point unidentified fault, @code{FACOSH}
13317: Platform-dependent; on IEEE-FP systems typically produces a NaN.
13318:
13319: @item @i{float}=<-1 (@code{FLNP1}):
13320: @cindex @code{FLNP1}, @i{float}=<-1
13321: @cindex floating-point unidentified fault, @code{FLNP1}
13322: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13323: negative infinity for @i{float}=-1).
13324:
13325: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13326: @cindex @code{FLN}, @i{float}=<0
13327: @cindex @code{FLOG}, @i{float}=<0
13328: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
13329: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13330: negative infinity for @i{float}=0).
13331:
13332: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13333: @cindex @code{FASINH}, @i{float}<0
13334: @cindex @code{FSQRT}, @i{float}<0
13335: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
13336: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13337: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13338: C library?).
13339:
13340: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13341: @cindex @code{FACOS}, |@i{float}|>1
13342: @cindex @code{FASIN}, |@i{float}|>1
13343: @cindex @code{FATANH}, |@i{float}|>1
13344: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
13345: Platform-dependent; IEEE-FP systems typically produce a NaN.
13346:
13347: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13348: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
13349: @cindex floating-point unidentified fault, @code{F>D}
13350: Platform-dependent; typically, some double number is produced and no
13351: error is reported.
13352:
13353: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13354: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
13355: @code{Precision} characters of the numeric output area are used. If
13356: @code{precision} is too high, these words will smash the data or code
13357: close to @code{here}.
13358: @end table
13359:
13360: @c =====================================================================
13361: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13362: @section The optional Locals word set
13363: @c =====================================================================
13364: @cindex system documentation, locals words
13365: @cindex locals words, system documentation
13366:
13367: @menu
13368: * locals-idef:: Implementation Defined Options
13369: * locals-ambcond:: Ambiguous Conditions
13370: @end menu
13371:
13372:
13373: @c ---------------------------------------------------------------------
13374: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13375: @subsection Implementation Defined Options
13376: @c ---------------------------------------------------------------------
13377: @cindex implementation-defined options, locals words
13378: @cindex locals words, implementation-defined options
13379:
13380: @table @i
13381: @item maximum number of locals in a definition:
13382: @cindex maximum number of locals in a definition
13383: @cindex locals, maximum number in a definition
13384: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13385: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13386: characters. The number of locals in a definition is bounded by the size
13387: of locals-buffer, which contains the names of the locals.
13388:
13389: @end table
13390:
13391:
13392: @c ---------------------------------------------------------------------
13393: @node locals-ambcond, , locals-idef, The optional Locals word set
13394: @subsection Ambiguous conditions
13395: @c ---------------------------------------------------------------------
13396: @cindex locals words, ambiguous conditions
13397: @cindex ambiguous conditions, locals words
13398:
13399: @table @i
13400: @item executing a named local in interpretation state:
13401: @cindex local in interpretation state
13402: @cindex Interpreting a compile-only word, for a local
13403: Locals have no interpretation semantics. If you try to perform the
13404: interpretation semantics, you will get a @code{-14 throw} somewhere
13405: (Interpreting a compile-only word). If you perform the compilation
13406: semantics, the locals access will be compiled (irrespective of state).
13407:
13408: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
13409: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13410: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13411: @cindex Invalid name argument, @code{TO}
13412: @code{-32 throw} (Invalid name argument)
13413:
13414: @end table
13415:
13416:
13417: @c =====================================================================
13418: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13419: @section The optional Memory-Allocation word set
13420: @c =====================================================================
13421: @cindex system documentation, memory-allocation words
13422: @cindex memory-allocation words, system documentation
13423:
13424: @menu
13425: * memory-idef:: Implementation Defined Options
13426: @end menu
13427:
13428:
13429: @c ---------------------------------------------------------------------
13430: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13431: @subsection Implementation Defined Options
13432: @c ---------------------------------------------------------------------
13433: @cindex implementation-defined options, memory-allocation words
13434: @cindex memory-allocation words, implementation-defined options
13435:
13436: @table @i
13437: @item values and meaning of @i{ior}:
13438: @cindex @i{ior} values and meaning
13439: The @i{ior}s returned by the file and memory allocation words are
13440: intended as throw codes. They typically are in the range
13441: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
13442: @i{ior}s is -512@minus{}@i{errno}.
13443:
13444: @end table
13445:
13446: @c =====================================================================
13447: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13448: @section The optional Programming-Tools word set
13449: @c =====================================================================
13450: @cindex system documentation, programming-tools words
13451: @cindex programming-tools words, system documentation
13452:
13453: @menu
13454: * programming-idef:: Implementation Defined Options
13455: * programming-ambcond:: Ambiguous Conditions
13456: @end menu
13457:
13458:
13459: @c ---------------------------------------------------------------------
13460: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13461: @subsection Implementation Defined Options
13462: @c ---------------------------------------------------------------------
13463: @cindex implementation-defined options, programming-tools words
13464: @cindex programming-tools words, implementation-defined options
13465:
13466: @table @i
13467: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13468: @cindex @code{;CODE} ending sequence
13469: @cindex @code{CODE} ending sequence
13470: @code{END-CODE}
13471:
13472: @item manner of processing input following @code{;CODE} and @code{CODE}:
13473: @cindex @code{;CODE}, processing input
13474: @cindex @code{CODE}, processing input
13475: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13476: the input is processed by the text interpreter, (starting) in interpret
13477: state.
13478:
13479: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13480: @cindex @code{ASSEMBLER}, search order capability
13481: The ANS Forth search order word set.
13482:
13483: @item source and format of display by @code{SEE}:
13484: @cindex @code{SEE}, source and format of output
13485: The source for @code{see} is the executable code used by the inner
13486: interpreter. The current @code{see} tries to output Forth source code
13487: (and on some platforms, assembly code for primitives) as well as
13488: possible.
13489:
13490: @end table
13491:
13492: @c ---------------------------------------------------------------------
13493: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13494: @subsection Ambiguous conditions
13495: @c ---------------------------------------------------------------------
13496: @cindex programming-tools words, ambiguous conditions
13497: @cindex ambiguous conditions, programming-tools words
13498:
13499: @table @i
13500:
13501: @item deleting the compilation word list (@code{FORGET}):
13502: @cindex @code{FORGET}, deleting the compilation word list
13503: Not implemented (yet).
13504:
13505: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13506: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13507: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
13508: @cindex control-flow stack underflow
13509: This typically results in an @code{abort"} with a descriptive error
13510: message (may change into a @code{-22 throw} (Control structure mismatch)
13511: in the future). You may also get a memory access error. If you are
13512: unlucky, this ambiguous condition is not caught.
13513:
13514: @item @i{name} can't be found (@code{FORGET}):
13515: @cindex @code{FORGET}, @i{name} can't be found
13516: Not implemented (yet).
13517:
13518: @item @i{name} not defined via @code{CREATE}:
13519: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
13520: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13521: the execution semantics of the last defined word no matter how it was
13522: defined.
13523:
13524: @item @code{POSTPONE} applied to @code{[IF]}:
13525: @cindex @code{POSTPONE} applied to @code{[IF]}
13526: @cindex @code{[IF]} and @code{POSTPONE}
13527: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13528: equivalent to @code{[IF]}.
13529:
13530: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13531: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13532: Continue in the same state of conditional compilation in the next outer
13533: input source. Currently there is no warning to the user about this.
13534:
13535: @item removing a needed definition (@code{FORGET}):
13536: @cindex @code{FORGET}, removing a needed definition
13537: Not implemented (yet).
13538:
13539: @end table
13540:
13541:
13542: @c =====================================================================
13543: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13544: @section The optional Search-Order word set
13545: @c =====================================================================
13546: @cindex system documentation, search-order words
13547: @cindex search-order words, system documentation
13548:
13549: @menu
13550: * search-idef:: Implementation Defined Options
13551: * search-ambcond:: Ambiguous Conditions
13552: @end menu
13553:
13554:
13555: @c ---------------------------------------------------------------------
13556: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13557: @subsection Implementation Defined Options
13558: @c ---------------------------------------------------------------------
13559: @cindex implementation-defined options, search-order words
13560: @cindex search-order words, implementation-defined options
13561:
13562: @table @i
13563: @item maximum number of word lists in search order:
13564: @cindex maximum number of word lists in search order
13565: @cindex search order, maximum depth
13566: @code{s" wordlists" environment? drop .}. Currently 16.
13567:
13568: @item minimum search order:
13569: @cindex minimum search order
13570: @cindex search order, minimum
13571: @code{root root}.
13572:
13573: @end table
13574:
13575: @c ---------------------------------------------------------------------
13576: @node search-ambcond, , search-idef, The optional Search-Order word set
13577: @subsection Ambiguous conditions
13578: @c ---------------------------------------------------------------------
13579: @cindex search-order words, ambiguous conditions
13580: @cindex ambiguous conditions, search-order words
13581:
13582: @table @i
13583: @item changing the compilation word list (during compilation):
13584: @cindex changing the compilation word list (during compilation)
13585: @cindex compilation word list, change before definition ends
13586: The word is entered into the word list that was the compilation word list
13587: at the start of the definition. Any changes to the name field (e.g.,
13588: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13589: are applied to the latest defined word (as reported by @code{latest} or
13590: @code{latestxt}), if possible, irrespective of the compilation word list.
13591:
13592: @item search order empty (@code{previous}):
13593: @cindex @code{previous}, search order empty
13594: @cindex vocstack empty, @code{previous}
13595: @code{abort" Vocstack empty"}.
13596:
13597: @item too many word lists in search order (@code{also}):
13598: @cindex @code{also}, too many word lists in search order
13599: @cindex vocstack full, @code{also}
13600: @code{abort" Vocstack full"}.
13601:
13602: @end table
13603:
13604: @c ***************************************************************
13605: @node Standard vs Extensions, Model, ANS conformance, Top
13606: @chapter Should I use Gforth extensions?
13607: @cindex Gforth extensions
13608:
13609: As you read through the rest of this manual, you will see documentation
13610: for @i{Standard} words, and documentation for some appealing Gforth
13611: @i{extensions}. You might ask yourself the question: @i{``Should I
13612: restrict myself to the standard, or should I use the extensions?''}
13613:
13614: The answer depends on the goals you have for the program you are working
13615: on:
13616:
13617: @itemize @bullet
13618:
13619: @item Is it just for yourself or do you want to share it with others?
13620:
13621: @item
13622: If you want to share it, do the others all use Gforth?
13623:
13624: @item
13625: If it is just for yourself, do you want to restrict yourself to Gforth?
13626:
13627: @end itemize
13628:
13629: If restricting the program to Gforth is ok, then there is no reason not
13630: to use extensions. It is still a good idea to keep to the standard
13631: where it is easy, in case you want to reuse these parts in another
13632: program that you want to be portable.
13633:
13634: If you want to be able to port the program to other Forth systems, there
13635: are the following points to consider:
13636:
13637: @itemize @bullet
13638:
13639: @item
13640: Most Forth systems that are being maintained support the ANS Forth
13641: standard. So if your program complies with the standard, it will be
13642: portable among many systems.
13643:
13644: @item
13645: A number of the Gforth extensions can be implemented in ANS Forth using
13646: public-domain files provided in the @file{compat/} directory. These are
13647: mentioned in the text in passing. There is no reason not to use these
13648: extensions, your program will still be ANS Forth compliant; just include
13649: the appropriate compat files with your program.
13650:
13651: @item
13652: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13653: analyse your program and determine what non-Standard words it relies
13654: upon. However, it does not check whether you use standard words in a
13655: non-standard way.
13656:
13657: @item
13658: Some techniques are not standardized by ANS Forth, and are hard or
13659: impossible to implement in a standard way, but can be implemented in
13660: most Forth systems easily, and usually in similar ways (e.g., accessing
13661: word headers). Forth has a rich historical precedent for programmers
13662: taking advantage of implementation-dependent features of their tools
13663: (for example, relying on a knowledge of the dictionary
13664: structure). Sometimes these techniques are necessary to extract every
13665: last bit of performance from the hardware, sometimes they are just a
13666: programming shorthand.
13667:
13668: @item
13669: Does using a Gforth extension save more work than the porting this part
13670: to other Forth systems (if any) will cost?
13671:
13672: @item
13673: Is the additional functionality worth the reduction in portability and
13674: the additional porting problems?
13675:
13676: @end itemize
13677:
13678: In order to perform these consideratios, you need to know what's
13679: standard and what's not. This manual generally states if something is
13680: non-standard, but the authoritative source is the
13681: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
13682: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13683: into the thought processes of the technical committee.
13684:
13685: Note also that portability between Forth systems is not the only
13686: portability issue; there is also the issue of portability between
13687: different platforms (processor/OS combinations).
13688:
13689: @c ***************************************************************
13690: @node Model, Integrating Gforth, Standard vs Extensions, Top
13691: @chapter Model
13692:
13693: This chapter has yet to be written. It will contain information, on
13694: which internal structures you can rely.
13695:
13696: @c ***************************************************************
13697: @node Integrating Gforth, Emacs and Gforth, Model, Top
13698: @chapter Integrating Gforth into C programs
13699:
13700: This is not yet implemented.
13701:
13702: Several people like to use Forth as scripting language for applications
13703: that are otherwise written in C, C++, or some other language.
13704:
13705: The Forth system ATLAST provides facilities for embedding it into
13706: applications; unfortunately it has several disadvantages: most
13707: importantly, it is not based on ANS Forth, and it is apparently dead
13708: (i.e., not developed further and not supported). The facilities
13709: provided by Gforth in this area are inspired by ATLAST's facilities, so
13710: making the switch should not be hard.
13711:
13712: We also tried to design the interface such that it can easily be
13713: implemented by other Forth systems, so that we may one day arrive at a
13714: standardized interface. Such a standard interface would allow you to
13715: replace the Forth system without having to rewrite C code.
13716:
13717: You embed the Gforth interpreter by linking with the library
13718: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13719: global symbols in this library that belong to the interface, have the
13720: prefix @code{forth_}. (Global symbols that are used internally have the
13721: prefix @code{gforth_}).
13722:
13723: You can include the declarations of Forth types and the functions and
13724: variables of the interface with @code{#include <forth.h>}.
13725:
13726: Types.
13727:
13728: Variables.
13729:
13730: Data and FP Stack pointer. Area sizes.
13731:
13732: functions.
13733:
13734: forth_init(imagefile)
13735: forth_evaluate(string) exceptions?
13736: forth_goto(address) (or forth_execute(xt)?)
13737: forth_continue() (a corountining mechanism)
13738:
13739: Adding primitives.
13740:
13741: No checking.
13742:
13743: Signals?
13744:
13745: Accessing the Stacks
13746:
13747: @c ******************************************************************
13748: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13749: @chapter Emacs and Gforth
13750: @cindex Emacs and Gforth
13751:
13752: @cindex @file{gforth.el}
13753: @cindex @file{forth.el}
13754: @cindex Rydqvist, Goran
13755: @cindex Kuehling, David
13756: @cindex comment editing commands
13757: @cindex @code{\}, editing with Emacs
13758: @cindex debug tracer editing commands
13759: @cindex @code{~~}, removal with Emacs
13760: @cindex Forth mode in Emacs
13761:
13762: Gforth comes with @file{gforth.el}, an improved version of
13763: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
13764: improvements are:
13765:
13766: @itemize @bullet
13767: @item
13768: A better handling of indentation.
13769: @item
13770: A custom hilighting engine for Forth-code.
13771: @item
13772: Comment paragraph filling (@kbd{M-q})
13773: @item
13774: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13775: @item
13776: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
13777: @item
13778: Support of the @code{info-lookup} feature for looking up the
13779: documentation of a word.
13780: @item
13781: Support for reading and writing blocks files.
13782: @end itemize
13783:
13784: To get a basic description of these features, enter Forth mode and
13785: type @kbd{C-h m}.
13786:
13787: @cindex source location of error or debugging output in Emacs
13788: @cindex error output, finding the source location in Emacs
13789: @cindex debugging output, finding the source location in Emacs
13790: In addition, Gforth supports Emacs quite well: The source code locations
13791: given in error messages, debugging output (from @code{~~}) and failed
13792: assertion messages are in the right format for Emacs' compilation mode
13793: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13794: Manual}) so the source location corresponding to an error or other
13795: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13796: @kbd{C-c C-c} for the error under the cursor).
13797:
13798: @cindex viewing the documentation of a word in Emacs
13799: @cindex context-sensitive help
13800: Moreover, for words documented in this manual, you can look up the
13801: glossary entry quickly by using @kbd{C-h TAB}
13802: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13803: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
13804: later and does not work for words containing @code{:}.
13805:
13806: @menu
13807: * Installing gforth.el:: Making Emacs aware of Forth.
13808: * Emacs Tags:: Viewing the source of a word in Emacs.
13809: * Hilighting:: Making Forth code look prettier.
13810: * Auto-Indentation:: Customizing auto-indentation.
13811: * Blocks Files:: Reading and writing blocks files.
13812: @end menu
13813:
13814: @c ----------------------------------
13815: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
13816: @section Installing gforth.el
13817: @cindex @file{.emacs}
13818: @cindex @file{gforth.el}, installation
13819: To make the features from @file{gforth.el} available in Emacs, add
13820: the following lines to your @file{.emacs} file:
13821:
13822: @example
13823: (autoload 'forth-mode "gforth.el")
13824: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
13825: auto-mode-alist))
13826: (autoload 'forth-block-mode "gforth.el")
13827: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
13828: auto-mode-alist))
13829: (add-hook 'forth-mode-hook (function (lambda ()
13830: ;; customize variables here:
13831: (setq forth-indent-level 4)
13832: (setq forth-minor-indent-level 2)
13833: (setq forth-hilight-level 3)
13834: ;;; ...
13835: )))
13836: @end example
13837:
13838: @c ----------------------------------
13839: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
13840: @section Emacs Tags
13841: @cindex @file{TAGS} file
13842: @cindex @file{etags.fs}
13843: @cindex viewing the source of a word in Emacs
13844: @cindex @code{require}, placement in files
13845: @cindex @code{include}, placement in files
13846: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
13847: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
13848: contains the definitions of all words defined afterwards. You can then
13849: find the source for a word using @kbd{M-.}. Note that Emacs can use
13850: several tags files at the same time (e.g., one for the Gforth sources
13851: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13852: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13853: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
13854: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
13855: with @file{etags.fs}, you should avoid putting definitions both before
13856: and after @code{require} etc., otherwise you will see the same file
13857: visited several times by commands like @code{tags-search}.
13858:
13859: @c ----------------------------------
13860: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
13861: @section Hilighting
13862: @cindex hilighting Forth code in Emacs
13863: @cindex highlighting Forth code in Emacs
13864: @file{gforth.el} comes with a custom source hilighting engine. When
13865: you open a file in @code{forth-mode}, it will be completely parsed,
13866: assigning faces to keywords, comments, strings etc. While you edit
13867: the file, modified regions get parsed and updated on-the-fly.
13868:
13869: Use the variable `forth-hilight-level' to change the level of
13870: decoration from 0 (no hilighting at all) to 3 (the default). Even if
13871: you set the hilighting level to 0, the parser will still work in the
13872: background, collecting information about whether regions of text are
13873: ``compiled'' or ``interpreted''. Those information are required for
13874: auto-indentation to work properly. Set `forth-disable-parser' to
13875: non-nil if your computer is too slow to handle parsing. This will
13876: have an impact on the smartness of the auto-indentation engine,
13877: though.
13878:
13879: Sometimes Forth sources define new features that should be hilighted,
13880: new control structures, defining-words etc. You can use the variable
13881: `forth-custom-words' to make @code{forth-mode} hilight additional
13882: words and constructs. See the docstring of `forth-words' for details
13883: (in Emacs, type @kbd{C-h v forth-words}).
13884:
13885: `forth-custom-words' is meant to be customized in your
13886: @file{.emacs} file. To customize hilighing in a file-specific manner,
13887: set `forth-local-words' in a local-variables section at the end of
13888: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
13889:
13890: Example:
13891: @example
13892: 0 [IF]
13893: Local Variables:
13894: forth-local-words:
13895: ((("t:") definition-starter (font-lock-keyword-face . 1)
13896: "[ \t\n]" t name (font-lock-function-name-face . 3))
13897: ((";t") definition-ender (font-lock-keyword-face . 1)))
13898: End:
13899: [THEN]
13900: @end example
13901:
13902: @c ----------------------------------
13903: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
13904: @section Auto-Indentation
13905: @cindex auto-indentation of Forth code in Emacs
13906: @cindex indentation of Forth code in Emacs
13907: @code{forth-mode} automatically tries to indent lines in a smart way,
13908: whenever you type @key{TAB} or break a line with @kbd{C-m}.
13909:
13910: Simple customization can be achieved by setting
13911: `forth-indent-level' and `forth-minor-indent-level' in your
13912: @file{.emacs} file. For historical reasons @file{gforth.el} indents
13913: per default by multiples of 4 columns. To use the more traditional
13914: 3-column indentation, add the following lines to your @file{.emacs}:
13915:
13916: @example
13917: (add-hook 'forth-mode-hook (function (lambda ()
13918: ;; customize variables here:
13919: (setq forth-indent-level 3)
13920: (setq forth-minor-indent-level 1)
13921: )))
13922: @end example
13923:
13924: If you want indentation to recognize non-default words, customize it
13925: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
13926: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
13927: v forth-indent-words}).
13928:
13929: To customize indentation in a file-specific manner, set
13930: `forth-local-indent-words' in a local-variables section at the end of
13931: your source file (@pxref{Local Variables in Files, Variables,,emacs,
13932: Emacs Manual}).
13933:
13934: Example:
13935: @example
13936: 0 [IF]
13937: Local Variables:
13938: forth-local-indent-words:
13939: ((("t:") (0 . 2) (0 . 2))
13940: ((";t") (-2 . 0) (0 . -2)))
13941: End:
13942: [THEN]
13943: @end example
13944:
13945: @c ----------------------------------
13946: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
13947: @section Blocks Files
13948: @cindex blocks files, use with Emacs
13949: @code{forth-mode} Autodetects blocks files by checking whether the
13950: length of the first line exceeds 1023 characters. It then tries to
13951: convert the file into normal text format. When you save the file, it
13952: will be written to disk as normal stream-source file.
13953:
13954: If you want to write blocks files, use @code{forth-blocks-mode}. It
13955: inherits all the features from @code{forth-mode}, plus some additions:
13956:
13957: @itemize @bullet
13958: @item
13959: Files are written to disk in blocks file format.
13960: @item
13961: Screen numbers are displayed in the mode line (enumerated beginning
13962: with the value of `forth-block-base')
13963: @item
13964: Warnings are displayed when lines exceed 64 characters.
13965: @item
13966: The beginning of the currently edited block is marked with an
13967: overlay-arrow.
13968: @end itemize
13969:
13970: There are some restrictions you should be aware of. When you open a
13971: blocks file that contains tabulator or newline characters, these
13972: characters will be translated into spaces when the file is written
13973: back to disk. If tabs or newlines are encountered during blocks file
13974: reading, an error is output to the echo area. So have a look at the
13975: `*Messages*' buffer, when Emacs' bell rings during reading.
13976:
13977: Please consult the docstring of @code{forth-blocks-mode} for more
13978: information by typing @kbd{C-h v forth-blocks-mode}).
13979:
13980: @c ******************************************************************
13981: @node Image Files, Engine, Emacs and Gforth, Top
13982: @chapter Image Files
13983: @cindex image file
13984: @cindex @file{.fi} files
13985: @cindex precompiled Forth code
13986: @cindex dictionary in persistent form
13987: @cindex persistent form of dictionary
13988:
13989: An image file is a file containing an image of the Forth dictionary,
13990: i.e., compiled Forth code and data residing in the dictionary. By
13991: convention, we use the extension @code{.fi} for image files.
13992:
13993: @menu
13994: * Image Licensing Issues:: Distribution terms for images.
13995: * Image File Background:: Why have image files?
13996: * Non-Relocatable Image Files:: don't always work.
13997: * Data-Relocatable Image Files:: are better.
13998: * Fully Relocatable Image Files:: better yet.
13999: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
14000: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
14001: * Modifying the Startup Sequence:: and turnkey applications.
14002: @end menu
14003:
14004: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14005: @section Image Licensing Issues
14006: @cindex license for images
14007: @cindex image license
14008:
14009: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14010: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14011: original image; i.e., according to copyright law it is a derived work of
14012: the original image.
14013:
14014: Since Gforth is distributed under the GNU GPL, the newly created image
14015: falls under the GNU GPL, too. In particular, this means that if you
14016: distribute the image, you have to make all of the sources for the image
14017: available, including those you wrote. For details see @ref{Copying, ,
14018: GNU General Public License (Section 3)}.
14019:
14020: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14021: contains only code compiled from the sources you gave it; if none of
14022: these sources is under the GPL, the terms discussed above do not apply
14023: to the image. However, if your image needs an engine (a gforth binary)
14024: that is under the GPL, you should make sure that you distribute both in
14025: a way that is at most a @emph{mere aggregation}, if you don't want the
14026: terms of the GPL to apply to the image.
14027:
14028: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
14029: @section Image File Background
14030: @cindex image file background
14031:
14032: Gforth consists not only of primitives (in the engine), but also of
14033: definitions written in Forth. Since the Forth compiler itself belongs to
14034: those definitions, it is not possible to start the system with the
14035: engine and the Forth source alone. Therefore we provide the Forth
14036: code as an image file in nearly executable form. When Gforth starts up,
14037: a C routine loads the image file into memory, optionally relocates the
14038: addresses, then sets up the memory (stacks etc.) according to
14039: information in the image file, and (finally) starts executing Forth
14040: code.
14041:
14042: The image file variants represent different compromises between the
14043: goals of making it easy to generate image files and making them
14044: portable.
14045:
14046: @cindex relocation at run-time
14047: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
14048: run-time. This avoids many of the complications discussed below (image
14049: files are data relocatable without further ado), but costs performance
14050: (one addition per memory access).
14051:
14052: @cindex relocation at load-time
14053: By contrast, the Gforth loader performs relocation at image load time. The
14054: loader also has to replace tokens that represent primitive calls with the
14055: appropriate code-field addresses (or code addresses in the case of
14056: direct threading).
14057:
14058: There are three kinds of image files, with different degrees of
14059: relocatability: non-relocatable, data-relocatable, and fully relocatable
14060: image files.
14061:
14062: @cindex image file loader
14063: @cindex relocating loader
14064: @cindex loader for image files
14065: These image file variants have several restrictions in common; they are
14066: caused by the design of the image file loader:
14067:
14068: @itemize @bullet
14069: @item
14070: There is only one segment; in particular, this means, that an image file
14071: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
14072: them). The contents of the stacks are not represented, either.
14073:
14074: @item
14075: The only kinds of relocation supported are: adding the same offset to
14076: all cells that represent data addresses; and replacing special tokens
14077: with code addresses or with pieces of machine code.
14078:
14079: If any complex computations involving addresses are performed, the
14080: results cannot be represented in the image file. Several applications that
14081: use such computations come to mind:
14082: @itemize @minus
14083: @item
14084: Hashing addresses (or data structures which contain addresses) for table
14085: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14086: purpose, you will have no problem, because the hash tables are
14087: recomputed automatically when the system is started. If you use your own
14088: hash tables, you will have to do something similar.
14089:
14090: @item
14091: There's a cute implementation of doubly-linked lists that uses
14092: @code{XOR}ed addresses. You could represent such lists as singly-linked
14093: in the image file, and restore the doubly-linked representation on
14094: startup.@footnote{In my opinion, though, you should think thrice before
14095: using a doubly-linked list (whatever implementation).}
14096:
14097: @item
14098: The code addresses of run-time routines like @code{docol:} cannot be
14099: represented in the image file (because their tokens would be replaced by
14100: machine code in direct threaded implementations). As a workaround,
14101: compute these addresses at run-time with @code{>code-address} from the
14102: executions tokens of appropriate words (see the definitions of
14103: @code{docol:} and friends in @file{kernel/getdoers.fs}).
14104:
14105: @item
14106: On many architectures addresses are represented in machine code in some
14107: shifted or mangled form. You cannot put @code{CODE} words that contain
14108: absolute addresses in this form in a relocatable image file. Workarounds
14109: are representing the address in some relative form (e.g., relative to
14110: the CFA, which is present in some register), or loading the address from
14111: a place where it is stored in a non-mangled form.
14112: @end itemize
14113: @end itemize
14114:
14115: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14116: @section Non-Relocatable Image Files
14117: @cindex non-relocatable image files
14118: @cindex image file, non-relocatable
14119:
14120: These files are simple memory dumps of the dictionary. They are specific
14121: to the executable (i.e., @file{gforth} file) they were created
14122: with. What's worse, they are specific to the place on which the
14123: dictionary resided when the image was created. Now, there is no
14124: guarantee that the dictionary will reside at the same place the next
14125: time you start Gforth, so there's no guarantee that a non-relocatable
14126: image will work the next time (Gforth will complain instead of crashing,
14127: though).
14128:
14129: You can create a non-relocatable image file with
14130:
14131:
14132: doc-savesystem
14133:
14134:
14135: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14136: @section Data-Relocatable Image Files
14137: @cindex data-relocatable image files
14138: @cindex image file, data-relocatable
14139:
14140: These files contain relocatable data addresses, but fixed code addresses
14141: (instead of tokens). They are specific to the executable (i.e.,
14142: @file{gforth} file) they were created with. For direct threading on some
14143: architectures (e.g., the i386), data-relocatable images do not work. You
14144: get a data-relocatable image, if you use @file{gforthmi} with a
14145: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14146: Relocatable Image Files}).
14147:
14148: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14149: @section Fully Relocatable Image Files
14150: @cindex fully relocatable image files
14151: @cindex image file, fully relocatable
14152:
14153: @cindex @file{kern*.fi}, relocatability
14154: @cindex @file{gforth.fi}, relocatability
14155: These image files have relocatable data addresses, and tokens for code
14156: addresses. They can be used with different binaries (e.g., with and
14157: without debugging) on the same machine, and even across machines with
14158: the same data formats (byte order, cell size, floating point
14159: format). However, they are usually specific to the version of Gforth
14160: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14161: are fully relocatable.
14162:
14163: There are two ways to create a fully relocatable image file:
14164:
14165: @menu
14166: * gforthmi:: The normal way
14167: * cross.fs:: The hard way
14168: @end menu
14169:
14170: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14171: @subsection @file{gforthmi}
14172: @cindex @file{comp-i.fs}
14173: @cindex @file{gforthmi}
14174:
14175: You will usually use @file{gforthmi}. If you want to create an
14176: image @i{file} that contains everything you would load by invoking
14177: Gforth with @code{gforth @i{options}}, you simply say:
14178: @example
14179: gforthmi @i{file} @i{options}
14180: @end example
14181:
14182: E.g., if you want to create an image @file{asm.fi} that has the file
14183: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14184: like this:
14185:
14186: @example
14187: gforthmi asm.fi asm.fs
14188: @end example
14189:
14190: @file{gforthmi} is implemented as a sh script and works like this: It
14191: produces two non-relocatable images for different addresses and then
14192: compares them. Its output reflects this: first you see the output (if
14193: any) of the two Gforth invocations that produce the non-relocatable image
14194: files, then you see the output of the comparing program: It displays the
14195: offset used for data addresses and the offset used for code addresses;
14196: moreover, for each cell that cannot be represented correctly in the
14197: image files, it displays a line like this:
14198:
14199: @example
14200: 78DC BFFFFA50 BFFFFA40
14201: @end example
14202:
14203: This means that at offset $78dc from @code{forthstart}, one input image
14204: contains $bffffa50, and the other contains $bffffa40. Since these cells
14205: cannot be represented correctly in the output image, you should examine
14206: these places in the dictionary and verify that these cells are dead
14207: (i.e., not read before they are written).
14208:
14209: @cindex --application, @code{gforthmi} option
14210: If you insert the option @code{--application} in front of the image file
14211: name, you will get an image that uses the @code{--appl-image} option
14212: instead of the @code{--image-file} option (@pxref{Invoking
14213: Gforth}). When you execute such an image on Unix (by typing the image
14214: name as command), the Gforth engine will pass all options to the image
14215: instead of trying to interpret them as engine options.
14216:
14217: If you type @file{gforthmi} with no arguments, it prints some usage
14218: instructions.
14219:
14220: @cindex @code{savesystem} during @file{gforthmi}
14221: @cindex @code{bye} during @file{gforthmi}
14222: @cindex doubly indirect threaded code
14223: @cindex environment variables
14224: @cindex @code{GFORTHD} -- environment variable
14225: @cindex @code{GFORTH} -- environment variable
14226: @cindex @code{gforth-ditc}
14227: There are a few wrinkles: After processing the passed @i{options}, the
14228: words @code{savesystem} and @code{bye} must be visible. A special doubly
14229: indirect threaded version of the @file{gforth} executable is used for
14230: creating the non-relocatable images; you can pass the exact filename of
14231: this executable through the environment variable @code{GFORTHD}
14232: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14233: indirect threaded, you will not get a fully relocatable image, but a
14234: data-relocatable image (because there is no code address offset). The
14235: normal @file{gforth} executable is used for creating the relocatable
14236: image; you can pass the exact filename of this executable through the
14237: environment variable @code{GFORTH}.
14238:
14239: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14240: @subsection @file{cross.fs}
14241: @cindex @file{cross.fs}
14242: @cindex cross-compiler
14243: @cindex metacompiler
14244: @cindex target compiler
14245:
14246: You can also use @code{cross}, a batch compiler that accepts a Forth-like
14247: programming language (@pxref{Cross Compiler}).
14248:
14249: @code{cross} allows you to create image files for machines with
14250: different data sizes and data formats than the one used for generating
14251: the image file. You can also use it to create an application image that
14252: does not contain a Forth compiler. These features are bought with
14253: restrictions and inconveniences in programming. E.g., addresses have to
14254: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14255: order to make the code relocatable.
14256:
14257:
14258: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14259: @section Stack and Dictionary Sizes
14260: @cindex image file, stack and dictionary sizes
14261: @cindex dictionary size default
14262: @cindex stack size default
14263:
14264: If you invoke Gforth with a command line flag for the size
14265: (@pxref{Invoking Gforth}), the size you specify is stored in the
14266: dictionary. If you save the dictionary with @code{savesystem} or create
14267: an image with @file{gforthmi}, this size will become the default
14268: for the resulting image file. E.g., the following will create a
14269: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
14270:
14271: @example
14272: gforthmi gforth.fi -m 1M
14273: @end example
14274:
14275: In other words, if you want to set the default size for the dictionary
14276: and the stacks of an image, just invoke @file{gforthmi} with the
14277: appropriate options when creating the image.
14278:
14279: @cindex stack size, cache-friendly
14280: Note: For cache-friendly behaviour (i.e., good performance), you should
14281: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14282: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14283: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14284:
14285: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14286: @section Running Image Files
14287: @cindex running image files
14288: @cindex invoking image files
14289: @cindex image file invocation
14290:
14291: @cindex -i, invoke image file
14292: @cindex --image file, invoke image file
14293: You can invoke Gforth with an image file @i{image} instead of the
14294: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14295: @example
14296: gforth -i @i{image}
14297: @end example
14298:
14299: @cindex executable image file
14300: @cindex image file, executable
14301: If your operating system supports starting scripts with a line of the
14302: form @code{#! ...}, you just have to type the image file name to start
14303: Gforth with this image file (note that the file extension @code{.fi} is
14304: just a convention). I.e., to run Gforth with the image file @i{image},
14305: you can just type @i{image} instead of @code{gforth -i @i{image}}.
14306: This works because every @code{.fi} file starts with a line of this
14307: format:
14308:
14309: @example
14310: #! /usr/local/bin/gforth-0.4.0 -i
14311: @end example
14312:
14313: The file and pathname for the Gforth engine specified on this line is
14314: the specific Gforth executable that it was built against; i.e. the value
14315: of the environment variable @code{GFORTH} at the time that
14316: @file{gforthmi} was executed.
14317:
14318: You can make use of the same shell capability to make a Forth source
14319: file into an executable. For example, if you place this text in a file:
14320:
14321: @example
14322: #! /usr/local/bin/gforth
14323:
14324: ." Hello, world" CR
14325: bye
14326: @end example
14327:
14328: @noindent
14329: and then make the file executable (chmod +x in Unix), you can run it
14330: directly from the command line. The sequence @code{#!} is used in two
14331: ways; firstly, it is recognised as a ``magic sequence'' by the operating
14332: system@footnote{The Unix kernel actually recognises two types of files:
14333: executable files and files of data, where the data is processed by an
14334: interpreter that is specified on the ``interpreter line'' -- the first
14335: line of the file, starting with the sequence #!. There may be a small
14336: limit (e.g., 32) on the number of characters that may be specified on
14337: the interpreter line.} secondly it is treated as a comment character by
14338: Gforth. Because of the second usage, a space is required between
14339: @code{#!} and the path to the executable (moreover, some Unixes
14340: require the sequence @code{#! /}).
14341:
14342: The disadvantage of this latter technique, compared with using
14343: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14344: compiled on-the-fly, each time the program is invoked.
14345:
14346: doc-#!
14347:
14348:
14349: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14350: @section Modifying the Startup Sequence
14351: @cindex startup sequence for image file
14352: @cindex image file initialization sequence
14353: @cindex initialization sequence of image file
14354:
14355: You can add your own initialization to the startup sequence of an image
14356: through the deferred word @code{'cold}. @code{'cold} is invoked just
14357: before the image-specific command line processing (i.e., loading files
14358: and evaluating (@code{-e}) strings) starts.
14359:
14360: A sequence for adding your initialization usually looks like this:
14361:
14362: @example
14363: :noname
14364: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14365: ... \ your stuff
14366: ; IS 'cold
14367: @end example
14368:
14369: @cindex turnkey image files
14370: @cindex image file, turnkey applications
14371: You can make a turnkey image by letting @code{'cold} execute a word
14372: (your turnkey application) that never returns; instead, it exits Gforth
14373: via @code{bye} or @code{throw}.
14374:
14375: You can access the (image-specific) command-line arguments through
14376: @code{argc}, @code{argv} and @code{arg} (@pxref{OS command line
14377: arguments}).
14378:
14379: If @code{'cold} exits normally, Gforth processes the command-line
14380: arguments as files to be loaded and strings to be evaluated. Therefore,
14381: @code{'cold} should remove the arguments it has used in this case.
14382:
14383: doc-'cold
14384:
14385: @c ******************************************************************
14386: @node Engine, Cross Compiler, Image Files, Top
14387: @chapter Engine
14388: @cindex engine
14389: @cindex virtual machine
14390:
14391: Reading this chapter is not necessary for programming with Gforth. It
14392: may be helpful for finding your way in the Gforth sources.
14393:
14394: The ideas in this section have also been published in the following
14395: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14396: Forth-Tagung '93; M. Anton Ertl,
14397: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14398: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14399: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14400: Threaded code variations and optimizations (extended version)}},
14401: Forth-Tagung '02.
14402:
14403: @menu
14404: * Portability::
14405: * Threading::
14406: * Primitives::
14407: * Performance::
14408: @end menu
14409:
14410: @node Portability, Threading, Engine, Engine
14411: @section Portability
14412: @cindex engine portability
14413:
14414: An important goal of the Gforth Project is availability across a wide
14415: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14416: achieved this goal by manually coding the engine in assembly language
14417: for several then-popular processors. This approach is very
14418: labor-intensive and the results are short-lived due to progress in
14419: computer architecture.
14420:
14421: @cindex C, using C for the engine
14422: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14423: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14424: particularly popular for UNIX-based Forths due to the large variety of
14425: architectures of UNIX machines. Unfortunately an implementation in C
14426: does not mix well with the goals of efficiency and with using
14427: traditional techniques: Indirect or direct threading cannot be expressed
14428: in C, and switch threading, the fastest technique available in C, is
14429: significantly slower. Another problem with C is that it is very
14430: cumbersome to express double integer arithmetic.
14431:
14432: @cindex GNU C for the engine
14433: @cindex long long
14434: Fortunately, there is a portable language that does not have these
14435: limitations: GNU C, the version of C processed by the GNU C compiler
14436: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14437: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14438: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14439: threading possible, its @code{long long} type (@pxref{Long Long, ,
14440: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
14441: double numbers on many systems. GNU C is freely available on all
14442: important (and many unimportant) UNIX machines, VMS, 80386s running
14443: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14444: on all these machines.
14445:
14446: Writing in a portable language has the reputation of producing code that
14447: is slower than assembly. For our Forth engine we repeatedly looked at
14448: the code produced by the compiler and eliminated most compiler-induced
14449: inefficiencies by appropriate changes in the source code.
14450:
14451: @cindex explicit register declarations
14452: @cindex --enable-force-reg, configuration flag
14453: @cindex -DFORCE_REG
14454: However, register allocation cannot be portably influenced by the
14455: programmer, leading to some inefficiencies on register-starved
14456: machines. We use explicit register declarations (@pxref{Explicit Reg
14457: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14458: improve the speed on some machines. They are turned on by using the
14459: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14460: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14461: machine, but also on the compiler version: On some machines some
14462: compiler versions produce incorrect code when certain explicit register
14463: declarations are used. So by default @code{-DFORCE_REG} is not used.
14464:
14465: @node Threading, Primitives, Portability, Engine
14466: @section Threading
14467: @cindex inner interpreter implementation
14468: @cindex threaded code implementation
14469:
14470: @cindex labels as values
14471: GNU C's labels as values extension (available since @code{gcc-2.0},
14472: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
14473: makes it possible to take the address of @i{label} by writing
14474: @code{&&@i{label}}. This address can then be used in a statement like
14475: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
14476: @code{goto x}.
14477:
14478: @cindex @code{NEXT}, indirect threaded
14479: @cindex indirect threaded inner interpreter
14480: @cindex inner interpreter, indirect threaded
14481: With this feature an indirect threaded @code{NEXT} looks like:
14482: @example
14483: cfa = *ip++;
14484: ca = *cfa;
14485: goto *ca;
14486: @end example
14487: @cindex instruction pointer
14488: For those unfamiliar with the names: @code{ip} is the Forth instruction
14489: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14490: execution token and points to the code field of the next word to be
14491: executed; The @code{ca} (code address) fetched from there points to some
14492: executable code, e.g., a primitive or the colon definition handler
14493: @code{docol}.
14494:
14495: @cindex @code{NEXT}, direct threaded
14496: @cindex direct threaded inner interpreter
14497: @cindex inner interpreter, direct threaded
14498: Direct threading is even simpler:
14499: @example
14500: ca = *ip++;
14501: goto *ca;
14502: @end example
14503:
14504: Of course we have packaged the whole thing neatly in macros called
14505: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
14506:
14507: @menu
14508: * Scheduling::
14509: * Direct or Indirect Threaded?::
14510: * Dynamic Superinstructions::
14511: * DOES>::
14512: @end menu
14513:
14514: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14515: @subsection Scheduling
14516: @cindex inner interpreter optimization
14517:
14518: There is a little complication: Pipelined and superscalar processors,
14519: i.e., RISC and some modern CISC machines can process independent
14520: instructions while waiting for the results of an instruction. The
14521: compiler usually reorders (schedules) the instructions in a way that
14522: achieves good usage of these delay slots. However, on our first tries
14523: the compiler did not do well on scheduling primitives. E.g., for
14524: @code{+} implemented as
14525: @example
14526: n=sp[0]+sp[1];
14527: sp++;
14528: sp[0]=n;
14529: NEXT;
14530: @end example
14531: the @code{NEXT} comes strictly after the other code, i.e., there is
14532: nearly no scheduling. After a little thought the problem becomes clear:
14533: The compiler cannot know that @code{sp} and @code{ip} point to different
14534: addresses (and the version of @code{gcc} we used would not know it even
14535: if it was possible), so it could not move the load of the cfa above the
14536: store to the TOS. Indeed the pointers could be the same, if code on or
14537: very near the top of stack were executed. In the interest of speed we
14538: chose to forbid this probably unused ``feature'' and helped the compiler
14539: in scheduling: @code{NEXT} is divided into several parts:
14540: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14541: like:
14542: @example
14543: NEXT_P0;
14544: n=sp[0]+sp[1];
14545: sp++;
14546: NEXT_P1;
14547: sp[0]=n;
14548: NEXT_P2;
14549: @end example
14550:
14551: There are various schemes that distribute the different operations of
14552: NEXT between these parts in several ways; in general, different schemes
14553: perform best on different processors. We use a scheme for most
14554: architectures that performs well for most processors of this
14555: architecture; in the future we may switch to benchmarking and chosing
14556: the scheme on installation time.
14557:
14558:
14559: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
14560: @subsection Direct or Indirect Threaded?
14561: @cindex threading, direct or indirect?
14562:
14563: Threaded forth code consists of references to primitives (simple machine
14564: code routines like @code{+}) and to non-primitives (e.g., colon
14565: definitions, variables, constants); for a specific class of
14566: non-primitives (e.g., variables) there is one code routine (e.g.,
14567: @code{dovar}), but each variable needs a separate reference to its data.
14568:
14569: Traditionally Forth has been implemented as indirect threaded code,
14570: because this allows to use only one cell to reference a non-primitive
14571: (basically you point to the data, and find the code address there).
14572:
14573: @cindex primitive-centric threaded code
14574: However, threaded code in Gforth (since 0.6.0) uses two cells for
14575: non-primitives, one for the code address, and one for the data address;
14576: the data pointer is an immediate argument for the virtual machine
14577: instruction represented by the code address. We call this
14578: @emph{primitive-centric} threaded code, because all code addresses point
14579: to simple primitives. E.g., for a variable, the code address is for
14580: @code{lit} (also used for integer literals like @code{99}).
14581:
14582: Primitive-centric threaded code allows us to use (faster) direct
14583: threading as dispatch method, completely portably (direct threaded code
14584: in Gforth before 0.6.0 required architecture-specific code). It also
14585: eliminates the performance problems related to I-cache consistency that
14586: 386 implementations have with direct threaded code, and allows
14587: additional optimizations.
14588:
14589: @cindex hybrid direct/indirect threaded code
14590: There is a catch, however: the @var{xt} parameter of @code{execute} can
14591: occupy only one cell, so how do we pass non-primitives with their code
14592: @emph{and} data addresses to them? Our answer is to use indirect
14593: threaded dispatch for @code{execute} and other words that use a
14594: single-cell xt. So, normal threaded code in colon definitions uses
14595: direct threading, and @code{execute} and similar words, which dispatch
14596: to xts on the data stack, use indirect threaded code. We call this
14597: @emph{hybrid direct/indirect} threaded code.
14598:
14599: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14600: @cindex gforth engine
14601: @cindex gforth-fast engine
14602: The engines @command{gforth} and @command{gforth-fast} use hybrid
14603: direct/indirect threaded code. This means that with these engines you
14604: cannot use @code{,} to compile an xt. Instead, you have to use
14605: @code{compile,}.
14606:
14607: @cindex gforth-itc engine
14608: If you want to compile xts with @code{,}, use @command{gforth-itc}.
14609: This engine uses plain old indirect threaded code. It still compiles in
14610: a primitive-centric style, so you cannot use @code{compile,} instead of
14611: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
14612: ... [}). If you want to do that, you have to use @command{gforth-itc}
14613: and execute @code{' , is compile,}. Your program can check if it is
14614: running on a hybrid direct/indirect threaded engine or a pure indirect
14615: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14616:
14617:
14618: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14619: @subsection Dynamic Superinstructions
14620: @cindex Dynamic superinstructions with replication
14621: @cindex Superinstructions
14622: @cindex Replication
14623:
14624: The engines @command{gforth} and @command{gforth-fast} use another
14625: optimization: Dynamic superinstructions with replication. As an
14626: example, consider the following colon definition:
14627:
14628: @example
14629: : squared ( n1 -- n2 )
14630: dup * ;
14631: @end example
14632:
14633: Gforth compiles this into the threaded code sequence
14634:
14635: @example
14636: dup
14637: *
14638: ;s
14639: @end example
14640:
14641: In normal direct threaded code there is a code address occupying one
14642: cell for each of these primitives. Each code address points to a
14643: machine code routine, and the interpreter jumps to this machine code in
14644: order to execute the primitive. The routines for these three
14645: primitives are (in @command{gforth-fast} on the 386):
14646:
14647: @example
14648: Code dup
14649: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
14650: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
14651: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14652: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14653: end-code
14654: Code *
14655: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14656: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
14657: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
14658: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
14659: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14660: end-code
14661: Code ;s
14662: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
14663: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
14664: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14665: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14666: end-code
14667: @end example
14668:
14669: With dynamic superinstructions and replication the compiler does not
14670: just lay down the threaded code, but also copies the machine code
14671: fragments, usually without the jump at the end.
14672:
14673: @example
14674: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
14675: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
14676: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14677: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14678: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
14679: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
14680: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
14681: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
14682: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
14683: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14684: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14685: @end example
14686:
14687: Only when a threaded-code control-flow change happens (e.g., in
14688: @code{;s}), the jump is appended. This optimization eliminates many of
14689: these jumps and makes the rest much more predictable. The speedup
14690: depends on the processor and the application; on the Athlon and Pentium
14691: III this optimization typically produces a speedup by a factor of 2.
14692:
14693: The code addresses in the direct-threaded code are set to point to the
14694: appropriate points in the copied machine code, in this example like
14695: this:
14696:
14697: @example
14698: primitive code address
14699: dup $4057D27D
14700: * $4057D286
14701: ;s $4057D292
14702: @end example
14703:
14704: Thus there can be threaded-code jumps to any place in this piece of
14705: code. This also simplifies decompilation quite a bit.
14706:
14707: @cindex --no-dynamic command-line option
14708: @cindex --no-super command-line option
14709: You can disable this optimization with @option{--no-dynamic}. You can
14710: use the copying without eliminating the jumps (i.e., dynamic
14711: replication, but without superinstructions) with @option{--no-super};
14712: this gives the branch prediction benefit alone; the effect on
14713: performance depends on the CPU; on the Athlon and Pentium III the
14714: speedup is a little less than for dynamic superinstructions with
14715: replication.
14716:
14717: @cindex patching threaded code
14718: One use of these options is if you want to patch the threaded code.
14719: With superinstructions, many of the dispatch jumps are eliminated, so
14720: patching often has no effect. These options preserve all the dispatch
14721: jumps.
14722:
14723: @cindex --dynamic command-line option
14724: On some machines dynamic superinstructions are disabled by default,
14725: because it is unsafe on these machines. However, if you feel
14726: adventurous, you can enable it with @option{--dynamic}.
14727:
14728: @node DOES>, , Dynamic Superinstructions, Threading
14729: @subsection DOES>
14730: @cindex @code{DOES>} implementation
14731:
14732: @cindex @code{dodoes} routine
14733: @cindex @code{DOES>}-code
14734: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14735: the chunk of code executed by every word defined by a
14736: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
14737: this is only needed if the xt of the word is @code{execute}d. The main
14738: problem here is: How to find the Forth code to be executed, i.e. the
14739: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
14740: solutions:
14741:
14742: In fig-Forth the code field points directly to the @code{dodoes} and the
14743: @code{DOES>}-code address is stored in the cell after the code address
14744: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
14745: illegal in the Forth-79 and all later standards, because in fig-Forth
14746: this address lies in the body (which is illegal in these
14747: standards). However, by making the code field larger for all words this
14748: solution becomes legal again. We use this approach. Leaving a cell
14749: unused in most words is a bit wasteful, but on the machines we are
14750: targeting this is hardly a problem.
14751:
14752:
14753: @node Primitives, Performance, Threading, Engine
14754: @section Primitives
14755: @cindex primitives, implementation
14756: @cindex virtual machine instructions, implementation
14757:
14758: @menu
14759: * Automatic Generation::
14760: * TOS Optimization::
14761: * Produced code::
14762: @end menu
14763:
14764: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14765: @subsection Automatic Generation
14766: @cindex primitives, automatic generation
14767:
14768: @cindex @file{prims2x.fs}
14769:
14770: Since the primitives are implemented in a portable language, there is no
14771: longer any need to minimize the number of primitives. On the contrary,
14772: having many primitives has an advantage: speed. In order to reduce the
14773: number of errors in primitives and to make programming them easier, we
14774: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
14775: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
14776: generates most (and sometimes all) of the C code for a primitive from
14777: the stack effect notation. The source for a primitive has the following
14778: form:
14779:
14780: @cindex primitive source format
14781: @format
14782: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
14783: [@code{""}@i{glossary entry}@code{""}]
14784: @i{C code}
14785: [@code{:}
14786: @i{Forth code}]
14787: @end format
14788:
14789: The items in brackets are optional. The category and glossary fields
14790: are there for generating the documentation, the Forth code is there
14791: for manual implementations on machines without GNU C. E.g., the source
14792: for the primitive @code{+} is:
14793: @example
14794: + ( n1 n2 -- n ) core plus
14795: n = n1+n2;
14796: @end example
14797:
14798: This looks like a specification, but in fact @code{n = n1+n2} is C
14799: code. Our primitive generation tool extracts a lot of information from
14800: the stack effect notations@footnote{We use a one-stack notation, even
14801: though we have separate data and floating-point stacks; The separate
14802: notation can be generated easily from the unified notation.}: The number
14803: of items popped from and pushed on the stack, their type, and by what
14804: name they are referred to in the C code. It then generates a C code
14805: prelude and postlude for each primitive. The final C code for @code{+}
14806: looks like this:
14807:
14808: @example
14809: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
14810: /* */ /* documentation */
14811: NAME("+") /* debugging output (with -DDEBUG) */
14812: @{
14813: DEF_CA /* definition of variable ca (indirect threading) */
14814: Cell n1; /* definitions of variables */
14815: Cell n2;
14816: Cell n;
14817: NEXT_P0; /* NEXT part 0 */
14818: n1 = (Cell) sp[1]; /* input */
14819: n2 = (Cell) TOS;
14820: sp += 1; /* stack adjustment */
14821: @{
14822: n = n1+n2; /* C code taken from the source */
14823: @}
14824: NEXT_P1; /* NEXT part 1 */
14825: TOS = (Cell)n; /* output */
14826: NEXT_P2; /* NEXT part 2 */
14827: @}
14828: @end example
14829:
14830: This looks long and inefficient, but the GNU C compiler optimizes quite
14831: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14832: HP RISC machines: Defining the @code{n}s does not produce any code, and
14833: using them as intermediate storage also adds no cost.
14834:
14835: There are also other optimizations that are not illustrated by this
14836: example: assignments between simple variables are usually for free (copy
14837: propagation). If one of the stack items is not used by the primitive
14838: (e.g. in @code{drop}), the compiler eliminates the load from the stack
14839: (dead code elimination). On the other hand, there are some things that
14840: the compiler does not do, therefore they are performed by
14841: @file{prims2x.fs}: The compiler does not optimize code away that stores
14842: a stack item to the place where it just came from (e.g., @code{over}).
14843:
14844: While programming a primitive is usually easy, there are a few cases
14845: where the programmer has to take the actions of the generator into
14846: account, most notably @code{?dup}, but also words that do not (always)
14847: fall through to @code{NEXT}.
14848:
14849: For more information
14850:
14851: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14852: @subsection TOS Optimization
14853: @cindex TOS optimization for primitives
14854: @cindex primitives, keeping the TOS in a register
14855:
14856: An important optimization for stack machine emulators, e.g., Forth
14857: engines, is keeping one or more of the top stack items in
14858: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
14859: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
14860: @itemize @bullet
14861: @item
14862: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
14863: due to fewer loads from and stores to the stack.
14864: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14865: @i{y<n}, due to additional moves between registers.
14866: @end itemize
14867:
14868: @cindex -DUSE_TOS
14869: @cindex -DUSE_NO_TOS
14870: In particular, keeping one item in a register is never a disadvantage,
14871: if there are enough registers. Keeping two items in registers is a
14872: disadvantage for frequent words like @code{?branch}, constants,
14873: variables, literals and @code{i}. Therefore our generator only produces
14874: code that keeps zero or one items in registers. The generated C code
14875: covers both cases; the selection between these alternatives is made at
14876: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14877: code for @code{+} is just a simple variable name in the one-item case,
14878: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14879: GNU C compiler tries to keep simple variables like @code{TOS} in
14880: registers, and it usually succeeds, if there are enough registers.
14881:
14882: @cindex -DUSE_FTOS
14883: @cindex -DUSE_NO_FTOS
14884: The primitive generator performs the TOS optimization for the
14885: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14886: operations the benefit of this optimization is even larger:
14887: floating-point operations take quite long on most processors, but can be
14888: performed in parallel with other operations as long as their results are
14889: not used. If the FP-TOS is kept in a register, this works. If
14890: it is kept on the stack, i.e., in memory, the store into memory has to
14891: wait for the result of the floating-point operation, lengthening the
14892: execution time of the primitive considerably.
14893:
14894: The TOS optimization makes the automatic generation of primitives a
14895: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14896: @code{TOS} is not sufficient. There are some special cases to
14897: consider:
14898: @itemize @bullet
14899: @item In the case of @code{dup ( w -- w w )} the generator must not
14900: eliminate the store to the original location of the item on the stack,
14901: if the TOS optimization is turned on.
14902: @item Primitives with stack effects of the form @code{--}
14903: @i{out1}...@i{outy} must store the TOS to the stack at the start.
14904: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
14905: must load the TOS from the stack at the end. But for the null stack
14906: effect @code{--} no stores or loads should be generated.
14907: @end itemize
14908:
14909: @node Produced code, , TOS Optimization, Primitives
14910: @subsection Produced code
14911: @cindex primitives, assembly code listing
14912:
14913: @cindex @file{engine.s}
14914: To see what assembly code is produced for the primitives on your machine
14915: with your compiler and your flag settings, type @code{make engine.s} and
14916: look at the resulting file @file{engine.s}. Alternatively, you can also
14917: disassemble the code of primitives with @code{see} on some architectures.
14918:
14919: @node Performance, , Primitives, Engine
14920: @section Performance
14921: @cindex performance of some Forth interpreters
14922: @cindex engine performance
14923: @cindex benchmarking Forth systems
14924: @cindex Gforth performance
14925:
14926: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
14927: impossible to write a significantly faster threaded-code engine.
14928:
14929: On register-starved machines like the 386 architecture processors
14930: improvements are possible, because @code{gcc} does not utilize the
14931: registers as well as a human, even with explicit register declarations;
14932: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
14933: and hand-tuned it for the 486; this system is 1.19 times faster on the
14934: Sieve benchmark on a 486DX2/66 than Gforth compiled with
14935: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
14936: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
14937: registers fit in real registers (and we can even afford to use the TOS
14938: optimization), resulting in a speedup of 1.14 on the sieve over the
14939: earlier results. And dynamic superinstructions provide another speedup
14940: (but only around a factor 1.2 on the 486).
14941:
14942: @cindex Win32Forth performance
14943: @cindex NT Forth performance
14944: @cindex eforth performance
14945: @cindex ThisForth performance
14946: @cindex PFE performance
14947: @cindex TILE performance
14948: The potential advantage of assembly language implementations is not
14949: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
14950: (direct threaded, compiled with @code{gcc-2.95.1} and
14951: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
14952: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
14953: (with and without peephole (aka pinhole) optimization of the threaded
14954: code); all these systems were written in assembly language. We also
14955: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
14956: with @code{gcc-2.6.3} with the default configuration for Linux:
14957: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
14958: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
14959: employs peephole optimization of the threaded code) and TILE (compiled
14960: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
14961: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
14962: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
14963: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
14964: then extended it to run the benchmarks, added the peephole optimizer,
14965: ran the benchmarks and reported the results.
14966:
14967: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
14968: matrix multiplication come from the Stanford integer benchmarks and have
14969: been translated into Forth by Martin Fraeman; we used the versions
14970: included in the TILE Forth package, but with bigger data set sizes; and
14971: a recursive Fibonacci number computation for benchmarking calling
14972: performance. The following table shows the time taken for the benchmarks
14973: scaled by the time taken by Gforth (in other words, it shows the speedup
14974: factor that Gforth achieved over the other systems).
14975:
14976: @example
14977: relative Win32- NT eforth This-
14978: time Gforth Forth Forth eforth +opt PFE Forth TILE
14979: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
14980: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
14981: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
14982: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
14983: @end example
14984:
14985: You may be quite surprised by the good performance of Gforth when
14986: compared with systems written in assembly language. One important reason
14987: for the disappointing performance of these other systems is probably
14988: that they are not written optimally for the 486 (e.g., they use the
14989: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
14990: but costly method for relocating the Forth image: like @code{cforth}, it
14991: computes the actual addresses at run time, resulting in two address
14992: computations per @code{NEXT} (@pxref{Image File Background}).
14993:
14994: The speedup of Gforth over PFE, ThisForth and TILE can be easily
14995: explained with the self-imposed restriction of the latter systems to
14996: standard C, which makes efficient threading impossible (however, the
14997: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
14998: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
14999: Moreover, current C compilers have a hard time optimizing other aspects
15000: of the ThisForth and the TILE source.
15001:
15002: The performance of Gforth on 386 architecture processors varies widely
15003: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15004: allocate any of the virtual machine registers into real machine
15005: registers by itself and would not work correctly with explicit register
15006: declarations, giving a significantly slower engine (on a 486DX2/66
15007: running the Sieve) than the one measured above.
15008:
15009: Note that there have been several releases of Win32Forth since the
15010: release presented here, so the results presented above may have little
15011: predictive value for the performance of Win32Forth today (results for
15012: the current release on an i486DX2/66 are welcome).
15013:
15014: @cindex @file{Benchres}
15015: In
15016: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15017: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
15018: Maierhofer (presented at EuroForth '95), an indirect threaded version of
15019: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15020: several native code systems; that version of Gforth is slower on a 486
15021: than the version used here. You can find a newer version of these
15022: measurements at
15023: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
15024: find numbers for Gforth on various machines in @file{Benchres}.
15025:
15026: @c ******************************************************************
15027: @c @node Binding to System Library, Cross Compiler, Engine, Top
15028: @c @chapter Binding to System Library
15029:
15030: @c ****************************************************************
15031: @node Cross Compiler, Bugs, Engine, Top
15032: @chapter Cross Compiler
15033: @cindex @file{cross.fs}
15034: @cindex cross-compiler
15035: @cindex metacompiler
15036: @cindex target compiler
15037:
15038: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15039: mostly written in Forth, including crucial parts like the outer
15040: interpreter and compiler, it needs compiled Forth code to get
15041: started. The cross compiler allows to create new images for other
15042: architectures, even running under another Forth system.
15043:
15044: @menu
15045: * Using the Cross Compiler::
15046: * How the Cross Compiler Works::
15047: @end menu
15048:
15049: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
15050: @section Using the Cross Compiler
15051:
15052: The cross compiler uses a language that resembles Forth, but isn't. The
15053: main difference is that you can execute Forth code after definition,
15054: while you usually can't execute the code compiled by cross, because the
15055: code you are compiling is typically for a different computer than the
15056: one you are compiling on.
15057:
15058: @c anton: This chapter is somewhat different from waht I would expect: I
15059: @c would expect an explanation of the cross language and how to create an
15060: @c application image with it. The section explains some aspects of
15061: @c creating a Gforth kernel.
15062:
15063: The Makefile is already set up to allow you to create kernels for new
15064: architectures with a simple make command. The generic kernels using the
15065: GCC compiled virtual machine are created in the normal build process
15066: with @code{make}. To create a embedded Gforth executable for e.g. the
15067: 8086 processor (running on a DOS machine), type
15068:
15069: @example
15070: make kernl-8086.fi
15071: @end example
15072:
15073: This will use the machine description from the @file{arch/8086}
15074: directory to create a new kernel. A machine file may look like that:
15075:
15076: @example
15077: \ Parameter for target systems 06oct92py
15078:
15079: 4 Constant cell \ cell size in bytes
15080: 2 Constant cell<< \ cell shift to bytes
15081: 5 Constant cell>bit \ cell shift to bits
15082: 8 Constant bits/char \ bits per character
15083: 8 Constant bits/byte \ bits per byte [default: 8]
15084: 8 Constant float \ bytes per float
15085: 8 Constant /maxalign \ maximum alignment in bytes
15086: false Constant bigendian \ byte order
15087: ( true=big, false=little )
15088:
15089: include machpc.fs \ feature list
15090: @end example
15091:
15092: This part is obligatory for the cross compiler itself, the feature list
15093: is used by the kernel to conditionally compile some features in and out,
15094: depending on whether the target supports these features.
15095:
15096: There are some optional features, if you define your own primitives,
15097: have an assembler, or need special, nonstandard preparation to make the
15098: boot process work. @code{asm-include} includes an assembler,
15099: @code{prims-include} includes primitives, and @code{>boot} prepares for
15100: booting.
15101:
15102: @example
15103: : asm-include ." Include assembler" cr
15104: s" arch/8086/asm.fs" included ;
15105:
15106: : prims-include ." Include primitives" cr
15107: s" arch/8086/prim.fs" included ;
15108:
15109: : >boot ." Prepare booting" cr
15110: s" ' boot >body into-forth 1+ !" evaluate ;
15111: @end example
15112:
15113: These words are used as sort of macro during the cross compilation in
15114: the file @file{kernel/main.fs}. Instead of using these macros, it would
15115: be possible --- but more complicated --- to write a new kernel project
15116: file, too.
15117:
15118: @file{kernel/main.fs} expects the machine description file name on the
15119: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15120: @code{mach-file} leaves a counted string on the stack, or
15121: @code{machine-file} leaves an address, count pair of the filename on the
15122: stack.
15123:
15124: The feature list is typically controlled using @code{SetValue}, generic
15125: files that are used by several projects can use @code{DefaultValue}
15126: instead. Both functions work like @code{Value}, when the value isn't
15127: defined, but @code{SetValue} works like @code{to} if the value is
15128: defined, and @code{DefaultValue} doesn't set anything, if the value is
15129: defined.
15130:
15131: @example
15132: \ generic mach file for pc gforth 03sep97jaw
15133:
15134: true DefaultValue NIL \ relocating
15135:
15136: >ENVIRON
15137:
15138: true DefaultValue file \ controls the presence of the
15139: \ file access wordset
15140: true DefaultValue OS \ flag to indicate a operating system
15141:
15142: true DefaultValue prims \ true: primitives are c-code
15143:
15144: true DefaultValue floating \ floating point wordset is present
15145:
15146: true DefaultValue glocals \ gforth locals are present
15147: \ will be loaded
15148: true DefaultValue dcomps \ double number comparisons
15149:
15150: true DefaultValue hash \ hashing primitives are loaded/present
15151:
15152: true DefaultValue xconds \ used together with glocals,
15153: \ special conditionals supporting gforths'
15154: \ local variables
15155: true DefaultValue header \ save a header information
15156:
15157: true DefaultValue backtrace \ enables backtrace code
15158:
15159: false DefaultValue ec
15160: false DefaultValue crlf
15161:
15162: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15163:
15164: &16 KB DefaultValue stack-size
15165: &15 KB &512 + DefaultValue fstack-size
15166: &15 KB DefaultValue rstack-size
15167: &14 KB &512 + DefaultValue lstack-size
15168: @end example
15169:
15170: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
15171: @section How the Cross Compiler Works
15172:
15173: @node Bugs, Origin, Cross Compiler, Top
15174: @appendix Bugs
15175: @cindex bug reporting
15176:
15177: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
15178:
15179: If you find a bug, please submit a bug report through
15180: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
15181:
15182: @itemize @bullet
15183: @item
15184: A program (or a sequence of keyboard commands) that reproduces the bug.
15185: @item
15186: A description of what you think constitutes the buggy behaviour.
15187: @item
15188: The Gforth version used (it is announced at the start of an
15189: interactive Gforth session).
15190: @item
15191: The machine and operating system (on Unix
15192: systems @code{uname -a} will report this information).
15193: @item
15194: The installation options (you can find the configure options at the
15195: start of @file{config.status}) and configuration (@code{configure}
15196: output or @file{config.cache}).
15197: @item
15198: A complete list of changes (if any) you (or your installer) have made to the
15199: Gforth sources.
15200: @end itemize
15201:
15202: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15203: to Report Bugs, gcc.info, GNU C Manual}.
15204:
15205:
15206: @node Origin, Forth-related information, Bugs, Top
15207: @appendix Authors and Ancestors of Gforth
15208:
15209: @section Authors and Contributors
15210: @cindex authors of Gforth
15211: @cindex contributors to Gforth
15212:
15213: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
15214: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15215: lot to the manual. Assemblers and disassemblers were contributed by
15216: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
15217: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15218: inspired us with their continuous feedback. Lennart Benshop contributed
15219: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15220: support for calling C libraries. Helpful comments also came from Paul
15221: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
15222: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert
15223: Epprecht, Dennis Ruffer and David N. Williams. Since the release of
15224: Gforth-0.2.1 there were also helpful comments from many others; thank
15225: you all, sorry for not listing you here (but digging through my mailbox
15226: to extract your names is on my to-do list).
15227:
15228: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15229: and autoconf, among others), and to the creators of the Internet: Gforth
15230: was developed across the Internet, and its authors did not meet
15231: physically for the first 4 years of development.
15232:
15233: @section Pedigree
15234: @cindex pedigree of Gforth
15235:
15236: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15237: significant part of the design of Gforth was prescribed by ANS Forth.
15238:
15239: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
15240: 32 bit native code version of VolksForth for the Atari ST, written
15241: mostly by Dietrich Weineck.
15242:
15243: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15244: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
15245: the mid-80s and ported to the Atari ST in 1986. It descends from F83.
15246:
15247: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15248: Forth-83 standard. !! Pedigree? When?
15249:
15250: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15251: 1979. Robert Selzer and Bill Ragsdale developed the original
15252: implementation of fig-Forth for the 6502 based on microForth.
15253:
15254: The principal architect of microForth was Dean Sanderson. microForth was
15255: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15256: the 1802, and subsequently implemented on the 8080, the 6800 and the
15257: Z80.
15258:
15259: All earlier Forth systems were custom-made, usually by Charles Moore,
15260: who discovered (as he puts it) Forth during the late 60s. The first full
15261: Forth existed in 1971.
15262:
15263: A part of the information in this section comes from
15264: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15265: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
15266: Charles H. Moore, presented at the HOPL-II conference and preprinted in
15267: SIGPLAN Notices 28(3), 1993. You can find more historical and
15268: genealogical information about Forth there.
15269:
15270: @c ------------------------------------------------------------------
15271: @node Forth-related information, Licenses, Origin, Top
15272: @appendix Other Forth-related information
15273: @cindex Forth-related information
15274:
15275: @c anton: I threw most of this stuff out, because it can be found through
15276: @c the FAQ and the FAQ is more likely to be up-to-date.
15277:
15278: @cindex comp.lang.forth
15279: @cindex frequently asked questions
15280: There is an active news group (comp.lang.forth) discussing Forth
15281: (including Gforth) and Forth-related issues. Its
15282: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15283: (frequently asked questions and their answers) contains a lot of
15284: information on Forth. You should read it before posting to
15285: comp.lang.forth.
15286:
15287: The ANS Forth standard is most usable in its
15288: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
15289:
15290: @c ---------------------------------------------------
15291: @node Licenses, Word Index, Forth-related information, Top
15292: @appendix Licenses
15293:
15294: @menu
15295: * GNU Free Documentation License:: License for copying this manual.
15296: * Copying:: GPL (for copying this software).
15297: @end menu
15298:
15299: @include fdl.texi
15300:
15301: @include gpl.texi
15302:
15303:
15304:
15305: @c ------------------------------------------------------------------
15306: @node Word Index, Concept Index, Licenses, Top
15307: @unnumbered Word Index
15308:
15309: This index is a list of Forth words that have ``glossary'' entries
15310: within this manual. Each word is listed with its stack effect and
15311: wordset.
15312:
15313: @printindex fn
15314:
15315: @c anton: the name index seems superfluous given the word and concept indices.
15316:
15317: @c @node Name Index, Concept Index, Word Index, Top
15318: @c @unnumbered Name Index
15319:
15320: @c This index is a list of Forth words that have ``glossary'' entries
15321: @c within this manual.
15322:
15323: @c @printindex ky
15324:
15325: @c -------------------------------------------------------
15326: @node Concept Index, , Word Index, Top
15327: @unnumbered Concept and Word Index
15328:
15329: Not all entries listed in this index are present verbatim in the
15330: text. This index also duplicates, in abbreviated form, all of the words
15331: listed in the Word Index (only the names are listed for the words here).
15332:
15333: @printindex cp
15334:
15335: @bye
15336:
15337:
15338:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>