File:
[gforth] /
gforth /
doc /
gforth.ds
Revision
1.159:
download - view:
text,
annotated -
select for diffs
Sat May 20 07:07:29 2006 UTC (17 years, 10 months ago) by
anton
Branches:
MAIN
CVS tags:
HEAD
Makefile: undid change requiring gforth-fast to build first
other changes for packaging
added POST_INSTALL etc. tags
Updated NEWS files to 2006-05-07
minor documentation changes
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, 2004,2005 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: * C Interface::
227: * Assembler and Code Words::
228: * Threading Words::
229: * Passing Commands to the OS::
230: * Keeping track of Time::
231: * Miscellaneous Words::
232:
233: Arithmetic
234:
235: * Single precision::
236: * Double precision:: Double-cell integer arithmetic
237: * Bitwise operations::
238: * Numeric comparison::
239: * Mixed precision:: Operations with single and double-cell integers
240: * Floating Point::
241:
242: Stack Manipulation
243:
244: * Data stack::
245: * Floating point stack::
246: * Return stack::
247: * Locals stack::
248: * Stack pointer manipulation::
249:
250: Memory
251:
252: * Memory model::
253: * Dictionary allocation::
254: * Heap Allocation::
255: * Memory Access::
256: * Address arithmetic::
257: * Memory Blocks::
258:
259: Control Structures
260:
261: * Selection:: IF ... ELSE ... ENDIF
262: * Simple Loops:: BEGIN ...
263: * Counted Loops:: DO
264: * Arbitrary control structures::
265: * Calls and returns::
266: * Exception Handling::
267:
268: Defining Words
269:
270: * CREATE::
271: * Variables:: Variables and user variables
272: * Constants::
273: * Values:: Initialised variables
274: * Colon Definitions::
275: * Anonymous Definitions:: Definitions without names
276: * Supplying names:: Passing definition names as strings
277: * User-defined Defining Words::
278: * Deferred words:: Allow forward references
279: * Aliases::
280:
281: User-defined Defining Words
282:
283: * CREATE..DOES> applications::
284: * CREATE..DOES> details::
285: * Advanced does> usage example::
286: * Const-does>::
287:
288: Interpretation and Compilation Semantics
289:
290: * Combined words::
291:
292: Tokens for Words
293:
294: * Execution token:: represents execution/interpretation semantics
295: * Compilation token:: represents compilation semantics
296: * Name token:: represents named words
297:
298: Compiling words
299:
300: * Literals:: Compiling data values
301: * Macros:: Compiling words
302:
303: The Text Interpreter
304:
305: * Input Sources::
306: * Number Conversion::
307: * Interpret/Compile states::
308: * Interpreter Directives::
309:
310: Word Lists
311:
312: * Vocabularies::
313: * Why use word lists?::
314: * Word list example::
315:
316: Files
317:
318: * Forth source files::
319: * General files::
320: * Search Paths::
321:
322: Search Paths
323:
324: * Source Search Paths::
325: * General Search Paths::
326:
327: Other I/O
328:
329: * Simple numeric output:: Predefined formats
330: * Formatted numeric output:: Formatted (pictured) output
331: * String Formats:: How Forth stores strings in memory
332: * Displaying characters and strings:: Other stuff
333: * Input:: Input
334: * Pipes:: How to create your own pipes
335: * Xchars and Unicode:: Non-ASCII characters
336:
337: Locals
338:
339: * Gforth locals::
340: * ANS Forth locals::
341:
342: Gforth locals
343:
344: * Where are locals visible by name?::
345: * How long do locals live?::
346: * Locals programming style::
347: * Locals implementation::
348:
349: Structures
350:
351: * Why explicit structure support?::
352: * Structure Usage::
353: * Structure Naming Convention::
354: * Structure Implementation::
355: * Structure Glossary::
356:
357: Object-oriented Forth
358:
359: * Why object-oriented programming?::
360: * Object-Oriented Terminology::
361: * Objects::
362: * OOF::
363: * Mini-OOF::
364: * Comparison with other object models::
365:
366: The @file{objects.fs} model
367:
368: * Properties of the Objects model::
369: * Basic Objects Usage::
370: * The Objects base class::
371: * Creating objects::
372: * Object-Oriented Programming Style::
373: * Class Binding::
374: * Method conveniences::
375: * Classes and Scoping::
376: * Dividing classes::
377: * Object Interfaces::
378: * Objects Implementation::
379: * Objects Glossary::
380:
381: The @file{oof.fs} model
382:
383: * Properties of the OOF model::
384: * Basic OOF Usage::
385: * The OOF base class::
386: * Class Declaration::
387: * Class Implementation::
388:
389: The @file{mini-oof.fs} model
390:
391: * Basic Mini-OOF Usage::
392: * Mini-OOF Example::
393: * Mini-OOF Implementation::
394:
395: Programming Tools
396:
397: * Examining:: Data and Code.
398: * Forgetting words:: Usually before reloading.
399: * Debugging:: Simple and quick.
400: * Assertions:: Making your programs self-checking.
401: * Singlestep Debugger:: Executing your program word by word.
402:
403: C Interface
404:
405: * Calling C Functions::
406: * Declaring C Functions::
407: * Callbacks::
408: * Low-Level C Interface Words::
409:
410: Assembler and Code Words
411:
412: * Code and ;code::
413: * Common Assembler:: Assembler Syntax
414: * Common Disassembler::
415: * 386 Assembler:: Deviations and special cases
416: * Alpha Assembler:: Deviations and special cases
417: * MIPS assembler:: Deviations and special cases
418: * Other assemblers:: How to write them
419:
420: Tools
421:
422: * ANS Report:: Report the words used, sorted by wordset.
423: * Stack depth changes:: Where does this stack item come from?
424:
425: ANS conformance
426:
427: * The Core Words::
428: * The optional Block word set::
429: * The optional Double Number word set::
430: * The optional Exception word set::
431: * The optional Facility word set::
432: * The optional File-Access word set::
433: * The optional Floating-Point word set::
434: * The optional Locals word set::
435: * The optional Memory-Allocation word set::
436: * The optional Programming-Tools word set::
437: * The optional Search-Order word set::
438:
439: The Core Words
440:
441: * core-idef:: Implementation Defined Options
442: * core-ambcond:: Ambiguous Conditions
443: * core-other:: Other System Documentation
444:
445: The optional Block word set
446:
447: * block-idef:: Implementation Defined Options
448: * block-ambcond:: Ambiguous Conditions
449: * block-other:: Other System Documentation
450:
451: The optional Double Number word set
452:
453: * double-ambcond:: Ambiguous Conditions
454:
455: The optional Exception word set
456:
457: * exception-idef:: Implementation Defined Options
458:
459: The optional Facility word set
460:
461: * facility-idef:: Implementation Defined Options
462: * facility-ambcond:: Ambiguous Conditions
463:
464: The optional File-Access word set
465:
466: * file-idef:: Implementation Defined Options
467: * file-ambcond:: Ambiguous Conditions
468:
469: The optional Floating-Point word set
470:
471: * floating-idef:: Implementation Defined Options
472: * floating-ambcond:: Ambiguous Conditions
473:
474: The optional Locals word set
475:
476: * locals-idef:: Implementation Defined Options
477: * locals-ambcond:: Ambiguous Conditions
478:
479: The optional Memory-Allocation word set
480:
481: * memory-idef:: Implementation Defined Options
482:
483: The optional Programming-Tools word set
484:
485: * programming-idef:: Implementation Defined Options
486: * programming-ambcond:: Ambiguous Conditions
487:
488: The optional Search-Order word set
489:
490: * search-idef:: Implementation Defined Options
491: * search-ambcond:: Ambiguous Conditions
492:
493: Emacs and Gforth
494:
495: * Installing gforth.el:: Making Emacs aware of Forth.
496: * Emacs Tags:: Viewing the source of a word in Emacs.
497: * Hilighting:: Making Forth code look prettier.
498: * Auto-Indentation:: Customizing auto-indentation.
499: * Blocks Files:: Reading and writing blocks files.
500:
501: Image Files
502:
503: * Image Licensing Issues:: Distribution terms for images.
504: * Image File Background:: Why have image files?
505: * Non-Relocatable Image Files:: don't always work.
506: * Data-Relocatable Image Files:: are better.
507: * Fully Relocatable Image Files:: better yet.
508: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
509: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
510: * Modifying the Startup Sequence:: and turnkey applications.
511:
512: Fully Relocatable Image Files
513:
514: * gforthmi:: The normal way
515: * cross.fs:: The hard way
516:
517: Engine
518:
519: * Portability::
520: * Threading::
521: * Primitives::
522: * Performance::
523:
524: Threading
525:
526: * Scheduling::
527: * Direct or Indirect Threaded?::
528: * Dynamic Superinstructions::
529: * DOES>::
530:
531: Primitives
532:
533: * Automatic Generation::
534: * TOS Optimization::
535: * Produced code::
536:
537: Cross Compiler
538:
539: * Using the Cross Compiler::
540: * How the Cross Compiler Works::
541:
542: Licenses
543:
544: * GNU Free Documentation License:: License for copying this manual.
545: * Copying:: GPL (for copying this software).
546:
547: @end detailmenu
548: @end menu
549:
550: @c ----------------------------------------------------------
551: @iftex
552: @unnumbered Preface
553: @cindex Preface
554: This manual documents Gforth. Some introductory material is provided for
555: readers who are unfamiliar with Forth or who are migrating to Gforth
556: from other Forth compilers. However, this manual is primarily a
557: reference manual.
558: @end iftex
559:
560: @comment TODO much more blurb here.
561:
562: @c ******************************************************************
563: @node Goals, Gforth Environment, Top, Top
564: @comment node-name, next, previous, up
565: @chapter Goals of Gforth
566: @cindex goals of the Gforth project
567: The goal of the Gforth Project is to develop a standard model for
568: ANS Forth. This can be split into several subgoals:
569:
570: @itemize @bullet
571: @item
572: Gforth should conform to the ANS Forth Standard.
573: @item
574: It should be a model, i.e. it should define all the
575: implementation-dependent things.
576: @item
577: It should become standard, i.e. widely accepted and used. This goal
578: is the most difficult one.
579: @end itemize
580:
581: To achieve these goals Gforth should be
582: @itemize @bullet
583: @item
584: Similar to previous models (fig-Forth, F83)
585: @item
586: Powerful. It should provide for all the things that are considered
587: necessary today and even some that are not yet considered necessary.
588: @item
589: Efficient. It should not get the reputation of being exceptionally
590: slow.
591: @item
592: Free.
593: @item
594: Available on many machines/easy to port.
595: @end itemize
596:
597: Have we achieved these goals? Gforth conforms to the ANS Forth
598: standard. It may be considered a model, but we have not yet documented
599: which parts of the model are stable and which parts we are likely to
600: change. It certainly has not yet become a de facto standard, but it
601: appears to be quite popular. It has some similarities to and some
602: differences from previous models. It has some powerful features, but not
603: yet everything that we envisioned. We certainly have achieved our
604: execution speed goals (@pxref{Performance})@footnote{However, in 1998
605: the bar was raised when the major commercial Forth vendors switched to
606: native code compilers.}. It is free and available on many machines.
607:
608: @c ******************************************************************
609: @node Gforth Environment, Tutorial, Goals, Top
610: @chapter Gforth Environment
611: @cindex Gforth environment
612:
613: Note: ultimately, the Gforth man page will be auto-generated from the
614: material in this chapter.
615:
616: @menu
617: * Invoking Gforth:: Getting in
618: * Leaving Gforth:: Getting out
619: * Command-line editing::
620: * Environment variables:: that affect how Gforth starts up
621: * Gforth Files:: What gets installed and where
622: * Gforth in pipes::
623: * Startup speed:: When 35ms is not fast enough ...
624: @end menu
625:
626: For related information about the creation of images see @ref{Image Files}.
627:
628: @comment ----------------------------------------------
629: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
630: @section Invoking Gforth
631: @cindex invoking Gforth
632: @cindex running Gforth
633: @cindex command-line options
634: @cindex options on the command line
635: @cindex flags on the command line
636:
637: Gforth is made up of two parts; an executable ``engine'' (named
638: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
639: will usually just say @code{gforth} -- this automatically loads the
640: default image file @file{gforth.fi}. In many other cases the default
641: Gforth image will be invoked like this:
642: @example
643: gforth [file | -e forth-code] ...
644: @end example
645: @noindent
646: This interprets the contents of the files and the Forth code in the order they
647: are given.
648:
649: In addition to the @command{gforth} engine, there is also an engine
650: called @command{gforth-fast}, which is faster, but gives less
651: informative error messages (@pxref{Error messages}) and may catch some
652: stack underflows later or not at all. You should use it for debugged,
653: performance-critical programs.
654:
655: Moreover, there is an engine called @command{gforth-itc}, which is
656: useful in some backwards-compatibility situations (@pxref{Direct or
657: Indirect Threaded?}).
658:
659: In general, the command line looks like this:
660:
661: @example
662: gforth[-fast] [engine options] [image options]
663: @end example
664:
665: The engine options must come before the rest of the command
666: line. They are:
667:
668: @table @code
669: @cindex -i, command-line option
670: @cindex --image-file, command-line option
671: @item --image-file @i{file}
672: @itemx -i @i{file}
673: Loads the Forth image @i{file} instead of the default
674: @file{gforth.fi} (@pxref{Image Files}).
675:
676: @cindex --appl-image, command-line option
677: @item --appl-image @i{file}
678: Loads the image @i{file} and leaves all further command-line arguments
679: to the image (instead of processing them as engine options). This is
680: useful for building executable application images on Unix, built with
681: @code{gforthmi --application ...}.
682:
683: @cindex --path, command-line option
684: @cindex -p, command-line option
685: @item --path @i{path}
686: @itemx -p @i{path}
687: Uses @i{path} for searching the image file and Forth source code files
688: instead of the default in the environment variable @code{GFORTHPATH} or
689: the path specified at installation time (e.g.,
690: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
691: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
692:
693: @cindex --dictionary-size, command-line option
694: @cindex -m, command-line option
695: @cindex @i{size} parameters for command-line options
696: @cindex size of the dictionary and the stacks
697: @item --dictionary-size @i{size}
698: @itemx -m @i{size}
699: Allocate @i{size} space for the Forth dictionary space instead of
700: using the default specified in the image (typically 256K). The
701: @i{size} specification for this and subsequent options consists of
702: an integer and a unit (e.g.,
703: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
704: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
705: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
706: @code{e} is used.
707:
708: @cindex --data-stack-size, command-line option
709: @cindex -d, command-line option
710: @item --data-stack-size @i{size}
711: @itemx -d @i{size}
712: Allocate @i{size} space for the data stack instead of using the
713: default specified in the image (typically 16K).
714:
715: @cindex --return-stack-size, command-line option
716: @cindex -r, command-line option
717: @item --return-stack-size @i{size}
718: @itemx -r @i{size}
719: Allocate @i{size} space for the return stack instead of using the
720: default specified in the image (typically 15K).
721:
722: @cindex --fp-stack-size, command-line option
723: @cindex -f, command-line option
724: @item --fp-stack-size @i{size}
725: @itemx -f @i{size}
726: Allocate @i{size} space for the floating point stack instead of
727: using the default specified in the image (typically 15.5K). In this case
728: the unit specifier @code{e} refers to floating point numbers.
729:
730: @cindex --locals-stack-size, command-line option
731: @cindex -l, command-line option
732: @item --locals-stack-size @i{size}
733: @itemx -l @i{size}
734: Allocate @i{size} space for the locals stack instead of using the
735: default specified in the image (typically 14.5K).
736:
737: @cindex -h, command-line option
738: @cindex --help, command-line option
739: @item --help
740: @itemx -h
741: Print a message about the command-line options
742:
743: @cindex -v, command-line option
744: @cindex --version, command-line option
745: @item --version
746: @itemx -v
747: Print version and exit
748:
749: @cindex --debug, command-line option
750: @item --debug
751: Print some information useful for debugging on startup.
752:
753: @cindex --offset-image, command-line option
754: @item --offset-image
755: Start the dictionary at a slightly different position than would be used
756: otherwise (useful for creating data-relocatable images,
757: @pxref{Data-Relocatable Image Files}).
758:
759: @cindex --no-offset-im, command-line option
760: @item --no-offset-im
761: Start the dictionary at the normal position.
762:
763: @cindex --clear-dictionary, command-line option
764: @item --clear-dictionary
765: Initialize all bytes in the dictionary to 0 before loading the image
766: (@pxref{Data-Relocatable Image Files}).
767:
768: @cindex --die-on-signal, command-line-option
769: @item --die-on-signal
770: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
771: or the segmentation violation SIGSEGV) by translating it into a Forth
772: @code{THROW}. With this option, Gforth exits if it receives such a
773: signal. This option is useful when the engine and/or the image might be
774: severely broken (such that it causes another signal before recovering
775: from the first); this option avoids endless loops in such cases.
776:
777: @cindex --no-dynamic, command-line option
778: @cindex --dynamic, command-line option
779: @item --no-dynamic
780: @item --dynamic
781: Disable or enable dynamic superinstructions with replication
782: (@pxref{Dynamic Superinstructions}).
783:
784: @cindex --no-super, command-line option
785: @item --no-super
786: Disable dynamic superinstructions, use just dynamic replication; this is
787: useful if you want to patch threaded code (@pxref{Dynamic
788: Superinstructions}).
789:
790: @cindex --ss-number, command-line option
791: @item --ss-number=@var{N}
792: Use only the first @var{N} static superinstructions compiled into the
793: engine (default: use them all; note that only @code{gforth-fast} has
794: any). This option is useful for measuring the performance impact of
795: static superinstructions.
796:
797: @cindex --ss-min-..., command-line options
798: @item --ss-min-codesize
799: @item --ss-min-ls
800: @item --ss-min-lsu
801: @item --ss-min-nexts
802: Use specified metric for determining the cost of a primitive or static
803: superinstruction for static superinstruction selection. @code{Codesize}
804: is the native code size of the primive or static superinstruction,
805: @code{ls} is the number of loads and stores, @code{lsu} is the number of
806: loads, stores, and updates, and @code{nexts} is the number of dispatches
807: (not taking dynamic superinstructions into account), i.e. every
808: primitive or static superinstruction has cost 1. Default:
809: @code{codesize} if you use dynamic code generation, otherwise
810: @code{nexts}.
811:
812: @cindex --ss-greedy, command-line option
813: @item --ss-greedy
814: This option is useful for measuring the performance impact of static
815: superinstructions. By default, an optimal shortest-path algorithm is
816: used for selecting static superinstructions. With @option{--ss-greedy}
817: this algorithm is modified to assume that anything after the static
818: superinstruction currently under consideration is not combined into
819: static superinstructions. With @option{--ss-min-nexts} this produces
820: the same result as a greedy algorithm that always selects the longest
821: superinstruction available at the moment. E.g., if there are
822: superinstructions AB and BCD, then for the sequence A B C D the optimal
823: algorithm will select A BCD and the greedy algorithm will select AB C D.
824:
825: @cindex --print-metrics, command-line option
826: @item --print-metrics
827: Prints some metrics used during static superinstruction selection:
828: @code{code size} is the actual size of the dynamically generated code.
829: @code{Metric codesize} is the sum of the codesize metrics as seen by
830: static superinstruction selection; there is a difference from @code{code
831: size}, because not all primitives and static superinstructions are
832: compiled into dynamically generated code, and because of markers. The
833: other metrics correspond to the @option{ss-min-...} options. This
834: option is useful for evaluating the effects of the @option{--ss-...}
835: options.
836:
837: @end table
838:
839: @cindex loading files at startup
840: @cindex executing code on startup
841: @cindex batch processing with Gforth
842: As explained above, the image-specific command-line arguments for the
843: default image @file{gforth.fi} consist of a sequence of filenames and
844: @code{-e @var{forth-code}} options that are interpreted in the sequence
845: in which they are given. The @code{-e @var{forth-code}} or
846: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
847: option takes only one argument; if you want to evaluate more Forth
848: words, you have to quote them or use @code{-e} several times. To exit
849: after processing the command line (instead of entering interactive mode)
850: append @code{-e bye} to the command line. You can also process the
851: command-line arguments with a Forth program (@pxref{OS command line
852: arguments}).
853:
854: @cindex versions, invoking other versions of Gforth
855: If you have several versions of Gforth installed, @code{gforth} will
856: invoke the version that was installed last. @code{gforth-@i{version}}
857: invokes a specific version. If your environment contains the variable
858: @code{GFORTHPATH}, you may want to override it by using the
859: @code{--path} option.
860:
861: Not yet implemented:
862: On startup the system first executes the system initialization file
863: (unless the option @code{--no-init-file} is given; note that the system
864: resulting from using this option may not be ANS Forth conformant). Then
865: the user initialization file @file{.gforth.fs} is executed, unless the
866: option @code{--no-rc} is given; this file is searched for in @file{.},
867: then in @file{~}, then in the normal path (see above).
868:
869:
870:
871: @comment ----------------------------------------------
872: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
873: @section Leaving Gforth
874: @cindex Gforth - leaving
875: @cindex leaving Gforth
876:
877: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
878: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
879: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
880: data are discarded. For ways of saving the state of the system before
881: leaving Gforth see @ref{Image Files}.
882:
883: doc-bye
884:
885:
886: @comment ----------------------------------------------
887: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
888: @section Command-line editing
889: @cindex command-line editing
890:
891: Gforth maintains a history file that records every line that you type to
892: the text interpreter. This file is preserved between sessions, and is
893: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
894: repeatedly you can recall successively older commands from this (or
895: previous) session(s). The full list of command-line editing facilities is:
896:
897: @itemize @bullet
898: @item
899: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
900: commands from the history buffer.
901: @item
902: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
903: from the history buffer.
904: @item
905: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
906: @item
907: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
908: @item
909: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
910: closing up the line.
911: @item
912: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
913: @item
914: @kbd{Ctrl-a} to move the cursor to the start of the line.
915: @item
916: @kbd{Ctrl-e} to move the cursor to the end of the line.
917: @item
918: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
919: line.
920: @item
921: @key{TAB} to step through all possible full-word completions of the word
922: currently being typed.
923: @item
924: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
925: using @code{bye}).
926: @item
927: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
928: character under the cursor.
929: @end itemize
930:
931: When editing, displayable characters are inserted to the left of the
932: cursor position; the line is always in ``insert'' (as opposed to
933: ``overstrike'') mode.
934:
935: @cindex history file
936: @cindex @file{.gforth-history}
937: On Unix systems, the history file is @file{~/.gforth-history} by
938: default@footnote{i.e. it is stored in the user's home directory.}. You
939: can find out the name and location of your history file using:
940:
941: @example
942: history-file type \ Unix-class systems
943:
944: history-file type \ Other systems
945: history-dir type
946: @end example
947:
948: If you enter long definitions by hand, you can use a text editor to
949: paste them out of the history file into a Forth source file for reuse at
950: a later time.
951:
952: Gforth never trims the size of the history file, so you should do this
953: periodically, if necessary.
954:
955: @comment this is all defined in history.fs
956: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
957: @comment chosen?
958:
959:
960: @comment ----------------------------------------------
961: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
962: @section Environment variables
963: @cindex environment variables
964:
965: Gforth uses these environment variables:
966:
967: @itemize @bullet
968: @item
969: @cindex @code{GFORTHHIST} -- environment variable
970: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
971: open/create the history file, @file{.gforth-history}. Default:
972: @code{$HOME}.
973:
974: @item
975: @cindex @code{GFORTHPATH} -- environment variable
976: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
977: for Forth source-code files.
978:
979: @item
980: @cindex @code{LANG} -- environment variable
981: @code{LANG} -- see @code{LC_CTYPE}
982:
983: @item
984: @cindex @code{LC_ALL} -- environment variable
985: @code{LC_ALL} -- see @code{LC_CTYPE}
986:
987: @item
988: @cindex @code{LC_CTYPE} -- environment variable
989: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
990: startup, Gforth uses the UTF-8 encoding for strings internally and
991: expects its input and produces its output in UTF-8 encoding, otherwise
992: the encoding is 8bit (see @pxref{Xchars and Unicode}). If this
993: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
994: that is unset, in @code{LANG}.
995:
996: @item
997: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
998:
999: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
1000: of @code{system} before passing it to C's @code{system()}. Default:
1001: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1002: and the command are directly concatenated, so if a space between them is
1003: necessary, append it to the prefix.
1004:
1005: @item
1006: @cindex @code{GFORTH} -- environment variable
1007: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1008:
1009: @item
1010: @cindex @code{GFORTHD} -- environment variable
1011: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1012:
1013: @item
1014: @cindex @code{TMP}, @code{TEMP} - environment variable
1015: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1016: location for the history file.
1017: @end itemize
1018:
1019: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1020: @comment mentioning these.
1021:
1022: All the Gforth environment variables default to sensible values if they
1023: are not set.
1024:
1025:
1026: @comment ----------------------------------------------
1027: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1028: @section Gforth files
1029: @cindex Gforth files
1030:
1031: When you install Gforth on a Unix system, it installs files in these
1032: locations by default:
1033:
1034: @itemize @bullet
1035: @item
1036: @file{/usr/local/bin/gforth}
1037: @item
1038: @file{/usr/local/bin/gforthmi}
1039: @item
1040: @file{/usr/local/man/man1/gforth.1} - man page.
1041: @item
1042: @file{/usr/local/info} - the Info version of this manual.
1043: @item
1044: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1045: @item
1046: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1047: @item
1048: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1049: @item
1050: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1051: @end itemize
1052:
1053: You can select different places for installation by using
1054: @code{configure} options (listed with @code{configure --help}).
1055:
1056: @comment ----------------------------------------------
1057: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1058: @section Gforth in pipes
1059: @cindex pipes, Gforth as part of
1060:
1061: Gforth can be used in pipes created elsewhere (described here). It can
1062: also create pipes on its own (@pxref{Pipes}).
1063:
1064: @cindex input from pipes
1065: If you pipe into Gforth, your program should read with @code{read-file}
1066: or @code{read-line} from @code{stdin} (@pxref{General files}).
1067: @code{Key} does not recognize the end of input. Words like
1068: @code{accept} echo the input and are therefore usually not useful for
1069: reading from a pipe. You have to invoke the Forth program with an OS
1070: command-line option, as you have no chance to use the Forth command line
1071: (the text interpreter would try to interpret the pipe input).
1072:
1073: @cindex output in pipes
1074: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1075:
1076: @cindex silent exiting from Gforth
1077: When you write to a pipe that has been closed at the other end, Gforth
1078: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1079: into the exception @code{broken-pipe-error}. If your application does
1080: not catch that exception, the system catches it and exits, usually
1081: silently (unless you were working on the Forth command line; then it
1082: prints an error message and exits). This is usually the desired
1083: behaviour.
1084:
1085: If you do not like this behaviour, you have to catch the exception
1086: yourself, and react to it.
1087:
1088: Here's an example of an invocation of Gforth that is usable in a pipe:
1089:
1090: @example
1091: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1092: type repeat ; foo bye"
1093: @end example
1094:
1095: This example just copies the input verbatim to the output. A very
1096: simple pipe containing this example looks like this:
1097:
1098: @example
1099: cat startup.fs |
1100: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1101: type repeat ; foo bye"|
1102: head
1103: @end example
1104:
1105: @cindex stderr and pipes
1106: Pipes involving Gforth's @code{stderr} output do not work.
1107:
1108: @comment ----------------------------------------------
1109: @node Startup speed, , Gforth in pipes, Gforth Environment
1110: @section Startup speed
1111: @cindex Startup speed
1112: @cindex speed, startup
1113:
1114: If Gforth is used for CGI scripts or in shell scripts, its startup
1115: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1116: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1117: system time.
1118:
1119: If startup speed is a problem, you may consider the following ways to
1120: improve it; or you may consider ways to reduce the number of startups
1121: (for example, by using Fast-CGI).
1122:
1123: An easy step that influences Gforth startup speed is the use of the
1124: @option{--no-dynamic} option; this decreases image loading speed, but
1125: increases compile-time and run-time.
1126:
1127: Another step to improve startup speed is to statically link Gforth, by
1128: building it with @code{XLDFLAGS=-static}. This requires more memory for
1129: the code and will therefore slow down the first invocation, but
1130: subsequent invocations avoid the dynamic linking overhead. Another
1131: disadvantage is that Gforth won't profit from library upgrades. As a
1132: result, @code{gforth-static -e bye} takes about 17.1ms user and
1133: 8.2ms system time.
1134:
1135: The next step to improve startup speed is to use a non-relocatable image
1136: (@pxref{Non-Relocatable Image Files}). You can create this image with
1137: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1138: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1139: and a part of the copy-on-write overhead. The disadvantage is that the
1140: non-relocatable image does not work if the OS gives Gforth a different
1141: address for the dictionary, for whatever reason; so you better provide a
1142: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1143: bye} takes about 15.3ms user and 7.5ms system time.
1144:
1145: The final step is to disable dictionary hashing in Gforth. Gforth
1146: builds the hash table on startup, which takes much of the startup
1147: overhead. You can do this by commenting out the @code{include hash.fs}
1148: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1149: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1150: The disadvantages are that functionality like @code{table} and
1151: @code{ekey} is missing and that text interpretation (e.g., compiling)
1152: now takes much longer. So, you should only use this method if there is
1153: no significant text interpretation to perform (the script should be
1154: compiled into the image, amongst other things). @code{gforth-static -i
1155: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1156:
1157: @c ******************************************************************
1158: @node Tutorial, Introduction, Gforth Environment, Top
1159: @chapter Forth Tutorial
1160: @cindex Tutorial
1161: @cindex Forth Tutorial
1162:
1163: @c Topics from nac's Introduction that could be mentioned:
1164: @c press <ret> after each line
1165: @c Prompt
1166: @c numbers vs. words in dictionary on text interpretation
1167: @c what happens on redefinition
1168: @c parsing words (in particular, defining words)
1169:
1170: The difference of this chapter from the Introduction
1171: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1172: be used while sitting in front of a computer, and covers much more
1173: material, but does not explain how the Forth system works.
1174:
1175: This tutorial can be used with any ANS-compliant Forth; any
1176: Gforth-specific features are marked as such and you can skip them if you
1177: work with another Forth. This tutorial does not explain all features of
1178: Forth, just enough to get you started and give you some ideas about the
1179: facilities available in Forth. Read the rest of the manual and the
1180: standard when you are through this.
1181:
1182: The intended way to use this tutorial is that you work through it while
1183: sitting in front of the console, take a look at the examples and predict
1184: what they will do, then try them out; if the outcome is not as expected,
1185: find out why (e.g., by trying out variations of the example), so you
1186: understand what's going on. There are also some assignments that you
1187: should solve.
1188:
1189: This tutorial assumes that you have programmed before and know what,
1190: e.g., a loop is.
1191:
1192: @c !! explain compat library
1193:
1194: @menu
1195: * Starting Gforth Tutorial::
1196: * Syntax Tutorial::
1197: * Crash Course Tutorial::
1198: * Stack Tutorial::
1199: * Arithmetics Tutorial::
1200: * Stack Manipulation Tutorial::
1201: * Using files for Forth code Tutorial::
1202: * Comments Tutorial::
1203: * Colon Definitions Tutorial::
1204: * Decompilation Tutorial::
1205: * Stack-Effect Comments Tutorial::
1206: * Types Tutorial::
1207: * Factoring Tutorial::
1208: * Designing the stack effect Tutorial::
1209: * Local Variables Tutorial::
1210: * Conditional execution Tutorial::
1211: * Flags and Comparisons Tutorial::
1212: * General Loops Tutorial::
1213: * Counted loops Tutorial::
1214: * Recursion Tutorial::
1215: * Leaving definitions or loops Tutorial::
1216: * Return Stack Tutorial::
1217: * Memory Tutorial::
1218: * Characters and Strings Tutorial::
1219: * Alignment Tutorial::
1220: * Files Tutorial::
1221: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1222: * Execution Tokens Tutorial::
1223: * Exceptions Tutorial::
1224: * Defining Words Tutorial::
1225: * Arrays and Records Tutorial::
1226: * POSTPONE Tutorial::
1227: * Literal Tutorial::
1228: * Advanced macros Tutorial::
1229: * Compilation Tokens Tutorial::
1230: * Wordlists and Search Order Tutorial::
1231: @end menu
1232:
1233: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1234: @section Starting Gforth
1235: @cindex starting Gforth tutorial
1236: You can start Gforth by typing its name:
1237:
1238: @example
1239: gforth
1240: @end example
1241:
1242: That puts you into interactive mode; you can leave Gforth by typing
1243: @code{bye}. While in Gforth, you can edit the command line and access
1244: the command line history with cursor keys, similar to bash.
1245:
1246:
1247: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1248: @section Syntax
1249: @cindex syntax tutorial
1250:
1251: A @dfn{word} is a sequence of arbitrary characters (expcept white
1252: space). Words are separated by white space. E.g., each of the
1253: following lines contains exactly one word:
1254:
1255: @example
1256: word
1257: !@@#$%^&*()
1258: 1234567890
1259: 5!a
1260: @end example
1261:
1262: A frequent beginner's error is to leave away necessary white space,
1263: resulting in an error like @samp{Undefined word}; so if you see such an
1264: error, check if you have put spaces wherever necessary.
1265:
1266: @example
1267: ." hello, world" \ correct
1268: ."hello, world" \ gives an "Undefined word" error
1269: @end example
1270:
1271: Gforth and most other Forth systems ignore differences in case (they are
1272: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1273: your system is case-sensitive, you may have to type all the examples
1274: given here in upper case.
1275:
1276:
1277: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1278: @section Crash Course
1279:
1280: Type
1281:
1282: @example
1283: 0 0 !
1284: here execute
1285: ' catch >body 20 erase abort
1286: ' (quit) >body 20 erase
1287: @end example
1288:
1289: The last two examples are guaranteed to destroy parts of Gforth (and
1290: most other systems), so you better leave Gforth afterwards (if it has
1291: not finished by itself). On some systems you may have to kill gforth
1292: from outside (e.g., in Unix with @code{kill}).
1293:
1294: Now that you know how to produce crashes (and that there's not much to
1295: them), let's learn how to produce meaningful programs.
1296:
1297:
1298: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1299: @section Stack
1300: @cindex stack tutorial
1301:
1302: The most obvious feature of Forth is the stack. When you type in a
1303: number, it is pushed on the stack. You can display the content of the
1304: stack with @code{.s}.
1305:
1306: @example
1307: 1 2 .s
1308: 3 .s
1309: @end example
1310:
1311: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1312: appear in @code{.s} output as they appeared in the input.
1313:
1314: You can print the top of stack element with @code{.}.
1315:
1316: @example
1317: 1 2 3 . . .
1318: @end example
1319:
1320: In general, words consume their stack arguments (@code{.s} is an
1321: exception).
1322:
1323: @quotation Assignment
1324: What does the stack contain after @code{5 6 7 .}?
1325: @end quotation
1326:
1327:
1328: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1329: @section Arithmetics
1330: @cindex arithmetics tutorial
1331:
1332: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1333: operate on the top two stack items:
1334:
1335: @example
1336: 2 2 .s
1337: + .s
1338: .
1339: 2 1 - .
1340: 7 3 mod .
1341: @end example
1342:
1343: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1344: as in the corresponding infix expression (this is generally the case in
1345: Forth).
1346:
1347: Parentheses are superfluous (and not available), because the order of
1348: the words unambiguously determines the order of evaluation and the
1349: operands:
1350:
1351: @example
1352: 3 4 + 5 * .
1353: 3 4 5 * + .
1354: @end example
1355:
1356: @quotation Assignment
1357: What are the infix expressions corresponding to the Forth code above?
1358: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1359: known as Postfix or RPN (Reverse Polish Notation).}.
1360: @end quotation
1361:
1362: To change the sign, use @code{negate}:
1363:
1364: @example
1365: 2 negate .
1366: @end example
1367:
1368: @quotation Assignment
1369: Convert -(-3)*4-5 to Forth.
1370: @end quotation
1371:
1372: @code{/mod} performs both @code{/} and @code{mod}.
1373:
1374: @example
1375: 7 3 /mod . .
1376: @end example
1377:
1378: Reference: @ref{Arithmetic}.
1379:
1380:
1381: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1382: @section Stack Manipulation
1383: @cindex stack manipulation tutorial
1384:
1385: Stack manipulation words rearrange the data on the stack.
1386:
1387: @example
1388: 1 .s drop .s
1389: 1 .s dup .s drop drop .s
1390: 1 2 .s over .s drop drop drop
1391: 1 2 .s swap .s drop drop
1392: 1 2 3 .s rot .s drop drop drop
1393: @end example
1394:
1395: These are the most important stack manipulation words. There are also
1396: variants that manipulate twice as many stack items:
1397:
1398: @example
1399: 1 2 3 4 .s 2swap .s 2drop 2drop
1400: @end example
1401:
1402: Two more stack manipulation words are:
1403:
1404: @example
1405: 1 2 .s nip .s drop
1406: 1 2 .s tuck .s 2drop drop
1407: @end example
1408:
1409: @quotation Assignment
1410: Replace @code{nip} and @code{tuck} with combinations of other stack
1411: manipulation words.
1412:
1413: @example
1414: Given: How do you get:
1415: 1 2 3 3 2 1
1416: 1 2 3 1 2 3 2
1417: 1 2 3 1 2 3 3
1418: 1 2 3 1 3 3
1419: 1 2 3 2 1 3
1420: 1 2 3 4 4 3 2 1
1421: 1 2 3 1 2 3 1 2 3
1422: 1 2 3 4 1 2 3 4 1 2
1423: 1 2 3
1424: 1 2 3 1 2 3 4
1425: 1 2 3 1 3
1426: @end example
1427: @end quotation
1428:
1429: @example
1430: 5 dup * .
1431: @end example
1432:
1433: @quotation Assignment
1434: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1435: Write a piece of Forth code that expects two numbers on the stack
1436: (@var{a} and @var{b}, with @var{b} on top) and computes
1437: @code{(a-b)(a+1)}.
1438: @end quotation
1439:
1440: Reference: @ref{Stack Manipulation}.
1441:
1442:
1443: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1444: @section Using files for Forth code
1445: @cindex loading Forth code, tutorial
1446: @cindex files containing Forth code, tutorial
1447:
1448: While working at the Forth command line is convenient for one-line
1449: examples and short one-off code, you probably want to store your source
1450: code in files for convenient editing and persistence. You can use your
1451: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1452: Gforth}) to create @var{file.fs} and use
1453:
1454: @example
1455: s" @var{file.fs}" included
1456: @end example
1457:
1458: to load it into your Forth system. The file name extension I use for
1459: Forth files is @samp{.fs}.
1460:
1461: You can easily start Gforth with some files loaded like this:
1462:
1463: @example
1464: gforth @var{file1.fs} @var{file2.fs}
1465: @end example
1466:
1467: If an error occurs during loading these files, Gforth terminates,
1468: whereas an error during @code{INCLUDED} within Gforth usually gives you
1469: a Gforth command line. Starting the Forth system every time gives you a
1470: clean start every time, without interference from the results of earlier
1471: tries.
1472:
1473: I often put all the tests in a file, then load the code and run the
1474: tests with
1475:
1476: @example
1477: gforth @var{code.fs} @var{tests.fs} -e bye
1478: @end example
1479:
1480: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1481: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1482: restart this command without ado.
1483:
1484: The advantage of this approach is that the tests can be repeated easily
1485: every time the program ist changed, making it easy to catch bugs
1486: introduced by the change.
1487:
1488: Reference: @ref{Forth source files}.
1489:
1490:
1491: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1492: @section Comments
1493: @cindex comments tutorial
1494:
1495: @example
1496: \ That's a comment; it ends at the end of the line
1497: ( Another comment; it ends here: ) .s
1498: @end example
1499:
1500: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1501: separated with white space from the following text.
1502:
1503: @example
1504: \This gives an "Undefined word" error
1505: @end example
1506:
1507: The first @code{)} ends a comment started with @code{(}, so you cannot
1508: nest @code{(}-comments; and you cannot comment out text containing a
1509: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1510: avoid @code{)} in word names.}.
1511:
1512: I use @code{\}-comments for descriptive text and for commenting out code
1513: of one or more line; I use @code{(}-comments for describing the stack
1514: effect, the stack contents, or for commenting out sub-line pieces of
1515: code.
1516:
1517: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1518: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1519: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1520: with @kbd{M-q}.
1521:
1522: Reference: @ref{Comments}.
1523:
1524:
1525: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1526: @section Colon Definitions
1527: @cindex colon definitions, tutorial
1528: @cindex definitions, tutorial
1529: @cindex procedures, tutorial
1530: @cindex functions, tutorial
1531:
1532: are similar to procedures and functions in other programming languages.
1533:
1534: @example
1535: : squared ( n -- n^2 )
1536: dup * ;
1537: 5 squared .
1538: 7 squared .
1539: @end example
1540:
1541: @code{:} starts the colon definition; its name is @code{squared}. The
1542: following comment describes its stack effect. The words @code{dup *}
1543: are not executed, but compiled into the definition. @code{;} ends the
1544: colon definition.
1545:
1546: The newly-defined word can be used like any other word, including using
1547: it in other definitions:
1548:
1549: @example
1550: : cubed ( n -- n^3 )
1551: dup squared * ;
1552: -5 cubed .
1553: : fourth-power ( n -- n^4 )
1554: squared squared ;
1555: 3 fourth-power .
1556: @end example
1557:
1558: @quotation Assignment
1559: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1560: @code{/mod} in terms of other Forth words, and check if they work (hint:
1561: test your tests on the originals first). Don't let the
1562: @samp{redefined}-Messages spook you, they are just warnings.
1563: @end quotation
1564:
1565: Reference: @ref{Colon Definitions}.
1566:
1567:
1568: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1569: @section Decompilation
1570: @cindex decompilation tutorial
1571: @cindex see tutorial
1572:
1573: You can decompile colon definitions with @code{see}:
1574:
1575: @example
1576: see squared
1577: see cubed
1578: @end example
1579:
1580: In Gforth @code{see} shows you a reconstruction of the source code from
1581: the executable code. Informations that were present in the source, but
1582: not in the executable code, are lost (e.g., comments).
1583:
1584: You can also decompile the predefined words:
1585:
1586: @example
1587: see .
1588: see +
1589: @end example
1590:
1591:
1592: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1593: @section Stack-Effect Comments
1594: @cindex stack-effect comments, tutorial
1595: @cindex --, tutorial
1596: By convention the comment after the name of a definition describes the
1597: stack effect: The part in from of the @samp{--} describes the state of
1598: the stack before the execution of the definition, i.e., the parameters
1599: that are passed into the colon definition; the part behind the @samp{--}
1600: is the state of the stack after the execution of the definition, i.e.,
1601: the results of the definition. The stack comment only shows the top
1602: stack items that the definition accesses and/or changes.
1603:
1604: You should put a correct stack effect on every definition, even if it is
1605: just @code{( -- )}. You should also add some descriptive comment to
1606: more complicated words (I usually do this in the lines following
1607: @code{:}). If you don't do this, your code becomes unreadable (because
1608: you have to work through every definition before you can understand
1609: any).
1610:
1611: @quotation Assignment
1612: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1613: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1614: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1615: are done, you can compare your stack effects to those in this manual
1616: (@pxref{Word Index}).
1617: @end quotation
1618:
1619: Sometimes programmers put comments at various places in colon
1620: definitions that describe the contents of the stack at that place (stack
1621: comments); i.e., they are like the first part of a stack-effect
1622: comment. E.g.,
1623:
1624: @example
1625: : cubed ( n -- n^3 )
1626: dup squared ( n n^2 ) * ;
1627: @end example
1628:
1629: In this case the stack comment is pretty superfluous, because the word
1630: is simple enough. If you think it would be a good idea to add such a
1631: comment to increase readability, you should also consider factoring the
1632: word into several simpler words (@pxref{Factoring Tutorial,,
1633: Factoring}), which typically eliminates the need for the stack comment;
1634: however, if you decide not to refactor it, then having such a comment is
1635: better than not having it.
1636:
1637: The names of the stack items in stack-effect and stack comments in the
1638: standard, in this manual, and in many programs specify the type through
1639: a type prefix, similar to Fortran and Hungarian notation. The most
1640: frequent prefixes are:
1641:
1642: @table @code
1643: @item n
1644: signed integer
1645: @item u
1646: unsigned integer
1647: @item c
1648: character
1649: @item f
1650: Boolean flags, i.e. @code{false} or @code{true}.
1651: @item a-addr,a-
1652: Cell-aligned address
1653: @item c-addr,c-
1654: Char-aligned address (note that a Char may have two bytes in Windows NT)
1655: @item xt
1656: Execution token, same size as Cell
1657: @item w,x
1658: Cell, can contain an integer or an address. It usually takes 32, 64 or
1659: 16 bits (depending on your platform and Forth system). A cell is more
1660: commonly known as machine word, but the term @emph{word} already means
1661: something different in Forth.
1662: @item d
1663: signed double-cell integer
1664: @item ud
1665: unsigned double-cell integer
1666: @item r
1667: Float (on the FP stack)
1668: @end table
1669:
1670: You can find a more complete list in @ref{Notation}.
1671:
1672: @quotation Assignment
1673: Write stack-effect comments for all definitions you have written up to
1674: now.
1675: @end quotation
1676:
1677:
1678: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1679: @section Types
1680: @cindex types tutorial
1681:
1682: In Forth the names of the operations are not overloaded; so similar
1683: operations on different types need different names; e.g., @code{+} adds
1684: integers, and you have to use @code{f+} to add floating-point numbers.
1685: The following prefixes are often used for related operations on
1686: different types:
1687:
1688: @table @code
1689: @item (none)
1690: signed integer
1691: @item u
1692: unsigned integer
1693: @item c
1694: character
1695: @item d
1696: signed double-cell integer
1697: @item ud, du
1698: unsigned double-cell integer
1699: @item 2
1700: two cells (not-necessarily double-cell numbers)
1701: @item m, um
1702: mixed single-cell and double-cell operations
1703: @item f
1704: floating-point (note that in stack comments @samp{f} represents flags,
1705: and @samp{r} represents FP numbers).
1706: @end table
1707:
1708: If there are no differences between the signed and the unsigned variant
1709: (e.g., for @code{+}), there is only the prefix-less variant.
1710:
1711: Forth does not perform type checking, neither at compile time, nor at
1712: run time. If you use the wrong oeration, the data are interpreted
1713: incorrectly:
1714:
1715: @example
1716: -1 u.
1717: @end example
1718:
1719: If you have only experience with type-checked languages until now, and
1720: have heard how important type-checking is, don't panic! In my
1721: experience (and that of other Forthers), type errors in Forth code are
1722: usually easy to find (once you get used to it), the increased vigilance
1723: of the programmer tends to catch some harder errors in addition to most
1724: type errors, and you never have to work around the type system, so in
1725: most situations the lack of type-checking seems to be a win (projects to
1726: add type checking to Forth have not caught on).
1727:
1728:
1729: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1730: @section Factoring
1731: @cindex factoring tutorial
1732:
1733: If you try to write longer definitions, you will soon find it hard to
1734: keep track of the stack contents. Therefore, good Forth programmers
1735: tend to write only short definitions (e.g., three lines). The art of
1736: finding meaningful short definitions is known as factoring (as in
1737: factoring polynomials).
1738:
1739: Well-factored programs offer additional advantages: smaller, more
1740: general words, are easier to test and debug and can be reused more and
1741: better than larger, specialized words.
1742:
1743: So, if you run into difficulties with stack management, when writing
1744: code, try to define meaningful factors for the word, and define the word
1745: in terms of those. Even if a factor contains only two words, it is
1746: often helpful.
1747:
1748: Good factoring is not easy, and it takes some practice to get the knack
1749: for it; but even experienced Forth programmers often don't find the
1750: right solution right away, but only when rewriting the program. So, if
1751: you don't come up with a good solution immediately, keep trying, don't
1752: despair.
1753:
1754: @c example !!
1755:
1756:
1757: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1758: @section Designing the stack effect
1759: @cindex Stack effect design, tutorial
1760: @cindex design of stack effects, tutorial
1761:
1762: In other languages you can use an arbitrary order of parameters for a
1763: function; and since there is only one result, you don't have to deal with
1764: the order of results, either.
1765:
1766: In Forth (and other stack-based languages, e.g., PostScript) the
1767: parameter and result order of a definition is important and should be
1768: designed well. The general guideline is to design the stack effect such
1769: that the word is simple to use in most cases, even if that complicates
1770: the implementation of the word. Some concrete rules are:
1771:
1772: @itemize @bullet
1773:
1774: @item
1775: Words consume all of their parameters (e.g., @code{.}).
1776:
1777: @item
1778: If there is a convention on the order of parameters (e.g., from
1779: mathematics or another programming language), stick with it (e.g.,
1780: @code{-}).
1781:
1782: @item
1783: If one parameter usually requires only a short computation (e.g., it is
1784: a constant), pass it on the top of the stack. Conversely, parameters
1785: that usually require a long sequence of code to compute should be passed
1786: as the bottom (i.e., first) parameter. This makes the code easier to
1787: read, because reader does not need to keep track of the bottom item
1788: through a long sequence of code (or, alternatively, through stack
1789: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1790: address on top of the stack because it is usually simpler to compute
1791: than the stored value (often the address is just a variable).
1792:
1793: @item
1794: Similarly, results that are usually consumed quickly should be returned
1795: on the top of stack, whereas a result that is often used in long
1796: computations should be passed as bottom result. E.g., the file words
1797: like @code{open-file} return the error code on the top of stack, because
1798: it is usually consumed quickly by @code{throw}; moreover, the error code
1799: has to be checked before doing anything with the other results.
1800:
1801: @end itemize
1802:
1803: These rules are just general guidelines, don't lose sight of the overall
1804: goal to make the words easy to use. E.g., if the convention rule
1805: conflicts with the computation-length rule, you might decide in favour
1806: of the convention if the word will be used rarely, and in favour of the
1807: computation-length rule if the word will be used frequently (because
1808: with frequent use the cost of breaking the computation-length rule would
1809: be quite high, and frequent use makes it easier to remember an
1810: unconventional order).
1811:
1812: @c example !! structure package
1813:
1814:
1815: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1816: @section Local Variables
1817: @cindex local variables, tutorial
1818:
1819: You can define local variables (@emph{locals}) in a colon definition:
1820:
1821: @example
1822: : swap @{ a b -- b a @}
1823: b a ;
1824: 1 2 swap .s 2drop
1825: @end example
1826:
1827: (If your Forth system does not support this syntax, include
1828: @file{compat/anslocals.fs} first).
1829:
1830: In this example @code{@{ a b -- b a @}} is the locals definition; it
1831: takes two cells from the stack, puts the top of stack in @code{b} and
1832: the next stack element in @code{a}. @code{--} starts a comment ending
1833: with @code{@}}. After the locals definition, using the name of the
1834: local will push its value on the stack. You can leave the comment
1835: part (@code{-- b a}) away:
1836:
1837: @example
1838: : swap ( x1 x2 -- x2 x1 )
1839: @{ a b @} b a ;
1840: @end example
1841:
1842: In Gforth you can have several locals definitions, anywhere in a colon
1843: definition; in contrast, in a standard program you can have only one
1844: locals definition per colon definition, and that locals definition must
1845: be outside any controll structure.
1846:
1847: With locals you can write slightly longer definitions without running
1848: into stack trouble. However, I recommend trying to write colon
1849: definitions without locals for exercise purposes to help you gain the
1850: essential factoring skills.
1851:
1852: @quotation Assignment
1853: Rewrite your definitions until now with locals
1854: @end quotation
1855:
1856: Reference: @ref{Locals}.
1857:
1858:
1859: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1860: @section Conditional execution
1861: @cindex conditionals, tutorial
1862: @cindex if, tutorial
1863:
1864: In Forth you can use control structures only inside colon definitions.
1865: An @code{if}-structure looks like this:
1866:
1867: @example
1868: : abs ( n1 -- +n2 )
1869: dup 0 < if
1870: negate
1871: endif ;
1872: 5 abs .
1873: -5 abs .
1874: @end example
1875:
1876: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1877: the following code is performed, otherwise execution continues after the
1878: @code{endif} (or @code{else}). @code{<} compares the top two stack
1879: elements and prioduces a flag:
1880:
1881: @example
1882: 1 2 < .
1883: 2 1 < .
1884: 1 1 < .
1885: @end example
1886:
1887: Actually the standard name for @code{endif} is @code{then}. This
1888: tutorial presents the examples using @code{endif}, because this is often
1889: less confusing for people familiar with other programming languages
1890: where @code{then} has a different meaning. If your system does not have
1891: @code{endif}, define it with
1892:
1893: @example
1894: : endif postpone then ; immediate
1895: @end example
1896:
1897: You can optionally use an @code{else}-part:
1898:
1899: @example
1900: : min ( n1 n2 -- n )
1901: 2dup < if
1902: drop
1903: else
1904: nip
1905: endif ;
1906: 2 3 min .
1907: 3 2 min .
1908: @end example
1909:
1910: @quotation Assignment
1911: Write @code{min} without @code{else}-part (hint: what's the definition
1912: of @code{nip}?).
1913: @end quotation
1914:
1915: Reference: @ref{Selection}.
1916:
1917:
1918: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1919: @section Flags and Comparisons
1920: @cindex flags tutorial
1921: @cindex comparison tutorial
1922:
1923: In a false-flag all bits are clear (0 when interpreted as integer). In
1924: a canonical true-flag all bits are set (-1 as a twos-complement signed
1925: integer); in many contexts (e.g., @code{if}) any non-zero value is
1926: treated as true flag.
1927:
1928: @example
1929: false .
1930: true .
1931: true hex u. decimal
1932: @end example
1933:
1934: Comparison words produce canonical flags:
1935:
1936: @example
1937: 1 1 = .
1938: 1 0= .
1939: 0 1 < .
1940: 0 0 < .
1941: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1942: -1 1 < .
1943: @end example
1944:
1945: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1946: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1947: these combinations are standard (for details see the standard,
1948: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1949:
1950: You can use @code{and or xor invert} can be used as operations on
1951: canonical flags. Actually they are bitwise operations:
1952:
1953: @example
1954: 1 2 and .
1955: 1 2 or .
1956: 1 3 xor .
1957: 1 invert .
1958: @end example
1959:
1960: You can convert a zero/non-zero flag into a canonical flag with
1961: @code{0<>} (and complement it on the way with @code{0=}).
1962:
1963: @example
1964: 1 0= .
1965: 1 0<> .
1966: @end example
1967:
1968: You can use the all-bits-set feature of canonical flags and the bitwise
1969: operation of the Boolean operations to avoid @code{if}s:
1970:
1971: @example
1972: : foo ( n1 -- n2 )
1973: 0= if
1974: 14
1975: else
1976: 0
1977: endif ;
1978: 0 foo .
1979: 1 foo .
1980:
1981: : foo ( n1 -- n2 )
1982: 0= 14 and ;
1983: 0 foo .
1984: 1 foo .
1985: @end example
1986:
1987: @quotation Assignment
1988: Write @code{min} without @code{if}.
1989: @end quotation
1990:
1991: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
1992: @ref{Bitwise operations}.
1993:
1994:
1995: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
1996: @section General Loops
1997: @cindex loops, indefinite, tutorial
1998:
1999: The endless loop is the most simple one:
2000:
2001: @example
2002: : endless ( -- )
2003: 0 begin
2004: dup . 1+
2005: again ;
2006: endless
2007: @end example
2008:
2009: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2010: does nothing at run-time, @code{again} jumps back to @code{begin}.
2011:
2012: A loop with one exit at any place looks like this:
2013:
2014: @example
2015: : log2 ( +n1 -- n2 )
2016: \ logarithmus dualis of n1>0, rounded down to the next integer
2017: assert( dup 0> )
2018: 2/ 0 begin
2019: over 0> while
2020: 1+ swap 2/ swap
2021: repeat
2022: nip ;
2023: 7 log2 .
2024: 8 log2 .
2025: @end example
2026:
2027: At run-time @code{while} consumes a flag; if it is 0, execution
2028: continues behind the @code{repeat}; if the flag is non-zero, execution
2029: continues behind the @code{while}. @code{Repeat} jumps back to
2030: @code{begin}, just like @code{again}.
2031:
2032: In Forth there are many combinations/abbreviations, like @code{1+}.
2033: However, @code{2/} is not one of them; it shifts its argument right by
2034: one bit (arithmetic shift right):
2035:
2036: @example
2037: -5 2 / .
2038: -5 2/ .
2039: @end example
2040:
2041: @code{assert(} is no standard word, but you can get it on systems other
2042: then Gforth by including @file{compat/assert.fs}. You can see what it
2043: does by trying
2044:
2045: @example
2046: 0 log2 .
2047: @end example
2048:
2049: Here's a loop with an exit at the end:
2050:
2051: @example
2052: : log2 ( +n1 -- n2 )
2053: \ logarithmus dualis of n1>0, rounded down to the next integer
2054: assert( dup 0 > )
2055: -1 begin
2056: 1+ swap 2/ swap
2057: over 0 <=
2058: until
2059: nip ;
2060: @end example
2061:
2062: @code{Until} consumes a flag; if it is non-zero, execution continues at
2063: the @code{begin}, otherwise after the @code{until}.
2064:
2065: @quotation Assignment
2066: Write a definition for computing the greatest common divisor.
2067: @end quotation
2068:
2069: Reference: @ref{Simple Loops}.
2070:
2071:
2072: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2073: @section Counted loops
2074: @cindex loops, counted, tutorial
2075:
2076: @example
2077: : ^ ( n1 u -- n )
2078: \ n = the uth power of u1
2079: 1 swap 0 u+do
2080: over *
2081: loop
2082: nip ;
2083: 3 2 ^ .
2084: 4 3 ^ .
2085: @end example
2086:
2087: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2088: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2089: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2090: times (or not at all, if @code{u3-u4<0}).
2091:
2092: You can see the stack effect design rules at work in the stack effect of
2093: the loop start words: Since the start value of the loop is more
2094: frequently constant than the end value, the start value is passed on
2095: the top-of-stack.
2096:
2097: You can access the counter of a counted loop with @code{i}:
2098:
2099: @example
2100: : fac ( u -- u! )
2101: 1 swap 1+ 1 u+do
2102: i *
2103: loop ;
2104: 5 fac .
2105: 7 fac .
2106: @end example
2107:
2108: There is also @code{+do}, which expects signed numbers (important for
2109: deciding whether to enter the loop).
2110:
2111: @quotation Assignment
2112: Write a definition for computing the nth Fibonacci number.
2113: @end quotation
2114:
2115: You can also use increments other than 1:
2116:
2117: @example
2118: : up2 ( n1 n2 -- )
2119: +do
2120: i .
2121: 2 +loop ;
2122: 10 0 up2
2123:
2124: : down2 ( n1 n2 -- )
2125: -do
2126: i .
2127: 2 -loop ;
2128: 0 10 down2
2129: @end example
2130:
2131: Reference: @ref{Counted Loops}.
2132:
2133:
2134: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2135: @section Recursion
2136: @cindex recursion tutorial
2137:
2138: Usually the name of a definition is not visible in the definition; but
2139: earlier definitions are usually visible:
2140:
2141: @example
2142: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2143: : / ( n1 n2 -- n )
2144: dup 0= if
2145: -10 throw \ report division by zero
2146: endif
2147: / \ old version
2148: ;
2149: 1 0 /
2150: @end example
2151:
2152: For recursive definitions you can use @code{recursive} (non-standard) or
2153: @code{recurse}:
2154:
2155: @example
2156: : fac1 ( n -- n! ) recursive
2157: dup 0> if
2158: dup 1- fac1 *
2159: else
2160: drop 1
2161: endif ;
2162: 7 fac1 .
2163:
2164: : fac2 ( n -- n! )
2165: dup 0> if
2166: dup 1- recurse *
2167: else
2168: drop 1
2169: endif ;
2170: 8 fac2 .
2171: @end example
2172:
2173: @quotation Assignment
2174: Write a recursive definition for computing the nth Fibonacci number.
2175: @end quotation
2176:
2177: Reference (including indirect recursion): @xref{Calls and returns}.
2178:
2179:
2180: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2181: @section Leaving definitions or loops
2182: @cindex leaving definitions, tutorial
2183: @cindex leaving loops, tutorial
2184:
2185: @code{EXIT} exits the current definition right away. For every counted
2186: loop that is left in this way, an @code{UNLOOP} has to be performed
2187: before the @code{EXIT}:
2188:
2189: @c !! real examples
2190: @example
2191: : ...
2192: ... u+do
2193: ... if
2194: ... unloop exit
2195: endif
2196: ...
2197: loop
2198: ... ;
2199: @end example
2200:
2201: @code{LEAVE} leaves the innermost counted loop right away:
2202:
2203: @example
2204: : ...
2205: ... u+do
2206: ... if
2207: ... leave
2208: endif
2209: ...
2210: loop
2211: ... ;
2212: @end example
2213:
2214: @c !! example
2215:
2216: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2217:
2218:
2219: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2220: @section Return Stack
2221: @cindex return stack tutorial
2222:
2223: In addition to the data stack Forth also has a second stack, the return
2224: stack; most Forth systems store the return addresses of procedure calls
2225: there (thus its name). Programmers can also use this stack:
2226:
2227: @example
2228: : foo ( n1 n2 -- )
2229: .s
2230: >r .s
2231: r@@ .
2232: >r .s
2233: r@@ .
2234: r> .
2235: r@@ .
2236: r> . ;
2237: 1 2 foo
2238: @end example
2239:
2240: @code{>r} takes an element from the data stack and pushes it onto the
2241: return stack; conversely, @code{r>} moves an elementm from the return to
2242: the data stack; @code{r@@} pushes a copy of the top of the return stack
2243: on the data stack.
2244:
2245: Forth programmers usually use the return stack for storing data
2246: temporarily, if using the data stack alone would be too complex, and
2247: factoring and locals are not an option:
2248:
2249: @example
2250: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2251: rot >r rot r> ;
2252: @end example
2253:
2254: The return address of the definition and the loop control parameters of
2255: counted loops usually reside on the return stack, so you have to take
2256: all items, that you have pushed on the return stack in a colon
2257: definition or counted loop, from the return stack before the definition
2258: or loop ends. You cannot access items that you pushed on the return
2259: stack outside some definition or loop within the definition of loop.
2260:
2261: If you miscount the return stack items, this usually ends in a crash:
2262:
2263: @example
2264: : crash ( n -- )
2265: >r ;
2266: 5 crash
2267: @end example
2268:
2269: You cannot mix using locals and using the return stack (according to the
2270: standard; Gforth has no problem). However, they solve the same
2271: problems, so this shouldn't be an issue.
2272:
2273: @quotation Assignment
2274: Can you rewrite any of the definitions you wrote until now in a better
2275: way using the return stack?
2276: @end quotation
2277:
2278: Reference: @ref{Return stack}.
2279:
2280:
2281: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2282: @section Memory
2283: @cindex memory access/allocation tutorial
2284:
2285: You can create a global variable @code{v} with
2286:
2287: @example
2288: variable v ( -- addr )
2289: @end example
2290:
2291: @code{v} pushes the address of a cell in memory on the stack. This cell
2292: was reserved by @code{variable}. You can use @code{!} (store) to store
2293: values into this cell and @code{@@} (fetch) to load the value from the
2294: stack into memory:
2295:
2296: @example
2297: v .
2298: 5 v ! .s
2299: v @@ .
2300: @end example
2301:
2302: You can see a raw dump of memory with @code{dump}:
2303:
2304: @example
2305: v 1 cells .s dump
2306: @end example
2307:
2308: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2309: generally, address units (aus)) that @code{n1 cells} occupy. You can
2310: also reserve more memory:
2311:
2312: @example
2313: create v2 20 cells allot
2314: v2 20 cells dump
2315: @end example
2316:
2317: creates a word @code{v2} and reserves 20 uninitialized cells; the
2318: address pushed by @code{v2} points to the start of these 20 cells. You
2319: can use address arithmetic to access these cells:
2320:
2321: @example
2322: 3 v2 5 cells + !
2323: v2 20 cells dump
2324: @end example
2325:
2326: You can reserve and initialize memory with @code{,}:
2327:
2328: @example
2329: create v3
2330: 5 , 4 , 3 , 2 , 1 ,
2331: v3 @@ .
2332: v3 cell+ @@ .
2333: v3 2 cells + @@ .
2334: v3 5 cells dump
2335: @end example
2336:
2337: @quotation Assignment
2338: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2339: @code{u} cells, with the first of these cells at @code{addr}, the next
2340: one at @code{addr cell+} etc.
2341: @end quotation
2342:
2343: You can also reserve memory without creating a new word:
2344:
2345: @example
2346: here 10 cells allot .
2347: here .
2348: @end example
2349:
2350: @code{Here} pushes the start address of the memory area. You should
2351: store it somewhere, or you will have a hard time finding the memory area
2352: again.
2353:
2354: @code{Allot} manages dictionary memory. The dictionary memory contains
2355: the system's data structures for words etc. on Gforth and most other
2356: Forth systems. It is managed like a stack: You can free the memory that
2357: you have just @code{allot}ed with
2358:
2359: @example
2360: -10 cells allot
2361: here .
2362: @end example
2363:
2364: Note that you cannot do this if you have created a new word in the
2365: meantime (because then your @code{allot}ed memory is no longer on the
2366: top of the dictionary ``stack'').
2367:
2368: Alternatively, you can use @code{allocate} and @code{free} which allow
2369: freeing memory in any order:
2370:
2371: @example
2372: 10 cells allocate throw .s
2373: 20 cells allocate throw .s
2374: swap
2375: free throw
2376: free throw
2377: @end example
2378:
2379: The @code{throw}s deal with errors (e.g., out of memory).
2380:
2381: And there is also a
2382: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2383: garbage collector}, which eliminates the need to @code{free} memory
2384: explicitly.
2385:
2386: Reference: @ref{Memory}.
2387:
2388:
2389: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2390: @section Characters and Strings
2391: @cindex strings tutorial
2392: @cindex characters tutorial
2393:
2394: On the stack characters take up a cell, like numbers. In memory they
2395: have their own size (one 8-bit byte on most systems), and therefore
2396: require their own words for memory access:
2397:
2398: @example
2399: create v4
2400: 104 c, 97 c, 108 c, 108 c, 111 c,
2401: v4 4 chars + c@@ .
2402: v4 5 chars dump
2403: @end example
2404:
2405: The preferred representation of strings on the stack is @code{addr
2406: u-count}, where @code{addr} is the address of the first character and
2407: @code{u-count} is the number of characters in the string.
2408:
2409: @example
2410: v4 5 type
2411: @end example
2412:
2413: You get a string constant with
2414:
2415: @example
2416: s" hello, world" .s
2417: type
2418: @end example
2419:
2420: Make sure you have a space between @code{s"} and the string; @code{s"}
2421: is a normal Forth word and must be delimited with white space (try what
2422: happens when you remove the space).
2423:
2424: However, this interpretive use of @code{s"} is quite restricted: the
2425: string exists only until the next call of @code{s"} (some Forth systems
2426: keep more than one of these strings, but usually they still have a
2427: limited lifetime).
2428:
2429: @example
2430: s" hello," s" world" .s
2431: type
2432: type
2433: @end example
2434:
2435: You can also use @code{s"} in a definition, and the resulting
2436: strings then live forever (well, for as long as the definition):
2437:
2438: @example
2439: : foo s" hello," s" world" ;
2440: foo .s
2441: type
2442: type
2443: @end example
2444:
2445: @quotation Assignment
2446: @code{Emit ( c -- )} types @code{c} as character (not a number).
2447: Implement @code{type ( addr u -- )}.
2448: @end quotation
2449:
2450: Reference: @ref{Memory Blocks}.
2451:
2452:
2453: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
2454: @section Alignment
2455: @cindex alignment tutorial
2456: @cindex memory alignment tutorial
2457:
2458: On many processors cells have to be aligned in memory, if you want to
2459: access them with @code{@@} and @code{!} (and even if the processor does
2460: not require alignment, access to aligned cells is faster).
2461:
2462: @code{Create} aligns @code{here} (i.e., the place where the next
2463: allocation will occur, and that the @code{create}d word points to).
2464: Likewise, the memory produced by @code{allocate} starts at an aligned
2465: address. Adding a number of @code{cells} to an aligned address produces
2466: another aligned address.
2467:
2468: However, address arithmetic involving @code{char+} and @code{chars} can
2469: create an address that is not cell-aligned. @code{Aligned ( addr --
2470: a-addr )} produces the next aligned address:
2471:
2472: @example
2473: v3 char+ aligned .s @@ .
2474: v3 char+ .s @@ .
2475: @end example
2476:
2477: Similarly, @code{align} advances @code{here} to the next aligned
2478: address:
2479:
2480: @example
2481: create v5 97 c,
2482: here .
2483: align here .
2484: 1000 ,
2485: @end example
2486:
2487: Note that you should use aligned addresses even if your processor does
2488: not require them, if you want your program to be portable.
2489:
2490: Reference: @ref{Address arithmetic}.
2491:
2492:
2493: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2494: @section Files
2495: @cindex files tutorial
2496:
2497: This section gives a short introduction into how to use files inside
2498: Forth. It's broken up into five easy steps:
2499:
2500: @enumerate 1
2501: @item Opened an ASCII text file for input
2502: @item Opened a file for output
2503: @item Read input file until string matched (or some other condition matched)
2504: @item Wrote some lines from input ( modified or not) to output
2505: @item Closed the files.
2506: @end enumerate
2507:
2508: Reference: @ref{General files}.
2509:
2510: @subsection Open file for input
2511:
2512: @example
2513: s" foo.in" r/o open-file throw Value fd-in
2514: @end example
2515:
2516: @subsection Create file for output
2517:
2518: @example
2519: s" foo.out" w/o create-file throw Value fd-out
2520: @end example
2521:
2522: The available file modes are r/o for read-only access, r/w for
2523: read-write access, and w/o for write-only access. You could open both
2524: files with r/w, too, if you like. All file words return error codes; for
2525: most applications, it's best to pass there error codes with @code{throw}
2526: to the outer error handler.
2527:
2528: If you want words for opening and assigning, define them as follows:
2529:
2530: @example
2531: 0 Value fd-in
2532: 0 Value fd-out
2533: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2534: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2535: @end example
2536:
2537: Usage example:
2538:
2539: @example
2540: s" foo.in" open-input
2541: s" foo.out" open-output
2542: @end example
2543:
2544: @subsection Scan file for a particular line
2545:
2546: @example
2547: 256 Constant max-line
2548: Create line-buffer max-line 2 + allot
2549:
2550: : scan-file ( addr u -- )
2551: begin
2552: line-buffer max-line fd-in read-line throw
2553: while
2554: >r 2dup line-buffer r> compare 0=
2555: until
2556: else
2557: drop
2558: then
2559: 2drop ;
2560: @end example
2561:
2562: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
2563: the buffer at addr, and returns the number of bytes read, a flag that is
2564: false when the end of file is reached, and an error code.
2565:
2566: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2567: returns zero if both strings are equal. It returns a positive number if
2568: the first string is lexically greater, a negative if the second string
2569: is lexically greater.
2570:
2571: We haven't seen this loop here; it has two exits. Since the @code{while}
2572: exits with the number of bytes read on the stack, we have to clean up
2573: that separately; that's after the @code{else}.
2574:
2575: Usage example:
2576:
2577: @example
2578: s" The text I search is here" scan-file
2579: @end example
2580:
2581: @subsection Copy input to output
2582:
2583: @example
2584: : copy-file ( -- )
2585: begin
2586: line-buffer max-line fd-in read-line throw
2587: while
2588: line-buffer swap fd-out write-file throw
2589: repeat ;
2590: @end example
2591:
2592: @subsection Close files
2593:
2594: @example
2595: fd-in close-file throw
2596: fd-out close-file throw
2597: @end example
2598:
2599: Likewise, you can put that into definitions, too:
2600:
2601: @example
2602: : close-input ( -- ) fd-in close-file throw ;
2603: : close-output ( -- ) fd-out close-file throw ;
2604: @end example
2605:
2606: @quotation Assignment
2607: How could you modify @code{copy-file} so that it copies until a second line is
2608: matched? Can you write a program that extracts a section of a text file,
2609: given the line that starts and the line that terminates that section?
2610: @end quotation
2611:
2612: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
2613: @section Interpretation and Compilation Semantics and Immediacy
2614: @cindex semantics tutorial
2615: @cindex interpretation semantics tutorial
2616: @cindex compilation semantics tutorial
2617: @cindex immediate, tutorial
2618:
2619: When a word is compiled, it behaves differently from being interpreted.
2620: E.g., consider @code{+}:
2621:
2622: @example
2623: 1 2 + .
2624: : foo + ;
2625: @end example
2626:
2627: These two behaviours are known as compilation and interpretation
2628: semantics. For normal words (e.g., @code{+}), the compilation semantics
2629: is to append the interpretation semantics to the currently defined word
2630: (@code{foo} in the example above). I.e., when @code{foo} is executed
2631: later, the interpretation semantics of @code{+} (i.e., adding two
2632: numbers) will be performed.
2633:
2634: However, there are words with non-default compilation semantics, e.g.,
2635: the control-flow words like @code{if}. You can use @code{immediate} to
2636: change the compilation semantics of the last defined word to be equal to
2637: the interpretation semantics:
2638:
2639: @example
2640: : [FOO] ( -- )
2641: 5 . ; immediate
2642:
2643: [FOO]
2644: : bar ( -- )
2645: [FOO] ;
2646: bar
2647: see bar
2648: @end example
2649:
2650: Two conventions to mark words with non-default compilation semnatics are
2651: names with brackets (more frequently used) and to write them all in
2652: upper case (less frequently used).
2653:
2654: In Gforth (and many other systems) you can also remove the
2655: interpretation semantics with @code{compile-only} (the compilation
2656: semantics is derived from the original interpretation semantics):
2657:
2658: @example
2659: : flip ( -- )
2660: 6 . ; compile-only \ but not immediate
2661: flip
2662:
2663: : flop ( -- )
2664: flip ;
2665: flop
2666: @end example
2667:
2668: In this example the interpretation semantics of @code{flop} is equal to
2669: the original interpretation semantics of @code{flip}.
2670:
2671: The text interpreter has two states: in interpret state, it performs the
2672: interpretation semantics of words it encounters; in compile state, it
2673: performs the compilation semantics of these words.
2674:
2675: Among other things, @code{:} switches into compile state, and @code{;}
2676: switches back to interpret state. They contain the factors @code{]}
2677: (switch to compile state) and @code{[} (switch to interpret state), that
2678: do nothing but switch the state.
2679:
2680: @example
2681: : xxx ( -- )
2682: [ 5 . ]
2683: ;
2684:
2685: xxx
2686: see xxx
2687: @end example
2688:
2689: These brackets are also the source of the naming convention mentioned
2690: above.
2691:
2692: Reference: @ref{Interpretation and Compilation Semantics}.
2693:
2694:
2695: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2696: @section Execution Tokens
2697: @cindex execution tokens tutorial
2698: @cindex XT tutorial
2699:
2700: @code{' word} gives you the execution token (XT) of a word. The XT is a
2701: cell representing the interpretation semantics of a word. You can
2702: execute this semantics with @code{execute}:
2703:
2704: @example
2705: ' + .s
2706: 1 2 rot execute .
2707: @end example
2708:
2709: The XT is similar to a function pointer in C. However, parameter
2710: passing through the stack makes it a little more flexible:
2711:
2712: @example
2713: : map-array ( ... addr u xt -- ... )
2714: \ executes xt ( ... x -- ... ) for every element of the array starting
2715: \ at addr and containing u elements
2716: @{ xt @}
2717: cells over + swap ?do
2718: i @@ xt execute
2719: 1 cells +loop ;
2720:
2721: create a 3 , 4 , 2 , -1 , 4 ,
2722: a 5 ' . map-array .s
2723: 0 a 5 ' + map-array .
2724: s" max-n" environment? drop .s
2725: a 5 ' min map-array .
2726: @end example
2727:
2728: You can use map-array with the XTs of words that consume one element
2729: more than they produce. In theory you can also use it with other XTs,
2730: but the stack effect then depends on the size of the array, which is
2731: hard to understand.
2732:
2733: Since XTs are cell-sized, you can store them in memory and manipulate
2734: them on the stack like other cells. You can also compile the XT into a
2735: word with @code{compile,}:
2736:
2737: @example
2738: : foo1 ( n1 n2 -- n )
2739: [ ' + compile, ] ;
2740: see foo
2741: @end example
2742:
2743: This is non-standard, because @code{compile,} has no compilation
2744: semantics in the standard, but it works in good Forth systems. For the
2745: broken ones, use
2746:
2747: @example
2748: : [compile,] compile, ; immediate
2749:
2750: : foo1 ( n1 n2 -- n )
2751: [ ' + ] [compile,] ;
2752: see foo
2753: @end example
2754:
2755: @code{'} is a word with default compilation semantics; it parses the
2756: next word when its interpretation semantics are executed, not during
2757: compilation:
2758:
2759: @example
2760: : foo ( -- xt )
2761: ' ;
2762: see foo
2763: : bar ( ... "word" -- ... )
2764: ' execute ;
2765: see bar
2766: 1 2 bar + .
2767: @end example
2768:
2769: You often want to parse a word during compilation and compile its XT so
2770: it will be pushed on the stack at run-time. @code{[']} does this:
2771:
2772: @example
2773: : xt-+ ( -- xt )
2774: ['] + ;
2775: see xt-+
2776: 1 2 xt-+ execute .
2777: @end example
2778:
2779: Many programmers tend to see @code{'} and the word it parses as one
2780: unit, and expect it to behave like @code{[']} when compiled, and are
2781: confused by the actual behaviour. If you are, just remember that the
2782: Forth system just takes @code{'} as one unit and has no idea that it is
2783: a parsing word (attempts to convenience programmers in this issue have
2784: usually resulted in even worse pitfalls, see
2785: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2786: @code{State}-smartness---Why it is evil and How to Exorcise it}).
2787:
2788: Note that the state of the interpreter does not come into play when
2789: creating and executing XTs. I.e., even when you execute @code{'} in
2790: compile state, it still gives you the interpretation semantics. And
2791: whatever that state is, @code{execute} performs the semantics
2792: represented by the XT (i.e., for XTs produced with @code{'} the
2793: interpretation semantics).
2794:
2795: Reference: @ref{Tokens for Words}.
2796:
2797:
2798: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2799: @section Exceptions
2800: @cindex exceptions tutorial
2801:
2802: @code{throw ( n -- )} causes an exception unless n is zero.
2803:
2804: @example
2805: 100 throw .s
2806: 0 throw .s
2807: @end example
2808:
2809: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2810: it catches exceptions and pushes the number of the exception on the
2811: stack (or 0, if the xt executed without exception). If there was an
2812: exception, the stacks have the same depth as when entering @code{catch}:
2813:
2814: @example
2815: .s
2816: 3 0 ' / catch .s
2817: 3 2 ' / catch .s
2818: @end example
2819:
2820: @quotation Assignment
2821: Try the same with @code{execute} instead of @code{catch}.
2822: @end quotation
2823:
2824: @code{Throw} always jumps to the dynamically next enclosing
2825: @code{catch}, even if it has to leave several call levels to achieve
2826: this:
2827:
2828: @example
2829: : foo 100 throw ;
2830: : foo1 foo ." after foo" ;
2831: : bar ['] foo1 catch ;
2832: bar .
2833: @end example
2834:
2835: It is often important to restore a value upon leaving a definition, even
2836: if the definition is left through an exception. You can ensure this
2837: like this:
2838:
2839: @example
2840: : ...
2841: save-x
2842: ['] word-changing-x catch ( ... n )
2843: restore-x
2844: ( ... n ) throw ;
2845: @end example
2846:
2847: Gforth provides an alternative syntax in addition to @code{catch}:
2848: @code{try ... recover ... endtry}. If the code between @code{try} and
2849: @code{recover} has an exception, the stack depths are restored, the
2850: exception number is pushed on the stack, and the code between
2851: @code{recover} and @code{endtry} is performed. E.g., the definition for
2852: @code{catch} is
2853:
2854: @example
2855: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
2856: try
2857: execute 0
2858: recover
2859: nip
2860: endtry ;
2861: @end example
2862:
2863: The equivalent to the restoration code above is
2864:
2865: @example
2866: : ...
2867: save-x
2868: try
2869: word-changing-x 0
2870: recover endtry
2871: restore-x
2872: throw ;
2873: @end example
2874:
2875: This works if @code{word-changing-x} does not change the stack depth,
2876: otherwise you should add some code between @code{recover} and
2877: @code{endtry} to balance the stack.
2878:
2879: Reference: @ref{Exception Handling}.
2880:
2881:
2882: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2883: @section Defining Words
2884: @cindex defining words tutorial
2885: @cindex does> tutorial
2886: @cindex create...does> tutorial
2887:
2888: @c before semantics?
2889:
2890: @code{:}, @code{create}, and @code{variable} are definition words: They
2891: define other words. @code{Constant} is another definition word:
2892:
2893: @example
2894: 5 constant foo
2895: foo .
2896: @end example
2897:
2898: You can also use the prefixes @code{2} (double-cell) and @code{f}
2899: (floating point) with @code{variable} and @code{constant}.
2900:
2901: You can also define your own defining words. E.g.:
2902:
2903: @example
2904: : variable ( "name" -- )
2905: create 0 , ;
2906: @end example
2907:
2908: You can also define defining words that create words that do something
2909: other than just producing their address:
2910:
2911: @example
2912: : constant ( n "name" -- )
2913: create ,
2914: does> ( -- n )
2915: ( addr ) @@ ;
2916:
2917: 5 constant foo
2918: foo .
2919: @end example
2920:
2921: The definition of @code{constant} above ends at the @code{does>}; i.e.,
2922: @code{does>} replaces @code{;}, but it also does something else: It
2923: changes the last defined word such that it pushes the address of the
2924: body of the word and then performs the code after the @code{does>}
2925: whenever it is called.
2926:
2927: In the example above, @code{constant} uses @code{,} to store 5 into the
2928: body of @code{foo}. When @code{foo} executes, it pushes the address of
2929: the body onto the stack, then (in the code after the @code{does>})
2930: fetches the 5 from there.
2931:
2932: The stack comment near the @code{does>} reflects the stack effect of the
2933: defined word, not the stack effect of the code after the @code{does>}
2934: (the difference is that the code expects the address of the body that
2935: the stack comment does not show).
2936:
2937: You can use these definition words to do factoring in cases that involve
2938: (other) definition words. E.g., a field offset is always added to an
2939: address. Instead of defining
2940:
2941: @example
2942: 2 cells constant offset-field1
2943: @end example
2944:
2945: and using this like
2946:
2947: @example
2948: ( addr ) offset-field1 +
2949: @end example
2950:
2951: you can define a definition word
2952:
2953: @example
2954: : simple-field ( n "name" -- )
2955: create ,
2956: does> ( n1 -- n1+n )
2957: ( addr ) @@ + ;
2958: @end example
2959:
2960: Definition and use of field offsets now look like this:
2961:
2962: @example
2963: 2 cells simple-field field1
2964: create mystruct 4 cells allot
2965: mystruct .s field1 .s drop
2966: @end example
2967:
2968: If you want to do something with the word without performing the code
2969: after the @code{does>}, you can access the body of a @code{create}d word
2970: with @code{>body ( xt -- addr )}:
2971:
2972: @example
2973: : value ( n "name" -- )
2974: create ,
2975: does> ( -- n1 )
2976: @@ ;
2977: : to ( n "name" -- )
2978: ' >body ! ;
2979:
2980: 5 value foo
2981: foo .
2982: 7 to foo
2983: foo .
2984: @end example
2985:
2986: @quotation Assignment
2987: Define @code{defer ( "name" -- )}, which creates a word that stores an
2988: XT (at the start the XT of @code{abort}), and upon execution
2989: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
2990: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
2991: recursion is one application of @code{defer}.
2992: @end quotation
2993:
2994: Reference: @ref{User-defined Defining Words}.
2995:
2996:
2997: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
2998: @section Arrays and Records
2999: @cindex arrays tutorial
3000: @cindex records tutorial
3001: @cindex structs tutorial
3002:
3003: Forth has no standard words for defining data structures such as arrays
3004: and records (structs in C terminology), but you can build them yourself
3005: based on address arithmetic. You can also define words for defining
3006: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
3007:
3008: One of the first projects a Forth newcomer sets out upon when learning
3009: about defining words is an array defining word (possibly for
3010: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3011: learn something from it. However, don't be disappointed when you later
3012: learn that you have little use for these words (inappropriate use would
3013: be even worse). I have not yet found a set of useful array words yet;
3014: the needs are just too diverse, and named, global arrays (the result of
3015: naive use of defining words) are often not flexible enough (e.g.,
3016: consider how to pass them as parameters). Another such project is a set
3017: of words to help dealing with strings.
3018:
3019: On the other hand, there is a useful set of record words, and it has
3020: been defined in @file{compat/struct.fs}; these words are predefined in
3021: Gforth. They are explained in depth elsewhere in this manual (see
3022: @pxref{Structures}). The @code{simple-field} example above is
3023: simplified variant of fields in this package.
3024:
3025:
3026: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3027: @section @code{POSTPONE}
3028: @cindex postpone tutorial
3029:
3030: You can compile the compilation semantics (instead of compiling the
3031: interpretation semantics) of a word with @code{POSTPONE}:
3032:
3033: @example
3034: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3035: POSTPONE + ; immediate
3036: : foo ( n1 n2 -- n )
3037: MY-+ ;
3038: 1 2 foo .
3039: see foo
3040: @end example
3041:
3042: During the definition of @code{foo} the text interpreter performs the
3043: compilation semantics of @code{MY-+}, which performs the compilation
3044: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3045:
3046: This example also displays separate stack comments for the compilation
3047: semantics and for the stack effect of the compiled code. For words with
3048: default compilation semantics these stack effects are usually not
3049: displayed; the stack effect of the compilation semantics is always
3050: @code{( -- )} for these words, the stack effect for the compiled code is
3051: the stack effect of the interpretation semantics.
3052:
3053: Note that the state of the interpreter does not come into play when
3054: performing the compilation semantics in this way. You can also perform
3055: it interpretively, e.g.:
3056:
3057: @example
3058: : foo2 ( n1 n2 -- n )
3059: [ MY-+ ] ;
3060: 1 2 foo .
3061: see foo
3062: @end example
3063:
3064: However, there are some broken Forth systems where this does not always
3065: work, and therefore this practice was been declared non-standard in
3066: 1999.
3067: @c !! repair.fs
3068:
3069: Here is another example for using @code{POSTPONE}:
3070:
3071: @example
3072: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3073: POSTPONE negate POSTPONE + ; immediate compile-only
3074: : bar ( n1 n2 -- n )
3075: MY-- ;
3076: 2 1 bar .
3077: see bar
3078: @end example
3079:
3080: You can define @code{ENDIF} in this way:
3081:
3082: @example
3083: : ENDIF ( Compilation: orig -- )
3084: POSTPONE then ; immediate
3085: @end example
3086:
3087: @quotation Assignment
3088: Write @code{MY-2DUP} that has compilation semantics equivalent to
3089: @code{2dup}, but compiles @code{over over}.
3090: @end quotation
3091:
3092: @c !! @xref{Macros} for reference
3093:
3094:
3095: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3096: @section @code{Literal}
3097: @cindex literal tutorial
3098:
3099: You cannot @code{POSTPONE} numbers:
3100:
3101: @example
3102: : [FOO] POSTPONE 500 ; immediate
3103: @end example
3104:
3105: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
3106:
3107: @example
3108: : [FOO] ( compilation: --; run-time: -- n )
3109: 500 POSTPONE literal ; immediate
3110:
3111: : flip [FOO] ;
3112: flip .
3113: see flip
3114: @end example
3115:
3116: @code{LITERAL} consumes a number at compile-time (when it's compilation
3117: semantics are executed) and pushes it at run-time (when the code it
3118: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3119: number computed at compile time into the current word:
3120:
3121: @example
3122: : bar ( -- n )
3123: [ 2 2 + ] literal ;
3124: see bar
3125: @end example
3126:
3127: @quotation Assignment
3128: Write @code{]L} which allows writing the example above as @code{: bar (
3129: -- n ) [ 2 2 + ]L ;}
3130: @end quotation
3131:
3132: @c !! @xref{Macros} for reference
3133:
3134:
3135: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3136: @section Advanced macros
3137: @cindex macros, advanced tutorial
3138: @cindex run-time code generation, tutorial
3139:
3140: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3141: Execution Tokens}. It frequently performs @code{execute}, a relatively
3142: expensive operation in some Forth implementations. You can use
3143: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3144: and produce a word that contains the word to be performed directly:
3145:
3146: @c use ]] ... [[
3147: @example
3148: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3149: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3150: \ array beginning at addr and containing u elements
3151: @{ xt @}
3152: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
3153: POSTPONE i POSTPONE @@ xt compile,
3154: 1 cells POSTPONE literal POSTPONE +loop ;
3155:
3156: : sum-array ( addr u -- n )
3157: 0 rot rot [ ' + compile-map-array ] ;
3158: see sum-array
3159: a 5 sum-array .
3160: @end example
3161:
3162: You can use the full power of Forth for generating the code; here's an
3163: example where the code is generated in a loop:
3164:
3165: @example
3166: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3167: \ n2=n1+(addr1)*n, addr2=addr1+cell
3168: POSTPONE tuck POSTPONE @@
3169: POSTPONE literal POSTPONE * POSTPONE +
3170: POSTPONE swap POSTPONE cell+ ;
3171:
3172: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
3173: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
3174: 0 postpone literal postpone swap
3175: [ ' compile-vmul-step compile-map-array ]
3176: postpone drop ;
3177: see compile-vmul
3178:
3179: : a-vmul ( addr -- n )
3180: \ n=a*v, where v is a vector that's as long as a and starts at addr
3181: [ a 5 compile-vmul ] ;
3182: see a-vmul
3183: a a-vmul .
3184: @end example
3185:
3186: This example uses @code{compile-map-array} to show off, but you could
3187: also use @code{map-array} instead (try it now!).
3188:
3189: You can use this technique for efficient multiplication of large
3190: matrices. In matrix multiplication, you multiply every line of one
3191: matrix with every column of the other matrix. You can generate the code
3192: for one line once, and use it for every column. The only downside of
3193: this technique is that it is cumbersome to recover the memory consumed
3194: by the generated code when you are done (and in more complicated cases
3195: it is not possible portably).
3196:
3197: @c !! @xref{Macros} for reference
3198:
3199:
3200: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3201: @section Compilation Tokens
3202: @cindex compilation tokens, tutorial
3203: @cindex CT, tutorial
3204:
3205: This section is Gforth-specific. You can skip it.
3206:
3207: @code{' word compile,} compiles the interpretation semantics. For words
3208: with default compilation semantics this is the same as performing the
3209: compilation semantics. To represent the compilation semantics of other
3210: words (e.g., words like @code{if} that have no interpretation
3211: semantics), Gforth has the concept of a compilation token (CT,
3212: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3213: You can perform the compilation semantics represented by a CT with
3214: @code{execute}:
3215:
3216: @example
3217: : foo2 ( n1 n2 -- n )
3218: [ comp' + execute ] ;
3219: see foo
3220: @end example
3221:
3222: You can compile the compilation semantics represented by a CT with
3223: @code{postpone,}:
3224:
3225: @example
3226: : foo3 ( -- )
3227: [ comp' + postpone, ] ;
3228: see foo3
3229: @end example
3230:
3231: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
3232: @code{comp'} is particularly useful for words that have no
3233: interpretation semantics:
3234:
3235: @example
3236: ' if
3237: comp' if .s 2drop
3238: @end example
3239:
3240: Reference: @ref{Tokens for Words}.
3241:
3242:
3243: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3244: @section Wordlists and Search Order
3245: @cindex wordlists tutorial
3246: @cindex search order, tutorial
3247:
3248: The dictionary is not just a memory area that allows you to allocate
3249: memory with @code{allot}, it also contains the Forth words, arranged in
3250: several wordlists. When searching for a word in a wordlist,
3251: conceptually you start searching at the youngest and proceed towards
3252: older words (in reality most systems nowadays use hash-tables); i.e., if
3253: you define a word with the same name as an older word, the new word
3254: shadows the older word.
3255:
3256: Which wordlists are searched in which order is determined by the search
3257: order. You can display the search order with @code{order}. It displays
3258: first the search order, starting with the wordlist searched first, then
3259: it displays the wordlist that will contain newly defined words.
3260:
3261: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
3262:
3263: @example
3264: wordlist constant mywords
3265: @end example
3266:
3267: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3268: defined words (the @emph{current} wordlist):
3269:
3270: @example
3271: mywords set-current
3272: order
3273: @end example
3274:
3275: Gforth does not display a name for the wordlist in @code{mywords}
3276: because this wordlist was created anonymously with @code{wordlist}.
3277:
3278: You can get the current wordlist with @code{get-current ( -- wid)}. If
3279: you want to put something into a specific wordlist without overall
3280: effect on the current wordlist, this typically looks like this:
3281:
3282: @example
3283: get-current mywords set-current ( wid )
3284: create someword
3285: ( wid ) set-current
3286: @end example
3287:
3288: You can write the search order with @code{set-order ( wid1 .. widn n --
3289: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3290: searched wordlist is topmost.
3291:
3292: @example
3293: get-order mywords swap 1+ set-order
3294: order
3295: @end example
3296:
3297: Yes, the order of wordlists in the output of @code{order} is reversed
3298: from stack comments and the output of @code{.s} and thus unintuitive.
3299:
3300: @quotation Assignment
3301: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3302: wordlist to the search order. Define @code{previous ( -- )}, which
3303: removes the first searched wordlist from the search order. Experiment
3304: with boundary conditions (you will see some crashes or situations that
3305: are hard or impossible to leave).
3306: @end quotation
3307:
3308: The search order is a powerful foundation for providing features similar
3309: to Modula-2 modules and C++ namespaces. However, trying to modularize
3310: programs in this way has disadvantages for debugging and reuse/factoring
3311: that overcome the advantages in my experience (I don't do huge projects,
3312: though). These disadvantages are not so clear in other
3313: languages/programming environments, because these languages are not so
3314: strong in debugging and reuse.
3315:
3316: @c !! example
3317:
3318: Reference: @ref{Word Lists}.
3319:
3320: @c ******************************************************************
3321: @node Introduction, Words, Tutorial, Top
3322: @comment node-name, next, previous, up
3323: @chapter An Introduction to ANS Forth
3324: @cindex Forth - an introduction
3325:
3326: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3327: that it is slower-paced in its examples, but uses them to dive deep into
3328: explaining Forth internals (not covered by the Tutorial). Apart from
3329: that, this chapter covers far less material. It is suitable for reading
3330: without using a computer.
3331:
3332: The primary purpose of this manual is to document Gforth. However, since
3333: Forth is not a widely-known language and there is a lack of up-to-date
3334: teaching material, it seems worthwhile to provide some introductory
3335: material. For other sources of Forth-related
3336: information, see @ref{Forth-related information}.
3337:
3338: The examples in this section should work on any ANS Forth; the
3339: output shown was produced using Gforth. Each example attempts to
3340: reproduce the exact output that Gforth produces. If you try out the
3341: examples (and you should), what you should type is shown @kbd{like this}
3342: and Gforth's response is shown @code{like this}. The single exception is
3343: that, where the example shows @key{RET} it means that you should
3344: press the ``carriage return'' key. Unfortunately, some output formats for
3345: this manual cannot show the difference between @kbd{this} and
3346: @code{this} which will make trying out the examples harder (but not
3347: impossible).
3348:
3349: Forth is an unusual language. It provides an interactive development
3350: environment which includes both an interpreter and compiler. Forth
3351: programming style encourages you to break a problem down into many
3352: @cindex factoring
3353: small fragments (@dfn{factoring}), and then to develop and test each
3354: fragment interactively. Forth advocates assert that breaking the
3355: edit-compile-test cycle used by conventional programming languages can
3356: lead to great productivity improvements.
3357:
3358: @menu
3359: * Introducing the Text Interpreter::
3360: * Stacks and Postfix notation::
3361: * Your first definition::
3362: * How does that work?::
3363: * Forth is written in Forth::
3364: * Review - elements of a Forth system::
3365: * Where to go next::
3366: * Exercises::
3367: @end menu
3368:
3369: @comment ----------------------------------------------
3370: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3371: @section Introducing the Text Interpreter
3372: @cindex text interpreter
3373: @cindex outer interpreter
3374:
3375: @c IMO this is too detailed and the pace is too slow for
3376: @c an introduction. If you know German, take a look at
3377: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3378: @c to see how I do it - anton
3379:
3380: @c nac-> Where I have accepted your comments 100% and modified the text
3381: @c accordingly, I have deleted your comments. Elsewhere I have added a
3382: @c response like this to attempt to rationalise what I have done. Of
3383: @c course, this is a very clumsy mechanism for something that would be
3384: @c done far more efficiently over a beer. Please delete any dialogue
3385: @c you consider closed.
3386:
3387: When you invoke the Forth image, you will see a startup banner printed
3388: and nothing else (if you have Gforth installed on your system, try
3389: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
3390: its command line interpreter, which is called the @dfn{Text Interpreter}
3391: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
3392: about the text interpreter as you read through this chapter, for more
3393: detail @pxref{The Text Interpreter}).
3394:
3395: Although it's not obvious, Forth is actually waiting for your
3396: input. Type a number and press the @key{RET} key:
3397:
3398: @example
3399: @kbd{45@key{RET}} ok
3400: @end example
3401:
3402: Rather than give you a prompt to invite you to input something, the text
3403: interpreter prints a status message @i{after} it has processed a line
3404: of input. The status message in this case (``@code{ ok}'' followed by
3405: carriage-return) indicates that the text interpreter was able to process
3406: all of your input successfully. Now type something illegal:
3407:
3408: @example
3409: @kbd{qwer341@key{RET}}
3410: *the terminal*:2: Undefined word
3411: >>>qwer341<<<
3412: Backtrace:
3413: $2A95B42A20 throw
3414: $2A95B57FB8 no.extensions
3415: @end example
3416:
3417: The exact text, other than the ``Undefined word'' may differ slightly
3418: on your system, but the effect is the same; when the text interpreter
3419: detects an error, it discards any remaining text on a line, resets
3420: certain internal state and prints an error message. For a detailed
3421: description of error messages see @ref{Error messages}.
3422:
3423: The text interpreter waits for you to press carriage-return, and then
3424: processes your input line. Starting at the beginning of the line, it
3425: breaks the line into groups of characters separated by spaces. For each
3426: group of characters in turn, it makes two attempts to do something:
3427:
3428: @itemize @bullet
3429: @item
3430: @cindex name dictionary
3431: It tries to treat it as a command. It does this by searching a @dfn{name
3432: dictionary}. If the group of characters matches an entry in the name
3433: dictionary, the name dictionary provides the text interpreter with
3434: information that allows the text interpreter perform some actions. In
3435: Forth jargon, we say that the group
3436: @cindex word
3437: @cindex definition
3438: @cindex execution token
3439: @cindex xt
3440: of characters names a @dfn{word}, that the dictionary search returns an
3441: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3442: word, and that the text interpreter executes the xt. Often, the terms
3443: @dfn{word} and @dfn{definition} are used interchangeably.
3444: @item
3445: If the text interpreter fails to find a match in the name dictionary, it
3446: tries to treat the group of characters as a number in the current number
3447: base (when you start up Forth, the current number base is base 10). If
3448: the group of characters legitimately represents a number, the text
3449: interpreter pushes the number onto a stack (we'll learn more about that
3450: in the next section).
3451: @end itemize
3452:
3453: If the text interpreter is unable to do either of these things with any
3454: group of characters, it discards the group of characters and the rest of
3455: the line, then prints an error message. If the text interpreter reaches
3456: the end of the line without error, it prints the status message ``@code{ ok}''
3457: followed by carriage-return.
3458:
3459: This is the simplest command we can give to the text interpreter:
3460:
3461: @example
3462: @key{RET} ok
3463: @end example
3464:
3465: The text interpreter did everything we asked it to do (nothing) without
3466: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3467: command:
3468:
3469: @example
3470: @kbd{12 dup fred dup@key{RET}}
3471: *the terminal*:3: Undefined word
3472: 12 dup >>>fred<<< dup
3473: Backtrace:
3474: $2A95B42A20 throw
3475: $2A95B57FB8 no.extensions
3476: @end example
3477:
3478: When you press the carriage-return key, the text interpreter starts to
3479: work its way along the line:
3480:
3481: @itemize @bullet
3482: @item
3483: When it gets to the space after the @code{2}, it takes the group of
3484: characters @code{12} and looks them up in the name
3485: dictionary@footnote{We can't tell if it found them or not, but assume
3486: for now that it did not}. There is no match for this group of characters
3487: in the name dictionary, so it tries to treat them as a number. It is
3488: able to do this successfully, so it puts the number, 12, ``on the stack''
3489: (whatever that means).
3490: @item
3491: The text interpreter resumes scanning the line and gets the next group
3492: of characters, @code{dup}. It looks it up in the name dictionary and
3493: (you'll have to take my word for this) finds it, and executes the word
3494: @code{dup} (whatever that means).
3495: @item
3496: Once again, the text interpreter resumes scanning the line and gets the
3497: group of characters @code{fred}. It looks them up in the name
3498: dictionary, but can't find them. It tries to treat them as a number, but
3499: they don't represent any legal number.
3500: @end itemize
3501:
3502: At this point, the text interpreter gives up and prints an error
3503: message. The error message shows exactly how far the text interpreter
3504: got in processing the line. In particular, it shows that the text
3505: interpreter made no attempt to do anything with the final character
3506: group, @code{dup}, even though we have good reason to believe that the
3507: text interpreter would have no problem looking that word up and
3508: executing it a second time.
3509:
3510:
3511: @comment ----------------------------------------------
3512: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3513: @section Stacks, postfix notation and parameter passing
3514: @cindex text interpreter
3515: @cindex outer interpreter
3516:
3517: In procedural programming languages (like C and Pascal), the
3518: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3519: functions or procedures are called with @dfn{explicit parameters}. For
3520: example, in C we might write:
3521:
3522: @example
3523: total = total + new_volume(length,height,depth);
3524: @end example
3525:
3526: @noindent
3527: where new_volume is a function-call to another piece of code, and total,
3528: length, height and depth are all variables. length, height and depth are
3529: parameters to the function-call.
3530:
3531: In Forth, the equivalent of the function or procedure is the
3532: @dfn{definition} and parameters are implicitly passed between
3533: definitions using a shared stack that is visible to the
3534: programmer. Although Forth does support variables, the existence of the
3535: stack means that they are used far less often than in most other
3536: programming languages. When the text interpreter encounters a number, it
3537: will place (@dfn{push}) it on the stack. There are several stacks (the
3538: actual number is implementation-dependent ...) and the particular stack
3539: used for any operation is implied unambiguously by the operation being
3540: performed. The stack used for all integer operations is called the @dfn{data
3541: stack} and, since this is the stack used most commonly, references to
3542: ``the data stack'' are often abbreviated to ``the stack''.
3543:
3544: The stacks have a last-in, first-out (LIFO) organisation. If you type:
3545:
3546: @example
3547: @kbd{1 2 3@key{RET}} ok
3548: @end example
3549:
3550: Then this instructs the text interpreter to placed three numbers on the
3551: (data) stack. An analogy for the behaviour of the stack is to take a
3552: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3553: the table. The 3 was the last card onto the pile (``last-in'') and if
3554: you take a card off the pile then, unless you're prepared to fiddle a
3555: bit, the card that you take off will be the 3 (``first-out''). The
3556: number that will be first-out of the stack is called the @dfn{top of
3557: stack}, which
3558: @cindex TOS definition
3559: is often abbreviated to @dfn{TOS}.
3560:
3561: To understand how parameters are passed in Forth, consider the
3562: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3563: be surprised to learn that this definition performs addition. More
3564: precisely, it adds two number together and produces a result. Where does
3565: it get the two numbers from? It takes the top two numbers off the
3566: stack. Where does it place the result? On the stack. You can act-out the
3567: behaviour of @code{+} with your playing cards like this:
3568:
3569: @itemize @bullet
3570: @item
3571: Pick up two cards from the stack on the table
3572: @item
3573: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3574: numbers''
3575: @item
3576: Decide that the answer is 5
3577: @item
3578: Shuffle the two cards back into the pack and find a 5
3579: @item
3580: Put a 5 on the remaining ace that's on the table.
3581: @end itemize
3582:
3583: If you don't have a pack of cards handy but you do have Forth running,
3584: you can use the definition @code{.s} to show the current state of the stack,
3585: without affecting the stack. Type:
3586:
3587: @example
3588: @kbd{clearstacks 1 2 3@key{RET}} ok
3589: @kbd{.s@key{RET}} <3> 1 2 3 ok
3590: @end example
3591:
3592: The text interpreter looks up the word @code{clearstacks} and executes
3593: it; it tidies up the stacks and removes any entries that may have been
3594: left on it by earlier examples. The text interpreter pushes each of the
3595: three numbers in turn onto the stack. Finally, the text interpreter
3596: looks up the word @code{.s} and executes it. The effect of executing
3597: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3598: followed by a list of all the items on the stack; the item on the far
3599: right-hand side is the TOS.
3600:
3601: You can now type:
3602:
3603: @example
3604: @kbd{+ .s@key{RET}} <2> 1 5 ok
3605: @end example
3606:
3607: @noindent
3608: which is correct; there are now 2 items on the stack and the result of
3609: the addition is 5.
3610:
3611: If you're playing with cards, try doing a second addition: pick up the
3612: two cards, work out that their sum is 6, shuffle them into the pack,
3613: look for a 6 and place that on the table. You now have just one item on
3614: the stack. What happens if you try to do a third addition? Pick up the
3615: first card, pick up the second card -- ah! There is no second card. This
3616: is called a @dfn{stack underflow} and consitutes an error. If you try to
3617: do the same thing with Forth it often reports an error (probably a Stack
3618: Underflow or an Invalid Memory Address error).
3619:
3620: The opposite situation to a stack underflow is a @dfn{stack overflow},
3621: which simply accepts that there is a finite amount of storage space
3622: reserved for the stack. To stretch the playing card analogy, if you had
3623: enough packs of cards and you piled the cards up on the table, you would
3624: eventually be unable to add another card; you'd hit the ceiling. Gforth
3625: allows you to set the maximum size of the stacks. In general, the only
3626: time that you will get a stack overflow is because a definition has a
3627: bug in it and is generating data on the stack uncontrollably.
3628:
3629: There's one final use for the playing card analogy. If you model your
3630: stack using a pack of playing cards, the maximum number of items on
3631: your stack will be 52 (I assume you didn't use the Joker). The maximum
3632: @i{value} of any item on the stack is 13 (the King). In fact, the only
3633: possible numbers are positive integer numbers 1 through 13; you can't
3634: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3635: think about some of the cards, you can accommodate different
3636: numbers. For example, you could think of the Jack as representing 0,
3637: the Queen as representing -1 and the King as representing -2. Your
3638: @i{range} remains unchanged (you can still only represent a total of 13
3639: numbers) but the numbers that you can represent are -2 through 10.
3640:
3641: In that analogy, the limit was the amount of information that a single
3642: stack entry could hold, and Forth has a similar limit. In Forth, the
3643: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3644: implementation dependent and affects the maximum value that a stack
3645: entry can hold. A Standard Forth provides a cell size of at least
3646: 16-bits, and most desktop systems use a cell size of 32-bits.
3647:
3648: Forth does not do any type checking for you, so you are free to
3649: manipulate and combine stack items in any way you wish. A convenient way
3650: of treating stack items is as 2's complement signed integers, and that
3651: is what Standard words like @code{+} do. Therefore you can type:
3652:
3653: @example
3654: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
3655: @end example
3656:
3657: If you use numbers and definitions like @code{+} in order to turn Forth
3658: into a great big pocket calculator, you will realise that it's rather
3659: different from a normal calculator. Rather than typing 2 + 3 = you had
3660: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3661: result). The terminology used to describe this difference is to say that
3662: your calculator uses @dfn{Infix Notation} (parameters and operators are
3663: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3664: operators are separate), also called @dfn{Reverse Polish Notation}.
3665:
3666: Whilst postfix notation might look confusing to begin with, it has
3667: several important advantages:
3668:
3669: @itemize @bullet
3670: @item
3671: it is unambiguous
3672: @item
3673: it is more concise
3674: @item
3675: it fits naturally with a stack-based system
3676: @end itemize
3677:
3678: To examine these claims in more detail, consider these sums:
3679:
3680: @example
3681: 6 + 5 * 4 =
3682: 4 * 5 + 6 =
3683: @end example
3684:
3685: If you're just learning maths or your maths is very rusty, you will
3686: probably come up with the answer 44 for the first and 26 for the
3687: second. If you are a bit of a whizz at maths you will remember the
3688: @i{convention} that multiplication takes precendence over addition, and
3689: you'd come up with the answer 26 both times. To explain the answer 26
3690: to someone who got the answer 44, you'd probably rewrite the first sum
3691: like this:
3692:
3693: @example
3694: 6 + (5 * 4) =
3695: @end example
3696:
3697: If what you really wanted was to perform the addition before the
3698: multiplication, you would have to use parentheses to force it.
3699:
3700: If you did the first two sums on a pocket calculator you would probably
3701: get the right answers, unless you were very cautious and entered them using
3702: these keystroke sequences:
3703:
3704: 6 + 5 = * 4 =
3705: 4 * 5 = + 6 =
3706:
3707: Postfix notation is unambiguous because the order that the operators
3708: are applied is always explicit; that also means that parentheses are
3709: never required. The operators are @i{active} (the act of quoting the
3710: operator makes the operation occur) which removes the need for ``=''.
3711:
3712: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3713: equivalent ways:
3714:
3715: @example
3716: 6 5 4 * + or:
3717: 5 4 * 6 +
3718: @end example
3719:
3720: An important thing that you should notice about this notation is that
3721: the @i{order} of the numbers does not change; if you want to subtract
3722: 2 from 10 you type @code{10 2 -}.
3723:
3724: The reason that Forth uses postfix notation is very simple to explain: it
3725: makes the implementation extremely simple, and it follows naturally from
3726: using the stack as a mechanism for passing parameters. Another way of
3727: thinking about this is to realise that all Forth definitions are
3728: @i{active}; they execute as they are encountered by the text
3729: interpreter. The result of this is that the syntax of Forth is trivially
3730: simple.
3731:
3732:
3733:
3734: @comment ----------------------------------------------
3735: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3736: @section Your first Forth definition
3737: @cindex first definition
3738:
3739: Until now, the examples we've seen have been trivial; we've just been
3740: using Forth as a bigger-than-pocket calculator. Also, each calculation
3741: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3742: again@footnote{That's not quite true. If you press the up-arrow key on
3743: your keyboard you should be able to scroll back to any earlier command,
3744: edit it and re-enter it.} In this section we'll see how to add new
3745: words to Forth's vocabulary.
3746:
3747: The easiest way to create a new word is to use a @dfn{colon
3748: definition}. We'll define a few and try them out before worrying too
3749: much about how they work. Try typing in these examples; be careful to
3750: copy the spaces accurately:
3751:
3752: @example
3753: : add-two 2 + . ;
3754: : greet ." Hello and welcome" ;
3755: : demo 5 add-two ;
3756: @end example
3757:
3758: @noindent
3759: Now try them out:
3760:
3761: @example
3762: @kbd{greet@key{RET}} Hello and welcome ok
3763: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3764: @kbd{4 add-two@key{RET}} 6 ok
3765: @kbd{demo@key{RET}} 7 ok
3766: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
3767: @end example
3768:
3769: The first new thing that we've introduced here is the pair of words
3770: @code{:} and @code{;}. These are used to start and terminate a new
3771: definition, respectively. The first word after the @code{:} is the name
3772: for the new definition.
3773:
3774: As you can see from the examples, a definition is built up of words that
3775: have already been defined; Forth makes no distinction between
3776: definitions that existed when you started the system up, and those that
3777: you define yourself.
3778:
3779: The examples also introduce the words @code{.} (dot), @code{."}
3780: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3781: the stack and displays it. It's like @code{.s} except that it only
3782: displays the top item of the stack and it is destructive; after it has
3783: executed, the number is no longer on the stack. There is always one
3784: space printed after the number, and no spaces before it. Dot-quote
3785: defines a string (a sequence of characters) that will be printed when
3786: the word is executed. The string can contain any printable characters
3787: except @code{"}. A @code{"} has a special function; it is not a Forth
3788: word but it acts as a delimiter (the way that delimiters work is
3789: described in the next section). Finally, @code{dup} duplicates the value
3790: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
3791:
3792: We already know that the text interpreter searches through the
3793: dictionary to locate names. If you've followed the examples earlier, you
3794: will already have a definition called @code{add-two}. Lets try modifying
3795: it by typing in a new definition:
3796:
3797: @example
3798: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
3799: @end example
3800:
3801: Forth recognised that we were defining a word that already exists, and
3802: printed a message to warn us of that fact. Let's try out the new
3803: definition:
3804:
3805: @example
3806: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
3807: @end example
3808:
3809: @noindent
3810: All that we've actually done here, though, is to create a new
3811: definition, with a particular name. The fact that there was already a
3812: definition with the same name did not make any difference to the way
3813: that the new definition was created (except that Forth printed a warning
3814: message). The old definition of add-two still exists (try @code{demo}
3815: again to see that this is true). Any new definition will use the new
3816: definition of @code{add-two}, but old definitions continue to use the
3817: version that already existed at the time that they were @code{compiled}.
3818:
3819: Before you go on to the next section, try defining and redefining some
3820: words of your own.
3821:
3822: @comment ----------------------------------------------
3823: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3824: @section How does that work?
3825: @cindex parsing words
3826:
3827: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3828:
3829: @c Is it a good idea to talk about the interpretation semantics of a
3830: @c number? We don't have an xt to go along with it. - anton
3831:
3832: @c Now that I have eliminated execution semantics, I wonder if it would not
3833: @c be better to keep them (or add run-time semantics), to make it easier to
3834: @c explain what compilation semantics usually does. - anton
3835:
3836: @c nac-> I removed the term ``default compilation sematics'' from the
3837: @c introductory chapter. Removing ``execution semantics'' was making
3838: @c everything simpler to explain, then I think the use of this term made
3839: @c everything more complex again. I replaced it with ``default
3840: @c semantics'' (which is used elsewhere in the manual) by which I mean
3841: @c ``a definition that has neither the immediate nor the compile-only
3842: @c flag set''.
3843:
3844: @c anton: I have eliminated default semantics (except in one place where it
3845: @c means "default interpretation and compilation semantics"), because it
3846: @c makes no sense in the presence of combined words. I reverted to
3847: @c "execution semantics" where necessary.
3848:
3849: @c nac-> I reworded big chunks of the ``how does that work''
3850: @c section (and, unusually for me, I think I even made it shorter!). See
3851: @c what you think -- I know I have not addressed your primary concern
3852: @c that it is too heavy-going for an introduction. From what I understood
3853: @c of your course notes it looks as though they might be a good framework.
3854: @c Things that I've tried to capture here are some things that came as a
3855: @c great revelation here when I first understood them. Also, I like the
3856: @c fact that a very simple code example shows up almost all of the issues
3857: @c that you need to understand to see how Forth works. That's unique and
3858: @c worthwhile to emphasise.
3859:
3860: @c anton: I think it's a good idea to present the details, especially those
3861: @c that you found to be a revelation, and probably the tutorial tries to be
3862: @c too superficial and does not get some of the things across that make
3863: @c Forth special. I do believe that most of the time these things should
3864: @c be discussed at the end of a section or in separate sections instead of
3865: @c in the middle of a section (e.g., the stuff you added in "User-defined
3866: @c defining words" leads in a completely different direction from the rest
3867: @c of the section).
3868:
3869: Now we're going to take another look at the definition of @code{add-two}
3870: from the previous section. From our knowledge of the way that the text
3871: interpreter works, we would have expected this result when we tried to
3872: define @code{add-two}:
3873:
3874: @example
3875: @kbd{: add-two 2 + . ;@key{RET}}
3876: *the terminal*:4: Undefined word
3877: : >>>add-two<<< 2 + . ;
3878: @end example
3879:
3880: The reason that this didn't happen is bound up in the way that @code{:}
3881: works. The word @code{:} does two special things. The first special
3882: thing that it does prevents the text interpreter from ever seeing the
3883: characters @code{add-two}. The text interpreter uses a variable called
3884: @cindex modifying >IN
3885: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
3886: input line. When it encounters the word @code{:} it behaves in exactly
3887: the same way as it does for any other word; it looks it up in the name
3888: dictionary, finds its xt and executes it. When @code{:} executes, it
3889: looks at the input buffer, finds the word @code{add-two} and advances the
3890: value of @code{>IN} to point past it. It then does some other stuff
3891: associated with creating the new definition (including creating an entry
3892: for @code{add-two} in the name dictionary). When the execution of @code{:}
3893: completes, control returns to the text interpreter, which is oblivious
3894: to the fact that it has been tricked into ignoring part of the input
3895: line.
3896:
3897: @cindex parsing words
3898: Words like @code{:} -- words that advance the value of @code{>IN} and so
3899: prevent the text interpreter from acting on the whole of the input line
3900: -- are called @dfn{parsing words}.
3901:
3902: @cindex @code{state} - effect on the text interpreter
3903: @cindex text interpreter - effect of state
3904: The second special thing that @code{:} does is change the value of a
3905: variable called @code{state}, which affects the way that the text
3906: interpreter behaves. When Gforth starts up, @code{state} has the value
3907: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3908: colon definition (started with @code{:}), @code{state} is set to -1 and
3909: the text interpreter is said to be @dfn{compiling}.
3910:
3911: In this example, the text interpreter is compiling when it processes the
3912: string ``@code{2 + . ;}''. It still breaks the string down into
3913: character sequences in the same way. However, instead of pushing the
3914: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
3915: into the definition of @code{add-two} that will make the number @code{2} get
3916: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
3917: the behaviours of @code{+} and @code{.} are also compiled into the
3918: definition.
3919:
3920: One category of words don't get compiled. These so-called @dfn{immediate
3921: words} get executed (performed @i{now}) regardless of whether the text
3922: interpreter is interpreting or compiling. The word @code{;} is an
3923: immediate word. Rather than being compiled into the definition, it
3924: executes. Its effect is to terminate the current definition, which
3925: includes changing the value of @code{state} back to 0.
3926:
3927: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
3928: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
3929: definition.
3930:
3931: In Forth, every word or number can be described in terms of two
3932: properties:
3933:
3934: @itemize @bullet
3935: @item
3936: @cindex interpretation semantics
3937: Its @dfn{interpretation semantics} describe how it will behave when the
3938: text interpreter encounters it in @dfn{interpret} state. The
3939: interpretation semantics of a word are represented by an @dfn{execution
3940: token}.
3941: @item
3942: @cindex compilation semantics
3943: Its @dfn{compilation semantics} describe how it will behave when the
3944: text interpreter encounters it in @dfn{compile} state. The compilation
3945: semantics of a word are represented in an implementation-dependent way;
3946: Gforth uses a @dfn{compilation token}.
3947: @end itemize
3948:
3949: @noindent
3950: Numbers are always treated in a fixed way:
3951:
3952: @itemize @bullet
3953: @item
3954: When the number is @dfn{interpreted}, its behaviour is to push the
3955: number onto the stack.
3956: @item
3957: When the number is @dfn{compiled}, a piece of code is appended to the
3958: current definition that pushes the number when it runs. (In other words,
3959: the compilation semantics of a number are to postpone its interpretation
3960: semantics until the run-time of the definition that it is being compiled
3961: into.)
3962: @end itemize
3963:
3964: Words don't behave in such a regular way, but most have @i{default
3965: semantics} which means that they behave like this:
3966:
3967: @itemize @bullet
3968: @item
3969: The @dfn{interpretation semantics} of the word are to do something useful.
3970: @item
3971: The @dfn{compilation semantics} of the word are to append its
3972: @dfn{interpretation semantics} to the current definition (so that its
3973: run-time behaviour is to do something useful).
3974: @end itemize
3975:
3976: @cindex immediate words
3977: The actual behaviour of any particular word can be controlled by using
3978: the words @code{immediate} and @code{compile-only} when the word is
3979: defined. These words set flags in the name dictionary entry of the most
3980: recently defined word, and these flags are retrieved by the text
3981: interpreter when it finds the word in the name dictionary.
3982:
3983: A word that is marked as @dfn{immediate} has compilation semantics that
3984: are identical to its interpretation semantics. In other words, it
3985: behaves like this:
3986:
3987: @itemize @bullet
3988: @item
3989: The @dfn{interpretation semantics} of the word are to do something useful.
3990: @item
3991: The @dfn{compilation semantics} of the word are to do something useful
3992: (and actually the same thing); i.e., it is executed during compilation.
3993: @end itemize
3994:
3995: Marking a word as @dfn{compile-only} prohibits the text interpreter from
3996: performing the interpretation semantics of the word directly; an attempt
3997: to do so will generate an error. It is never necessary to use
3998: @code{compile-only} (and it is not even part of ANS Forth, though it is
3999: provided by many implementations) but it is good etiquette to apply it
4000: to a word that will not behave correctly (and might have unexpected
4001: side-effects) in interpret state. For example, it is only legal to use
4002: the conditional word @code{IF} within a definition. If you forget this
4003: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4004: @code{compile-only} allows the text interpreter to generate a helpful
4005: error message rather than subjecting you to the consequences of your
4006: folly.
4007:
4008: This example shows the difference between an immediate and a
4009: non-immediate word:
4010:
4011: @example
4012: : show-state state @@ . ;
4013: : show-state-now show-state ; immediate
4014: : word1 show-state ;
4015: : word2 show-state-now ;
4016: @end example
4017:
4018: The word @code{immediate} after the definition of @code{show-state-now}
4019: makes that word an immediate word. These definitions introduce a new
4020: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4021: variable, and leaves it on the stack. Therefore, the behaviour of
4022: @code{show-state} is to print a number that represents the current value
4023: of @code{state}.
4024:
4025: When you execute @code{word1}, it prints the number 0, indicating that
4026: the system is interpreting. When the text interpreter compiled the
4027: definition of @code{word1}, it encountered @code{show-state} whose
4028: compilation semantics are to append its interpretation semantics to the
4029: current definition. When you execute @code{word1}, it performs the
4030: interpretation semantics of @code{show-state}. At the time that @code{word1}
4031: (and therefore @code{show-state}) are executed, the system is
4032: interpreting.
4033:
4034: When you pressed @key{RET} after entering the definition of @code{word2},
4035: you should have seen the number -1 printed, followed by ``@code{
4036: ok}''. When the text interpreter compiled the definition of
4037: @code{word2}, it encountered @code{show-state-now}, an immediate word,
4038: whose compilation semantics are therefore to perform its interpretation
4039: semantics. It is executed straight away (even before the text
4040: interpreter has moved on to process another group of characters; the
4041: @code{;} in this example). The effect of executing it are to display the
4042: value of @code{state} @i{at the time that the definition of}
4043: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4044: system is compiling at this time. If you execute @code{word2} it does
4045: nothing at all.
4046:
4047: @cindex @code{."}, how it works
4048: Before leaving the subject of immediate words, consider the behaviour of
4049: @code{."} in the definition of @code{greet}, in the previous
4050: section. This word is both a parsing word and an immediate word. Notice
4051: that there is a space between @code{."} and the start of the text
4052: @code{Hello and welcome}, but that there is no space between the last
4053: letter of @code{welcome} and the @code{"} character. The reason for this
4054: is that @code{."} is a Forth word; it must have a space after it so that
4055: the text interpreter can identify it. The @code{"} is not a Forth word;
4056: it is a @dfn{delimiter}. The examples earlier show that, when the string
4057: is displayed, there is neither a space before the @code{H} nor after the
4058: @code{e}. Since @code{."} is an immediate word, it executes at the time
4059: that @code{greet} is defined. When it executes, its behaviour is to
4060: search forward in the input line looking for the delimiter. When it
4061: finds the delimiter, it updates @code{>IN} to point past the
4062: delimiter. It also compiles some magic code into the definition of
4063: @code{greet}; the xt of a run-time routine that prints a text string. It
4064: compiles the string @code{Hello and welcome} into memory so that it is
4065: available to be printed later. When the text interpreter gains control,
4066: the next word it finds in the input stream is @code{;} and so it
4067: terminates the definition of @code{greet}.
4068:
4069:
4070: @comment ----------------------------------------------
4071: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4072: @section Forth is written in Forth
4073: @cindex structure of Forth programs
4074:
4075: When you start up a Forth compiler, a large number of definitions
4076: already exist. In Forth, you develop a new application using bottom-up
4077: programming techniques to create new definitions that are defined in
4078: terms of existing definitions. As you create each definition you can
4079: test and debug it interactively.
4080:
4081: If you have tried out the examples in this section, you will probably
4082: have typed them in by hand; when you leave Gforth, your definitions will
4083: be lost. You can avoid this by using a text editor to enter Forth source
4084: code into a file, and then loading code from the file using
4085: @code{include} (@pxref{Forth source files}). A Forth source file is
4086: processed by the text interpreter, just as though you had typed it in by
4087: hand@footnote{Actually, there are some subtle differences -- see
4088: @ref{The Text Interpreter}.}.
4089:
4090: Gforth also supports the traditional Forth alternative to using text
4091: files for program entry (@pxref{Blocks}).
4092:
4093: In common with many, if not most, Forth compilers, most of Gforth is
4094: actually written in Forth. All of the @file{.fs} files in the
4095: installation directory@footnote{For example,
4096: @file{/usr/local/share/gforth...}} are Forth source files, which you can
4097: study to see examples of Forth programming.
4098:
4099: Gforth maintains a history file that records every line that you type to
4100: the text interpreter. This file is preserved between sessions, and is
4101: used to provide a command-line recall facility. If you enter long
4102: definitions by hand, you can use a text editor to paste them out of the
4103: history file into a Forth source file for reuse at a later time
4104: (for more information @pxref{Command-line editing}).
4105:
4106:
4107: @comment ----------------------------------------------
4108: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4109: @section Review - elements of a Forth system
4110: @cindex elements of a Forth system
4111:
4112: To summarise this chapter:
4113:
4114: @itemize @bullet
4115: @item
4116: Forth programs use @dfn{factoring} to break a problem down into small
4117: fragments called @dfn{words} or @dfn{definitions}.
4118: @item
4119: Forth program development is an interactive process.
4120: @item
4121: The main command loop that accepts input, and controls both
4122: interpretation and compilation, is called the @dfn{text interpreter}
4123: (also known as the @dfn{outer interpreter}).
4124: @item
4125: Forth has a very simple syntax, consisting of words and numbers
4126: separated by spaces or carriage-return characters. Any additional syntax
4127: is imposed by @dfn{parsing words}.
4128: @item
4129: Forth uses a stack to pass parameters between words. As a result, it
4130: uses postfix notation.
4131: @item
4132: To use a word that has previously been defined, the text interpreter
4133: searches for the word in the @dfn{name dictionary}.
4134: @item
4135: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
4136: @item
4137: The text interpreter uses the value of @code{state} to select between
4138: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4139: semantics} of a word that it encounters.
4140: @item
4141: The relationship between the @dfn{interpretation semantics} and
4142: @dfn{compilation semantics} for a word
4143: depend upon the way in which the word was defined (for example, whether
4144: it is an @dfn{immediate} word).
4145: @item
4146: Forth definitions can be implemented in Forth (called @dfn{high-level
4147: definitions}) or in some other way (usually a lower-level language and
4148: as a result often called @dfn{low-level definitions}, @dfn{code
4149: definitions} or @dfn{primitives}).
4150: @item
4151: Many Forth systems are implemented mainly in Forth.
4152: @end itemize
4153:
4154:
4155: @comment ----------------------------------------------
4156: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
4157: @section Where To Go Next
4158: @cindex where to go next
4159:
4160: Amazing as it may seem, if you have read (and understood) this far, you
4161: know almost all the fundamentals about the inner workings of a Forth
4162: system. You certainly know enough to be able to read and understand the
4163: rest of this manual and the ANS Forth document, to learn more about the
4164: facilities that Forth in general and Gforth in particular provide. Even
4165: scarier, you know almost enough to implement your own Forth system.
4166: However, that's not a good idea just yet... better to try writing some
4167: programs in Gforth.
4168:
4169: Forth has such a rich vocabulary that it can be hard to know where to
4170: start in learning it. This section suggests a few sets of words that are
4171: enough to write small but useful programs. Use the word index in this
4172: document to learn more about each word, then try it out and try to write
4173: small definitions using it. Start by experimenting with these words:
4174:
4175: @itemize @bullet
4176: @item
4177: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4178: @item
4179: Comparison: @code{MIN MAX =}
4180: @item
4181: Logic: @code{AND OR XOR NOT}
4182: @item
4183: Stack manipulation: @code{DUP DROP SWAP OVER}
4184: @item
4185: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
4186: @item
4187: Input/Output: @code{. ." EMIT CR KEY}
4188: @item
4189: Defining words: @code{: ; CREATE}
4190: @item
4191: Memory allocation words: @code{ALLOT ,}
4192: @item
4193: Tools: @code{SEE WORDS .S MARKER}
4194: @end itemize
4195:
4196: When you have mastered those, go on to:
4197:
4198: @itemize @bullet
4199: @item
4200: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
4201: @item
4202: Memory access: @code{@@ !}
4203: @end itemize
4204:
4205: When you have mastered these, there's nothing for it but to read through
4206: the whole of this manual and find out what you've missed.
4207:
4208: @comment ----------------------------------------------
4209: @node Exercises, , Where to go next, Introduction
4210: @section Exercises
4211: @cindex exercises
4212:
4213: TODO: provide a set of programming excercises linked into the stuff done
4214: already and into other sections of the manual. Provide solutions to all
4215: the exercises in a .fs file in the distribution.
4216:
4217: @c Get some inspiration from Starting Forth and Kelly&Spies.
4218:
4219: @c excercises:
4220: @c 1. take inches and convert to feet and inches.
4221: @c 2. take temperature and convert from fahrenheight to celcius;
4222: @c may need to care about symmetric vs floored??
4223: @c 3. take input line and do character substitution
4224: @c to encipher or decipher
4225: @c 4. as above but work on a file for in and out
4226: @c 5. take input line and convert to pig-latin
4227: @c
4228: @c thing of sets of things to exercise then come up with
4229: @c problems that need those things.
4230:
4231:
4232: @c ******************************************************************
4233: @node Words, Error messages, Introduction, Top
4234: @chapter Forth Words
4235: @cindex words
4236:
4237: @menu
4238: * Notation::
4239: * Case insensitivity::
4240: * Comments::
4241: * Boolean Flags::
4242: * Arithmetic::
4243: * Stack Manipulation::
4244: * Memory::
4245: * Control Structures::
4246: * Defining Words::
4247: * Interpretation and Compilation Semantics::
4248: * Tokens for Words::
4249: * Compiling words::
4250: * The Text Interpreter::
4251: * The Input Stream::
4252: * Word Lists::
4253: * Environmental Queries::
4254: * Files::
4255: * Blocks::
4256: * Other I/O::
4257: * OS command line arguments::
4258: * Locals::
4259: * Structures::
4260: * Object-oriented Forth::
4261: * Programming Tools::
4262: * C Interface::
4263: * Assembler and Code Words::
4264: * Threading Words::
4265: * Passing Commands to the OS::
4266: * Keeping track of Time::
4267: * Miscellaneous Words::
4268: @end menu
4269:
4270: @node Notation, Case insensitivity, Words, Words
4271: @section Notation
4272: @cindex notation of glossary entries
4273: @cindex format of glossary entries
4274: @cindex glossary notation format
4275: @cindex word glossary entry format
4276:
4277: The Forth words are described in this section in the glossary notation
4278: that has become a de-facto standard for Forth texts:
4279:
4280: @format
4281: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
4282: @end format
4283: @i{Description}
4284:
4285: @table @var
4286: @item word
4287: The name of the word.
4288:
4289: @item Stack effect
4290: @cindex stack effect
4291: The stack effect is written in the notation @code{@i{before} --
4292: @i{after}}, where @i{before} and @i{after} describe the top of
4293: stack entries before and after the execution of the word. The rest of
4294: the stack is not touched by the word. The top of stack is rightmost,
4295: i.e., a stack sequence is written as it is typed in. Note that Gforth
4296: uses a separate floating point stack, but a unified stack
4297: notation. Also, return stack effects are not shown in @i{stack
4298: effect}, but in @i{Description}. The name of a stack item describes
4299: the type and/or the function of the item. See below for a discussion of
4300: the types.
4301:
4302: All words have two stack effects: A compile-time stack effect and a
4303: run-time stack effect. The compile-time stack-effect of most words is
4304: @i{ -- }. If the compile-time stack-effect of a word deviates from
4305: this standard behaviour, or the word does other unusual things at
4306: compile time, both stack effects are shown; otherwise only the run-time
4307: stack effect is shown.
4308:
4309: @cindex pronounciation of words
4310: @item pronunciation
4311: How the word is pronounced.
4312:
4313: @cindex wordset
4314: @cindex environment wordset
4315: @item wordset
4316: The ANS Forth standard is divided into several word sets. A standard
4317: system need not support all of them. Therefore, in theory, the fewer
4318: word sets your program uses the more portable it will be. However, we
4319: suspect that most ANS Forth systems on personal machines will feature
4320: all word sets. Words that are not defined in ANS Forth have
4321: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
4322: describes words that will work in future releases of Gforth;
4323: @code{gforth-internal} words are more volatile. Environmental query
4324: strings are also displayed like words; you can recognize them by the
4325: @code{environment} in the word set field.
4326:
4327: @item Description
4328: A description of the behaviour of the word.
4329: @end table
4330:
4331: @cindex types of stack items
4332: @cindex stack item types
4333: The type of a stack item is specified by the character(s) the name
4334: starts with:
4335:
4336: @table @code
4337: @item f
4338: @cindex @code{f}, stack item type
4339: Boolean flags, i.e. @code{false} or @code{true}.
4340: @item c
4341: @cindex @code{c}, stack item type
4342: Char
4343: @item w
4344: @cindex @code{w}, stack item type
4345: Cell, can contain an integer or an address
4346: @item n
4347: @cindex @code{n}, stack item type
4348: signed integer
4349: @item u
4350: @cindex @code{u}, stack item type
4351: unsigned integer
4352: @item d
4353: @cindex @code{d}, stack item type
4354: double sized signed integer
4355: @item ud
4356: @cindex @code{ud}, stack item type
4357: double sized unsigned integer
4358: @item r
4359: @cindex @code{r}, stack item type
4360: Float (on the FP stack)
4361: @item a-
4362: @cindex @code{a_}, stack item type
4363: Cell-aligned address
4364: @item c-
4365: @cindex @code{c_}, stack item type
4366: Char-aligned address (note that a Char may have two bytes in Windows NT)
4367: @item f-
4368: @cindex @code{f_}, stack item type
4369: Float-aligned address
4370: @item df-
4371: @cindex @code{df_}, stack item type
4372: Address aligned for IEEE double precision float
4373: @item sf-
4374: @cindex @code{sf_}, stack item type
4375: Address aligned for IEEE single precision float
4376: @item xt
4377: @cindex @code{xt}, stack item type
4378: Execution token, same size as Cell
4379: @item wid
4380: @cindex @code{wid}, stack item type
4381: Word list ID, same size as Cell
4382: @item ior, wior
4383: @cindex ior type description
4384: @cindex wior type description
4385: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
4386: @item f83name
4387: @cindex @code{f83name}, stack item type
4388: Pointer to a name structure
4389: @item "
4390: @cindex @code{"}, stack item type
4391: string in the input stream (not on the stack). The terminating character
4392: is a blank by default. If it is not a blank, it is shown in @code{<>}
4393: quotes.
4394: @end table
4395:
4396: @comment ----------------------------------------------
4397: @node Case insensitivity, Comments, Notation, Words
4398: @section Case insensitivity
4399: @cindex case sensitivity
4400: @cindex upper and lower case
4401:
4402: Gforth is case-insensitive; you can enter definitions and invoke
4403: Standard words using upper, lower or mixed case (however,
4404: @pxref{core-idef, Implementation-defined options, Implementation-defined
4405: options}).
4406:
4407: ANS Forth only @i{requires} implementations to recognise Standard words
4408: when they are typed entirely in upper case. Therefore, a Standard
4409: program must use upper case for all Standard words. You can use whatever
4410: case you like for words that you define, but in a Standard program you
4411: have to use the words in the same case that you defined them.
4412:
4413: Gforth supports case sensitivity through @code{table}s (case-sensitive
4414: wordlists, @pxref{Word Lists}).
4415:
4416: Two people have asked how to convert Gforth to be case-sensitive; while
4417: we think this is a bad idea, you can change all wordlists into tables
4418: like this:
4419:
4420: @example
4421: ' table-find forth-wordlist wordlist-map @ !
4422: @end example
4423:
4424: Note that you now have to type the predefined words in the same case
4425: that we defined them, which are varying. You may want to convert them
4426: to your favourite case before doing this operation (I won't explain how,
4427: because if you are even contemplating doing this, you'd better have
4428: enough knowledge of Forth systems to know this already).
4429:
4430: @node Comments, Boolean Flags, Case insensitivity, Words
4431: @section Comments
4432: @cindex comments
4433:
4434: Forth supports two styles of comment; the traditional @i{in-line} comment,
4435: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
4436:
4437:
4438: doc-(
4439: doc-\
4440: doc-\G
4441:
4442:
4443: @node Boolean Flags, Arithmetic, Comments, Words
4444: @section Boolean Flags
4445: @cindex Boolean flags
4446:
4447: A Boolean flag is cell-sized. A cell with all bits clear represents the
4448: flag @code{false} and a flag with all bits set represents the flag
4449: @code{true}. Words that check a flag (for example, @code{IF}) will treat
4450: a cell that has @i{any} bit set as @code{true}.
4451: @c on and off to Memory?
4452: @c true and false to "Bitwise operations" or "Numeric comparison"?
4453:
4454: doc-true
4455: doc-false
4456: doc-on
4457: doc-off
4458:
4459:
4460: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
4461: @section Arithmetic
4462: @cindex arithmetic words
4463:
4464: @cindex division with potentially negative operands
4465: Forth arithmetic is not checked, i.e., you will not hear about integer
4466: overflow on addition or multiplication, you may hear about division by
4467: zero if you are lucky. The operator is written after the operands, but
4468: the operands are still in the original order. I.e., the infix @code{2-1}
4469: corresponds to @code{2 1 -}. Forth offers a variety of division
4470: operators. If you perform division with potentially negative operands,
4471: you do not want to use @code{/} or @code{/mod} with its undefined
4472: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4473: former, @pxref{Mixed precision}).
4474: @comment TODO discuss the different division forms and the std approach
4475:
4476: @menu
4477: * Single precision::
4478: * Double precision:: Double-cell integer arithmetic
4479: * Bitwise operations::
4480: * Numeric comparison::
4481: * Mixed precision:: Operations with single and double-cell integers
4482: * Floating Point::
4483: @end menu
4484:
4485: @node Single precision, Double precision, Arithmetic, Arithmetic
4486: @subsection Single precision
4487: @cindex single precision arithmetic words
4488:
4489: @c !! cell undefined
4490:
4491: By default, numbers in Forth are single-precision integers that are one
4492: cell in size. They can be signed or unsigned, depending upon how you
4493: treat them. For the rules used by the text interpreter for recognising
4494: single-precision integers see @ref{Number Conversion}.
4495:
4496: These words are all defined for signed operands, but some of them also
4497: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4498: @code{*}.
4499:
4500: doc-+
4501: doc-1+
4502: doc-under+
4503: doc--
4504: doc-1-
4505: doc-*
4506: doc-/
4507: doc-mod
4508: doc-/mod
4509: doc-negate
4510: doc-abs
4511: doc-min
4512: doc-max
4513: doc-floored
4514:
4515:
4516: @node Double precision, Bitwise operations, Single precision, Arithmetic
4517: @subsection Double precision
4518: @cindex double precision arithmetic words
4519:
4520: For the rules used by the text interpreter for
4521: recognising double-precision integers, see @ref{Number Conversion}.
4522:
4523: A double precision number is represented by a cell pair, with the most
4524: significant cell at the TOS. It is trivial to convert an unsigned single
4525: to a double: simply push a @code{0} onto the TOS. Since numbers are
4526: represented by Gforth using 2's complement arithmetic, converting a
4527: signed single to a (signed) double requires sign-extension across the
4528: most significant cell. This can be achieved using @code{s>d}. The moral
4529: of the story is that you cannot convert a number without knowing whether
4530: it represents an unsigned or a signed number.
4531:
4532: These words are all defined for signed operands, but some of them also
4533: work for unsigned numbers: @code{d+}, @code{d-}.
4534:
4535: doc-s>d
4536: doc-d>s
4537: doc-d+
4538: doc-d-
4539: doc-dnegate
4540: doc-dabs
4541: doc-dmin
4542: doc-dmax
4543:
4544:
4545: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4546: @subsection Bitwise operations
4547: @cindex bitwise operation words
4548:
4549:
4550: doc-and
4551: doc-or
4552: doc-xor
4553: doc-invert
4554: doc-lshift
4555: doc-rshift
4556: doc-2*
4557: doc-d2*
4558: doc-2/
4559: doc-d2/
4560:
4561:
4562: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
4563: @subsection Numeric comparison
4564: @cindex numeric comparison words
4565:
4566: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4567: d0= d0<>}) work for for both signed and unsigned numbers.
4568:
4569: doc-<
4570: doc-<=
4571: doc-<>
4572: doc-=
4573: doc->
4574: doc->=
4575:
4576: doc-0<
4577: doc-0<=
4578: doc-0<>
4579: doc-0=
4580: doc-0>
4581: doc-0>=
4582:
4583: doc-u<
4584: doc-u<=
4585: @c u<> and u= exist but are the same as <> and =
4586: @c doc-u<>
4587: @c doc-u=
4588: doc-u>
4589: doc-u>=
4590:
4591: doc-within
4592:
4593: doc-d<
4594: doc-d<=
4595: doc-d<>
4596: doc-d=
4597: doc-d>
4598: doc-d>=
4599:
4600: doc-d0<
4601: doc-d0<=
4602: doc-d0<>
4603: doc-d0=
4604: doc-d0>
4605: doc-d0>=
4606:
4607: doc-du<
4608: doc-du<=
4609: @c du<> and du= exist but are the same as d<> and d=
4610: @c doc-du<>
4611: @c doc-du=
4612: doc-du>
4613: doc-du>=
4614:
4615:
4616: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
4617: @subsection Mixed precision
4618: @cindex mixed precision arithmetic words
4619:
4620:
4621: doc-m+
4622: doc-*/
4623: doc-*/mod
4624: doc-m*
4625: doc-um*
4626: doc-m*/
4627: doc-um/mod
4628: doc-fm/mod
4629: doc-sm/rem
4630:
4631:
4632: @node Floating Point, , Mixed precision, Arithmetic
4633: @subsection Floating Point
4634: @cindex floating point arithmetic words
4635:
4636: For the rules used by the text interpreter for
4637: recognising floating-point numbers see @ref{Number Conversion}.
4638:
4639: Gforth has a separate floating point stack, but the documentation uses
4640: the unified notation.@footnote{It's easy to generate the separate
4641: notation from that by just separating the floating-point numbers out:
4642: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4643: r3 )}.}
4644:
4645: @cindex floating-point arithmetic, pitfalls
4646: Floating point numbers have a number of unpleasant surprises for the
4647: unwary (e.g., floating point addition is not associative) and even a few
4648: for the wary. You should not use them unless you know what you are doing
4649: or you don't care that the results you get are totally bogus. If you
4650: want to learn about the problems of floating point numbers (and how to
4651: avoid them), you might start with @cite{David Goldberg,
4652: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4653: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4654: Surveys 23(1):5@minus{}48, March 1991}.
4655:
4656:
4657: doc-d>f
4658: doc-f>d
4659: doc-f+
4660: doc-f-
4661: doc-f*
4662: doc-f/
4663: doc-fnegate
4664: doc-fabs
4665: doc-fmax
4666: doc-fmin
4667: doc-floor
4668: doc-fround
4669: doc-f**
4670: doc-fsqrt
4671: doc-fexp
4672: doc-fexpm1
4673: doc-fln
4674: doc-flnp1
4675: doc-flog
4676: doc-falog
4677: doc-f2*
4678: doc-f2/
4679: doc-1/f
4680: doc-precision
4681: doc-set-precision
4682:
4683: @cindex angles in trigonometric operations
4684: @cindex trigonometric operations
4685: Angles in floating point operations are given in radians (a full circle
4686: has 2 pi radians).
4687:
4688: doc-fsin
4689: doc-fcos
4690: doc-fsincos
4691: doc-ftan
4692: doc-fasin
4693: doc-facos
4694: doc-fatan
4695: doc-fatan2
4696: doc-fsinh
4697: doc-fcosh
4698: doc-ftanh
4699: doc-fasinh
4700: doc-facosh
4701: doc-fatanh
4702: doc-pi
4703:
4704: @cindex equality of floats
4705: @cindex floating-point comparisons
4706: One particular problem with floating-point arithmetic is that comparison
4707: for equality often fails when you would expect it to succeed. For this
4708: reason approximate equality is often preferred (but you still have to
4709: know what you are doing). Also note that IEEE NaNs may compare
4710: differently from what you might expect. The comparison words are:
4711:
4712: doc-f~rel
4713: doc-f~abs
4714: doc-f~
4715: doc-f=
4716: doc-f<>
4717:
4718: doc-f<
4719: doc-f<=
4720: doc-f>
4721: doc-f>=
4722:
4723: doc-f0<
4724: doc-f0<=
4725: doc-f0<>
4726: doc-f0=
4727: doc-f0>
4728: doc-f0>=
4729:
4730:
4731: @node Stack Manipulation, Memory, Arithmetic, Words
4732: @section Stack Manipulation
4733: @cindex stack manipulation words
4734:
4735: @cindex floating-point stack in the standard
4736: Gforth maintains a number of separate stacks:
4737:
4738: @cindex data stack
4739: @cindex parameter stack
4740: @itemize @bullet
4741: @item
4742: A data stack (also known as the @dfn{parameter stack}) -- for
4743: characters, cells, addresses, and double cells.
4744:
4745: @cindex floating-point stack
4746: @item
4747: A floating point stack -- for holding floating point (FP) numbers.
4748:
4749: @cindex return stack
4750: @item
4751: A return stack -- for holding the return addresses of colon
4752: definitions and other (non-FP) data.
4753:
4754: @cindex locals stack
4755: @item
4756: A locals stack -- for holding local variables.
4757: @end itemize
4758:
4759: @menu
4760: * Data stack::
4761: * Floating point stack::
4762: * Return stack::
4763: * Locals stack::
4764: * Stack pointer manipulation::
4765: @end menu
4766:
4767: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4768: @subsection Data stack
4769: @cindex data stack manipulation words
4770: @cindex stack manipulations words, data stack
4771:
4772:
4773: doc-drop
4774: doc-nip
4775: doc-dup
4776: doc-over
4777: doc-tuck
4778: doc-swap
4779: doc-pick
4780: doc-rot
4781: doc--rot
4782: doc-?dup
4783: doc-roll
4784: doc-2drop
4785: doc-2nip
4786: doc-2dup
4787: doc-2over
4788: doc-2tuck
4789: doc-2swap
4790: doc-2rot
4791:
4792:
4793: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4794: @subsection Floating point stack
4795: @cindex floating-point stack manipulation words
4796: @cindex stack manipulation words, floating-point stack
4797:
4798: Whilst every sane Forth has a separate floating-point stack, it is not
4799: strictly required; an ANS Forth system could theoretically keep
4800: floating-point numbers on the data stack. As an additional difficulty,
4801: you don't know how many cells a floating-point number takes. It is
4802: reportedly possible to write words in a way that they work also for a
4803: unified stack model, but we do not recommend trying it. Instead, just
4804: say that your program has an environmental dependency on a separate
4805: floating-point stack.
4806:
4807: doc-floating-stack
4808:
4809: doc-fdrop
4810: doc-fnip
4811: doc-fdup
4812: doc-fover
4813: doc-ftuck
4814: doc-fswap
4815: doc-fpick
4816: doc-frot
4817:
4818:
4819: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4820: @subsection Return stack
4821: @cindex return stack manipulation words
4822: @cindex stack manipulation words, return stack
4823:
4824: @cindex return stack and locals
4825: @cindex locals and return stack
4826: A Forth system is allowed to keep local variables on the
4827: return stack. This is reasonable, as local variables usually eliminate
4828: the need to use the return stack explicitly. So, if you want to produce
4829: a standard compliant program and you are using local variables in a
4830: word, forget about return stack manipulations in that word (refer to the
4831: standard document for the exact rules).
4832:
4833: doc->r
4834: doc-r>
4835: doc-r@
4836: doc-rdrop
4837: doc-2>r
4838: doc-2r>
4839: doc-2r@
4840: doc-2rdrop
4841:
4842:
4843: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4844: @subsection Locals stack
4845:
4846: Gforth uses an extra locals stack. It is described, along with the
4847: reasons for its existence, in @ref{Locals implementation}.
4848:
4849: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4850: @subsection Stack pointer manipulation
4851: @cindex stack pointer manipulation words
4852:
4853: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
4854: doc-sp0
4855: doc-sp@
4856: doc-sp!
4857: doc-fp0
4858: doc-fp@
4859: doc-fp!
4860: doc-rp0
4861: doc-rp@
4862: doc-rp!
4863: doc-lp0
4864: doc-lp@
4865: doc-lp!
4866:
4867:
4868: @node Memory, Control Structures, Stack Manipulation, Words
4869: @section Memory
4870: @cindex memory words
4871:
4872: @menu
4873: * Memory model::
4874: * Dictionary allocation::
4875: * Heap Allocation::
4876: * Memory Access::
4877: * Address arithmetic::
4878: * Memory Blocks::
4879: @end menu
4880:
4881: In addition to the standard Forth memory allocation words, there is also
4882: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4883: garbage collector}.
4884:
4885: @node Memory model, Dictionary allocation, Memory, Memory
4886: @subsection ANS Forth and Gforth memory models
4887:
4888: @c The ANS Forth description is a mess (e.g., is the heap part of
4889: @c the dictionary?), so let's not stick to closely with it.
4890:
4891: ANS Forth considers a Forth system as consisting of several address
4892: spaces, of which only @dfn{data space} is managed and accessible with
4893: the memory words. Memory not necessarily in data space includes the
4894: stacks, the code (called code space) and the headers (called name
4895: space). In Gforth everything is in data space, but the code for the
4896: primitives is usually read-only.
4897:
4898: Data space is divided into a number of areas: The (data space portion of
4899: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4900: refer to the search data structure embodied in word lists and headers,
4901: because it is used for looking up names, just as you would in a
4902: conventional dictionary.}, the heap, and a number of system-allocated
4903: buffers.
4904:
4905: @cindex address arithmetic restrictions, ANS vs. Gforth
4906: @cindex contiguous regions, ANS vs. Gforth
4907: In ANS Forth data space is also divided into contiguous regions. You
4908: can only use address arithmetic within a contiguous region, not between
4909: them. Usually each allocation gives you one contiguous region, but the
4910: dictionary allocation words have additional rules (@pxref{Dictionary
4911: allocation}).
4912:
4913: Gforth provides one big address space, and address arithmetic can be
4914: performed between any addresses. However, in the dictionary headers or
4915: code are interleaved with data, so almost the only contiguous data space
4916: regions there are those described by ANS Forth as contiguous; but you
4917: can be sure that the dictionary is allocated towards increasing
4918: addresses even between contiguous regions. The memory order of
4919: allocations in the heap is platform-dependent (and possibly different
4920: from one run to the next).
4921:
4922:
4923: @node Dictionary allocation, Heap Allocation, Memory model, Memory
4924: @subsection Dictionary allocation
4925: @cindex reserving data space
4926: @cindex data space - reserving some
4927:
4928: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
4929: you want to deallocate X, you also deallocate everything
4930: allocated after X.
4931:
4932: @cindex contiguous regions in dictionary allocation
4933: The allocations using the words below are contiguous and grow the region
4934: towards increasing addresses. Other words that allocate dictionary
4935: memory of any kind (i.e., defining words including @code{:noname}) end
4936: the contiguous region and start a new one.
4937:
4938: In ANS Forth only @code{create}d words are guaranteed to produce an
4939: address that is the start of the following contiguous region. In
4940: particular, the cell allocated by @code{variable} is not guaranteed to
4941: be contiguous with following @code{allot}ed memory.
4942:
4943: You can deallocate memory by using @code{allot} with a negative argument
4944: (with some restrictions, see @code{allot}). For larger deallocations use
4945: @code{marker}.
4946:
4947:
4948: doc-here
4949: doc-unused
4950: doc-allot
4951: doc-c,
4952: doc-f,
4953: doc-,
4954: doc-2,
4955:
4956: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
4957: course you should allocate memory in an aligned way, too. I.e., before
4958: allocating allocating a cell, @code{here} must be cell-aligned, etc.
4959: The words below align @code{here} if it is not already. Basically it is
4960: only already aligned for a type, if the last allocation was a multiple
4961: of the size of this type and if @code{here} was aligned for this type
4962: before.
4963:
4964: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
4965: ANS Forth (@code{maxalign}ed in Gforth).
4966:
4967: doc-align
4968: doc-falign
4969: doc-sfalign
4970: doc-dfalign
4971: doc-maxalign
4972: doc-cfalign
4973:
4974:
4975: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
4976: @subsection Heap allocation
4977: @cindex heap allocation
4978: @cindex dynamic allocation of memory
4979: @cindex memory-allocation word set
4980:
4981: @cindex contiguous regions and heap allocation
4982: Heap allocation supports deallocation of allocated memory in any
4983: order. Dictionary allocation is not affected by it (i.e., it does not
4984: end a contiguous region). In Gforth, these words are implemented using
4985: the standard C library calls malloc(), free() and resize().
4986:
4987: The memory region produced by one invocation of @code{allocate} or
4988: @code{resize} is internally contiguous. There is no contiguity between
4989: such a region and any other region (including others allocated from the
4990: heap).
4991:
4992: doc-allocate
4993: doc-free
4994: doc-resize
4995:
4996:
4997: @node Memory Access, Address arithmetic, Heap Allocation, Memory
4998: @subsection Memory Access
4999: @cindex memory access words
5000:
5001: doc-@
5002: doc-!
5003: doc-+!
5004: doc-c@
5005: doc-c!
5006: doc-2@
5007: doc-2!
5008: doc-f@
5009: doc-f!
5010: doc-sf@
5011: doc-sf!
5012: doc-df@
5013: doc-df!
5014: doc-sw@
5015: doc-uw@
5016: doc-w!
5017: doc-sl@
5018: doc-ul@
5019: doc-l!
5020:
5021: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5022: @subsection Address arithmetic
5023: @cindex address arithmetic words
5024:
5025: Address arithmetic is the foundation on which you can build data
5026: structures like arrays, records (@pxref{Structures}) and objects
5027: (@pxref{Object-oriented Forth}).
5028:
5029: @cindex address unit
5030: @cindex au (address unit)
5031: ANS Forth does not specify the sizes of the data types. Instead, it
5032: offers a number of words for computing sizes and doing address
5033: arithmetic. Address arithmetic is performed in terms of address units
5034: (aus); on most systems the address unit is one byte. Note that a
5035: character may have more than one au, so @code{chars} is no noop (on
5036: platforms where it is a noop, it compiles to nothing).
5037:
5038: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5039: you have the address of a cell, perform @code{1 cells +}, and you will
5040: have the address of the next cell.
5041:
5042: @cindex contiguous regions and address arithmetic
5043: In ANS Forth you can perform address arithmetic only within a contiguous
5044: region, i.e., if you have an address into one region, you can only add
5045: and subtract such that the result is still within the region; you can
5046: only subtract or compare addresses from within the same contiguous
5047: region. Reasons: several contiguous regions can be arranged in memory
5048: in any way; on segmented systems addresses may have unusual
5049: representations, such that address arithmetic only works within a
5050: region. Gforth provides a few more guarantees (linear address space,
5051: dictionary grows upwards), but in general I have found it easy to stay
5052: within contiguous regions (exception: computing and comparing to the
5053: address just beyond the end of an array).
5054:
5055: @cindex alignment of addresses for types
5056: ANS Forth also defines words for aligning addresses for specific
5057: types. Many computers require that accesses to specific data types
5058: must only occur at specific addresses; e.g., that cells may only be
5059: accessed at addresses divisible by 4. Even if a machine allows unaligned
5060: accesses, it can usually perform aligned accesses faster.
5061:
5062: For the performance-conscious: alignment operations are usually only
5063: necessary during the definition of a data structure, not during the
5064: (more frequent) accesses to it.
5065:
5066: ANS Forth defines no words for character-aligning addresses. This is not
5067: an oversight, but reflects the fact that addresses that are not
5068: char-aligned have no use in the standard and therefore will not be
5069: created.
5070:
5071: @cindex @code{CREATE} and alignment
5072: ANS Forth guarantees that addresses returned by @code{CREATE}d words
5073: are cell-aligned; in addition, Gforth guarantees that these addresses
5074: are aligned for all purposes.
5075:
5076: Note that the ANS Forth word @code{char} has nothing to do with address
5077: arithmetic.
5078:
5079:
5080: doc-chars
5081: doc-char+
5082: doc-cells
5083: doc-cell+
5084: doc-cell
5085: doc-aligned
5086: doc-floats
5087: doc-float+
5088: doc-float
5089: doc-faligned
5090: doc-sfloats
5091: doc-sfloat+
5092: doc-sfaligned
5093: doc-dfloats
5094: doc-dfloat+
5095: doc-dfaligned
5096: doc-maxaligned
5097: doc-cfaligned
5098: doc-address-unit-bits
5099: doc-/w
5100: doc-/l
5101:
5102: @node Memory Blocks, , Address arithmetic, Memory
5103: @subsection Memory Blocks
5104: @cindex memory block words
5105: @cindex character strings - moving and copying
5106:
5107: Memory blocks often represent character strings; For ways of storing
5108: character strings in memory see @ref{String Formats}. For other
5109: string-processing words see @ref{Displaying characters and strings}.
5110:
5111: A few of these words work on address unit blocks. In that case, you
5112: usually have to insert @code{CHARS} before the word when working on
5113: character strings. Most words work on character blocks, and expect a
5114: char-aligned address.
5115:
5116: When copying characters between overlapping memory regions, use
5117: @code{chars move} or choose carefully between @code{cmove} and
5118: @code{cmove>}.
5119:
5120: doc-move
5121: doc-erase
5122: doc-cmove
5123: doc-cmove>
5124: doc-fill
5125: doc-blank
5126: doc-compare
5127: doc-str=
5128: doc-str<
5129: doc-string-prefix?
5130: doc-search
5131: doc--trailing
5132: doc-/string
5133: doc-bounds
5134: doc-pad
5135:
5136: @comment TODO examples
5137:
5138:
5139: @node Control Structures, Defining Words, Memory, Words
5140: @section Control Structures
5141: @cindex control structures
5142:
5143: Control structures in Forth cannot be used interpretively, only in a
5144: colon definition@footnote{To be precise, they have no interpretation
5145: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5146: not like this limitation, but have not seen a satisfying way around it
5147: yet, although many schemes have been proposed.
5148:
5149: @menu
5150: * Selection:: IF ... ELSE ... ENDIF
5151: * Simple Loops:: BEGIN ...
5152: * Counted Loops:: DO
5153: * Arbitrary control structures::
5154: * Calls and returns::
5155: * Exception Handling::
5156: @end menu
5157:
5158: @node Selection, Simple Loops, Control Structures, Control Structures
5159: @subsection Selection
5160: @cindex selection control structures
5161: @cindex control structures for selection
5162:
5163: @cindex @code{IF} control structure
5164: @example
5165: @i{flag}
5166: IF
5167: @i{code}
5168: ENDIF
5169: @end example
5170: @noindent
5171:
5172: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5173: with any bit set represents truth) @i{code} is executed.
5174:
5175: @example
5176: @i{flag}
5177: IF
5178: @i{code1}
5179: ELSE
5180: @i{code2}
5181: ENDIF
5182: @end example
5183:
5184: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5185: executed.
5186:
5187: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5188: standard, and @code{ENDIF} is not, although it is quite popular. We
5189: recommend using @code{ENDIF}, because it is less confusing for people
5190: who also know other languages (and is not prone to reinforcing negative
5191: prejudices against Forth in these people). Adding @code{ENDIF} to a
5192: system that only supplies @code{THEN} is simple:
5193: @example
5194: : ENDIF POSTPONE then ; immediate
5195: @end example
5196:
5197: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5198: (adv.)} has the following meanings:
5199: @quotation
5200: ... 2b: following next after in order ... 3d: as a necessary consequence
5201: (if you were there, then you saw them).
5202: @end quotation
5203: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5204: and many other programming languages has the meaning 3d.]
5205:
5206: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
5207: you can avoid using @code{?dup}. Using these alternatives is also more
5208: efficient than using @code{?dup}. Definitions in ANS Forth
5209: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5210: @file{compat/control.fs}.
5211:
5212: @cindex @code{CASE} control structure
5213: @example
5214: @i{n}
5215: CASE
5216: @i{n1} OF @i{code1} ENDOF
5217: @i{n2} OF @i{code2} ENDOF
5218: @dots{}
5219: ( n ) @i{default-code} ( n )
5220: ENDCASE ( )
5221: @end example
5222:
5223: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5224: no @i{ni} matches, the optional @i{default-code} is executed. The
5225: optional default case can be added by simply writing the code after
5226: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5227: but must not consume it. The value @i{n} is consumed by this
5228: construction (either by a OF that matches, or by the ENDCASE, if no OF
5229: matches).
5230:
5231: @progstyle
5232: To keep the code understandable, you should ensure that you change the
5233: stack in the same way (wrt. number and types of stack items consumed
5234: and pushed) on all paths through a selection construct.
5235:
5236: @node Simple Loops, Counted Loops, Selection, Control Structures
5237: @subsection Simple Loops
5238: @cindex simple loops
5239: @cindex loops without count
5240:
5241: @cindex @code{WHILE} loop
5242: @example
5243: BEGIN
5244: @i{code1}
5245: @i{flag}
5246: WHILE
5247: @i{code2}
5248: REPEAT
5249: @end example
5250:
5251: @i{code1} is executed and @i{flag} is computed. If it is true,
5252: @i{code2} is executed and the loop is restarted; If @i{flag} is
5253: false, execution continues after the @code{REPEAT}.
5254:
5255: @cindex @code{UNTIL} loop
5256: @example
5257: BEGIN
5258: @i{code}
5259: @i{flag}
5260: UNTIL
5261: @end example
5262:
5263: @i{code} is executed. The loop is restarted if @code{flag} is false.
5264:
5265: @progstyle
5266: To keep the code understandable, a complete iteration of the loop should
5267: not change the number and types of the items on the stacks.
5268:
5269: @cindex endless loop
5270: @cindex loops, endless
5271: @example
5272: BEGIN
5273: @i{code}
5274: AGAIN
5275: @end example
5276:
5277: This is an endless loop.
5278:
5279: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5280: @subsection Counted Loops
5281: @cindex counted loops
5282: @cindex loops, counted
5283: @cindex @code{DO} loops
5284:
5285: The basic counted loop is:
5286: @example
5287: @i{limit} @i{start}
5288: ?DO
5289: @i{body}
5290: LOOP
5291: @end example
5292:
5293: This performs one iteration for every integer, starting from @i{start}
5294: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
5295: accessed with @code{i}. For example, the loop:
5296: @example
5297: 10 0 ?DO
5298: i .
5299: LOOP
5300: @end example
5301: @noindent
5302: prints @code{0 1 2 3 4 5 6 7 8 9}
5303:
5304: The index of the innermost loop can be accessed with @code{i}, the index
5305: of the next loop with @code{j}, and the index of the third loop with
5306: @code{k}.
5307:
5308:
5309: doc-i
5310: doc-j
5311: doc-k
5312:
5313:
5314: The loop control data are kept on the return stack, so there are some
5315: restrictions on mixing return stack accesses and counted loop words. In
5316: particuler, if you put values on the return stack outside the loop, you
5317: cannot read them inside the loop@footnote{well, not in a way that is
5318: portable.}. If you put values on the return stack within a loop, you
5319: have to remove them before the end of the loop and before accessing the
5320: index of the loop.
5321:
5322: There are several variations on the counted loop:
5323:
5324: @itemize @bullet
5325: @item
5326: @code{LEAVE} leaves the innermost counted loop immediately; execution
5327: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5328:
5329: @example
5330: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5331: @end example
5332: prints @code{0 1 2 3}
5333:
5334:
5335: @item
5336: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5337: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5338: return stack so @code{EXIT} can get to its return address. For example:
5339:
5340: @example
5341: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5342: @end example
5343: prints @code{0 1 2 3}
5344:
5345:
5346: @item
5347: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
5348: (and @code{LOOP} iterates until they become equal by wrap-around
5349: arithmetic). This behaviour is usually not what you want. Therefore,
5350: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
5351: @code{?DO}), which do not enter the loop if @i{start} is greater than
5352: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
5353: unsigned loop parameters.
5354:
5355: @item
5356: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5357: the loop, independent of the loop parameters. Do not use @code{DO}, even
5358: if you know that the loop is entered in any case. Such knowledge tends
5359: to become invalid during maintenance of a program, and then the
5360: @code{DO} will make trouble.
5361:
5362: @item
5363: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5364: index by @i{n} instead of by 1. The loop is terminated when the border
5365: between @i{limit-1} and @i{limit} is crossed. E.g.:
5366:
5367: @example
5368: 4 0 +DO i . 2 +LOOP
5369: @end example
5370: @noindent
5371: prints @code{0 2}
5372:
5373: @example
5374: 4 1 +DO i . 2 +LOOP
5375: @end example
5376: @noindent
5377: prints @code{1 3}
5378:
5379: @item
5380: @cindex negative increment for counted loops
5381: @cindex counted loops with negative increment
5382: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
5383:
5384: @example
5385: -1 0 ?DO i . -1 +LOOP
5386: @end example
5387: @noindent
5388: prints @code{0 -1}
5389:
5390: @example
5391: 0 0 ?DO i . -1 +LOOP
5392: @end example
5393: prints nothing.
5394:
5395: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5396: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5397: index by @i{u} each iteration. The loop is terminated when the border
5398: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
5399: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5400:
5401: @example
5402: -2 0 -DO i . 1 -LOOP
5403: @end example
5404: @noindent
5405: prints @code{0 -1}
5406:
5407: @example
5408: -1 0 -DO i . 1 -LOOP
5409: @end example
5410: @noindent
5411: prints @code{0}
5412:
5413: @example
5414: 0 0 -DO i . 1 -LOOP
5415: @end example
5416: @noindent
5417: prints nothing.
5418:
5419: @end itemize
5420:
5421: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
5422: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5423: for these words that uses only standard words is provided in
5424: @file{compat/loops.fs}.
5425:
5426:
5427: @cindex @code{FOR} loops
5428: Another counted loop is:
5429: @example
5430: @i{n}
5431: FOR
5432: @i{body}
5433: NEXT
5434: @end example
5435: This is the preferred loop of native code compiler writers who are too
5436: lazy to optimize @code{?DO} loops properly. This loop structure is not
5437: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5438: @code{i} produces values starting with @i{n} and ending with 0. Other
5439: Forth systems may behave differently, even if they support @code{FOR}
5440: loops. To avoid problems, don't use @code{FOR} loops.
5441:
5442: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5443: @subsection Arbitrary control structures
5444: @cindex control structures, user-defined
5445:
5446: @cindex control-flow stack
5447: ANS Forth permits and supports using control structures in a non-nested
5448: way. Information about incomplete control structures is stored on the
5449: control-flow stack. This stack may be implemented on the Forth data
5450: stack, and this is what we have done in Gforth.
5451:
5452: @cindex @code{orig}, control-flow stack item
5453: @cindex @code{dest}, control-flow stack item
5454: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5455: entry represents a backward branch target. A few words are the basis for
5456: building any control structure possible (except control structures that
5457: need storage, like calls, coroutines, and backtracking).
5458:
5459:
5460: doc-if
5461: doc-ahead
5462: doc-then
5463: doc-begin
5464: doc-until
5465: doc-again
5466: doc-cs-pick
5467: doc-cs-roll
5468:
5469:
5470: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5471: manipulate the control-flow stack in a portable way. Without them, you
5472: would need to know how many stack items are occupied by a control-flow
5473: entry (many systems use one cell. In Gforth they currently take three,
5474: but this may change in the future).
5475:
5476: Some standard control structure words are built from these words:
5477:
5478:
5479: doc-else
5480: doc-while
5481: doc-repeat
5482:
5483:
5484: @noindent
5485: Gforth adds some more control-structure words:
5486:
5487:
5488: doc-endif
5489: doc-?dup-if
5490: doc-?dup-0=-if
5491:
5492:
5493: @noindent
5494: Counted loop words constitute a separate group of words:
5495:
5496:
5497: doc-?do
5498: doc-+do
5499: doc-u+do
5500: doc--do
5501: doc-u-do
5502: doc-do
5503: doc-for
5504: doc-loop
5505: doc-+loop
5506: doc--loop
5507: doc-next
5508: doc-leave
5509: doc-?leave
5510: doc-unloop
5511: doc-done
5512:
5513:
5514: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5515: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
5516: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5517: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5518: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5519: resolved (by using one of the loop-ending words or @code{DONE}).
5520:
5521: @noindent
5522: Another group of control structure words are:
5523:
5524:
5525: doc-case
5526: doc-endcase
5527: doc-of
5528: doc-endof
5529:
5530:
5531: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5532: @code{CS-ROLL}.
5533:
5534: @subsubsection Programming Style
5535: @cindex control structures programming style
5536: @cindex programming style, arbitrary control structures
5537:
5538: In order to ensure readability we recommend that you do not create
5539: arbitrary control structures directly, but define new control structure
5540: words for the control structure you want and use these words in your
5541: program. For example, instead of writing:
5542:
5543: @example
5544: BEGIN
5545: ...
5546: IF [ 1 CS-ROLL ]
5547: ...
5548: AGAIN THEN
5549: @end example
5550:
5551: @noindent
5552: we recommend defining control structure words, e.g.,
5553:
5554: @example
5555: : WHILE ( DEST -- ORIG DEST )
5556: POSTPONE IF
5557: 1 CS-ROLL ; immediate
5558:
5559: : REPEAT ( orig dest -- )
5560: POSTPONE AGAIN
5561: POSTPONE THEN ; immediate
5562: @end example
5563:
5564: @noindent
5565: and then using these to create the control structure:
5566:
5567: @example
5568: BEGIN
5569: ...
5570: WHILE
5571: ...
5572: REPEAT
5573: @end example
5574:
5575: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5576: @code{WHILE} are predefined, so in this example it would not be
5577: necessary to define them.
5578:
5579: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5580: @subsection Calls and returns
5581: @cindex calling a definition
5582: @cindex returning from a definition
5583:
5584: @cindex recursive definitions
5585: A definition can be called simply be writing the name of the definition
5586: to be called. Normally a definition is invisible during its own
5587: definition. If you want to write a directly recursive definition, you
5588: can use @code{recursive} to make the current definition visible, or
5589: @code{recurse} to call the current definition directly.
5590:
5591:
5592: doc-recursive
5593: doc-recurse
5594:
5595:
5596: @comment TODO add example of the two recursion methods
5597: @quotation
5598: @progstyle
5599: I prefer using @code{recursive} to @code{recurse}, because calling the
5600: definition by name is more descriptive (if the name is well-chosen) than
5601: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5602: implementation, it is much better to read (and think) ``now sort the
5603: partitions'' than to read ``now do a recursive call''.
5604: @end quotation
5605:
5606: For mutual recursion, use @code{Defer}red words, like this:
5607:
5608: @example
5609: Defer foo
5610:
5611: : bar ( ... -- ... )
5612: ... foo ... ;
5613:
5614: :noname ( ... -- ... )
5615: ... bar ... ;
5616: IS foo
5617: @end example
5618:
5619: Deferred words are discussed in more detail in @ref{Deferred words}.
5620:
5621: The current definition returns control to the calling definition when
5622: the end of the definition is reached or @code{EXIT} is encountered.
5623:
5624: doc-exit
5625: doc-;s
5626:
5627:
5628: @node Exception Handling, , Calls and returns, Control Structures
5629: @subsection Exception Handling
5630: @cindex exceptions
5631:
5632: @c quit is a very bad idea for error handling,
5633: @c because it does not translate into a THROW
5634: @c it also does not belong into this chapter
5635:
5636: If a word detects an error condition that it cannot handle, it can
5637: @code{throw} an exception. In the simplest case, this will terminate
5638: your program, and report an appropriate error.
5639:
5640: doc-throw
5641:
5642: @code{Throw} consumes a cell-sized error number on the stack. There are
5643: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5644: Gforth (and most other systems) you can use the iors produced by various
5645: words as error numbers (e.g., a typical use of @code{allocate} is
5646: @code{allocate throw}). Gforth also provides the word @code{exception}
5647: to define your own error numbers (with decent error reporting); an ANS
5648: Forth version of this word (but without the error messages) is available
5649: in @code{compat/except.fs}. And finally, you can use your own error
5650: numbers (anything outside the range -4095..0), but won't get nice error
5651: messages, only numbers. For example, try:
5652:
5653: @example
5654: -10 throw \ ANS defined
5655: -267 throw \ system defined
5656: s" my error" exception throw \ user defined
5657: 7 throw \ arbitrary number
5658: @end example
5659:
5660: doc---exception-exception
5661:
5662: A common idiom to @code{THROW} a specific error if a flag is true is
5663: this:
5664:
5665: @example
5666: @code{( flag ) 0<> @i{errno} and throw}
5667: @end example
5668:
5669: Your program can provide exception handlers to catch exceptions. An
5670: exception handler can be used to correct the problem, or to clean up
5671: some data structures and just throw the exception to the next exception
5672: handler. Note that @code{throw} jumps to the dynamically innermost
5673: exception handler. The system's exception handler is outermost, and just
5674: prints an error and restarts command-line interpretation (or, in batch
5675: mode (i.e., while processing the shell command line), leaves Gforth).
5676:
5677: The ANS Forth way to catch exceptions is @code{catch}:
5678:
5679: doc-catch
5680:
5681: The most common use of exception handlers is to clean up the state when
5682: an error happens. E.g.,
5683:
5684: @example
5685: base @ >r hex \ actually the hex should be inside foo, or we h
5686: ['] foo catch ( nerror|0 )
5687: r> base !
5688: ( nerror|0 ) throw \ pass it on
5689: @end example
5690:
5691: A use of @code{catch} for handling the error @code{myerror} might look
5692: like this:
5693:
5694: @example
5695: ['] foo catch
5696: CASE
5697: myerror OF ... ( do something about it ) ENDOF
5698: dup throw \ default: pass other errors on, do nothing on non-errors
5699: ENDCASE
5700: @end example
5701:
5702: Having to wrap the code into a separate word is often cumbersome,
5703: therefore Gforth provides an alternative syntax:
5704:
5705: @example
5706: TRY
5707: @i{code1}
5708: RECOVER \ optional
5709: @i{code2} \ optional
5710: ENDTRY
5711: @end example
5712:
5713: This performs @i{Code1}. If @i{code1} completes normally, execution
5714: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5715: reset to the state during @code{try}, the throw value is pushed on the
5716: data stack, and execution constinues at @i{code2}, and finally falls
5717: through the @code{endtry} into the following code.
5718:
5719: doc-try
5720: doc-recover
5721: doc-endtry
5722:
5723: The cleanup example from above in this syntax:
5724:
5725: @example
5726: base @ >r TRY
5727: hex foo \ now the hex is placed correctly
5728: 0 \ value for throw
5729: RECOVER ENDTRY
5730: r> base ! throw
5731: @end example
5732:
5733: And here's the error handling example:
5734:
5735: @example
5736: TRY
5737: foo
5738: RECOVER
5739: CASE
5740: myerror OF ... ( do something about it ) ENDOF
5741: throw \ pass other errors on
5742: ENDCASE
5743: ENDTRY
5744: @end example
5745:
5746: @progstyle
5747: As usual, you should ensure that the stack depth is statically known at
5748: the end: either after the @code{throw} for passing on errors, or after
5749: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5750: selection construct for handling the error).
5751:
5752: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5753: and you can provide an error message. @code{Abort} just produces an
5754: ``Aborted'' error.
5755:
5756: The problem with these words is that exception handlers cannot
5757: differentiate between different @code{abort"}s; they just look like
5758: @code{-2 throw} to them (the error message cannot be accessed by
5759: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5760: exception handlers.
5761:
5762: doc-abort"
5763: doc-abort
5764:
5765:
5766:
5767: @c -------------------------------------------------------------
5768: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
5769: @section Defining Words
5770: @cindex defining words
5771:
5772: Defining words are used to extend Forth by creating new entries in the dictionary.
5773:
5774: @menu
5775: * CREATE::
5776: * Variables:: Variables and user variables
5777: * Constants::
5778: * Values:: Initialised variables
5779: * Colon Definitions::
5780: * Anonymous Definitions:: Definitions without names
5781: * Supplying names:: Passing definition names as strings
5782: * User-defined Defining Words::
5783: * Deferred words:: Allow forward references
5784: * Aliases::
5785: @end menu
5786:
5787: @node CREATE, Variables, Defining Words, Defining Words
5788: @subsection @code{CREATE}
5789: @cindex simple defining words
5790: @cindex defining words, simple
5791:
5792: Defining words are used to create new entries in the dictionary. The
5793: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5794: this:
5795:
5796: @example
5797: CREATE new-word1
5798: @end example
5799:
5800: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5801: input stream (@code{new-word1} in our example). It generates a
5802: dictionary entry for @code{new-word1}. When @code{new-word1} is
5803: executed, all that it does is leave an address on the stack. The address
5804: represents the value of the data space pointer (@code{HERE}) at the time
5805: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5806: associating a name with the address of a region of memory.
5807:
5808: doc-create
5809:
5810: Note that in ANS Forth guarantees only for @code{create} that its body
5811: is in dictionary data space (i.e., where @code{here}, @code{allot}
5812: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5813: @code{create}d words can be modified with @code{does>}
5814: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5815: can only be applied to @code{create}d words.
5816:
5817: By extending this example to reserve some memory in data space, we end
5818: up with something like a @i{variable}. Here are two different ways to do
5819: it:
5820:
5821: @example
5822: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5823: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5824: @end example
5825:
5826: The variable can be examined and modified using @code{@@} (``fetch'') and
5827: @code{!} (``store'') like this:
5828:
5829: @example
5830: new-word2 @@ . \ get address, fetch from it and display
5831: 1234 new-word2 ! \ new value, get address, store to it
5832: @end example
5833:
5834: @cindex arrays
5835: A similar mechanism can be used to create arrays. For example, an
5836: 80-character text input buffer:
5837:
5838: @example
5839: CREATE text-buf 80 chars allot
5840:
5841: text-buf 0 chars c@@ \ the 1st character (offset 0)
5842: text-buf 3 chars c@@ \ the 4th character (offset 3)
5843: @end example
5844:
5845: You can build arbitrarily complex data structures by allocating
5846: appropriate areas of memory. For further discussions of this, and to
5847: learn about some Gforth tools that make it easier,
5848: @xref{Structures}.
5849:
5850:
5851: @node Variables, Constants, CREATE, Defining Words
5852: @subsection Variables
5853: @cindex variables
5854:
5855: The previous section showed how a sequence of commands could be used to
5856: generate a variable. As a final refinement, the whole code sequence can
5857: be wrapped up in a defining word (pre-empting the subject of the next
5858: section), making it easier to create new variables:
5859:
5860: @example
5861: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5862: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5863:
5864: myvariableX foo \ variable foo starts off with an unknown value
5865: myvariable0 joe \ whilst joe is initialised to 0
5866:
5867: 45 3 * foo ! \ set foo to 135
5868: 1234 joe ! \ set joe to 1234
5869: 3 joe +! \ increment joe by 3.. to 1237
5870: @end example
5871:
5872: Not surprisingly, there is no need to define @code{myvariable}, since
5873: Forth already has a definition @code{Variable}. ANS Forth does not
5874: guarantee that a @code{Variable} is initialised when it is created
5875: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5876: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5877: like @code{myvariable0}). Forth also provides @code{2Variable} and
5878: @code{fvariable} for double and floating-point variables, respectively
5879: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
5880: store a boolean, you can use @code{on} and @code{off} to toggle its
5881: state.
5882:
5883: doc-variable
5884: doc-2variable
5885: doc-fvariable
5886:
5887: @cindex user variables
5888: @cindex user space
5889: The defining word @code{User} behaves in the same way as @code{Variable}.
5890: The difference is that it reserves space in @i{user (data) space} rather
5891: than normal data space. In a Forth system that has a multi-tasker, each
5892: task has its own set of user variables.
5893:
5894: doc-user
5895: @c doc-udp
5896: @c doc-uallot
5897:
5898: @comment TODO is that stuff about user variables strictly correct? Is it
5899: @comment just terminal tasks that have user variables?
5900: @comment should document tasker.fs (with some examples) elsewhere
5901: @comment in this manual, then expand on user space and user variables.
5902:
5903: @node Constants, Values, Variables, Defining Words
5904: @subsection Constants
5905: @cindex constants
5906:
5907: @code{Constant} allows you to declare a fixed value and refer to it by
5908: name. For example:
5909:
5910: @example
5911: 12 Constant INCHES-PER-FOOT
5912: 3E+08 fconstant SPEED-O-LIGHT
5913: @end example
5914:
5915: A @code{Variable} can be both read and written, so its run-time
5916: behaviour is to supply an address through which its current value can be
5917: manipulated. In contrast, the value of a @code{Constant} cannot be
5918: changed once it has been declared@footnote{Well, often it can be -- but
5919: not in a Standard, portable way. It's safer to use a @code{Value} (read
5920: on).} so it's not necessary to supply the address -- it is more
5921: efficient to return the value of the constant directly. That's exactly
5922: what happens; the run-time effect of a constant is to put its value on
5923: the top of the stack (You can find one
5924: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
5925:
5926: Forth also provides @code{2Constant} and @code{fconstant} for defining
5927: double and floating-point constants, respectively.
5928:
5929: doc-constant
5930: doc-2constant
5931: doc-fconstant
5932:
5933: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
5934: @c nac-> How could that not be true in an ANS Forth? You can't define a
5935: @c constant, use it and then delete the definition of the constant..
5936:
5937: @c anton->An ANS Forth system can compile a constant to a literal; On
5938: @c decompilation you would see only the number, just as if it had been used
5939: @c in the first place. The word will stay, of course, but it will only be
5940: @c used by the text interpreter (no run-time duties, except when it is
5941: @c POSTPONEd or somesuch).
5942:
5943: @c nac:
5944: @c I agree that it's rather deep, but IMO it is an important difference
5945: @c relative to other programming languages.. often it's annoying: it
5946: @c certainly changes my programming style relative to C.
5947:
5948: @c anton: In what way?
5949:
5950: Constants in Forth behave differently from their equivalents in other
5951: programming languages. In other languages, a constant (such as an EQU in
5952: assembler or a #define in C) only exists at compile-time; in the
5953: executable program the constant has been translated into an absolute
5954: number and, unless you are using a symbolic debugger, it's impossible to
5955: know what abstract thing that number represents. In Forth a constant has
5956: an entry in the header space and remains there after the code that uses
5957: it has been defined. In fact, it must remain in the dictionary since it
5958: has run-time duties to perform. For example:
5959:
5960: @example
5961: 12 Constant INCHES-PER-FOOT
5962: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
5963: @end example
5964:
5965: @cindex in-lining of constants
5966: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
5967: associated with the constant @code{INCHES-PER-FOOT}. If you use
5968: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
5969: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
5970: attempt to optimise constants by in-lining them where they are used. You
5971: can force Gforth to in-line a constant like this:
5972:
5973: @example
5974: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
5975: @end example
5976:
5977: If you use @code{see} to decompile @i{this} version of
5978: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
5979: longer present. To understand how this works, read
5980: @ref{Interpret/Compile states}, and @ref{Literals}.
5981:
5982: In-lining constants in this way might improve execution time
5983: fractionally, and can ensure that a constant is now only referenced at
5984: compile-time. However, the definition of the constant still remains in
5985: the dictionary. Some Forth compilers provide a mechanism for controlling
5986: a second dictionary for holding transient words such that this second
5987: dictionary can be deleted later in order to recover memory
5988: space. However, there is no standard way of doing this.
5989:
5990:
5991: @node Values, Colon Definitions, Constants, Defining Words
5992: @subsection Values
5993: @cindex values
5994:
5995: A @code{Value} behaves like a @code{Constant}, but it can be changed.
5996: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
5997: (not in ANS Forth) you can access (and change) a @code{value} also with
5998: @code{>body}.
5999:
6000: Here are some
6001: examples:
6002:
6003: @example
6004: 12 Value APPLES \ Define APPLES with an initial value of 12
6005: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6006: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6007: APPLES \ puts 35 on the top of the stack.
6008: @end example
6009:
6010: doc-value
6011: doc-to
6012:
6013:
6014:
6015: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6016: @subsection Colon Definitions
6017: @cindex colon definitions
6018:
6019: @example
6020: : name ( ... -- ... )
6021: word1 word2 word3 ;
6022: @end example
6023:
6024: @noindent
6025: Creates a word called @code{name} that, upon execution, executes
6026: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
6027:
6028: The explanation above is somewhat superficial. For simple examples of
6029: colon definitions see @ref{Your first definition}. For an in-depth
6030: discussion of some of the issues involved, @xref{Interpretation and
6031: Compilation Semantics}.
6032:
6033: doc-:
6034: doc-;
6035:
6036:
6037: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
6038: @subsection Anonymous Definitions
6039: @cindex colon definitions
6040: @cindex defining words without name
6041:
6042: Sometimes you want to define an @dfn{anonymous word}; a word without a
6043: name. You can do this with:
6044:
6045: doc-:noname
6046:
6047: This leaves the execution token for the word on the stack after the
6048: closing @code{;}. Here's an example in which a deferred word is
6049: initialised with an @code{xt} from an anonymous colon definition:
6050:
6051: @example
6052: Defer deferred
6053: :noname ( ... -- ... )
6054: ... ;
6055: IS deferred
6056: @end example
6057:
6058: @noindent
6059: Gforth provides an alternative way of doing this, using two separate
6060: words:
6061:
6062: doc-noname
6063: @cindex execution token of last defined word
6064: doc-latestxt
6065:
6066: @noindent
6067: The previous example can be rewritten using @code{noname} and
6068: @code{latestxt}:
6069:
6070: @example
6071: Defer deferred
6072: noname : ( ... -- ... )
6073: ... ;
6074: latestxt IS deferred
6075: @end example
6076:
6077: @noindent
6078: @code{noname} works with any defining word, not just @code{:}.
6079:
6080: @code{latestxt} also works when the last word was not defined as
6081: @code{noname}. It does not work for combined words, though. It also has
6082: the useful property that is is valid as soon as the header for a
6083: definition has been built. Thus:
6084:
6085: @example
6086: latestxt . : foo [ latestxt . ] ; ' foo .
6087: @end example
6088:
6089: @noindent
6090: prints 3 numbers; the last two are the same.
6091:
6092: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6093: @subsection Supplying the name of a defined word
6094: @cindex names for defined words
6095: @cindex defining words, name given in a string
6096:
6097: By default, a defining word takes the name for the defined word from the
6098: input stream. Sometimes you want to supply the name from a string. You
6099: can do this with:
6100:
6101: doc-nextname
6102:
6103: For example:
6104:
6105: @example
6106: s" foo" nextname create
6107: @end example
6108:
6109: @noindent
6110: is equivalent to:
6111:
6112: @example
6113: create foo
6114: @end example
6115:
6116: @noindent
6117: @code{nextname} works with any defining word.
6118:
6119:
6120: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
6121: @subsection User-defined Defining Words
6122: @cindex user-defined defining words
6123: @cindex defining words, user-defined
6124:
6125: You can create a new defining word by wrapping defining-time code around
6126: an existing defining word and putting the sequence in a colon
6127: definition.
6128:
6129: @c anton: This example is very complex and leads in a quite different
6130: @c direction from the CREATE-DOES> stuff that follows. It should probably
6131: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6132: @c subsection of Defining Words)
6133:
6134: For example, suppose that you have a word @code{stats} that
6135: gathers statistics about colon definitions given the @i{xt} of the
6136: definition, and you want every colon definition in your application to
6137: make a call to @code{stats}. You can define and use a new version of
6138: @code{:} like this:
6139:
6140: @example
6141: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6142: ... ; \ other code
6143:
6144: : my: : latestxt postpone literal ['] stats compile, ;
6145:
6146: my: foo + - ;
6147: @end example
6148:
6149: When @code{foo} is defined using @code{my:} these steps occur:
6150:
6151: @itemize @bullet
6152: @item
6153: @code{my:} is executed.
6154: @item
6155: The @code{:} within the definition (the one between @code{my:} and
6156: @code{latestxt}) is executed, and does just what it always does; it parses
6157: the input stream for a name, builds a dictionary header for the name
6158: @code{foo} and switches @code{state} from interpret to compile.
6159: @item
6160: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
6161: being defined -- @code{foo} -- onto the stack.
6162: @item
6163: The code that was produced by @code{postpone literal} is executed; this
6164: causes the value on the stack to be compiled as a literal in the code
6165: area of @code{foo}.
6166: @item
6167: The code @code{['] stats} compiles a literal into the definition of
6168: @code{my:}. When @code{compile,} is executed, that literal -- the
6169: execution token for @code{stats} -- is layed down in the code area of
6170: @code{foo} , following the literal@footnote{Strictly speaking, the
6171: mechanism that @code{compile,} uses to convert an @i{xt} into something
6172: in the code area is implementation-dependent. A threaded implementation
6173: might spit out the execution token directly whilst another
6174: implementation might spit out a native code sequence.}.
6175: @item
6176: At this point, the execution of @code{my:} is complete, and control
6177: returns to the text interpreter. The text interpreter is in compile
6178: state, so subsequent text @code{+ -} is compiled into the definition of
6179: @code{foo} and the @code{;} terminates the definition as always.
6180: @end itemize
6181:
6182: You can use @code{see} to decompile a word that was defined using
6183: @code{my:} and see how it is different from a normal @code{:}
6184: definition. For example:
6185:
6186: @example
6187: : bar + - ; \ like foo but using : rather than my:
6188: see bar
6189: : bar
6190: + - ;
6191: see foo
6192: : foo
6193: 107645672 stats + - ;
6194:
6195: \ use ' foo . to show that 107645672 is the xt for foo
6196: @end example
6197:
6198: You can use techniques like this to make new defining words in terms of
6199: @i{any} existing defining word.
6200:
6201:
6202: @cindex defining defining words
6203: @cindex @code{CREATE} ... @code{DOES>}
6204: If you want the words defined with your defining words to behave
6205: differently from words defined with standard defining words, you can
6206: write your defining word like this:
6207:
6208: @example
6209: : def-word ( "name" -- )
6210: CREATE @i{code1}
6211: DOES> ( ... -- ... )
6212: @i{code2} ;
6213:
6214: def-word name
6215: @end example
6216:
6217: @cindex child words
6218: This fragment defines a @dfn{defining word} @code{def-word} and then
6219: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6220: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6221: is not executed at this time. The word @code{name} is sometimes called a
6222: @dfn{child} of @code{def-word}.
6223:
6224: When you execute @code{name}, the address of the body of @code{name} is
6225: put on the data stack and @i{code2} is executed (the address of the body
6226: of @code{name} is the address @code{HERE} returns immediately after the
6227: @code{CREATE}, i.e., the address a @code{create}d word returns by
6228: default).
6229:
6230: @c anton:
6231: @c www.dictionary.com says:
6232: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6233: @c several generations of absence, usually caused by the chance
6234: @c recombination of genes. 2.An individual or a part that exhibits
6235: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6236: @c of previous behavior after a period of absence.
6237: @c
6238: @c Doesn't seem to fit.
6239:
6240: @c @cindex atavism in child words
6241: You can use @code{def-word} to define a set of child words that behave
6242: similarly; they all have a common run-time behaviour determined by
6243: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6244: body of the child word. The structure of the data is common to all
6245: children of @code{def-word}, but the data values are specific -- and
6246: private -- to each child word. When a child word is executed, the
6247: address of its private data area is passed as a parameter on TOS to be
6248: used and manipulated@footnote{It is legitimate both to read and write to
6249: this data area.} by @i{code2}.
6250:
6251: The two fragments of code that make up the defining words act (are
6252: executed) at two completely separate times:
6253:
6254: @itemize @bullet
6255: @item
6256: At @i{define time}, the defining word executes @i{code1} to generate a
6257: child word
6258: @item
6259: At @i{child execution time}, when a child word is invoked, @i{code2}
6260: is executed, using parameters (data) that are private and specific to
6261: the child word.
6262: @end itemize
6263:
6264: Another way of understanding the behaviour of @code{def-word} and
6265: @code{name} is to say that, if you make the following definitions:
6266: @example
6267: : def-word1 ( "name" -- )
6268: CREATE @i{code1} ;
6269:
6270: : action1 ( ... -- ... )
6271: @i{code2} ;
6272:
6273: def-word1 name1
6274: @end example
6275:
6276: @noindent
6277: Then using @code{name1 action1} is equivalent to using @code{name}.
6278:
6279: The classic example is that you can define @code{CONSTANT} in this way:
6280:
6281: @example
6282: : CONSTANT ( w "name" -- )
6283: CREATE ,
6284: DOES> ( -- w )
6285: @@ ;
6286: @end example
6287:
6288: @comment There is a beautiful description of how this works and what
6289: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6290: @comment commentary on the Counting Fruits problem.
6291:
6292: When you create a constant with @code{5 CONSTANT five}, a set of
6293: define-time actions take place; first a new word @code{five} is created,
6294: then the value 5 is laid down in the body of @code{five} with
6295: @code{,}. When @code{five} is executed, the address of the body is put on
6296: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6297: no code of its own; it simply contains a data field and a pointer to the
6298: code that follows @code{DOES>} in its defining word. That makes words
6299: created in this way very compact.
6300:
6301: The final example in this section is intended to remind you that space
6302: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6303: both read and written by a Standard program@footnote{Exercise: use this
6304: example as a starting point for your own implementation of @code{Value}
6305: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6306: @code{[']}.}:
6307:
6308: @example
6309: : foo ( "name" -- )
6310: CREATE -1 ,
6311: DOES> ( -- )
6312: @@ . ;
6313:
6314: foo first-word
6315: foo second-word
6316:
6317: 123 ' first-word >BODY !
6318: @end example
6319:
6320: If @code{first-word} had been a @code{CREATE}d word, we could simply
6321: have executed it to get the address of its data field. However, since it
6322: was defined to have @code{DOES>} actions, its execution semantics are to
6323: perform those @code{DOES>} actions. To get the address of its data field
6324: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6325: translate the xt into the address of the data field. When you execute
6326: @code{first-word}, it will display @code{123}. When you execute
6327: @code{second-word} it will display @code{-1}.
6328:
6329: @cindex stack effect of @code{DOES>}-parts
6330: @cindex @code{DOES>}-parts, stack effect
6331: In the examples above the stack comment after the @code{DOES>} specifies
6332: the stack effect of the defined words, not the stack effect of the
6333: following code (the following code expects the address of the body on
6334: the top of stack, which is not reflected in the stack comment). This is
6335: the convention that I use and recommend (it clashes a bit with using
6336: locals declarations for stack effect specification, though).
6337:
6338: @menu
6339: * CREATE..DOES> applications::
6340: * CREATE..DOES> details::
6341: * Advanced does> usage example::
6342: * Const-does>::
6343: @end menu
6344:
6345: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
6346: @subsubsection Applications of @code{CREATE..DOES>}
6347: @cindex @code{CREATE} ... @code{DOES>}, applications
6348:
6349: You may wonder how to use this feature. Here are some usage patterns:
6350:
6351: @cindex factoring similar colon definitions
6352: When you see a sequence of code occurring several times, and you can
6353: identify a meaning, you will factor it out as a colon definition. When
6354: you see similar colon definitions, you can factor them using
6355: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6356: that look very similar:
6357: @example
6358: : ori, ( reg-target reg-source n -- )
6359: 0 asm-reg-reg-imm ;
6360: : andi, ( reg-target reg-source n -- )
6361: 1 asm-reg-reg-imm ;
6362: @end example
6363:
6364: @noindent
6365: This could be factored with:
6366: @example
6367: : reg-reg-imm ( op-code -- )
6368: CREATE ,
6369: DOES> ( reg-target reg-source n -- )
6370: @@ asm-reg-reg-imm ;
6371:
6372: 0 reg-reg-imm ori,
6373: 1 reg-reg-imm andi,
6374: @end example
6375:
6376: @cindex currying
6377: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6378: supply a part of the parameters for a word (known as @dfn{currying} in
6379: the functional language community). E.g., @code{+} needs two
6380: parameters. Creating versions of @code{+} with one parameter fixed can
6381: be done like this:
6382:
6383: @example
6384: : curry+ ( n1 "name" -- )
6385: CREATE ,
6386: DOES> ( n2 -- n1+n2 )
6387: @@ + ;
6388:
6389: 3 curry+ 3+
6390: -2 curry+ 2-
6391: @end example
6392:
6393:
6394: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
6395: @subsubsection The gory details of @code{CREATE..DOES>}
6396: @cindex @code{CREATE} ... @code{DOES>}, details
6397:
6398: doc-does>
6399:
6400: @cindex @code{DOES>} in a separate definition
6401: This means that you need not use @code{CREATE} and @code{DOES>} in the
6402: same definition; you can put the @code{DOES>}-part in a separate
6403: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
6404: @example
6405: : does1
6406: DOES> ( ... -- ... )
6407: ... ;
6408:
6409: : does2
6410: DOES> ( ... -- ... )
6411: ... ;
6412:
6413: : def-word ( ... -- ... )
6414: create ...
6415: IF
6416: does1
6417: ELSE
6418: does2
6419: ENDIF ;
6420: @end example
6421:
6422: In this example, the selection of whether to use @code{does1} or
6423: @code{does2} is made at definition-time; at the time that the child word is
6424: @code{CREATE}d.
6425:
6426: @cindex @code{DOES>} in interpretation state
6427: In a standard program you can apply a @code{DOES>}-part only if the last
6428: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6429: will override the behaviour of the last word defined in any case. In a
6430: standard program, you can use @code{DOES>} only in a colon
6431: definition. In Gforth, you can also use it in interpretation state, in a
6432: kind of one-shot mode; for example:
6433: @example
6434: CREATE name ( ... -- ... )
6435: @i{initialization}
6436: DOES>
6437: @i{code} ;
6438: @end example
6439:
6440: @noindent
6441: is equivalent to the standard:
6442: @example
6443: :noname
6444: DOES>
6445: @i{code} ;
6446: CREATE name EXECUTE ( ... -- ... )
6447: @i{initialization}
6448: @end example
6449:
6450: doc->body
6451:
6452: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
6453: @subsubsection Advanced does> usage example
6454:
6455: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6456: for disassembling instructions, that follow a very repetetive scheme:
6457:
6458: @example
6459: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6460: @var{entry-num} cells @var{table} + !
6461: @end example
6462:
6463: Of course, this inspires the idea to factor out the commonalities to
6464: allow a definition like
6465:
6466: @example
6467: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6468: @end example
6469:
6470: The parameters @var{disasm-operands} and @var{table} are usually
6471: correlated. Moreover, before I wrote the disassembler, there already
6472: existed code that defines instructions like this:
6473:
6474: @example
6475: @var{entry-num} @var{inst-format} @var{inst-name}
6476: @end example
6477:
6478: This code comes from the assembler and resides in
6479: @file{arch/mips/insts.fs}.
6480:
6481: So I had to define the @var{inst-format} words that performed the scheme
6482: above when executed. At first I chose to use run-time code-generation:
6483:
6484: @example
6485: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6486: :noname Postpone @var{disasm-operands}
6487: name Postpone sliteral Postpone type Postpone ;
6488: swap cells @var{table} + ! ;
6489: @end example
6490:
6491: Note that this supplies the other two parameters of the scheme above.
6492:
6493: An alternative would have been to write this using
6494: @code{create}/@code{does>}:
6495:
6496: @example
6497: : @var{inst-format} ( entry-num "name" -- )
6498: here name string, ( entry-num c-addr ) \ parse and save "name"
6499: noname create , ( entry-num )
6500: latestxt swap cells @var{table} + !
6501: does> ( addr w -- )
6502: \ disassemble instruction w at addr
6503: @@ >r
6504: @var{disasm-operands}
6505: r> count type ;
6506: @end example
6507:
6508: Somehow the first solution is simpler, mainly because it's simpler to
6509: shift a string from definition-time to use-time with @code{sliteral}
6510: than with @code{string,} and friends.
6511:
6512: I wrote a lot of words following this scheme and soon thought about
6513: factoring out the commonalities among them. Note that this uses a
6514: two-level defining word, i.e., a word that defines ordinary defining
6515: words.
6516:
6517: This time a solution involving @code{postpone} and friends seemed more
6518: difficult (try it as an exercise), so I decided to use a
6519: @code{create}/@code{does>} word; since I was already at it, I also used
6520: @code{create}/@code{does>} for the lower level (try using
6521: @code{postpone} etc. as an exercise), resulting in the following
6522: definition:
6523:
6524: @example
6525: : define-format ( disasm-xt table-xt -- )
6526: \ define an instruction format that uses disasm-xt for
6527: \ disassembling and enters the defined instructions into table
6528: \ table-xt
6529: create 2,
6530: does> ( u "inst" -- )
6531: \ defines an anonymous word for disassembling instruction inst,
6532: \ and enters it as u-th entry into table-xt
6533: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6534: noname create 2, \ define anonymous word
6535: execute latestxt swap ! \ enter xt of defined word into table-xt
6536: does> ( addr w -- )
6537: \ disassemble instruction w at addr
6538: 2@@ >r ( addr w disasm-xt R: c-addr )
6539: execute ( R: c-addr ) \ disassemble operands
6540: r> count type ; \ print name
6541: @end example
6542:
6543: Note that the tables here (in contrast to above) do the @code{cells +}
6544: by themselves (that's why you have to pass an xt). This word is used in
6545: the following way:
6546:
6547: @example
6548: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6549: @end example
6550:
6551: As shown above, the defined instruction format is then used like this:
6552:
6553: @example
6554: @var{entry-num} @var{inst-format} @var{inst-name}
6555: @end example
6556:
6557: In terms of currying, this kind of two-level defining word provides the
6558: parameters in three stages: first @var{disasm-operands} and @var{table},
6559: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6560: the instruction to be disassembled.
6561:
6562: Of course this did not quite fit all the instruction format names used
6563: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6564: the parameters into the right form.
6565:
6566: If you have trouble following this section, don't worry. First, this is
6567: involved and takes time (and probably some playing around) to
6568: understand; second, this is the first two-level
6569: @code{create}/@code{does>} word I have written in seventeen years of
6570: Forth; and if I did not have @file{insts.fs} to start with, I may well
6571: have elected to use just a one-level defining word (with some repeating
6572: of parameters when using the defining word). So it is not necessary to
6573: understand this, but it may improve your understanding of Forth.
6574:
6575:
6576: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
6577: @subsubsection @code{Const-does>}
6578:
6579: A frequent use of @code{create}...@code{does>} is for transferring some
6580: values from definition-time to run-time. Gforth supports this use with
6581:
6582: doc-const-does>
6583:
6584: A typical use of this word is:
6585:
6586: @example
6587: : curry+ ( n1 "name" -- )
6588: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6589: + ;
6590:
6591: 3 curry+ 3+
6592: @end example
6593:
6594: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6595: definition to run-time.
6596:
6597: The advantages of using @code{const-does>} are:
6598:
6599: @itemize
6600:
6601: @item
6602: You don't have to deal with storing and retrieving the values, i.e.,
6603: your program becomes more writable and readable.
6604:
6605: @item
6606: When using @code{does>}, you have to introduce a @code{@@} that cannot
6607: be optimized away (because you could change the data using
6608: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6609:
6610: @end itemize
6611:
6612: An ANS Forth implementation of @code{const-does>} is available in
6613: @file{compat/const-does.fs}.
6614:
6615:
6616: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6617: @subsection Deferred words
6618: @cindex deferred words
6619:
6620: The defining word @code{Defer} allows you to define a word by name
6621: without defining its behaviour; the definition of its behaviour is
6622: deferred. Here are two situation where this can be useful:
6623:
6624: @itemize @bullet
6625: @item
6626: Where you want to allow the behaviour of a word to be altered later, and
6627: for all precompiled references to the word to change when its behaviour
6628: is changed.
6629: @item
6630: For mutual recursion; @xref{Calls and returns}.
6631: @end itemize
6632:
6633: In the following example, @code{foo} always invokes the version of
6634: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6635: always invokes the version that prints ``@code{Hello}''. There is no way
6636: of getting @code{foo} to use the later version without re-ordering the
6637: source code and recompiling it.
6638:
6639: @example
6640: : greet ." Good morning" ;
6641: : foo ... greet ... ;
6642: : greet ." Hello" ;
6643: : bar ... greet ... ;
6644: @end example
6645:
6646: This problem can be solved by defining @code{greet} as a @code{Defer}red
6647: word. The behaviour of a @code{Defer}red word can be defined and
6648: redefined at any time by using @code{IS} to associate the xt of a
6649: previously-defined word with it. The previous example becomes:
6650:
6651: @example
6652: Defer greet ( -- )
6653: : foo ... greet ... ;
6654: : bar ... greet ... ;
6655: : greet1 ( -- ) ." Good morning" ;
6656: : greet2 ( -- ) ." Hello" ;
6657: ' greet2 IS greet \ make greet behave like greet2
6658: @end example
6659:
6660: @progstyle
6661: You should write a stack comment for every deferred word, and put only
6662: XTs into deferred words that conform to this stack effect. Otherwise
6663: it's too difficult to use the deferred word.
6664:
6665: A deferred word can be used to improve the statistics-gathering example
6666: from @ref{User-defined Defining Words}; rather than edit the
6667: application's source code to change every @code{:} to a @code{my:}, do
6668: this:
6669:
6670: @example
6671: : real: : ; \ retain access to the original
6672: defer : \ redefine as a deferred word
6673: ' my: IS : \ use special version of :
6674: \
6675: \ load application here
6676: \
6677: ' real: IS : \ go back to the original
6678: @end example
6679:
6680:
6681: One thing to note is that @code{IS} has special compilation semantics,
6682: such that it parses the name at compile time (like @code{TO}):
6683:
6684: @example
6685: : set-greet ( xt -- )
6686: IS greet ;
6687:
6688: ' greet1 set-greet
6689: @end example
6690:
6691: In situations where @code{IS} does not fit, use @code{defer!} instead.
6692:
6693: A deferred word can only inherit execution semantics from the xt
6694: (because that is all that an xt can represent -- for more discussion of
6695: this @pxref{Tokens for Words}); by default it will have default
6696: interpretation and compilation semantics deriving from this execution
6697: semantics. However, you can change the interpretation and compilation
6698: semantics of the deferred word in the usual ways:
6699:
6700: @example
6701: : bar .... ; immediate
6702: Defer fred immediate
6703: Defer jim
6704:
6705: ' bar IS jim \ jim has default semantics
6706: ' bar IS fred \ fred is immediate
6707: @end example
6708:
6709: doc-defer
6710: doc-defer!
6711: doc-is
6712: doc-defer@
6713: doc-action-of
6714: @comment TODO document these: what's defers [is]
6715: doc-defers
6716:
6717: @c Use @code{words-deferred} to see a list of deferred words.
6718:
6719: Definitions of these words (except @code{defers}) in ANS Forth are
6720: provided in @file{compat/defer.fs}.
6721:
6722:
6723: @node Aliases, , Deferred words, Defining Words
6724: @subsection Aliases
6725: @cindex aliases
6726:
6727: The defining word @code{Alias} allows you to define a word by name that
6728: has the same behaviour as some other word. Here are two situation where
6729: this can be useful:
6730:
6731: @itemize @bullet
6732: @item
6733: When you want access to a word's definition from a different word list
6734: (for an example of this, see the definition of the @code{Root} word list
6735: in the Gforth source).
6736: @item
6737: When you want to create a synonym; a definition that can be known by
6738: either of two names (for example, @code{THEN} and @code{ENDIF} are
6739: aliases).
6740: @end itemize
6741:
6742: Like deferred words, an alias has default compilation and interpretation
6743: semantics at the beginning (not the modifications of the other word),
6744: but you can change them in the usual ways (@code{immediate},
6745: @code{compile-only}). For example:
6746:
6747: @example
6748: : foo ... ; immediate
6749:
6750: ' foo Alias bar \ bar is not an immediate word
6751: ' foo Alias fooby immediate \ fooby is an immediate word
6752: @end example
6753:
6754: Words that are aliases have the same xt, different headers in the
6755: dictionary, and consequently different name tokens (@pxref{Tokens for
6756: Words}) and possibly different immediate flags. An alias can only have
6757: default or immediate compilation semantics; you can define aliases for
6758: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
6759:
6760: doc-alias
6761:
6762:
6763: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6764: @section Interpretation and Compilation Semantics
6765: @cindex semantics, interpretation and compilation
6766:
6767: @c !! state and ' are used without explanation
6768: @c example for immediate/compile-only? or is the tutorial enough
6769:
6770: @cindex interpretation semantics
6771: The @dfn{interpretation semantics} of a (named) word are what the text
6772: interpreter does when it encounters the word in interpret state. It also
6773: appears in some other contexts, e.g., the execution token returned by
6774: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6775: (in other words, @code{' @i{word} execute} is equivalent to
6776: interpret-state text interpretation of @code{@i{word}}).
6777:
6778: @cindex compilation semantics
6779: The @dfn{compilation semantics} of a (named) word are what the text
6780: interpreter does when it encounters the word in compile state. It also
6781: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6782: compiles@footnote{In standard terminology, ``appends to the current
6783: definition''.} the compilation semantics of @i{word}.
6784:
6785: @cindex execution semantics
6786: The standard also talks about @dfn{execution semantics}. They are used
6787: only for defining the interpretation and compilation semantics of many
6788: words. By default, the interpretation semantics of a word are to
6789: @code{execute} its execution semantics, and the compilation semantics of
6790: a word are to @code{compile,} its execution semantics.@footnote{In
6791: standard terminology: The default interpretation semantics are its
6792: execution semantics; the default compilation semantics are to append its
6793: execution semantics to the execution semantics of the current
6794: definition.}
6795:
6796: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6797: the text interpreter, ticked, or @code{postpone}d, so they have no
6798: interpretation or compilation semantics. Their behaviour is represented
6799: by their XT (@pxref{Tokens for Words}), and we call it execution
6800: semantics, too.
6801:
6802: @comment TODO expand, make it co-operate with new sections on text interpreter.
6803:
6804: @cindex immediate words
6805: @cindex compile-only words
6806: You can change the semantics of the most-recently defined word:
6807:
6808:
6809: doc-immediate
6810: doc-compile-only
6811: doc-restrict
6812:
6813: By convention, words with non-default compilation semantics (e.g.,
6814: immediate words) often have names surrounded with brackets (e.g.,
6815: @code{[']}, @pxref{Execution token}).
6816:
6817: Note that ticking (@code{'}) a compile-only word gives an error
6818: (``Interpreting a compile-only word'').
6819:
6820: @menu
6821: * Combined words::
6822: @end menu
6823:
6824:
6825: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
6826: @subsection Combined Words
6827: @cindex combined words
6828:
6829: Gforth allows you to define @dfn{combined words} -- words that have an
6830: arbitrary combination of interpretation and compilation semantics.
6831:
6832: doc-interpret/compile:
6833:
6834: This feature was introduced for implementing @code{TO} and @code{S"}. I
6835: recommend that you do not define such words, as cute as they may be:
6836: they make it hard to get at both parts of the word in some contexts.
6837: E.g., assume you want to get an execution token for the compilation
6838: part. Instead, define two words, one that embodies the interpretation
6839: part, and one that embodies the compilation part. Once you have done
6840: that, you can define a combined word with @code{interpret/compile:} for
6841: the convenience of your users.
6842:
6843: You might try to use this feature to provide an optimizing
6844: implementation of the default compilation semantics of a word. For
6845: example, by defining:
6846: @example
6847: :noname
6848: foo bar ;
6849: :noname
6850: POSTPONE foo POSTPONE bar ;
6851: interpret/compile: opti-foobar
6852: @end example
6853:
6854: @noindent
6855: as an optimizing version of:
6856:
6857: @example
6858: : foobar
6859: foo bar ;
6860: @end example
6861:
6862: Unfortunately, this does not work correctly with @code{[compile]},
6863: because @code{[compile]} assumes that the compilation semantics of all
6864: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
6865: opti-foobar} would compile compilation semantics, whereas
6866: @code{[compile] foobar} would compile interpretation semantics.
6867:
6868: @cindex state-smart words (are a bad idea)
6869: @anchor{state-smartness}
6870: Some people try to use @dfn{state-smart} words to emulate the feature provided
6871: by @code{interpret/compile:} (words are state-smart if they check
6872: @code{STATE} during execution). E.g., they would try to code
6873: @code{foobar} like this:
6874:
6875: @example
6876: : foobar
6877: STATE @@
6878: IF ( compilation state )
6879: POSTPONE foo POSTPONE bar
6880: ELSE
6881: foo bar
6882: ENDIF ; immediate
6883: @end example
6884:
6885: Although this works if @code{foobar} is only processed by the text
6886: interpreter, it does not work in other contexts (like @code{'} or
6887: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6888: for a state-smart word, not for the interpretation semantics of the
6889: original @code{foobar}; when you execute this execution token (directly
6890: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6891: state, the result will not be what you expected (i.e., it will not
6892: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6893: write them@footnote{For a more detailed discussion of this topic, see
6894: M. Anton Ertl,
6895: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6896: it is Evil and How to Exorcise it}}, EuroForth '98.}!
6897:
6898: @cindex defining words with arbitrary semantics combinations
6899: It is also possible to write defining words that define words with
6900: arbitrary combinations of interpretation and compilation semantics. In
6901: general, they look like this:
6902:
6903: @example
6904: : def-word
6905: create-interpret/compile
6906: @i{code1}
6907: interpretation>
6908: @i{code2}
6909: <interpretation
6910: compilation>
6911: @i{code3}
6912: <compilation ;
6913: @end example
6914:
6915: For a @i{word} defined with @code{def-word}, the interpretation
6916: semantics are to push the address of the body of @i{word} and perform
6917: @i{code2}, and the compilation semantics are to push the address of
6918: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
6919: can also be defined like this (except that the defined constants don't
6920: behave correctly when @code{[compile]}d):
6921:
6922: @example
6923: : constant ( n "name" -- )
6924: create-interpret/compile
6925: ,
6926: interpretation> ( -- n )
6927: @@
6928: <interpretation
6929: compilation> ( compilation. -- ; run-time. -- n )
6930: @@ postpone literal
6931: <compilation ;
6932: @end example
6933:
6934:
6935: doc-create-interpret/compile
6936: doc-interpretation>
6937: doc-<interpretation
6938: doc-compilation>
6939: doc-<compilation
6940:
6941:
6942: Words defined with @code{interpret/compile:} and
6943: @code{create-interpret/compile} have an extended header structure that
6944: differs from other words; however, unless you try to access them with
6945: plain address arithmetic, you should not notice this. Words for
6946: accessing the header structure usually know how to deal with this; e.g.,
6947: @code{'} @i{word} @code{>body} also gives you the body of a word created
6948: with @code{create-interpret/compile}.
6949:
6950:
6951: @c -------------------------------------------------------------
6952: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
6953: @section Tokens for Words
6954: @cindex tokens for words
6955:
6956: This section describes the creation and use of tokens that represent
6957: words.
6958:
6959: @menu
6960: * Execution token:: represents execution/interpretation semantics
6961: * Compilation token:: represents compilation semantics
6962: * Name token:: represents named words
6963: @end menu
6964:
6965: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
6966: @subsection Execution token
6967:
6968: @cindex xt
6969: @cindex execution token
6970: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
6971: You can use @code{execute} to invoke this behaviour.
6972:
6973: @cindex tick (')
6974: You can use @code{'} to get an execution token that represents the
6975: interpretation semantics of a named word:
6976:
6977: @example
6978: 5 ' . ( n xt )
6979: execute ( ) \ execute the xt (i.e., ".")
6980: @end example
6981:
6982: doc-'
6983:
6984: @code{'} parses at run-time; there is also a word @code{[']} that parses
6985: when it is compiled, and compiles the resulting XT:
6986:
6987: @example
6988: : foo ['] . execute ;
6989: 5 foo
6990: : bar ' execute ; \ by contrast,
6991: 5 bar . \ ' parses "." when bar executes
6992: @end example
6993:
6994: doc-[']
6995:
6996: If you want the execution token of @i{word}, write @code{['] @i{word}}
6997: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
6998: @code{'} and @code{[']} behave somewhat unusually by complaining about
6999: compile-only words (because these words have no interpretation
7000: semantics). You might get what you want by using @code{COMP' @i{word}
7001: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7002: token}).
7003:
7004: Another way to get an XT is @code{:noname} or @code{latestxt}
7005: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7006: for the only behaviour the word has (the execution semantics). For
7007: named words, @code{latestxt} produces an XT for the same behaviour it
7008: would produce if the word was defined anonymously.
7009:
7010: @example
7011: :noname ." hello" ;
7012: execute
7013: @end example
7014:
7015: An XT occupies one cell and can be manipulated like any other cell.
7016:
7017: @cindex code field address
7018: @cindex CFA
7019: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7020: operations that produce or consume it). For old hands: In Gforth, the
7021: XT is implemented as a code field address (CFA).
7022:
7023: doc-execute
7024: doc-perform
7025:
7026: @node Compilation token, Name token, Execution token, Tokens for Words
7027: @subsection Compilation token
7028:
7029: @cindex compilation token
7030: @cindex CT (compilation token)
7031: Gforth represents the compilation semantics of a named word by a
7032: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7033: @i{xt} is an execution token. The compilation semantics represented by
7034: the compilation token can be performed with @code{execute}, which
7035: consumes the whole compilation token, with an additional stack effect
7036: determined by the represented compilation semantics.
7037:
7038: At present, the @i{w} part of a compilation token is an execution token,
7039: and the @i{xt} part represents either @code{execute} or
7040: @code{compile,}@footnote{Depending upon the compilation semantics of the
7041: word. If the word has default compilation semantics, the @i{xt} will
7042: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7043: @i{xt} will represent @code{execute}.}. However, don't rely on that
7044: knowledge, unless necessary; future versions of Gforth may introduce
7045: unusual compilation tokens (e.g., a compilation token that represents
7046: the compilation semantics of a literal).
7047:
7048: You can perform the compilation semantics represented by the compilation
7049: token with @code{execute}. You can compile the compilation semantics
7050: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7051: equivalent to @code{postpone @i{word}}.
7052:
7053: doc-[comp']
7054: doc-comp'
7055: doc-postpone,
7056:
7057: @node Name token, , Compilation token, Tokens for Words
7058: @subsection Name token
7059:
7060: @cindex name token
7061: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7062: token is an abstract data type that occurs as argument or result of the
7063: words below.
7064:
7065: @c !! put this elswhere?
7066: @cindex name field address
7067: @cindex NFA
7068: The closest thing to the nt in older Forth systems is the name field
7069: address (NFA), but there are significant differences: in older Forth
7070: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7071: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7072: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7073: is a link field in the structure identified by the name token, but
7074: searching usually uses a hash table external to these structures; the
7075: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7076: implemented as the address of that count field.
7077:
7078: doc-find-name
7079: doc-latest
7080: doc->name
7081: doc-name>int
7082: doc-name?int
7083: doc-name>comp
7084: doc-name>string
7085: doc-id.
7086: doc-.name
7087: doc-.id
7088:
7089: @c ----------------------------------------------------------
7090: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7091: @section Compiling words
7092: @cindex compiling words
7093: @cindex macros
7094:
7095: In contrast to most other languages, Forth has no strict boundary
7096: between compilation and run-time. E.g., you can run arbitrary code
7097: between defining words (or for computing data used by defining words
7098: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7099: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7100: running arbitrary code while compiling a colon definition (exception:
7101: you must not allot dictionary space).
7102:
7103: @menu
7104: * Literals:: Compiling data values
7105: * Macros:: Compiling words
7106: @end menu
7107:
7108: @node Literals, Macros, Compiling words, Compiling words
7109: @subsection Literals
7110: @cindex Literals
7111:
7112: The simplest and most frequent example is to compute a literal during
7113: compilation. E.g., the following definition prints an array of strings,
7114: one string per line:
7115:
7116: @example
7117: : .strings ( addr u -- ) \ gforth
7118: 2* cells bounds U+DO
7119: cr i 2@@ type
7120: 2 cells +LOOP ;
7121: @end example
7122:
7123: With a simple-minded compiler like Gforth's, this computes @code{2
7124: cells} on every loop iteration. You can compute this value once and for
7125: all at compile time and compile it into the definition like this:
7126:
7127: @example
7128: : .strings ( addr u -- ) \ gforth
7129: 2* cells bounds U+DO
7130: cr i 2@@ type
7131: [ 2 cells ] literal +LOOP ;
7132: @end example
7133:
7134: @code{[} switches the text interpreter to interpret state (you will get
7135: an @code{ok} prompt if you type this example interactively and insert a
7136: newline between @code{[} and @code{]}), so it performs the
7137: interpretation semantics of @code{2 cells}; this computes a number.
7138: @code{]} switches the text interpreter back into compile state. It then
7139: performs @code{Literal}'s compilation semantics, which are to compile
7140: this number into the current word. You can decompile the word with
7141: @code{see .strings} to see the effect on the compiled code.
7142:
7143: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7144: *} in this way.
7145:
7146: doc-[
7147: doc-]
7148: doc-literal
7149: doc-]L
7150:
7151: There are also words for compiling other data types than single cells as
7152: literals:
7153:
7154: doc-2literal
7155: doc-fliteral
7156: doc-sliteral
7157:
7158: @cindex colon-sys, passing data across @code{:}
7159: @cindex @code{:}, passing data across
7160: You might be tempted to pass data from outside a colon definition to the
7161: inside on the data stack. This does not work, because @code{:} puhes a
7162: colon-sys, making stuff below unaccessible. E.g., this does not work:
7163:
7164: @example
7165: 5 : foo literal ; \ error: "unstructured"
7166: @end example
7167:
7168: Instead, you have to pass the value in some other way, e.g., through a
7169: variable:
7170:
7171: @example
7172: variable temp
7173: 5 temp !
7174: : foo [ temp @@ ] literal ;
7175: @end example
7176:
7177:
7178: @node Macros, , Literals, Compiling words
7179: @subsection Macros
7180: @cindex Macros
7181: @cindex compiling compilation semantics
7182:
7183: @code{Literal} and friends compile data values into the current
7184: definition. You can also write words that compile other words into the
7185: current definition. E.g.,
7186:
7187: @example
7188: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7189: POSTPONE + ;
7190:
7191: : foo ( n1 n2 -- n )
7192: [ compile-+ ] ;
7193: 1 2 foo .
7194: @end example
7195:
7196: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7197: What happens in this example? @code{Postpone} compiles the compilation
7198: semantics of @code{+} into @code{compile-+}; later the text interpreter
7199: executes @code{compile-+} and thus the compilation semantics of +, which
7200: compile (the execution semantics of) @code{+} into
7201: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7202: should only be executed in compile state, so this example is not
7203: guaranteed to work on all standard systems, but on any decent system it
7204: will work.}
7205:
7206: doc-postpone
7207: doc-[compile]
7208:
7209: Compiling words like @code{compile-+} are usually immediate (or similar)
7210: so you do not have to switch to interpret state to execute them;
7211: mopifying the last example accordingly produces:
7212:
7213: @example
7214: : [compile-+] ( compilation: --; interpretation: -- )
7215: \ compiled code: ( n1 n2 -- n )
7216: POSTPONE + ; immediate
7217:
7218: : foo ( n1 n2 -- n )
7219: [compile-+] ;
7220: 1 2 foo .
7221: @end example
7222:
7223: Immediate compiling words are similar to macros in other languages (in
7224: particular, Lisp). The important differences to macros in, e.g., C are:
7225:
7226: @itemize @bullet
7227:
7228: @item
7229: You use the same language for defining and processing macros, not a
7230: separate preprocessing language and processor.
7231:
7232: @item
7233: Consequently, the full power of Forth is available in macro definitions.
7234: E.g., you can perform arbitrarily complex computations, or generate
7235: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7236: Tutorial}). This power is very useful when writing a parser generators
7237: or other code-generating software.
7238:
7239: @item
7240: Macros defined using @code{postpone} etc. deal with the language at a
7241: higher level than strings; name binding happens at macro definition
7242: time, so you can avoid the pitfalls of name collisions that can happen
7243: in C macros. Of course, Forth is a liberal language and also allows to
7244: shoot yourself in the foot with text-interpreted macros like
7245:
7246: @example
7247: : [compile-+] s" +" evaluate ; immediate
7248: @end example
7249:
7250: Apart from binding the name at macro use time, using @code{evaluate}
7251: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7252: @end itemize
7253:
7254: You may want the macro to compile a number into a word. The word to do
7255: it is @code{literal}, but you have to @code{postpone} it, so its
7256: compilation semantics take effect when the macro is executed, not when
7257: it is compiled:
7258:
7259: @example
7260: : [compile-5] ( -- ) \ compiled code: ( -- n )
7261: 5 POSTPONE literal ; immediate
7262:
7263: : foo [compile-5] ;
7264: foo .
7265: @end example
7266:
7267: You may want to pass parameters to a macro, that the macro should
7268: compile into the current definition. If the parameter is a number, then
7269: you can use @code{postpone literal} (similar for other values).
7270:
7271: If you want to pass a word that is to be compiled, the usual way is to
7272: pass an execution token and @code{compile,} it:
7273:
7274: @example
7275: : twice1 ( xt -- ) \ compiled code: ... -- ...
7276: dup compile, compile, ;
7277:
7278: : 2+ ( n1 -- n2 )
7279: [ ' 1+ twice1 ] ;
7280: @end example
7281:
7282: doc-compile,
7283:
7284: An alternative available in Gforth, that allows you to pass compile-only
7285: words as parameters is to use the compilation token (@pxref{Compilation
7286: token}). The same example in this technique:
7287:
7288: @example
7289: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7290: 2dup 2>r execute 2r> execute ;
7291:
7292: : 2+ ( n1 -- n2 )
7293: [ comp' 1+ twice ] ;
7294: @end example
7295:
7296: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7297: works even if the executed compilation semantics has an effect on the
7298: data stack.
7299:
7300: You can also define complete definitions with these words; this provides
7301: an alternative to using @code{does>} (@pxref{User-defined Defining
7302: Words}). E.g., instead of
7303:
7304: @example
7305: : curry+ ( n1 "name" -- )
7306: CREATE ,
7307: DOES> ( n2 -- n1+n2 )
7308: @@ + ;
7309: @end example
7310:
7311: you could define
7312:
7313: @example
7314: : curry+ ( n1 "name" -- )
7315: \ name execution: ( n2 -- n1+n2 )
7316: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
7317:
7318: -3 curry+ 3-
7319: see 3-
7320: @end example
7321:
7322: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7323: colon-sys on the data stack that makes everything below it unaccessible.
7324:
7325: This way of writing defining words is sometimes more, sometimes less
7326: convenient than using @code{does>} (@pxref{Advanced does> usage
7327: example}). One advantage of this method is that it can be optimized
7328: better, because the compiler knows that the value compiled with
7329: @code{literal} is fixed, whereas the data associated with a
7330: @code{create}d word can be changed.
7331:
7332: @c ----------------------------------------------------------
7333: @node The Text Interpreter, The Input Stream, Compiling words, Words
7334: @section The Text Interpreter
7335: @cindex interpreter - outer
7336: @cindex text interpreter
7337: @cindex outer interpreter
7338:
7339: @c Should we really describe all these ugly details? IMO the text
7340: @c interpreter should be much cleaner, but that may not be possible within
7341: @c ANS Forth. - anton
7342: @c nac-> I wanted to explain how it works to show how you can exploit
7343: @c it in your own programs. When I was writing a cross-compiler, figuring out
7344: @c some of these gory details was very helpful to me. None of the textbooks
7345: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7346: @c seems to positively avoid going into too much detail for some of
7347: @c the internals.
7348:
7349: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7350: @c it is; for the ugly details, I would prefer another place. I wonder
7351: @c whether we should have a chapter before "Words" that describes some
7352: @c basic concepts referred to in words, and a chapter after "Words" that
7353: @c describes implementation details.
7354:
7355: The text interpreter@footnote{This is an expanded version of the
7356: material in @ref{Introducing the Text Interpreter}.} is an endless loop
7357: that processes input from the current input device. It is also called
7358: the outer interpreter, in contrast to the inner interpreter
7359: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7360: implementations.
7361:
7362: @cindex interpret state
7363: @cindex compile state
7364: The text interpreter operates in one of two states: @dfn{interpret
7365: state} and @dfn{compile state}. The current state is defined by the
7366: aptly-named variable @code{state}.
7367:
7368: This section starts by describing how the text interpreter behaves when
7369: it is in interpret state, processing input from the user input device --
7370: the keyboard. This is the mode that a Forth system is in after it starts
7371: up.
7372:
7373: @cindex input buffer
7374: @cindex terminal input buffer
7375: The text interpreter works from an area of memory called the @dfn{input
7376: buffer}@footnote{When the text interpreter is processing input from the
7377: keyboard, this area of memory is called the @dfn{terminal input buffer}
7378: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7379: @code{#TIB}.}, which stores your keyboard input when you press the
7380: @key{RET} key. Starting at the beginning of the input buffer, it skips
7381: leading spaces (called @dfn{delimiters}) then parses a string (a
7382: sequence of non-space characters) until it reaches either a space
7383: character or the end of the buffer. Having parsed a string, it makes two
7384: attempts to process it:
7385:
7386: @cindex dictionary
7387: @itemize @bullet
7388: @item
7389: It looks for the string in a @dfn{dictionary} of definitions. If the
7390: string is found, the string names a @dfn{definition} (also known as a
7391: @dfn{word}) and the dictionary search returns information that allows
7392: the text interpreter to perform the word's @dfn{interpretation
7393: semantics}. In most cases, this simply means that the word will be
7394: executed.
7395: @item
7396: If the string is not found in the dictionary, the text interpreter
7397: attempts to treat it as a number, using the rules described in
7398: @ref{Number Conversion}. If the string represents a legal number in the
7399: current radix, the number is pushed onto a parameter stack (the data
7400: stack for integers, the floating-point stack for floating-point
7401: numbers).
7402: @end itemize
7403:
7404: If both attempts fail, or if the word is found in the dictionary but has
7405: no interpretation semantics@footnote{This happens if the word was
7406: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7407: remainder of the input buffer, issues an error message and waits for
7408: more input. If one of the attempts succeeds, the text interpreter
7409: repeats the parsing process until the whole of the input buffer has been
7410: processed, at which point it prints the status message ``@code{ ok}''
7411: and waits for more input.
7412:
7413: @c anton: this should be in the input stream subsection (or below it)
7414:
7415: @cindex parse area
7416: The text interpreter keeps track of its position in the input buffer by
7417: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7418: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7419: of the input buffer. The region from offset @code{>IN @@} to the end of
7420: the input buffer is called the @dfn{parse area}@footnote{In other words,
7421: the text interpreter processes the contents of the input buffer by
7422: parsing strings from the parse area until the parse area is empty.}.
7423: This example shows how @code{>IN} changes as the text interpreter parses
7424: the input buffer:
7425:
7426: @example
7427: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7428: CR ." ->" TYPE ." <-" ; IMMEDIATE
7429:
7430: 1 2 3 remaining + remaining .
7431:
7432: : foo 1 2 3 remaining SWAP remaining ;
7433: @end example
7434:
7435: @noindent
7436: The result is:
7437:
7438: @example
7439: ->+ remaining .<-
7440: ->.<-5 ok
7441:
7442: ->SWAP remaining ;-<
7443: ->;<- ok
7444: @end example
7445:
7446: @cindex parsing words
7447: The value of @code{>IN} can also be modified by a word in the input
7448: buffer that is executed by the text interpreter. This means that a word
7449: can ``trick'' the text interpreter into either skipping a section of the
7450: input buffer@footnote{This is how parsing words work.} or into parsing a
7451: section twice. For example:
7452:
7453: @example
7454: : lat ." <<foo>>" ;
7455: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
7456: @end example
7457:
7458: @noindent
7459: When @code{flat} is executed, this output is produced@footnote{Exercise
7460: for the reader: what would happen if the @code{3} were replaced with
7461: @code{4}?}:
7462:
7463: @example
7464: <<bar>><<foo>>
7465: @end example
7466:
7467: This technique can be used to work around some of the interoperability
7468: problems of parsing words. Of course, it's better to avoid parsing
7469: words where possible.
7470:
7471: @noindent
7472: Two important notes about the behaviour of the text interpreter:
7473:
7474: @itemize @bullet
7475: @item
7476: It processes each input string to completion before parsing additional
7477: characters from the input buffer.
7478: @item
7479: It treats the input buffer as a read-only region (and so must your code).
7480: @end itemize
7481:
7482: @noindent
7483: When the text interpreter is in compile state, its behaviour changes in
7484: these ways:
7485:
7486: @itemize @bullet
7487: @item
7488: If a parsed string is found in the dictionary, the text interpreter will
7489: perform the word's @dfn{compilation semantics}. In most cases, this
7490: simply means that the execution semantics of the word will be appended
7491: to the current definition.
7492: @item
7493: When a number is encountered, it is compiled into the current definition
7494: (as a literal) rather than being pushed onto a parameter stack.
7495: @item
7496: If an error occurs, @code{state} is modified to put the text interpreter
7497: back into interpret state.
7498: @item
7499: Each time a line is entered from the keyboard, Gforth prints
7500: ``@code{ compiled}'' rather than `` @code{ok}''.
7501: @end itemize
7502:
7503: @cindex text interpreter - input sources
7504: When the text interpreter is using an input device other than the
7505: keyboard, its behaviour changes in these ways:
7506:
7507: @itemize @bullet
7508: @item
7509: When the parse area is empty, the text interpreter attempts to refill
7510: the input buffer from the input source. When the input source is
7511: exhausted, the input source is set back to the previous input source.
7512: @item
7513: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7514: time the parse area is emptied.
7515: @item
7516: If an error occurs, the input source is set back to the user input
7517: device.
7518: @end itemize
7519:
7520: You can read about this in more detail in @ref{Input Sources}.
7521:
7522: doc->in
7523: doc-source
7524:
7525: doc-tib
7526: doc-#tib
7527:
7528:
7529: @menu
7530: * Input Sources::
7531: * Number Conversion::
7532: * Interpret/Compile states::
7533: * Interpreter Directives::
7534: @end menu
7535:
7536: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7537: @subsection Input Sources
7538: @cindex input sources
7539: @cindex text interpreter - input sources
7540:
7541: By default, the text interpreter processes input from the user input
7542: device (the keyboard) when Forth starts up. The text interpreter can
7543: process input from any of these sources:
7544:
7545: @itemize @bullet
7546: @item
7547: The user input device -- the keyboard.
7548: @item
7549: A file, using the words described in @ref{Forth source files}.
7550: @item
7551: A block, using the words described in @ref{Blocks}.
7552: @item
7553: A text string, using @code{evaluate}.
7554: @end itemize
7555:
7556: A program can identify the current input device from the values of
7557: @code{source-id} and @code{blk}.
7558:
7559:
7560: doc-source-id
7561: doc-blk
7562:
7563: doc-save-input
7564: doc-restore-input
7565:
7566: doc-evaluate
7567: doc-query
7568:
7569:
7570:
7571: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
7572: @subsection Number Conversion
7573: @cindex number conversion
7574: @cindex double-cell numbers, input format
7575: @cindex input format for double-cell numbers
7576: @cindex single-cell numbers, input format
7577: @cindex input format for single-cell numbers
7578: @cindex floating-point numbers, input format
7579: @cindex input format for floating-point numbers
7580:
7581: This section describes the rules that the text interpreter uses when it
7582: tries to convert a string into a number.
7583:
7584: Let <digit> represent any character that is a legal digit in the current
7585: number base@footnote{For example, 0-9 when the number base is decimal or
7586: 0-9, A-F when the number base is hexadecimal.}.
7587:
7588: Let <decimal digit> represent any character in the range 0-9.
7589:
7590: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7591: in the braces (@i{a} or @i{b} or neither).
7592:
7593: Let * represent any number of instances of the previous character
7594: (including none).
7595:
7596: Let any other character represent itself.
7597:
7598: @noindent
7599: Now, the conversion rules are:
7600:
7601: @itemize @bullet
7602: @item
7603: A string of the form <digit><digit>* is treated as a single-precision
7604: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
7605: @item
7606: A string of the form -<digit><digit>* is treated as a single-precision
7607: (cell-sized) negative integer, and is represented using 2's-complement
7608: arithmetic. Examples are -45 -5681 -0
7609: @item
7610: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
7611: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7612: (all three of these represent the same number).
7613: @item
7614: A string of the form -<digit><digit>*.<digit>* is treated as a
7615: double-precision (double-cell-sized) negative integer, and is
7616: represented using 2's-complement arithmetic. Examples are -3465. -3.465
7617: -34.65 (all three of these represent the same number).
7618: @item
7619: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7620: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
7621: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
7622: number) +12.E-4
7623: @end itemize
7624:
7625: By default, the number base used for integer number conversion is given
7626: by the contents of the variable @code{base}. Note that a lot of
7627: confusion can result from unexpected values of @code{base}. If you
7628: change @code{base} anywhere, make sure to save the old value and restore
7629: it afterwards. In general I recommend keeping @code{base} decimal, and
7630: using the prefixes described below for the popular non-decimal bases.
7631:
7632: doc-dpl
7633: doc-base
7634: doc-hex
7635: doc-decimal
7636:
7637: @cindex '-prefix for character strings
7638: @cindex &-prefix for decimal numbers
7639: @cindex #-prefix for decimal numbers
7640: @cindex %-prefix for binary numbers
7641: @cindex $-prefix for hexadecimal numbers
7642: @cindex 0x-prefix for hexadecimal numbers
7643: Gforth allows you to override the value of @code{base} by using a
7644: prefix@footnote{Some Forth implementations provide a similar scheme by
7645: implementing @code{$} etc. as parsing words that process the subsequent
7646: number in the input stream and push it onto the stack. For example, see
7647: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7648: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7649: is required between the prefix and the number.} before the first digit
7650: of an (integer) number. The following prefixes are supported:
7651:
7652: @itemize @bullet
7653: @item
7654: @code{&} -- decimal
7655: @item
7656: @code{#} -- decimal
7657: @item
7658: @code{%} -- binary
7659: @item
7660: @code{$} -- hexadecimal
7661: @item
7662: @code{0x} -- hexadecimal, if base<33.
7663: @item
7664: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7665: optional @code{'} may be present after the character.
7666: @end itemize
7667:
7668: Here are some examples, with the equivalent decimal number shown after
7669: in braces:
7670:
7671: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
7672: 'A (65),
7673: -'a' (-97),
7674: &905 (905), $abc (2478), $ABC (2478).
7675:
7676: @cindex number conversion - traps for the unwary
7677: @noindent
7678: Number conversion has a number of traps for the unwary:
7679:
7680: @itemize @bullet
7681: @item
7682: You cannot determine the current number base using the code sequence
7683: @code{base @@ .} -- the number base is always 10 in the current number
7684: base. Instead, use something like @code{base @@ dec.}
7685: @item
7686: If the number base is set to a value greater than 14 (for example,
7687: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7688: it to be intepreted as either a single-precision integer or a
7689: floating-point number (Gforth treats it as an integer). The ambiguity
7690: can be resolved by explicitly stating the sign of the mantissa and/or
7691: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7692: ambiguity arises; either representation will be treated as a
7693: floating-point number.
7694: @item
7695: There is a word @code{bin} but it does @i{not} set the number base!
7696: It is used to specify file types.
7697: @item
7698: ANS Forth requires the @code{.} of a double-precision number to be the
7699: final character in the string. Gforth allows the @code{.} to be
7700: anywhere after the first digit.
7701: @item
7702: The number conversion process does not check for overflow.
7703: @item
7704: In an ANS Forth program @code{base} is required to be decimal when
7705: converting floating-point numbers. In Gforth, number conversion to
7706: floating-point numbers always uses base &10, irrespective of the value
7707: of @code{base}.
7708: @end itemize
7709:
7710: You can read numbers into your programs with the words described in
7711: @ref{Input}.
7712:
7713: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
7714: @subsection Interpret/Compile states
7715: @cindex Interpret/Compile states
7716:
7717: A standard program is not permitted to change @code{state}
7718: explicitly. However, it can change @code{state} implicitly, using the
7719: words @code{[} and @code{]}. When @code{[} is executed it switches
7720: @code{state} to interpret state, and therefore the text interpreter
7721: starts interpreting. When @code{]} is executed it switches @code{state}
7722: to compile state and therefore the text interpreter starts
7723: compiling. The most common usage for these words is for switching into
7724: interpret state and back from within a colon definition; this technique
7725: can be used to compile a literal (for an example, @pxref{Literals}) or
7726: for conditional compilation (for an example, @pxref{Interpreter
7727: Directives}).
7728:
7729:
7730: @c This is a bad example: It's non-standard, and it's not necessary.
7731: @c However, I can't think of a good example for switching into compile
7732: @c state when there is no current word (@code{state}-smart words are not a
7733: @c good reason). So maybe we should use an example for switching into
7734: @c interpret @code{state} in a colon def. - anton
7735: @c nac-> I agree. I started out by putting in the example, then realised
7736: @c that it was non-ANS, so wrote more words around it. I hope this
7737: @c re-written version is acceptable to you. I do want to keep the example
7738: @c as it is helpful for showing what is and what is not portable, particularly
7739: @c where it outlaws a style in common use.
7740:
7741: @c anton: it's more important to show what's portable. After we have done
7742: @c that, we can also show what's not. In any case, I have written a
7743: @c section Compiling Words which also deals with [ ].
7744:
7745: @c !! The following example does not work in Gforth 0.5.9 or later.
7746:
7747: @c @code{[} and @code{]} also give you the ability to switch into compile
7748: @c state and back, but we cannot think of any useful Standard application
7749: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7750:
7751: @c @example
7752: @c : AA ." this is A" ;
7753: @c : BB ." this is B" ;
7754: @c : CC ." this is C" ;
7755:
7756: @c create table ] aa bb cc [
7757:
7758: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7759: @c cells table + @@ execute ;
7760: @c @end example
7761:
7762: @c This example builds a jump table; @code{0 go} will display ``@code{this
7763: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7764: @c defining @code{table} like this:
7765:
7766: @c @example
7767: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7768: @c @end example
7769:
7770: @c The problem with this code is that the definition of @code{table} is not
7771: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7772: @c @i{may} work on systems where code space and data space co-incide, the
7773: @c Standard only allows data space to be assigned for a @code{CREATE}d
7774: @c word. In addition, the Standard only allows @code{@@} to access data
7775: @c space, whilst this example is using it to access code space. The only
7776: @c portable, Standard way to build this table is to build it in data space,
7777: @c like this:
7778:
7779: @c @example
7780: @c create table ' aa , ' bb , ' cc ,
7781: @c @end example
7782:
7783: @c doc-state
7784:
7785:
7786: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
7787: @subsection Interpreter Directives
7788: @cindex interpreter directives
7789: @cindex conditional compilation
7790:
7791: These words are usually used in interpret state; typically to control
7792: which parts of a source file are processed by the text
7793: interpreter. There are only a few ANS Forth Standard words, but Gforth
7794: supplements these with a rich set of immediate control structure words
7795: to compensate for the fact that the non-immediate versions can only be
7796: used in compile state (@pxref{Control Structures}). Typical usages:
7797:
7798: @example
7799: FALSE Constant HAVE-ASSEMBLER
7800: .
7801: .
7802: HAVE-ASSEMBLER [IF]
7803: : ASSEMBLER-FEATURE
7804: ...
7805: ;
7806: [ENDIF]
7807: .
7808: .
7809: : SEE
7810: ... \ general-purpose SEE code
7811: [ HAVE-ASSEMBLER [IF] ]
7812: ... \ assembler-specific SEE code
7813: [ [ENDIF] ]
7814: ;
7815: @end example
7816:
7817:
7818: doc-[IF]
7819: doc-[ELSE]
7820: doc-[THEN]
7821: doc-[ENDIF]
7822:
7823: doc-[IFDEF]
7824: doc-[IFUNDEF]
7825:
7826: doc-[?DO]
7827: doc-[DO]
7828: doc-[FOR]
7829: doc-[LOOP]
7830: doc-[+LOOP]
7831: doc-[NEXT]
7832:
7833: doc-[BEGIN]
7834: doc-[UNTIL]
7835: doc-[AGAIN]
7836: doc-[WHILE]
7837: doc-[REPEAT]
7838:
7839:
7840: @c -------------------------------------------------------------
7841: @node The Input Stream, Word Lists, The Text Interpreter, Words
7842: @section The Input Stream
7843: @cindex input stream
7844:
7845: @c !! integrate this better with the "Text Interpreter" section
7846: The text interpreter reads from the input stream, which can come from
7847: several sources (@pxref{Input Sources}). Some words, in particular
7848: defining words, but also words like @code{'}, read parameters from the
7849: input stream instead of from the stack.
7850:
7851: Such words are called parsing words, because they parse the input
7852: stream. Parsing words are hard to use in other words, because it is
7853: hard to pass program-generated parameters through the input stream.
7854: They also usually have an unintuitive combination of interpretation and
7855: compilation semantics when implemented naively, leading to various
7856: approaches that try to produce a more intuitive behaviour
7857: (@pxref{Combined words}).
7858:
7859: It should be obvious by now that parsing words are a bad idea. If you
7860: want to implement a parsing word for convenience, also provide a factor
7861: of the word that does not parse, but takes the parameters on the stack.
7862: To implement the parsing word on top if it, you can use the following
7863: words:
7864:
7865: @c anton: these belong in the input stream section
7866: doc-parse
7867: doc-parse-name
7868: doc-parse-word
7869: doc-name
7870: doc-word
7871: doc-\"-parse
7872: doc-refill
7873:
7874: Conversely, if you have the bad luck (or lack of foresight) to have to
7875: deal with parsing words without having such factors, how do you pass a
7876: string that is not in the input stream to it?
7877:
7878: doc-execute-parsing
7879:
7880: A definition of this word in ANS Forth is provided in
7881: @file{compat/execute-parsing.fs}.
7882:
7883: If you want to run a parsing word on a file, the following word should
7884: help:
7885:
7886: doc-execute-parsing-file
7887:
7888: @c -------------------------------------------------------------
7889: @node Word Lists, Environmental Queries, The Input Stream, Words
7890: @section Word Lists
7891: @cindex word lists
7892: @cindex header space
7893:
7894: A wordlist is a list of named words; you can add new words and look up
7895: words by name (and you can remove words in a restricted way with
7896: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7897:
7898: @cindex search order stack
7899: The text interpreter searches the wordlists present in the search order
7900: (a stack of wordlists), from the top to the bottom. Within each
7901: wordlist, the search starts conceptually at the newest word; i.e., if
7902: two words in a wordlist have the same name, the newer word is found.
7903:
7904: @cindex compilation word list
7905: New words are added to the @dfn{compilation wordlist} (aka current
7906: wordlist).
7907:
7908: @cindex wid
7909: A word list is identified by a cell-sized word list identifier (@i{wid})
7910: in much the same way as a file is identified by a file handle. The
7911: numerical value of the wid has no (portable) meaning, and might change
7912: from session to session.
7913:
7914: The ANS Forth ``Search order'' word set is intended to provide a set of
7915: low-level tools that allow various different schemes to be
7916: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
7917: word. @file{compat/vocabulary.fs} provides an implementation in ANS
7918: Forth.
7919:
7920: @comment TODO: locals section refers to here, saying that every word list (aka
7921: @comment vocabulary) has its own methods for searching etc. Need to document that.
7922: @c anton: but better in a separate subsection on wordlist internals
7923:
7924: @comment TODO: document markers, reveal, tables, mappedwordlist
7925:
7926: @comment the gforthman- prefix is used to pick out the true definition of a
7927: @comment word from the source files, rather than some alias.
7928:
7929: doc-forth-wordlist
7930: doc-definitions
7931: doc-get-current
7932: doc-set-current
7933: doc-get-order
7934: doc---gforthman-set-order
7935: doc-wordlist
7936: doc-table
7937: doc->order
7938: doc-previous
7939: doc-also
7940: doc---gforthman-forth
7941: doc-only
7942: doc---gforthman-order
7943:
7944: doc-find
7945: doc-search-wordlist
7946:
7947: doc-words
7948: doc-vlist
7949: @c doc-words-deferred
7950:
7951: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
7952: doc-root
7953: doc-vocabulary
7954: doc-seal
7955: doc-vocs
7956: doc-current
7957: doc-context
7958:
7959:
7960: @menu
7961: * Vocabularies::
7962: * Why use word lists?::
7963: * Word list example::
7964: @end menu
7965:
7966: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
7967: @subsection Vocabularies
7968: @cindex Vocabularies, detailed explanation
7969:
7970: Here is an example of creating and using a new wordlist using ANS
7971: Forth words:
7972:
7973: @example
7974: wordlist constant my-new-words-wordlist
7975: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
7976:
7977: \ add it to the search order
7978: also my-new-words
7979:
7980: \ alternatively, add it to the search order and make it
7981: \ the compilation word list
7982: also my-new-words definitions
7983: \ type "order" to see the problem
7984: @end example
7985:
7986: The problem with this example is that @code{order} has no way to
7987: associate the name @code{my-new-words} with the wid of the word list (in
7988: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7989: that has no associated name). There is no Standard way of associating a
7990: name with a wid.
7991:
7992: In Gforth, this example can be re-coded using @code{vocabulary}, which
7993: associates a name with a wid:
7994:
7995: @example
7996: vocabulary my-new-words
7997:
7998: \ add it to the search order
7999: also my-new-words
8000:
8001: \ alternatively, add it to the search order and make it
8002: \ the compilation word list
8003: my-new-words definitions
8004: \ type "order" to see that the problem is solved
8005: @end example
8006:
8007:
8008: @node Why use word lists?, Word list example, Vocabularies, Word Lists
8009: @subsection Why use word lists?
8010: @cindex word lists - why use them?
8011:
8012: Here are some reasons why people use wordlists:
8013:
8014: @itemize @bullet
8015:
8016: @c anton: Gforth's hashing implementation makes the search speed
8017: @c independent from the number of words. But it is linear with the number
8018: @c of wordlists that have to be searched, so in effect using more wordlists
8019: @c actually slows down compilation.
8020:
8021: @c @item
8022: @c To improve compilation speed by reducing the number of header space
8023: @c entries that must be searched. This is achieved by creating a new
8024: @c word list that contains all of the definitions that are used in the
8025: @c definition of a Forth system but which would not usually be used by
8026: @c programs running on that system. That word list would be on the search
8027: @c list when the Forth system was compiled but would be removed from the
8028: @c search list for normal operation. This can be a useful technique for
8029: @c low-performance systems (for example, 8-bit processors in embedded
8030: @c systems) but is unlikely to be necessary in high-performance desktop
8031: @c systems.
8032:
8033: @item
8034: To prevent a set of words from being used outside the context in which
8035: they are valid. Two classic examples of this are an integrated editor
8036: (all of the edit commands are defined in a separate word list; the
8037: search order is set to the editor word list when the editor is invoked;
8038: the old search order is restored when the editor is terminated) and an
8039: integrated assembler (the op-codes for the machine are defined in a
8040: separate word list which is used when a @code{CODE} word is defined).
8041:
8042: @item
8043: To organize the words of an application or library into a user-visible
8044: set (in @code{forth-wordlist} or some other common wordlist) and a set
8045: of helper words used just for the implementation (hidden in a separate
8046: wordlist). This keeps @code{words}' output smaller, separates
8047: implementation and interface, and reduces the chance of name conflicts
8048: within the common wordlist.
8049:
8050: @item
8051: To prevent a name-space clash between multiple definitions with the same
8052: name. For example, when building a cross-compiler you might have a word
8053: @code{IF} that generates conditional code for your target system. By
8054: placing this definition in a different word list you can control whether
8055: the host system's @code{IF} or the target system's @code{IF} get used in
8056: any particular context by controlling the order of the word lists on the
8057: search order stack.
8058:
8059: @end itemize
8060:
8061: The downsides of using wordlists are:
8062:
8063: @itemize
8064:
8065: @item
8066: Debugging becomes more cumbersome.
8067:
8068: @item
8069: Name conflicts worked around with wordlists are still there, and you
8070: have to arrange the search order carefully to get the desired results;
8071: if you forget to do that, you get hard-to-find errors (as in any case
8072: where you read the code differently from the compiler; @code{see} can
8073: help seeing which of several possible words the name resolves to in such
8074: cases). @code{See} displays just the name of the words, not what
8075: wordlist they belong to, so it might be misleading. Using unique names
8076: is a better approach to avoid name conflicts.
8077:
8078: @item
8079: You have to explicitly undo any changes to the search order. In many
8080: cases it would be more convenient if this happened implicitly. Gforth
8081: currently does not provide such a feature, but it may do so in the
8082: future.
8083: @end itemize
8084:
8085:
8086: @node Word list example, , Why use word lists?, Word Lists
8087: @subsection Word list example
8088: @cindex word lists - example
8089:
8090: The following example is from the
8091: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8092: garbage collector} and uses wordlists to separate public words from
8093: helper words:
8094:
8095: @example
8096: get-current ( wid )
8097: vocabulary garbage-collector also garbage-collector definitions
8098: ... \ define helper words
8099: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8100: ... \ define the public (i.e., API) words
8101: \ they can refer to the helper words
8102: previous \ restore original search order (helper words become invisible)
8103: @end example
8104:
8105: @c -------------------------------------------------------------
8106: @node Environmental Queries, Files, Word Lists, Words
8107: @section Environmental Queries
8108: @cindex environmental queries
8109:
8110: ANS Forth introduced the idea of ``environmental queries'' as a way
8111: for a program running on a system to determine certain characteristics of the system.
8112: The Standard specifies a number of strings that might be recognised by a system.
8113:
8114: The Standard requires that the header space used for environmental queries
8115: be distinct from the header space used for definitions.
8116:
8117: Typically, environmental queries are supported by creating a set of
8118: definitions in a word list that is @i{only} used during environmental
8119: queries; that is what Gforth does. There is no Standard way of adding
8120: definitions to the set of recognised environmental queries, but any
8121: implementation that supports the loading of optional word sets must have
8122: some mechanism for doing this (after loading the word set, the
8123: associated environmental query string must return @code{true}). In
8124: Gforth, the word list used to honour environmental queries can be
8125: manipulated just like any other word list.
8126:
8127:
8128: doc-environment?
8129: doc-environment-wordlist
8130:
8131: doc-gforth
8132: doc-os-class
8133:
8134:
8135: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8136: returning two items on the stack, querying it using @code{environment?}
8137: will return an additional item; the @code{true} flag that shows that the
8138: string was recognised.
8139:
8140: @comment TODO Document the standard strings or note where they are documented herein
8141:
8142: Here are some examples of using environmental queries:
8143:
8144: @example
8145: s" address-unit-bits" environment? 0=
8146: [IF]
8147: cr .( environmental attribute address-units-bits unknown... ) cr
8148: [ELSE]
8149: drop \ ensure balanced stack effect
8150: [THEN]
8151:
8152: \ this might occur in the prelude of a standard program that uses THROW
8153: s" exception" environment? [IF]
8154: 0= [IF]
8155: : throw abort" exception thrown" ;
8156: [THEN]
8157: [ELSE] \ we don't know, so make sure
8158: : throw abort" exception thrown" ;
8159: [THEN]
8160:
8161: s" gforth" environment? [IF] .( Gforth version ) TYPE
8162: [ELSE] .( Not Gforth..) [THEN]
8163:
8164: \ a program using v*
8165: s" gforth" environment? [IF]
8166: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8167: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8168: >r swap 2swap swap 0e r> 0 ?DO
8169: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8170: LOOP
8171: 2drop 2drop ;
8172: [THEN]
8173: [ELSE] \
8174: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8175: ...
8176: [THEN]
8177: @end example
8178:
8179: Here is an example of adding a definition to the environment word list:
8180:
8181: @example
8182: get-current environment-wordlist set-current
8183: true constant block
8184: true constant block-ext
8185: set-current
8186: @end example
8187:
8188: You can see what definitions are in the environment word list like this:
8189:
8190: @example
8191: environment-wordlist >order words previous
8192: @end example
8193:
8194:
8195: @c -------------------------------------------------------------
8196: @node Files, Blocks, Environmental Queries, Words
8197: @section Files
8198: @cindex files
8199: @cindex I/O - file-handling
8200:
8201: Gforth provides facilities for accessing files that are stored in the
8202: host operating system's file-system. Files that are processed by Gforth
8203: can be divided into two categories:
8204:
8205: @itemize @bullet
8206: @item
8207: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
8208: @item
8209: Files that are processed by some other program (@dfn{general files}).
8210: @end itemize
8211:
8212: @menu
8213: * Forth source files::
8214: * General files::
8215: * Search Paths::
8216: @end menu
8217:
8218: @c -------------------------------------------------------------
8219: @node Forth source files, General files, Files, Files
8220: @subsection Forth source files
8221: @cindex including files
8222: @cindex Forth source files
8223:
8224: The simplest way to interpret the contents of a file is to use one of
8225: these two formats:
8226:
8227: @example
8228: include mysource.fs
8229: s" mysource.fs" included
8230: @end example
8231:
8232: You usually want to include a file only if it is not included already
8233: (by, say, another source file). In that case, you can use one of these
8234: three formats:
8235:
8236: @example
8237: require mysource.fs
8238: needs mysource.fs
8239: s" mysource.fs" required
8240: @end example
8241:
8242: @cindex stack effect of included files
8243: @cindex including files, stack effect
8244: It is good practice to write your source files such that interpreting them
8245: does not change the stack. Source files designed in this way can be used with
8246: @code{required} and friends without complications. For example:
8247:
8248: @example
8249: 1024 require foo.fs drop
8250: @end example
8251:
8252: Here you want to pass the argument 1024 (e.g., a buffer size) to
8253: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8254: ), which allows its use with @code{require}. Of course with such
8255: parameters to required files, you have to ensure that the first
8256: @code{require} fits for all uses (i.e., @code{require} it early in the
8257: master load file).
8258:
8259: doc-include-file
8260: doc-included
8261: doc-included?
8262: doc-include
8263: doc-required
8264: doc-require
8265: doc-needs
8266: @c doc-init-included-files @c internal
8267: doc-sourcefilename
8268: doc-sourceline#
8269:
8270: A definition in ANS Forth for @code{required} is provided in
8271: @file{compat/required.fs}.
8272:
8273: @c -------------------------------------------------------------
8274: @node General files, Search Paths, Forth source files, Files
8275: @subsection General files
8276: @cindex general files
8277: @cindex file-handling
8278:
8279: Files are opened/created by name and type. The following file access
8280: methods (FAMs) are recognised:
8281:
8282: @cindex fam (file access method)
8283: doc-r/o
8284: doc-r/w
8285: doc-w/o
8286: doc-bin
8287:
8288:
8289: When a file is opened/created, it returns a file identifier,
8290: @i{wfileid} that is used for all other file commands. All file
8291: commands also return a status value, @i{wior}, that is 0 for a
8292: successful operation and an implementation-defined non-zero value in the
8293: case of an error.
8294:
8295:
8296: doc-open-file
8297: doc-create-file
8298:
8299: doc-close-file
8300: doc-delete-file
8301: doc-rename-file
8302: doc-read-file
8303: doc-read-line
8304: doc-key-file
8305: doc-key?-file
8306: doc-write-file
8307: doc-write-line
8308: doc-emit-file
8309: doc-flush-file
8310:
8311: doc-file-status
8312: doc-file-position
8313: doc-reposition-file
8314: doc-file-size
8315: doc-resize-file
8316:
8317: doc-slurp-file
8318: doc-slurp-fid
8319: doc-stdin
8320: doc-stdout
8321: doc-stderr
8322:
8323: @c ---------------------------------------------------------
8324: @node Search Paths, , General files, Files
8325: @subsection Search Paths
8326: @cindex path for @code{included}
8327: @cindex file search path
8328: @cindex @code{include} search path
8329: @cindex search path for files
8330:
8331: If you specify an absolute filename (i.e., a filename starting with
8332: @file{/} or @file{~}, or with @file{:} in the second position (as in
8333: @samp{C:...})) for @code{included} and friends, that file is included
8334: just as you would expect.
8335:
8336: If the filename starts with @file{./}, this refers to the directory that
8337: the present file was @code{included} from. This allows files to include
8338: other files relative to their own position (irrespective of the current
8339: working directory or the absolute position). This feature is essential
8340: for libraries consisting of several files, where a file may include
8341: other files from the library. It corresponds to @code{#include "..."}
8342: in C. If the current input source is not a file, @file{.} refers to the
8343: directory of the innermost file being included, or, if there is no file
8344: being included, to the current working directory.
8345:
8346: For relative filenames (not starting with @file{./}), Gforth uses a
8347: search path similar to Forth's search order (@pxref{Word Lists}). It
8348: tries to find the given filename in the directories present in the path,
8349: and includes the first one it finds. There are separate search paths for
8350: Forth source files and general files. If the search path contains the
8351: directory @file{.}, this refers to the directory of the current file, or
8352: the working directory, as if the file had been specified with @file{./}.
8353:
8354: Use @file{~+} to refer to the current working directory (as in the
8355: @code{bash}).
8356:
8357: @c anton: fold the following subsubsections into this subsection?
8358:
8359: @menu
8360: * Source Search Paths::
8361: * General Search Paths::
8362: @end menu
8363:
8364: @c ---------------------------------------------------------
8365: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8366: @subsubsection Source Search Paths
8367: @cindex search path control, source files
8368:
8369: The search path is initialized when you start Gforth (@pxref{Invoking
8370: Gforth}). You can display it and change it using @code{fpath} in
8371: combination with the general path handling words.
8372:
8373: doc-fpath
8374: @c the functionality of the following words is easily available through
8375: @c fpath and the general path words. The may go away.
8376: @c doc-.fpath
8377: @c doc-fpath+
8378: @c doc-fpath=
8379: @c doc-open-fpath-file
8380:
8381: @noindent
8382: Here is an example of using @code{fpath} and @code{require}:
8383:
8384: @example
8385: fpath path= /usr/lib/forth/|./
8386: require timer.fs
8387: @end example
8388:
8389:
8390: @c ---------------------------------------------------------
8391: @node General Search Paths, , Source Search Paths, Search Paths
8392: @subsubsection General Search Paths
8393: @cindex search path control, source files
8394:
8395: Your application may need to search files in several directories, like
8396: @code{included} does. To facilitate this, Gforth allows you to define
8397: and use your own search paths, by providing generic equivalents of the
8398: Forth search path words:
8399:
8400: doc-open-path-file
8401: doc-path-allot
8402: doc-clear-path
8403: doc-also-path
8404: doc-.path
8405: doc-path+
8406: doc-path=
8407:
8408: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
8409:
8410: Here's an example of creating an empty search path:
8411: @c
8412: @example
8413: create mypath 500 path-allot \ maximum length 500 chars (is checked)
8414: @end example
8415:
8416: @c -------------------------------------------------------------
8417: @node Blocks, Other I/O, Files, Words
8418: @section Blocks
8419: @cindex I/O - blocks
8420: @cindex blocks
8421:
8422: When you run Gforth on a modern desk-top computer, it runs under the
8423: control of an operating system which provides certain services. One of
8424: these services is @var{file services}, which allows Forth source code
8425: and data to be stored in files and read into Gforth (@pxref{Files}).
8426:
8427: Traditionally, Forth has been an important programming language on
8428: systems where it has interfaced directly to the underlying hardware with
8429: no intervening operating system. Forth provides a mechanism, called
8430: @dfn{blocks}, for accessing mass storage on such systems.
8431:
8432: A block is a 1024-byte data area, which can be used to hold data or
8433: Forth source code. No structure is imposed on the contents of the
8434: block. A block is identified by its number; blocks are numbered
8435: contiguously from 1 to an implementation-defined maximum.
8436:
8437: A typical system that used blocks but no operating system might use a
8438: single floppy-disk drive for mass storage, with the disks formatted to
8439: provide 256-byte sectors. Blocks would be implemented by assigning the
8440: first four sectors of the disk to block 1, the second four sectors to
8441: block 2 and so on, up to the limit of the capacity of the disk. The disk
8442: would not contain any file system information, just the set of blocks.
8443:
8444: @cindex blocks file
8445: On systems that do provide file services, blocks are typically
8446: implemented by storing a sequence of blocks within a single @dfn{blocks
8447: file}. The size of the blocks file will be an exact multiple of 1024
8448: bytes, corresponding to the number of blocks it contains. This is the
8449: mechanism that Gforth uses.
8450:
8451: @cindex @file{blocks.fb}
8452: Only one blocks file can be open at a time. If you use block words without
8453: having specified a blocks file, Gforth defaults to the blocks file
8454: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
8455: locate a blocks file (@pxref{Source Search Paths}).
8456:
8457: @cindex block buffers
8458: When you read and write blocks under program control, Gforth uses a
8459: number of @dfn{block buffers} as intermediate storage. These buffers are
8460: not used when you use @code{load} to interpret the contents of a block.
8461:
8462: The behaviour of the block buffers is analagous to that of a cache.
8463: Each block buffer has three states:
8464:
8465: @itemize @bullet
8466: @item
8467: Unassigned
8468: @item
8469: Assigned-clean
8470: @item
8471: Assigned-dirty
8472: @end itemize
8473:
8474: Initially, all block buffers are @i{unassigned}. In order to access a
8475: block, the block (specified by its block number) must be assigned to a
8476: block buffer.
8477:
8478: The assignment of a block to a block buffer is performed by @code{block}
8479: or @code{buffer}. Use @code{block} when you wish to modify the existing
8480: contents of a block. Use @code{buffer} when you don't care about the
8481: existing contents of the block@footnote{The ANS Forth definition of
8482: @code{buffer} is intended not to cause disk I/O; if the data associated
8483: with the particular block is already stored in a block buffer due to an
8484: earlier @code{block} command, @code{buffer} will return that block
8485: buffer and the existing contents of the block will be
8486: available. Otherwise, @code{buffer} will simply assign a new, empty
8487: block buffer for the block.}.
8488:
8489: Once a block has been assigned to a block buffer using @code{block} or
8490: @code{buffer}, that block buffer becomes the @i{current block
8491: buffer}. Data may only be manipulated (read or written) within the
8492: current block buffer.
8493:
8494: When the contents of the current block buffer has been modified it is
8495: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
8496: either abandon the changes (by doing nothing) or mark the block as
8497: changed (assigned-dirty), using @code{update}. Using @code{update} does
8498: not change the blocks file; it simply changes a block buffer's state to
8499: @i{assigned-dirty}. The block will be written implicitly when it's
8500: buffer is needed for another block, or explicitly by @code{flush} or
8501: @code{save-buffers}.
8502:
8503: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8504: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8505: @code{flush}.
8506:
8507: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
8508: algorithm to assign a block buffer to a block. That means that any
8509: particular block can only be assigned to one specific block buffer,
8510: called (for the particular operation) the @i{victim buffer}. If the
8511: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8512: the new block immediately. If it is @i{assigned-dirty} its current
8513: contents are written back to the blocks file on disk before it is
8514: allocated to the new block.
8515:
8516: Although no structure is imposed on the contents of a block, it is
8517: traditional to display the contents as 16 lines each of 64 characters. A
8518: block provides a single, continuous stream of input (for example, it
8519: acts as a single parse area) -- there are no end-of-line characters
8520: within a block, and no end-of-file character at the end of a
8521: block. There are two consequences of this:
8522:
8523: @itemize @bullet
8524: @item
8525: The last character of one line wraps straight into the first character
8526: of the following line
8527: @item
8528: The word @code{\} -- comment to end of line -- requires special
8529: treatment; in the context of a block it causes all characters until the
8530: end of the current 64-character ``line'' to be ignored.
8531: @end itemize
8532:
8533: In Gforth, when you use @code{block} with a non-existent block number,
8534: the current blocks file will be extended to the appropriate size and the
8535: block buffer will be initialised with spaces.
8536:
8537: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8538: for details) but doesn't encourage the use of blocks; the mechanism is
8539: only provided for backward compatibility -- ANS Forth requires blocks to
8540: be available when files are.
8541:
8542: Common techniques that are used when working with blocks include:
8543:
8544: @itemize @bullet
8545: @item
8546: A screen editor that allows you to edit blocks without leaving the Forth
8547: environment.
8548: @item
8549: Shadow screens; where every code block has an associated block
8550: containing comments (for example: code in odd block numbers, comments in
8551: even block numbers). Typically, the block editor provides a convenient
8552: mechanism to toggle between code and comments.
8553: @item
8554: Load blocks; a single block (typically block 1) contains a number of
8555: @code{thru} commands which @code{load} the whole of the application.
8556: @end itemize
8557:
8558: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8559: integrated into a Forth programming environment.
8560:
8561: @comment TODO what about errors on open-blocks?
8562:
8563: doc-open-blocks
8564: doc-use
8565: doc-block-offset
8566: doc-get-block-fid
8567: doc-block-position
8568:
8569: doc-list
8570: doc-scr
8571:
8572: doc---gforthman-block
8573: doc-buffer
8574:
8575: doc-empty-buffers
8576: doc-empty-buffer
8577: doc-update
8578: doc-updated?
8579: doc-save-buffers
8580: doc-save-buffer
8581: doc-flush
8582:
8583: doc-load
8584: doc-thru
8585: doc-+load
8586: doc-+thru
8587: doc---gforthman--->
8588: doc-block-included
8589:
8590:
8591: @c -------------------------------------------------------------
8592: @node Other I/O, OS command line arguments, Blocks, Words
8593: @section Other I/O
8594: @cindex I/O - keyboard and display
8595:
8596: @menu
8597: * Simple numeric output:: Predefined formats
8598: * Formatted numeric output:: Formatted (pictured) output
8599: * String Formats:: How Forth stores strings in memory
8600: * Displaying characters and strings:: Other stuff
8601: * Input:: Input
8602: * Pipes:: How to create your own pipes
8603: * Xchars and Unicode:: Non-ASCII characters
8604: @end menu
8605:
8606: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8607: @subsection Simple numeric output
8608: @cindex numeric output - simple/free-format
8609:
8610: The simplest output functions are those that display numbers from the
8611: data or floating-point stacks. Floating-point output is always displayed
8612: using base 10. Numbers displayed from the data stack use the value stored
8613: in @code{base}.
8614:
8615:
8616: doc-.
8617: doc-dec.
8618: doc-hex.
8619: doc-u.
8620: doc-.r
8621: doc-u.r
8622: doc-d.
8623: doc-ud.
8624: doc-d.r
8625: doc-ud.r
8626: doc-f.
8627: doc-fe.
8628: doc-fs.
8629: doc-f.rdp
8630:
8631: Examples of printing the number 1234.5678E23 in the different floating-point output
8632: formats are shown below:
8633:
8634: @example
8635: f. 123456779999999000000000000.
8636: fe. 123.456779999999E24
8637: fs. 1.23456779999999E26
8638: @end example
8639:
8640:
8641: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8642: @subsection Formatted numeric output
8643: @cindex formatted numeric output
8644: @cindex pictured numeric output
8645: @cindex numeric output - formatted
8646:
8647: Forth traditionally uses a technique called @dfn{pictured numeric
8648: output} for formatted printing of integers. In this technique, digits
8649: are extracted from the number (using the current output radix defined by
8650: @code{base}), converted to ASCII codes and appended to a string that is
8651: built in a scratch-pad area of memory (@pxref{core-idef,
8652: Implementation-defined options, Implementation-defined
8653: options}). Arbitrary characters can be appended to the string during the
8654: extraction process. The completed string is specified by an address
8655: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8656: under program control.
8657:
8658: All of the integer output words described in the previous section
8659: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8660: numeric output.
8661:
8662: Three important things to remember about pictured numeric output:
8663:
8664: @itemize @bullet
8665: @item
8666: It always operates on double-precision numbers; to display a
8667: single-precision number, convert it first (for ways of doing this
8668: @pxref{Double precision}).
8669: @item
8670: It always treats the double-precision number as though it were
8671: unsigned. The examples below show ways of printing signed numbers.
8672: @item
8673: The string is built up from right to left; least significant digit first.
8674: @end itemize
8675:
8676:
8677: doc-<#
8678: doc-<<#
8679: doc-#
8680: doc-#s
8681: doc-hold
8682: doc-sign
8683: doc-#>
8684: doc-#>>
8685:
8686: doc-represent
8687: doc-f>str-rdp
8688: doc-f>buf-rdp
8689:
8690:
8691: @noindent
8692: Here are some examples of using pictured numeric output:
8693:
8694: @example
8695: : my-u. ( u -- )
8696: \ Simplest use of pns.. behaves like Standard u.
8697: 0 \ convert to unsigned double
8698: <<# \ start conversion
8699: #s \ convert all digits
8700: #> \ complete conversion
8701: TYPE SPACE \ display, with trailing space
8702: #>> ; \ release hold area
8703:
8704: : cents-only ( u -- )
8705: 0 \ convert to unsigned double
8706: <<# \ start conversion
8707: # # \ convert two least-significant digits
8708: #> \ complete conversion, discard other digits
8709: TYPE SPACE \ display, with trailing space
8710: #>> ; \ release hold area
8711:
8712: : dollars-and-cents ( u -- )
8713: 0 \ convert to unsigned double
8714: <<# \ start conversion
8715: # # \ convert two least-significant digits
8716: [char] . hold \ insert decimal point
8717: #s \ convert remaining digits
8718: [char] $ hold \ append currency symbol
8719: #> \ complete conversion
8720: TYPE SPACE \ display, with trailing space
8721: #>> ; \ release hold area
8722:
8723: : my-. ( n -- )
8724: \ handling negatives.. behaves like Standard .
8725: s>d \ convert to signed double
8726: swap over dabs \ leave sign byte followed by unsigned double
8727: <<# \ start conversion
8728: #s \ convert all digits
8729: rot sign \ get at sign byte, append "-" if needed
8730: #> \ complete conversion
8731: TYPE SPACE \ display, with trailing space
8732: #>> ; \ release hold area
8733:
8734: : account. ( n -- )
8735: \ accountants don't like minus signs, they use parentheses
8736: \ for negative numbers
8737: s>d \ convert to signed double
8738: swap over dabs \ leave sign byte followed by unsigned double
8739: <<# \ start conversion
8740: 2 pick \ get copy of sign byte
8741: 0< IF [char] ) hold THEN \ right-most character of output
8742: #s \ convert all digits
8743: rot \ get at sign byte
8744: 0< IF [char] ( hold THEN
8745: #> \ complete conversion
8746: TYPE SPACE \ display, with trailing space
8747: #>> ; \ release hold area
8748:
8749: @end example
8750:
8751: Here are some examples of using these words:
8752:
8753: @example
8754: 1 my-u. 1
8755: hex -1 my-u. decimal FFFFFFFF
8756: 1 cents-only 01
8757: 1234 cents-only 34
8758: 2 dollars-and-cents $0.02
8759: 1234 dollars-and-cents $12.34
8760: 123 my-. 123
8761: -123 my. -123
8762: 123 account. 123
8763: -456 account. (456)
8764: @end example
8765:
8766:
8767: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8768: @subsection String Formats
8769: @cindex strings - see character strings
8770: @cindex character strings - formats
8771: @cindex I/O - see character strings
8772: @cindex counted strings
8773:
8774: @c anton: this does not really belong here; maybe the memory section,
8775: @c or the principles chapter
8776:
8777: Forth commonly uses two different methods for representing character
8778: strings:
8779:
8780: @itemize @bullet
8781: @item
8782: @cindex address of counted string
8783: @cindex counted string
8784: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8785: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8786: string and the string occupies the subsequent @i{n} char addresses in
8787: memory.
8788: @item
8789: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8790: of the string in characters, and @i{c-addr} is the address of the
8791: first byte of the string.
8792: @end itemize
8793:
8794: ANS Forth encourages the use of the second format when representing
8795: strings.
8796:
8797:
8798: doc-count
8799:
8800:
8801: For words that move, copy and search for strings see @ref{Memory
8802: Blocks}. For words that display characters and strings see
8803: @ref{Displaying characters and strings}.
8804:
8805: @node Displaying characters and strings, Input, String Formats, Other I/O
8806: @subsection Displaying characters and strings
8807: @cindex characters - compiling and displaying
8808: @cindex character strings - compiling and displaying
8809:
8810: This section starts with a glossary of Forth words and ends with a set
8811: of examples.
8812:
8813:
8814: doc-bl
8815: doc-space
8816: doc-spaces
8817: doc-emit
8818: doc-toupper
8819: doc-."
8820: doc-.(
8821: doc-.\"
8822: doc-type
8823: doc-typewhite
8824: doc-cr
8825: @cindex cursor control
8826: doc-at-xy
8827: doc-page
8828: doc-s"
8829: doc-s\"
8830: doc-c"
8831: doc-char
8832: doc-[char]
8833:
8834:
8835: @noindent
8836: As an example, consider the following text, stored in a file @file{test.fs}:
8837:
8838: @example
8839: .( text-1)
8840: : my-word
8841: ." text-2" cr
8842: .( text-3)
8843: ;
8844:
8845: ." text-4"
8846:
8847: : my-char
8848: [char] ALPHABET emit
8849: char emit
8850: ;
8851: @end example
8852:
8853: When you load this code into Gforth, the following output is generated:
8854:
8855: @example
8856: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
8857: @end example
8858:
8859: @itemize @bullet
8860: @item
8861: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8862: is an immediate word; it behaves in the same way whether it is used inside
8863: or outside a colon definition.
8864: @item
8865: Message @code{text-4} is displayed because of Gforth's added interpretation
8866: semantics for @code{."}.
8867: @item
8868: Message @code{text-2} is @i{not} displayed, because the text interpreter
8869: performs the compilation semantics for @code{."} within the definition of
8870: @code{my-word}.
8871: @end itemize
8872:
8873: Here are some examples of executing @code{my-word} and @code{my-char}:
8874:
8875: @example
8876: @kbd{my-word @key{RET}} text-2
8877: ok
8878: @kbd{my-char fred @key{RET}} Af ok
8879: @kbd{my-char jim @key{RET}} Aj ok
8880: @end example
8881:
8882: @itemize @bullet
8883: @item
8884: Message @code{text-2} is displayed because of the run-time behaviour of
8885: @code{."}.
8886: @item
8887: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8888: on the stack at run-time. @code{emit} always displays the character
8889: when @code{my-char} is executed.
8890: @item
8891: @code{char} parses a string at run-time and the second @code{emit} displays
8892: the first character of the string.
8893: @item
8894: If you type @code{see my-char} you can see that @code{[char]} discarded
8895: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8896: definition of @code{my-char}.
8897: @end itemize
8898:
8899:
8900:
8901: @node Input, Pipes, Displaying characters and strings, Other I/O
8902: @subsection Input
8903: @cindex input
8904: @cindex I/O - see input
8905: @cindex parsing a string
8906:
8907: For ways of storing character strings in memory see @ref{String Formats}.
8908:
8909: @comment TODO examples for >number >float accept key key? pad parse word refill
8910: @comment then index them
8911:
8912:
8913: doc-key
8914: doc-key?
8915: doc-ekey
8916: doc-ekey>char
8917: doc-ekey?
8918:
8919: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
8920: you need the ANSI.SYS driver to get that behaviour). These are the
8921: keyboard events produced by various common keys:
8922:
8923: doc-k-left
8924: doc-k-right
8925: doc-k-up
8926: doc-k-down
8927: doc-k-home
8928: doc-k-end
8929: doc-k-prior
8930: doc-k-next
8931: doc-k-insert
8932: doc-k-delete
8933:
8934: The function keys (aka keypad keys) are:
8935:
8936: doc-k1
8937: doc-k2
8938: doc-k3
8939: doc-k4
8940: doc-k5
8941: doc-k6
8942: doc-k7
8943: doc-k8
8944: doc-k9
8945: doc-k10
8946: doc-k11
8947: doc-k12
8948:
8949: Note that K11 and K12 are not as widely available. The shifted
8950: function keys are also not very widely available:
8951:
8952: doc-s-k1
8953: doc-s-k2
8954: doc-s-k3
8955: doc-s-k4
8956: doc-s-k5
8957: doc-s-k6
8958: doc-s-k7
8959: doc-s-k8
8960: doc-s-k9
8961: doc-s-k10
8962: doc-s-k11
8963: doc-s-k12
8964:
8965: Words for inputting one line from the keyboard:
8966:
8967: doc-accept
8968: doc-edit-line
8969:
8970: Conversion words:
8971:
8972: doc-s>number?
8973: doc-s>unumber?
8974: doc->number
8975: doc->float
8976:
8977:
8978: @comment obsolescent words..
8979: Obsolescent input and conversion words:
8980:
8981: doc-convert
8982: doc-expect
8983: doc-span
8984:
8985:
8986: @node Pipes, Xchars and Unicode, Input, Other I/O
8987: @subsection Pipes
8988: @cindex pipes, creating your own
8989:
8990: In addition to using Gforth in pipes created by other processes
8991: (@pxref{Gforth in pipes}), you can create your own pipe with
8992: @code{open-pipe}, and read from or write to it.
8993:
8994: doc-open-pipe
8995: doc-close-pipe
8996:
8997: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
8998: you don't catch this exception, Gforth will catch it and exit, usually
8999: silently (@pxref{Gforth in pipes}). Since you probably do not want
9000: this, you should wrap a @code{catch} or @code{try} block around the code
9001: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9002: problem yourself, and then return to regular processing.
9003:
9004: doc-broken-pipe-error
9005:
9006: @node Xchars and Unicode, , Pipes, Other I/O
9007: @subsection Xchars and Unicode
9008:
9009: This chapter needs completion
9010:
9011: @node OS command line arguments, Locals, Other I/O, Words
9012: @section OS command line arguments
9013: @cindex OS command line arguments
9014: @cindex command line arguments, OS
9015: @cindex arguments, OS command line
9016:
9017: The usual way to pass arguments to Gforth programs on the command line
9018: is via the @option{-e} option, e.g.
9019:
9020: @example
9021: gforth -e "123 456" foo.fs -e bye
9022: @end example
9023:
9024: However, you may want to interpret the command-line arguments directly.
9025: In that case, you can access the (image-specific) command-line arguments
9026: through @code{next-arg}:
9027:
9028: doc-next-arg
9029:
9030: Here's an example program @file{echo.fs} for @code{next-arg}:
9031:
9032: @example
9033: : echo ( -- )
9034: begin
9035: next-arg 2dup 0 0 d<> while
9036: type space
9037: repeat
9038: 2drop ;
9039:
9040: echo cr bye
9041: @end example
9042:
9043: This can be invoked with
9044:
9045: @example
9046: gforth echo.fs hello world
9047: @end example
9048:
9049: and it will print
9050:
9051: @example
9052: hello world
9053: @end example
9054:
9055: The next lower level of dealing with the OS command line are the
9056: following words:
9057:
9058: doc-arg
9059: doc-shift-args
9060:
9061: Finally, at the lowest level Gforth provides the following words:
9062:
9063: doc-argc
9064: doc-argv
9065:
9066: @c -------------------------------------------------------------
9067: @node Locals, Structures, OS command line arguments, Words
9068: @section Locals
9069: @cindex locals
9070:
9071: Local variables can make Forth programming more enjoyable and Forth
9072: programs easier to read. Unfortunately, the locals of ANS Forth are
9073: laden with restrictions. Therefore, we provide not only the ANS Forth
9074: locals wordset, but also our own, more powerful locals wordset (we
9075: implemented the ANS Forth locals wordset through our locals wordset).
9076:
9077: The ideas in this section have also been published in M. Anton Ertl,
9078: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9079: Automatic Scoping of Local Variables}}, EuroForth '94.
9080:
9081: @menu
9082: * Gforth locals::
9083: * ANS Forth locals::
9084: @end menu
9085:
9086: @node Gforth locals, ANS Forth locals, Locals, Locals
9087: @subsection Gforth locals
9088: @cindex Gforth locals
9089: @cindex locals, Gforth style
9090:
9091: Locals can be defined with
9092:
9093: @example
9094: @{ local1 local2 ... -- comment @}
9095: @end example
9096: or
9097: @example
9098: @{ local1 local2 ... @}
9099: @end example
9100:
9101: E.g.,
9102: @example
9103: : max @{ n1 n2 -- n3 @}
9104: n1 n2 > if
9105: n1
9106: else
9107: n2
9108: endif ;
9109: @end example
9110:
9111: The similarity of locals definitions with stack comments is intended. A
9112: locals definition often replaces the stack comment of a word. The order
9113: of the locals corresponds to the order in a stack comment and everything
9114: after the @code{--} is really a comment.
9115:
9116: This similarity has one disadvantage: It is too easy to confuse locals
9117: declarations with stack comments, causing bugs and making them hard to
9118: find. However, this problem can be avoided by appropriate coding
9119: conventions: Do not use both notations in the same program. If you do,
9120: they should be distinguished using additional means, e.g. by position.
9121:
9122: @cindex types of locals
9123: @cindex locals types
9124: The name of the local may be preceded by a type specifier, e.g.,
9125: @code{F:} for a floating point value:
9126:
9127: @example
9128: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9129: \ complex multiplication
9130: Ar Br f* Ai Bi f* f-
9131: Ar Bi f* Ai Br f* f+ ;
9132: @end example
9133:
9134: @cindex flavours of locals
9135: @cindex locals flavours
9136: @cindex value-flavoured locals
9137: @cindex variable-flavoured locals
9138: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9139: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9140: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9141: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9142: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9143: produces its address (which becomes invalid when the variable's scope is
9144: left). E.g., the standard word @code{emit} can be defined in terms of
9145: @code{type} like this:
9146:
9147: @example
9148: : emit @{ C^ char* -- @}
9149: char* 1 type ;
9150: @end example
9151:
9152: @cindex default type of locals
9153: @cindex locals, default type
9154: A local without type specifier is a @code{W:} local. Both flavours of
9155: locals are initialized with values from the data or FP stack.
9156:
9157: Currently there is no way to define locals with user-defined data
9158: structures, but we are working on it.
9159:
9160: Gforth allows defining locals everywhere in a colon definition. This
9161: poses the following questions:
9162:
9163: @menu
9164: * Where are locals visible by name?::
9165: * How long do locals live?::
9166: * Locals programming style::
9167: * Locals implementation::
9168: @end menu
9169:
9170: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9171: @subsubsection Where are locals visible by name?
9172: @cindex locals visibility
9173: @cindex visibility of locals
9174: @cindex scope of locals
9175:
9176: Basically, the answer is that locals are visible where you would expect
9177: it in block-structured languages, and sometimes a little longer. If you
9178: want to restrict the scope of a local, enclose its definition in
9179: @code{SCOPE}...@code{ENDSCOPE}.
9180:
9181:
9182: doc-scope
9183: doc-endscope
9184:
9185:
9186: These words behave like control structure words, so you can use them
9187: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9188: arbitrary ways.
9189:
9190: If you want a more exact answer to the visibility question, here's the
9191: basic principle: A local is visible in all places that can only be
9192: reached through the definition of the local@footnote{In compiler
9193: construction terminology, all places dominated by the definition of the
9194: local.}. In other words, it is not visible in places that can be reached
9195: without going through the definition of the local. E.g., locals defined
9196: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9197: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9198: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
9199:
9200: The reasoning behind this solution is: We want to have the locals
9201: visible as long as it is meaningful. The user can always make the
9202: visibility shorter by using explicit scoping. In a place that can
9203: only be reached through the definition of a local, the meaning of a
9204: local name is clear. In other places it is not: How is the local
9205: initialized at the control flow path that does not contain the
9206: definition? Which local is meant, if the same name is defined twice in
9207: two independent control flow paths?
9208:
9209: This should be enough detail for nearly all users, so you can skip the
9210: rest of this section. If you really must know all the gory details and
9211: options, read on.
9212:
9213: In order to implement this rule, the compiler has to know which places
9214: are unreachable. It knows this automatically after @code{AHEAD},
9215: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9216: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9217: compiler that the control flow never reaches that place. If
9218: @code{UNREACHABLE} is not used where it could, the only consequence is
9219: that the visibility of some locals is more limited than the rule above
9220: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9221: lie to the compiler), buggy code will be produced.
9222:
9223:
9224: doc-unreachable
9225:
9226:
9227: Another problem with this rule is that at @code{BEGIN}, the compiler
9228: does not know which locals will be visible on the incoming
9229: back-edge. All problems discussed in the following are due to this
9230: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9231: loops as examples; the discussion also applies to @code{?DO} and other
9232: loops). Perhaps the most insidious example is:
9233: @example
9234: AHEAD
9235: BEGIN
9236: x
9237: [ 1 CS-ROLL ] THEN
9238: @{ x @}
9239: ...
9240: UNTIL
9241: @end example
9242:
9243: This should be legal according to the visibility rule. The use of
9244: @code{x} can only be reached through the definition; but that appears
9245: textually below the use.
9246:
9247: From this example it is clear that the visibility rules cannot be fully
9248: implemented without major headaches. Our implementation treats common
9249: cases as advertised and the exceptions are treated in a safe way: The
9250: compiler makes a reasonable guess about the locals visible after a
9251: @code{BEGIN}; if it is too pessimistic, the
9252: user will get a spurious error about the local not being defined; if the
9253: compiler is too optimistic, it will notice this later and issue a
9254: warning. In the case above the compiler would complain about @code{x}
9255: being undefined at its use. You can see from the obscure examples in
9256: this section that it takes quite unusual control structures to get the
9257: compiler into trouble, and even then it will often do fine.
9258:
9259: If the @code{BEGIN} is reachable from above, the most optimistic guess
9260: is that all locals visible before the @code{BEGIN} will also be
9261: visible after the @code{BEGIN}. This guess is valid for all loops that
9262: are entered only through the @code{BEGIN}, in particular, for normal
9263: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9264: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9265: compiler. When the branch to the @code{BEGIN} is finally generated by
9266: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9267: warns the user if it was too optimistic:
9268: @example
9269: IF
9270: @{ x @}
9271: BEGIN
9272: \ x ?
9273: [ 1 cs-roll ] THEN
9274: ...
9275: UNTIL
9276: @end example
9277:
9278: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9279: optimistically assumes that it lives until the @code{THEN}. It notices
9280: this difference when it compiles the @code{UNTIL} and issues a
9281: warning. The user can avoid the warning, and make sure that @code{x}
9282: is not used in the wrong area by using explicit scoping:
9283: @example
9284: IF
9285: SCOPE
9286: @{ x @}
9287: ENDSCOPE
9288: BEGIN
9289: [ 1 cs-roll ] THEN
9290: ...
9291: UNTIL
9292: @end example
9293:
9294: Since the guess is optimistic, there will be no spurious error messages
9295: about undefined locals.
9296:
9297: If the @code{BEGIN} is not reachable from above (e.g., after
9298: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9299: optimistic guess, as the locals visible after the @code{BEGIN} may be
9300: defined later. Therefore, the compiler assumes that no locals are
9301: visible after the @code{BEGIN}. However, the user can use
9302: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9303: visible at the BEGIN as at the point where the top control-flow stack
9304: item was created.
9305:
9306:
9307: doc-assume-live
9308:
9309:
9310: @noindent
9311: E.g.,
9312: @example
9313: @{ x @}
9314: AHEAD
9315: ASSUME-LIVE
9316: BEGIN
9317: x
9318: [ 1 CS-ROLL ] THEN
9319: ...
9320: UNTIL
9321: @end example
9322:
9323: Other cases where the locals are defined before the @code{BEGIN} can be
9324: handled by inserting an appropriate @code{CS-ROLL} before the
9325: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9326: behind the @code{ASSUME-LIVE}).
9327:
9328: Cases where locals are defined after the @code{BEGIN} (but should be
9329: visible immediately after the @code{BEGIN}) can only be handled by
9330: rearranging the loop. E.g., the ``most insidious'' example above can be
9331: arranged into:
9332: @example
9333: BEGIN
9334: @{ x @}
9335: ... 0=
9336: WHILE
9337: x
9338: REPEAT
9339: @end example
9340:
9341: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9342: @subsubsection How long do locals live?
9343: @cindex locals lifetime
9344: @cindex lifetime of locals
9345:
9346: The right answer for the lifetime question would be: A local lives at
9347: least as long as it can be accessed. For a value-flavoured local this
9348: means: until the end of its visibility. However, a variable-flavoured
9349: local could be accessed through its address far beyond its visibility
9350: scope. Ultimately, this would mean that such locals would have to be
9351: garbage collected. Since this entails un-Forth-like implementation
9352: complexities, I adopted the same cowardly solution as some other
9353: languages (e.g., C): The local lives only as long as it is visible;
9354: afterwards its address is invalid (and programs that access it
9355: afterwards are erroneous).
9356:
9357: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9358: @subsubsection Locals programming style
9359: @cindex locals programming style
9360: @cindex programming style, locals
9361:
9362: The freedom to define locals anywhere has the potential to change
9363: programming styles dramatically. In particular, the need to use the
9364: return stack for intermediate storage vanishes. Moreover, all stack
9365: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9366: determined arguments) can be eliminated: If the stack items are in the
9367: wrong order, just write a locals definition for all of them; then
9368: write the items in the order you want.
9369:
9370: This seems a little far-fetched and eliminating stack manipulations is
9371: unlikely to become a conscious programming objective. Still, the number
9372: of stack manipulations will be reduced dramatically if local variables
9373: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9374: a traditional implementation of @code{max}).
9375:
9376: This shows one potential benefit of locals: making Forth programs more
9377: readable. Of course, this benefit will only be realized if the
9378: programmers continue to honour the principle of factoring instead of
9379: using the added latitude to make the words longer.
9380:
9381: @cindex single-assignment style for locals
9382: Using @code{TO} can and should be avoided. Without @code{TO},
9383: every value-flavoured local has only a single assignment and many
9384: advantages of functional languages apply to Forth. I.e., programs are
9385: easier to analyse, to optimize and to read: It is clear from the
9386: definition what the local stands for, it does not turn into something
9387: different later.
9388:
9389: E.g., a definition using @code{TO} might look like this:
9390: @example
9391: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9392: u1 u2 min 0
9393: ?do
9394: addr1 c@@ addr2 c@@ -
9395: ?dup-if
9396: unloop exit
9397: then
9398: addr1 char+ TO addr1
9399: addr2 char+ TO addr2
9400: loop
9401: u1 u2 - ;
9402: @end example
9403: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9404: every loop iteration. @code{strcmp} is a typical example of the
9405: readability problems of using @code{TO}. When you start reading
9406: @code{strcmp}, you think that @code{addr1} refers to the start of the
9407: string. Only near the end of the loop you realize that it is something
9408: else.
9409:
9410: This can be avoided by defining two locals at the start of the loop that
9411: are initialized with the right value for the current iteration.
9412: @example
9413: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9414: addr1 addr2
9415: u1 u2 min 0
9416: ?do @{ s1 s2 @}
9417: s1 c@@ s2 c@@ -
9418: ?dup-if
9419: unloop exit
9420: then
9421: s1 char+ s2 char+
9422: loop
9423: 2drop
9424: u1 u2 - ;
9425: @end example
9426: Here it is clear from the start that @code{s1} has a different value
9427: in every loop iteration.
9428:
9429: @node Locals implementation, , Locals programming style, Gforth locals
9430: @subsubsection Locals implementation
9431: @cindex locals implementation
9432: @cindex implementation of locals
9433:
9434: @cindex locals stack
9435: Gforth uses an extra locals stack. The most compelling reason for
9436: this is that the return stack is not float-aligned; using an extra stack
9437: also eliminates the problems and restrictions of using the return stack
9438: as locals stack. Like the other stacks, the locals stack grows toward
9439: lower addresses. A few primitives allow an efficient implementation:
9440:
9441:
9442: doc-@local#
9443: doc-f@local#
9444: doc-laddr#
9445: doc-lp+!#
9446: doc-lp!
9447: doc->l
9448: doc-f>l
9449:
9450:
9451: In addition to these primitives, some specializations of these
9452: primitives for commonly occurring inline arguments are provided for
9453: efficiency reasons, e.g., @code{@@local0} as specialization of
9454: @code{@@local#} for the inline argument 0. The following compiling words
9455: compile the right specialized version, or the general version, as
9456: appropriate:
9457:
9458:
9459: @c doc-compile-@local
9460: @c doc-compile-f@local
9461: doc-compile-lp+!
9462:
9463:
9464: Combinations of conditional branches and @code{lp+!#} like
9465: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9466: is taken) are provided for efficiency and correctness in loops.
9467:
9468: A special area in the dictionary space is reserved for keeping the
9469: local variable names. @code{@{} switches the dictionary pointer to this
9470: area and @code{@}} switches it back and generates the locals
9471: initializing code. @code{W:} etc.@ are normal defining words. This
9472: special area is cleared at the start of every colon definition.
9473:
9474: @cindex word list for defining locals
9475: A special feature of Gforth's dictionary is used to implement the
9476: definition of locals without type specifiers: every word list (aka
9477: vocabulary) has its own methods for searching
9478: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9479: with a special search method: When it is searched for a word, it
9480: actually creates that word using @code{W:}. @code{@{} changes the search
9481: order to first search the word list containing @code{@}}, @code{W:} etc.,
9482: and then the word list for defining locals without type specifiers.
9483:
9484: The lifetime rules support a stack discipline within a colon
9485: definition: The lifetime of a local is either nested with other locals
9486: lifetimes or it does not overlap them.
9487:
9488: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9489: pointer manipulation is generated. Between control structure words
9490: locals definitions can push locals onto the locals stack. @code{AGAIN}
9491: is the simplest of the other three control flow words. It has to
9492: restore the locals stack depth of the corresponding @code{BEGIN}
9493: before branching. The code looks like this:
9494: @format
9495: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9496: @code{branch} <begin>
9497: @end format
9498:
9499: @code{UNTIL} is a little more complicated: If it branches back, it
9500: must adjust the stack just like @code{AGAIN}. But if it falls through,
9501: the locals stack must not be changed. The compiler generates the
9502: following code:
9503: @format
9504: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9505: @end format
9506: The locals stack pointer is only adjusted if the branch is taken.
9507:
9508: @code{THEN} can produce somewhat inefficient code:
9509: @format
9510: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9511: <orig target>:
9512: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9513: @end format
9514: The second @code{lp+!#} adjusts the locals stack pointer from the
9515: level at the @i{orig} point to the level after the @code{THEN}. The
9516: first @code{lp+!#} adjusts the locals stack pointer from the current
9517: level to the level at the orig point, so the complete effect is an
9518: adjustment from the current level to the right level after the
9519: @code{THEN}.
9520:
9521: @cindex locals information on the control-flow stack
9522: @cindex control-flow stack items, locals information
9523: In a conventional Forth implementation a dest control-flow stack entry
9524: is just the target address and an orig entry is just the address to be
9525: patched. Our locals implementation adds a word list to every orig or dest
9526: item. It is the list of locals visible (or assumed visible) at the point
9527: described by the entry. Our implementation also adds a tag to identify
9528: the kind of entry, in particular to differentiate between live and dead
9529: (reachable and unreachable) orig entries.
9530:
9531: A few unusual operations have to be performed on locals word lists:
9532:
9533:
9534: doc-common-list
9535: doc-sub-list?
9536: doc-list-size
9537:
9538:
9539: Several features of our locals word list implementation make these
9540: operations easy to implement: The locals word lists are organised as
9541: linked lists; the tails of these lists are shared, if the lists
9542: contain some of the same locals; and the address of a name is greater
9543: than the address of the names behind it in the list.
9544:
9545: Another important implementation detail is the variable
9546: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9547: determine if they can be reached directly or only through the branch
9548: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9549: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9550: definition, by @code{BEGIN} and usually by @code{THEN}.
9551:
9552: Counted loops are similar to other loops in most respects, but
9553: @code{LEAVE} requires special attention: It performs basically the same
9554: service as @code{AHEAD}, but it does not create a control-flow stack
9555: entry. Therefore the information has to be stored elsewhere;
9556: traditionally, the information was stored in the target fields of the
9557: branches created by the @code{LEAVE}s, by organizing these fields into a
9558: linked list. Unfortunately, this clever trick does not provide enough
9559: space for storing our extended control flow information. Therefore, we
9560: introduce another stack, the leave stack. It contains the control-flow
9561: stack entries for all unresolved @code{LEAVE}s.
9562:
9563: Local names are kept until the end of the colon definition, even if
9564: they are no longer visible in any control-flow path. In a few cases
9565: this may lead to increased space needs for the locals name area, but
9566: usually less than reclaiming this space would cost in code size.
9567:
9568:
9569: @node ANS Forth locals, , Gforth locals, Locals
9570: @subsection ANS Forth locals
9571: @cindex locals, ANS Forth style
9572:
9573: The ANS Forth locals wordset does not define a syntax for locals, but
9574: words that make it possible to define various syntaxes. One of the
9575: possible syntaxes is a subset of the syntax we used in the Gforth locals
9576: wordset, i.e.:
9577:
9578: @example
9579: @{ local1 local2 ... -- comment @}
9580: @end example
9581: @noindent
9582: or
9583: @example
9584: @{ local1 local2 ... @}
9585: @end example
9586:
9587: The order of the locals corresponds to the order in a stack comment. The
9588: restrictions are:
9589:
9590: @itemize @bullet
9591: @item
9592: Locals can only be cell-sized values (no type specifiers are allowed).
9593: @item
9594: Locals can be defined only outside control structures.
9595: @item
9596: Locals can interfere with explicit usage of the return stack. For the
9597: exact (and long) rules, see the standard. If you don't use return stack
9598: accessing words in a definition using locals, you will be all right. The
9599: purpose of this rule is to make locals implementation on the return
9600: stack easier.
9601: @item
9602: The whole definition must be in one line.
9603: @end itemize
9604:
9605: Locals defined in ANS Forth behave like @code{VALUE}s
9606: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9607: name produces their value. Their value can be changed using @code{TO}.
9608:
9609: Since the syntax above is supported by Gforth directly, you need not do
9610: anything to use it. If you want to port a program using this syntax to
9611: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9612: syntax on the other system.
9613:
9614: Note that a syntax shown in the standard, section A.13 looks
9615: similar, but is quite different in having the order of locals
9616: reversed. Beware!
9617:
9618: The ANS Forth locals wordset itself consists of one word:
9619:
9620: doc-(local)
9621:
9622: The ANS Forth locals extension wordset defines a syntax using
9623: @code{locals|}, but it is so awful that we strongly recommend not to use
9624: it. We have implemented this syntax to make porting to Gforth easy, but
9625: do not document it here. The problem with this syntax is that the locals
9626: are defined in an order reversed with respect to the standard stack
9627: comment notation, making programs harder to read, and easier to misread
9628: and miswrite. The only merit of this syntax is that it is easy to
9629: implement using the ANS Forth locals wordset.
9630:
9631:
9632: @c ----------------------------------------------------------
9633: @node Structures, Object-oriented Forth, Locals, Words
9634: @section Structures
9635: @cindex structures
9636: @cindex records
9637:
9638: This section presents the structure package that comes with Gforth. A
9639: version of the package implemented in ANS Forth is available in
9640: @file{compat/struct.fs}. This package was inspired by a posting on
9641: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9642: possibly John Hayes). A version of this section has been published in
9643: M. Anton Ertl,
9644: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9645: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9646: 13--16. Marcel Hendrix provided helpful comments.
9647:
9648: @menu
9649: * Why explicit structure support?::
9650: * Structure Usage::
9651: * Structure Naming Convention::
9652: * Structure Implementation::
9653: * Structure Glossary::
9654: @end menu
9655:
9656: @node Why explicit structure support?, Structure Usage, Structures, Structures
9657: @subsection Why explicit structure support?
9658:
9659: @cindex address arithmetic for structures
9660: @cindex structures using address arithmetic
9661: If we want to use a structure containing several fields, we could simply
9662: reserve memory for it, and access the fields using address arithmetic
9663: (@pxref{Address arithmetic}). As an example, consider a structure with
9664: the following fields
9665:
9666: @table @code
9667: @item a
9668: is a float
9669: @item b
9670: is a cell
9671: @item c
9672: is a float
9673: @end table
9674:
9675: Given the (float-aligned) base address of the structure we get the
9676: address of the field
9677:
9678: @table @code
9679: @item a
9680: without doing anything further.
9681: @item b
9682: with @code{float+}
9683: @item c
9684: with @code{float+ cell+ faligned}
9685: @end table
9686:
9687: It is easy to see that this can become quite tiring.
9688:
9689: Moreover, it is not very readable, because seeing a
9690: @code{cell+} tells us neither which kind of structure is
9691: accessed nor what field is accessed; we have to somehow infer the kind
9692: of structure, and then look up in the documentation, which field of
9693: that structure corresponds to that offset.
9694:
9695: Finally, this kind of address arithmetic also causes maintenance
9696: troubles: If you add or delete a field somewhere in the middle of the
9697: structure, you have to find and change all computations for the fields
9698: afterwards.
9699:
9700: So, instead of using @code{cell+} and friends directly, how
9701: about storing the offsets in constants:
9702:
9703: @example
9704: 0 constant a-offset
9705: 0 float+ constant b-offset
9706: 0 float+ cell+ faligned c-offset
9707: @end example
9708:
9709: Now we can get the address of field @code{x} with @code{x-offset
9710: +}. This is much better in all respects. Of course, you still
9711: have to change all later offset definitions if you add a field. You can
9712: fix this by declaring the offsets in the following way:
9713:
9714: @example
9715: 0 constant a-offset
9716: a-offset float+ constant b-offset
9717: b-offset cell+ faligned constant c-offset
9718: @end example
9719:
9720: Since we always use the offsets with @code{+}, we could use a defining
9721: word @code{cfield} that includes the @code{+} in the action of the
9722: defined word:
9723:
9724: @example
9725: : cfield ( n "name" -- )
9726: create ,
9727: does> ( name execution: addr1 -- addr2 )
9728: @@ + ;
9729:
9730: 0 cfield a
9731: 0 a float+ cfield b
9732: 0 b cell+ faligned cfield c
9733: @end example
9734:
9735: Instead of @code{x-offset +}, we now simply write @code{x}.
9736:
9737: The structure field words now can be used quite nicely. However,
9738: their definition is still a bit cumbersome: We have to repeat the
9739: name, the information about size and alignment is distributed before
9740: and after the field definitions etc. The structure package presented
9741: here addresses these problems.
9742:
9743: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9744: @subsection Structure Usage
9745: @cindex structure usage
9746:
9747: @cindex @code{field} usage
9748: @cindex @code{struct} usage
9749: @cindex @code{end-struct} usage
9750: You can define a structure for a (data-less) linked list with:
9751: @example
9752: struct
9753: cell% field list-next
9754: end-struct list%
9755: @end example
9756:
9757: With the address of the list node on the stack, you can compute the
9758: address of the field that contains the address of the next node with
9759: @code{list-next}. E.g., you can determine the length of a list
9760: with:
9761:
9762: @example
9763: : list-length ( list -- n )
9764: \ "list" is a pointer to the first element of a linked list
9765: \ "n" is the length of the list
9766: 0 BEGIN ( list1 n1 )
9767: over
9768: WHILE ( list1 n1 )
9769: 1+ swap list-next @@ swap
9770: REPEAT
9771: nip ;
9772: @end example
9773:
9774: You can reserve memory for a list node in the dictionary with
9775: @code{list% %allot}, which leaves the address of the list node on the
9776: stack. For the equivalent allocation on the heap you can use @code{list%
9777: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9778: use @code{list% %allocate}). You can get the the size of a list
9779: node with @code{list% %size} and its alignment with @code{list%
9780: %alignment}.
9781:
9782: Note that in ANS Forth the body of a @code{create}d word is
9783: @code{aligned} but not necessarily @code{faligned};
9784: therefore, if you do a:
9785:
9786: @example
9787: create @emph{name} foo% %allot drop
9788: @end example
9789:
9790: @noindent
9791: then the memory alloted for @code{foo%} is guaranteed to start at the
9792: body of @code{@emph{name}} only if @code{foo%} contains only character,
9793: cell and double fields. Therefore, if your structure contains floats,
9794: better use
9795:
9796: @example
9797: foo% %allot constant @emph{name}
9798: @end example
9799:
9800: @cindex structures containing structures
9801: You can include a structure @code{foo%} as a field of
9802: another structure, like this:
9803: @example
9804: struct
9805: ...
9806: foo% field ...
9807: ...
9808: end-struct ...
9809: @end example
9810:
9811: @cindex structure extension
9812: @cindex extended records
9813: Instead of starting with an empty structure, you can extend an
9814: existing structure. E.g., a plain linked list without data, as defined
9815: above, is hardly useful; You can extend it to a linked list of integers,
9816: like this:@footnote{This feature is also known as @emph{extended
9817: records}. It is the main innovation in the Oberon language; in other
9818: words, adding this feature to Modula-2 led Wirth to create a new
9819: language, write a new compiler etc. Adding this feature to Forth just
9820: required a few lines of code.}
9821:
9822: @example
9823: list%
9824: cell% field intlist-int
9825: end-struct intlist%
9826: @end example
9827:
9828: @code{intlist%} is a structure with two fields:
9829: @code{list-next} and @code{intlist-int}.
9830:
9831: @cindex structures containing arrays
9832: You can specify an array type containing @emph{n} elements of
9833: type @code{foo%} like this:
9834:
9835: @example
9836: foo% @emph{n} *
9837: @end example
9838:
9839: You can use this array type in any place where you can use a normal
9840: type, e.g., when defining a @code{field}, or with
9841: @code{%allot}.
9842:
9843: @cindex first field optimization
9844: The first field is at the base address of a structure and the word for
9845: this field (e.g., @code{list-next}) actually does not change the address
9846: on the stack. You may be tempted to leave it away in the interest of
9847: run-time and space efficiency. This is not necessary, because the
9848: structure package optimizes this case: If you compile a first-field
9849: words, no code is generated. So, in the interest of readability and
9850: maintainability you should include the word for the field when accessing
9851: the field.
9852:
9853:
9854: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9855: @subsection Structure Naming Convention
9856: @cindex structure naming convention
9857:
9858: The field names that come to (my) mind are often quite generic, and,
9859: if used, would cause frequent name clashes. E.g., many structures
9860: probably contain a @code{counter} field. The structure names
9861: that come to (my) mind are often also the logical choice for the names
9862: of words that create such a structure.
9863:
9864: Therefore, I have adopted the following naming conventions:
9865:
9866: @itemize @bullet
9867: @cindex field naming convention
9868: @item
9869: The names of fields are of the form
9870: @code{@emph{struct}-@emph{field}}, where
9871: @code{@emph{struct}} is the basic name of the structure, and
9872: @code{@emph{field}} is the basic name of the field. You can
9873: think of field words as converting the (address of the)
9874: structure into the (address of the) field.
9875:
9876: @cindex structure naming convention
9877: @item
9878: The names of structures are of the form
9879: @code{@emph{struct}%}, where
9880: @code{@emph{struct}} is the basic name of the structure.
9881: @end itemize
9882:
9883: This naming convention does not work that well for fields of extended
9884: structures; e.g., the integer list structure has a field
9885: @code{intlist-int}, but has @code{list-next}, not
9886: @code{intlist-next}.
9887:
9888: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9889: @subsection Structure Implementation
9890: @cindex structure implementation
9891: @cindex implementation of structures
9892:
9893: The central idea in the implementation is to pass the data about the
9894: structure being built on the stack, not in some global
9895: variable. Everything else falls into place naturally once this design
9896: decision is made.
9897:
9898: The type description on the stack is of the form @emph{align
9899: size}. Keeping the size on the top-of-stack makes dealing with arrays
9900: very simple.
9901:
9902: @code{field} is a defining word that uses @code{Create}
9903: and @code{DOES>}. The body of the field contains the offset
9904: of the field, and the normal @code{DOES>} action is simply:
9905:
9906: @example
9907: @@ +
9908: @end example
9909:
9910: @noindent
9911: i.e., add the offset to the address, giving the stack effect
9912: @i{addr1 -- addr2} for a field.
9913:
9914: @cindex first field optimization, implementation
9915: This simple structure is slightly complicated by the optimization
9916: for fields with offset 0, which requires a different
9917: @code{DOES>}-part (because we cannot rely on there being
9918: something on the stack if such a field is invoked during
9919: compilation). Therefore, we put the different @code{DOES>}-parts
9920: in separate words, and decide which one to invoke based on the
9921: offset. For a zero offset, the field is basically a noop; it is
9922: immediate, and therefore no code is generated when it is compiled.
9923:
9924: @node Structure Glossary, , Structure Implementation, Structures
9925: @subsection Structure Glossary
9926: @cindex structure glossary
9927:
9928:
9929: doc-%align
9930: doc-%alignment
9931: doc-%alloc
9932: doc-%allocate
9933: doc-%allot
9934: doc-cell%
9935: doc-char%
9936: doc-dfloat%
9937: doc-double%
9938: doc-end-struct
9939: doc-field
9940: doc-float%
9941: doc-naligned
9942: doc-sfloat%
9943: doc-%size
9944: doc-struct
9945:
9946:
9947: @c -------------------------------------------------------------
9948: @node Object-oriented Forth, Programming Tools, Structures, Words
9949: @section Object-oriented Forth
9950:
9951: Gforth comes with three packages for object-oriented programming:
9952: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9953: is preloaded, so you have to @code{include} them before use. The most
9954: important differences between these packages (and others) are discussed
9955: in @ref{Comparison with other object models}. All packages are written
9956: in ANS Forth and can be used with any other ANS Forth.
9957:
9958: @menu
9959: * Why object-oriented programming?::
9960: * Object-Oriented Terminology::
9961: * Objects::
9962: * OOF::
9963: * Mini-OOF::
9964: * Comparison with other object models::
9965: @end menu
9966:
9967: @c ----------------------------------------------------------------
9968: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9969: @subsection Why object-oriented programming?
9970: @cindex object-oriented programming motivation
9971: @cindex motivation for object-oriented programming
9972:
9973: Often we have to deal with several data structures (@emph{objects}),
9974: that have to be treated similarly in some respects, but differently in
9975: others. Graphical objects are the textbook example: circles, triangles,
9976: dinosaurs, icons, and others, and we may want to add more during program
9977: development. We want to apply some operations to any graphical object,
9978: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9979: has to do something different for every kind of object.
9980: @comment TODO add some other operations eg perimeter, area
9981: @comment and tie in to concrete examples later..
9982:
9983: We could implement @code{draw} as a big @code{CASE}
9984: control structure that executes the appropriate code depending on the
9985: kind of object to be drawn. This would be not be very elegant, and,
9986: moreover, we would have to change @code{draw} every time we add
9987: a new kind of graphical object (say, a spaceship).
9988:
9989: What we would rather do is: When defining spaceships, we would tell
9990: the system: ``Here's how you @code{draw} a spaceship; you figure
9991: out the rest''.
9992:
9993: This is the problem that all systems solve that (rightfully) call
9994: themselves object-oriented; the object-oriented packages presented here
9995: solve this problem (and not much else).
9996: @comment TODO ?list properties of oo systems.. oo vs o-based?
9997:
9998: @c ------------------------------------------------------------------------
9999: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10000: @subsection Object-Oriented Terminology
10001: @cindex object-oriented terminology
10002: @cindex terminology for object-oriented programming
10003:
10004: This section is mainly for reference, so you don't have to understand
10005: all of it right away. The terminology is mainly Smalltalk-inspired. In
10006: short:
10007:
10008: @table @emph
10009: @cindex class
10010: @item class
10011: a data structure definition with some extras.
10012:
10013: @cindex object
10014: @item object
10015: an instance of the data structure described by the class definition.
10016:
10017: @cindex instance variables
10018: @item instance variables
10019: fields of the data structure.
10020:
10021: @cindex selector
10022: @cindex method selector
10023: @cindex virtual function
10024: @item selector
10025: (or @emph{method selector}) a word (e.g.,
10026: @code{draw}) that performs an operation on a variety of data
10027: structures (classes). A selector describes @emph{what} operation to
10028: perform. In C++ terminology: a (pure) virtual function.
10029:
10030: @cindex method
10031: @item method
10032: the concrete definition that performs the operation
10033: described by the selector for a specific class. A method specifies
10034: @emph{how} the operation is performed for a specific class.
10035:
10036: @cindex selector invocation
10037: @cindex message send
10038: @cindex invoking a selector
10039: @item selector invocation
10040: a call of a selector. One argument of the call (the TOS (top-of-stack))
10041: is used for determining which method is used. In Smalltalk terminology:
10042: a message (consisting of the selector and the other arguments) is sent
10043: to the object.
10044:
10045: @cindex receiving object
10046: @item receiving object
10047: the object used for determining the method executed by a selector
10048: invocation. In the @file{objects.fs} model, it is the object that is on
10049: the TOS when the selector is invoked. (@emph{Receiving} comes from
10050: the Smalltalk @emph{message} terminology.)
10051:
10052: @cindex child class
10053: @cindex parent class
10054: @cindex inheritance
10055: @item child class
10056: a class that has (@emph{inherits}) all properties (instance variables,
10057: selectors, methods) from a @emph{parent class}. In Smalltalk
10058: terminology: The subclass inherits from the superclass. In C++
10059: terminology: The derived class inherits from the base class.
10060:
10061: @end table
10062:
10063: @c If you wonder about the message sending terminology, it comes from
10064: @c a time when each object had it's own task and objects communicated via
10065: @c message passing; eventually the Smalltalk developers realized that
10066: @c they can do most things through simple (indirect) calls. They kept the
10067: @c terminology.
10068:
10069: @c --------------------------------------------------------------
10070: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10071: @subsection The @file{objects.fs} model
10072: @cindex objects
10073: @cindex object-oriented programming
10074:
10075: @cindex @file{objects.fs}
10076: @cindex @file{oof.fs}
10077:
10078: This section describes the @file{objects.fs} package. This material also
10079: has been published in M. Anton Ertl,
10080: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10081: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10082: 37--43.
10083: @c McKewan's and Zsoter's packages
10084:
10085: This section assumes that you have read @ref{Structures}.
10086:
10087: The techniques on which this model is based have been used to implement
10088: the parser generator, Gray, and have also been used in Gforth for
10089: implementing the various flavours of word lists (hashed or not,
10090: case-sensitive or not, special-purpose word lists for locals etc.).
10091:
10092:
10093: @menu
10094: * Properties of the Objects model::
10095: * Basic Objects Usage::
10096: * The Objects base class::
10097: * Creating objects::
10098: * Object-Oriented Programming Style::
10099: * Class Binding::
10100: * Method conveniences::
10101: * Classes and Scoping::
10102: * Dividing classes::
10103: * Object Interfaces::
10104: * Objects Implementation::
10105: * Objects Glossary::
10106: @end menu
10107:
10108: Marcel Hendrix provided helpful comments on this section.
10109:
10110: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10111: @subsubsection Properties of the @file{objects.fs} model
10112: @cindex @file{objects.fs} properties
10113:
10114: @itemize @bullet
10115: @item
10116: It is straightforward to pass objects on the stack. Passing
10117: selectors on the stack is a little less convenient, but possible.
10118:
10119: @item
10120: Objects are just data structures in memory, and are referenced by their
10121: address. You can create words for objects with normal defining words
10122: like @code{constant}. Likewise, there is no difference between instance
10123: variables that contain objects and those that contain other data.
10124:
10125: @item
10126: Late binding is efficient and easy to use.
10127:
10128: @item
10129: It avoids parsing, and thus avoids problems with state-smartness
10130: and reduced extensibility; for convenience there are a few parsing
10131: words, but they have non-parsing counterparts. There are also a few
10132: defining words that parse. This is hard to avoid, because all standard
10133: defining words parse (except @code{:noname}); however, such
10134: words are not as bad as many other parsing words, because they are not
10135: state-smart.
10136:
10137: @item
10138: It does not try to incorporate everything. It does a few things and does
10139: them well (IMO). In particular, this model was not designed to support
10140: information hiding (although it has features that may help); you can use
10141: a separate package for achieving this.
10142:
10143: @item
10144: It is layered; you don't have to learn and use all features to use this
10145: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10146: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10147: are optional and independent of each other.
10148:
10149: @item
10150: An implementation in ANS Forth is available.
10151:
10152: @end itemize
10153:
10154:
10155: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10156: @subsubsection Basic @file{objects.fs} Usage
10157: @cindex basic objects usage
10158: @cindex objects, basic usage
10159:
10160: You can define a class for graphical objects like this:
10161:
10162: @cindex @code{class} usage
10163: @cindex @code{end-class} usage
10164: @cindex @code{selector} usage
10165: @example
10166: object class \ "object" is the parent class
10167: selector draw ( x y graphical -- )
10168: end-class graphical
10169: @end example
10170:
10171: This code defines a class @code{graphical} with an
10172: operation @code{draw}. We can perform the operation
10173: @code{draw} on any @code{graphical} object, e.g.:
10174:
10175: @example
10176: 100 100 t-rex draw
10177: @end example
10178:
10179: @noindent
10180: where @code{t-rex} is a word (say, a constant) that produces a
10181: graphical object.
10182:
10183: @comment TODO add a 2nd operation eg perimeter.. and use for
10184: @comment a concrete example
10185:
10186: @cindex abstract class
10187: How do we create a graphical object? With the present definitions,
10188: we cannot create a useful graphical object. The class
10189: @code{graphical} describes graphical objects in general, but not
10190: any concrete graphical object type (C++ users would call it an
10191: @emph{abstract class}); e.g., there is no method for the selector
10192: @code{draw} in the class @code{graphical}.
10193:
10194: For concrete graphical objects, we define child classes of the
10195: class @code{graphical}, e.g.:
10196:
10197: @cindex @code{overrides} usage
10198: @cindex @code{field} usage in class definition
10199: @example
10200: graphical class \ "graphical" is the parent class
10201: cell% field circle-radius
10202:
10203: :noname ( x y circle -- )
10204: circle-radius @@ draw-circle ;
10205: overrides draw
10206:
10207: :noname ( n-radius circle -- )
10208: circle-radius ! ;
10209: overrides construct
10210:
10211: end-class circle
10212: @end example
10213:
10214: Here we define a class @code{circle} as a child of @code{graphical},
10215: with field @code{circle-radius} (which behaves just like a field
10216: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10217: for the selectors @code{draw} and @code{construct} (@code{construct} is
10218: defined in @code{object}, the parent class of @code{graphical}).
10219:
10220: Now we can create a circle on the heap (i.e.,
10221: @code{allocate}d memory) with:
10222:
10223: @cindex @code{heap-new} usage
10224: @example
10225: 50 circle heap-new constant my-circle
10226: @end example
10227:
10228: @noindent
10229: @code{heap-new} invokes @code{construct}, thus
10230: initializing the field @code{circle-radius} with 50. We can draw
10231: this new circle at (100,100) with:
10232:
10233: @example
10234: 100 100 my-circle draw
10235: @end example
10236:
10237: @cindex selector invocation, restrictions
10238: @cindex class definition, restrictions
10239: Note: You can only invoke a selector if the object on the TOS
10240: (the receiving object) belongs to the class where the selector was
10241: defined or one of its descendents; e.g., you can invoke
10242: @code{draw} only for objects belonging to @code{graphical}
10243: or its descendents (e.g., @code{circle}). Immediately before
10244: @code{end-class}, the search order has to be the same as
10245: immediately after @code{class}.
10246:
10247: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10248: @subsubsection The @file{object.fs} base class
10249: @cindex @code{object} class
10250:
10251: When you define a class, you have to specify a parent class. So how do
10252: you start defining classes? There is one class available from the start:
10253: @code{object}. It is ancestor for all classes and so is the
10254: only class that has no parent. It has two selectors: @code{construct}
10255: and @code{print}.
10256:
10257: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10258: @subsubsection Creating objects
10259: @cindex creating objects
10260: @cindex object creation
10261: @cindex object allocation options
10262:
10263: @cindex @code{heap-new} discussion
10264: @cindex @code{dict-new} discussion
10265: @cindex @code{construct} discussion
10266: You can create and initialize an object of a class on the heap with
10267: @code{heap-new} ( ... class -- object ) and in the dictionary
10268: (allocation with @code{allot}) with @code{dict-new} (
10269: ... class -- object ). Both words invoke @code{construct}, which
10270: consumes the stack items indicated by "..." above.
10271:
10272: @cindex @code{init-object} discussion
10273: @cindex @code{class-inst-size} discussion
10274: If you want to allocate memory for an object yourself, you can get its
10275: alignment and size with @code{class-inst-size 2@@} ( class --
10276: align size ). Once you have memory for an object, you can initialize
10277: it with @code{init-object} ( ... class object -- );
10278: @code{construct} does only a part of the necessary work.
10279:
10280: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10281: @subsubsection Object-Oriented Programming Style
10282: @cindex object-oriented programming style
10283: @cindex programming style, object-oriented
10284:
10285: This section is not exhaustive.
10286:
10287: @cindex stack effects of selectors
10288: @cindex selectors and stack effects
10289: In general, it is a good idea to ensure that all methods for the
10290: same selector have the same stack effect: when you invoke a selector,
10291: you often have no idea which method will be invoked, so, unless all
10292: methods have the same stack effect, you will not know the stack effect
10293: of the selector invocation.
10294:
10295: One exception to this rule is methods for the selector
10296: @code{construct}. We know which method is invoked, because we
10297: specify the class to be constructed at the same place. Actually, I
10298: defined @code{construct} as a selector only to give the users a
10299: convenient way to specify initialization. The way it is used, a
10300: mechanism different from selector invocation would be more natural
10301: (but probably would take more code and more space to explain).
10302:
10303: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10304: @subsubsection Class Binding
10305: @cindex class binding
10306: @cindex early binding
10307:
10308: @cindex late binding
10309: Normal selector invocations determine the method at run-time depending
10310: on the class of the receiving object. This run-time selection is called
10311: @i{late binding}.
10312:
10313: Sometimes it's preferable to invoke a different method. For example,
10314: you might want to use the simple method for @code{print}ing
10315: @code{object}s instead of the possibly long-winded @code{print} method
10316: of the receiver class. You can achieve this by replacing the invocation
10317: of @code{print} with:
10318:
10319: @cindex @code{[bind]} usage
10320: @example
10321: [bind] object print
10322: @end example
10323:
10324: @noindent
10325: in compiled code or:
10326:
10327: @cindex @code{bind} usage
10328: @example
10329: bind object print
10330: @end example
10331:
10332: @cindex class binding, alternative to
10333: @noindent
10334: in interpreted code. Alternatively, you can define the method with a
10335: name (e.g., @code{print-object}), and then invoke it through the
10336: name. Class binding is just a (often more convenient) way to achieve
10337: the same effect; it avoids name clutter and allows you to invoke
10338: methods directly without naming them first.
10339:
10340: @cindex superclass binding
10341: @cindex parent class binding
10342: A frequent use of class binding is this: When we define a method
10343: for a selector, we often want the method to do what the selector does
10344: in the parent class, and a little more. There is a special word for
10345: this purpose: @code{[parent]}; @code{[parent]
10346: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10347: selector}}, where @code{@emph{parent}} is the parent
10348: class of the current class. E.g., a method definition might look like:
10349:
10350: @cindex @code{[parent]} usage
10351: @example
10352: :noname
10353: dup [parent] foo \ do parent's foo on the receiving object
10354: ... \ do some more
10355: ; overrides foo
10356: @end example
10357:
10358: @cindex class binding as optimization
10359: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10360: March 1997), Andrew McKewan presents class binding as an optimization
10361: technique. I recommend not using it for this purpose unless you are in
10362: an emergency. Late binding is pretty fast with this model anyway, so the
10363: benefit of using class binding is small; the cost of using class binding
10364: where it is not appropriate is reduced maintainability.
10365:
10366: While we are at programming style questions: You should bind
10367: selectors only to ancestor classes of the receiving object. E.g., say,
10368: you know that the receiving object is of class @code{foo} or its
10369: descendents; then you should bind only to @code{foo} and its
10370: ancestors.
10371:
10372: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10373: @subsubsection Method conveniences
10374: @cindex method conveniences
10375:
10376: In a method you usually access the receiving object pretty often. If
10377: you define the method as a plain colon definition (e.g., with
10378: @code{:noname}), you may have to do a lot of stack
10379: gymnastics. To avoid this, you can define the method with @code{m:
10380: ... ;m}. E.g., you could define the method for
10381: @code{draw}ing a @code{circle} with
10382:
10383: @cindex @code{this} usage
10384: @cindex @code{m:} usage
10385: @cindex @code{;m} usage
10386: @example
10387: m: ( x y circle -- )
10388: ( x y ) this circle-radius @@ draw-circle ;m
10389: @end example
10390:
10391: @cindex @code{exit} in @code{m: ... ;m}
10392: @cindex @code{exitm} discussion
10393: @cindex @code{catch} in @code{m: ... ;m}
10394: When this method is executed, the receiver object is removed from the
10395: stack; you can access it with @code{this} (admittedly, in this
10396: example the use of @code{m: ... ;m} offers no advantage). Note
10397: that I specify the stack effect for the whole method (i.e. including
10398: the receiver object), not just for the code between @code{m:}
10399: and @code{;m}. You cannot use @code{exit} in
10400: @code{m:...;m}; instead, use
10401: @code{exitm}.@footnote{Moreover, for any word that calls
10402: @code{catch} and was defined before loading
10403: @code{objects.fs}, you have to redefine it like I redefined
10404: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10405:
10406: @cindex @code{inst-var} usage
10407: You will frequently use sequences of the form @code{this
10408: @emph{field}} (in the example above: @code{this
10409: circle-radius}). If you use the field only in this way, you can
10410: define it with @code{inst-var} and eliminate the
10411: @code{this} before the field name. E.g., the @code{circle}
10412: class above could also be defined with:
10413:
10414: @example
10415: graphical class
10416: cell% inst-var radius
10417:
10418: m: ( x y circle -- )
10419: radius @@ draw-circle ;m
10420: overrides draw
10421:
10422: m: ( n-radius circle -- )
10423: radius ! ;m
10424: overrides construct
10425:
10426: end-class circle
10427: @end example
10428:
10429: @code{radius} can only be used in @code{circle} and its
10430: descendent classes and inside @code{m:...;m}.
10431:
10432: @cindex @code{inst-value} usage
10433: You can also define fields with @code{inst-value}, which is
10434: to @code{inst-var} what @code{value} is to
10435: @code{variable}. You can change the value of such a field with
10436: @code{[to-inst]}. E.g., we could also define the class
10437: @code{circle} like this:
10438:
10439: @example
10440: graphical class
10441: inst-value radius
10442:
10443: m: ( x y circle -- )
10444: radius draw-circle ;m
10445: overrides draw
10446:
10447: m: ( n-radius circle -- )
10448: [to-inst] radius ;m
10449: overrides construct
10450:
10451: end-class circle
10452: @end example
10453:
10454: @c !! :m is easy to confuse with m:. Another name would be better.
10455:
10456: @c Finally, you can define named methods with @code{:m}. One use of this
10457: @c feature is the definition of words that occur only in one class and are
10458: @c not intended to be overridden, but which still need method context
10459: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10460: @c would be bound frequently, if defined anonymously.
10461:
10462:
10463: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10464: @subsubsection Classes and Scoping
10465: @cindex classes and scoping
10466: @cindex scoping and classes
10467:
10468: Inheritance is frequent, unlike structure extension. This exacerbates
10469: the problem with the field name convention (@pxref{Structure Naming
10470: Convention}): One always has to remember in which class the field was
10471: originally defined; changing a part of the class structure would require
10472: changes for renaming in otherwise unaffected code.
10473:
10474: @cindex @code{inst-var} visibility
10475: @cindex @code{inst-value} visibility
10476: To solve this problem, I added a scoping mechanism (which was not in my
10477: original charter): A field defined with @code{inst-var} (or
10478: @code{inst-value}) is visible only in the class where it is defined and in
10479: the descendent classes of this class. Using such fields only makes
10480: sense in @code{m:}-defined methods in these classes anyway.
10481:
10482: This scoping mechanism allows us to use the unadorned field name,
10483: because name clashes with unrelated words become much less likely.
10484:
10485: @cindex @code{protected} discussion
10486: @cindex @code{private} discussion
10487: Once we have this mechanism, we can also use it for controlling the
10488: visibility of other words: All words defined after
10489: @code{protected} are visible only in the current class and its
10490: descendents. @code{public} restores the compilation
10491: (i.e. @code{current}) word list that was in effect before. If you
10492: have several @code{protected}s without an intervening
10493: @code{public} or @code{set-current}, @code{public}
10494: will restore the compilation word list in effect before the first of
10495: these @code{protected}s.
10496:
10497: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10498: @subsubsection Dividing classes
10499: @cindex Dividing classes
10500: @cindex @code{methods}...@code{end-methods}
10501:
10502: You may want to do the definition of methods separate from the
10503: definition of the class, its selectors, fields, and instance variables,
10504: i.e., separate the implementation from the definition. You can do this
10505: in the following way:
10506:
10507: @example
10508: graphical class
10509: inst-value radius
10510: end-class circle
10511:
10512: ... \ do some other stuff
10513:
10514: circle methods \ now we are ready
10515:
10516: m: ( x y circle -- )
10517: radius draw-circle ;m
10518: overrides draw
10519:
10520: m: ( n-radius circle -- )
10521: [to-inst] radius ;m
10522: overrides construct
10523:
10524: end-methods
10525: @end example
10526:
10527: You can use several @code{methods}...@code{end-methods} sections. The
10528: only things you can do to the class in these sections are: defining
10529: methods, and overriding the class's selectors. You must not define new
10530: selectors or fields.
10531:
10532: Note that you often have to override a selector before using it. In
10533: particular, you usually have to override @code{construct} with a new
10534: method before you can invoke @code{heap-new} and friends. E.g., you
10535: must not create a circle before the @code{overrides construct} sequence
10536: in the example above.
10537:
10538: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10539: @subsubsection Object Interfaces
10540: @cindex object interfaces
10541: @cindex interfaces for objects
10542:
10543: In this model you can only call selectors defined in the class of the
10544: receiving objects or in one of its ancestors. If you call a selector
10545: with a receiving object that is not in one of these classes, the
10546: result is undefined; if you are lucky, the program crashes
10547: immediately.
10548:
10549: @cindex selectors common to hardly-related classes
10550: Now consider the case when you want to have a selector (or several)
10551: available in two classes: You would have to add the selector to a
10552: common ancestor class, in the worst case to @code{object}. You
10553: may not want to do this, e.g., because someone else is responsible for
10554: this ancestor class.
10555:
10556: The solution for this problem is interfaces. An interface is a
10557: collection of selectors. If a class implements an interface, the
10558: selectors become available to the class and its descendents. A class
10559: can implement an unlimited number of interfaces. For the problem
10560: discussed above, we would define an interface for the selector(s), and
10561: both classes would implement the interface.
10562:
10563: As an example, consider an interface @code{storage} for
10564: writing objects to disk and getting them back, and a class
10565: @code{foo} that implements it. The code would look like this:
10566:
10567: @cindex @code{interface} usage
10568: @cindex @code{end-interface} usage
10569: @cindex @code{implementation} usage
10570: @example
10571: interface
10572: selector write ( file object -- )
10573: selector read1 ( file object -- )
10574: end-interface storage
10575:
10576: bar class
10577: storage implementation
10578:
10579: ... overrides write
10580: ... overrides read1
10581: ...
10582: end-class foo
10583: @end example
10584:
10585: @noindent
10586: (I would add a word @code{read} @i{( file -- object )} that uses
10587: @code{read1} internally, but that's beyond the point illustrated
10588: here.)
10589:
10590: Note that you cannot use @code{protected} in an interface; and
10591: of course you cannot define fields.
10592:
10593: In the Neon model, all selectors are available for all classes;
10594: therefore it does not need interfaces. The price you pay in this model
10595: is slower late binding, and therefore, added complexity to avoid late
10596: binding.
10597:
10598: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10599: @subsubsection @file{objects.fs} Implementation
10600: @cindex @file{objects.fs} implementation
10601:
10602: @cindex @code{object-map} discussion
10603: An object is a piece of memory, like one of the data structures
10604: described with @code{struct...end-struct}. It has a field
10605: @code{object-map} that points to the method map for the object's
10606: class.
10607:
10608: @cindex method map
10609: @cindex virtual function table
10610: The @emph{method map}@footnote{This is Self terminology; in C++
10611: terminology: virtual function table.} is an array that contains the
10612: execution tokens (@i{xt}s) of the methods for the object's class. Each
10613: selector contains an offset into a method map.
10614:
10615: @cindex @code{selector} implementation, class
10616: @code{selector} is a defining word that uses
10617: @code{CREATE} and @code{DOES>}. The body of the
10618: selector contains the offset; the @code{DOES>} action for a
10619: class selector is, basically:
10620:
10621: @example
10622: ( object addr ) @@ over object-map @@ + @@ execute
10623: @end example
10624:
10625: Since @code{object-map} is the first field of the object, it
10626: does not generate any code. As you can see, calling a selector has a
10627: small, constant cost.
10628:
10629: @cindex @code{current-interface} discussion
10630: @cindex class implementation and representation
10631: A class is basically a @code{struct} combined with a method
10632: map. During the class definition the alignment and size of the class
10633: are passed on the stack, just as with @code{struct}s, so
10634: @code{field} can also be used for defining class
10635: fields. However, passing more items on the stack would be
10636: inconvenient, so @code{class} builds a data structure in memory,
10637: which is accessed through the variable
10638: @code{current-interface}. After its definition is complete, the
10639: class is represented on the stack by a pointer (e.g., as parameter for
10640: a child class definition).
10641:
10642: A new class starts off with the alignment and size of its parent,
10643: and a copy of the parent's method map. Defining new fields extends the
10644: size and alignment; likewise, defining new selectors extends the
10645: method map. @code{overrides} just stores a new @i{xt} in the method
10646: map at the offset given by the selector.
10647:
10648: @cindex class binding, implementation
10649: Class binding just gets the @i{xt} at the offset given by the selector
10650: from the class's method map and @code{compile,}s (in the case of
10651: @code{[bind]}) it.
10652:
10653: @cindex @code{this} implementation
10654: @cindex @code{catch} and @code{this}
10655: @cindex @code{this} and @code{catch}
10656: I implemented @code{this} as a @code{value}. At the
10657: start of an @code{m:...;m} method the old @code{this} is
10658: stored to the return stack and restored at the end; and the object on
10659: the TOS is stored @code{TO this}. This technique has one
10660: disadvantage: If the user does not leave the method via
10661: @code{;m}, but via @code{throw} or @code{exit},
10662: @code{this} is not restored (and @code{exit} may
10663: crash). To deal with the @code{throw} problem, I have redefined
10664: @code{catch} to save and restore @code{this}; the same
10665: should be done with any word that can catch an exception. As for
10666: @code{exit}, I simply forbid it (as a replacement, there is
10667: @code{exitm}).
10668:
10669: @cindex @code{inst-var} implementation
10670: @code{inst-var} is just the same as @code{field}, with
10671: a different @code{DOES>} action:
10672: @example
10673: @@ this +
10674: @end example
10675: Similar for @code{inst-value}.
10676:
10677: @cindex class scoping implementation
10678: Each class also has a word list that contains the words defined with
10679: @code{inst-var} and @code{inst-value}, and its protected
10680: words. It also has a pointer to its parent. @code{class} pushes
10681: the word lists of the class and all its ancestors onto the search order stack,
10682: and @code{end-class} drops them.
10683:
10684: @cindex interface implementation
10685: An interface is like a class without fields, parent and protected
10686: words; i.e., it just has a method map. If a class implements an
10687: interface, its method map contains a pointer to the method map of the
10688: interface. The positive offsets in the map are reserved for class
10689: methods, therefore interface map pointers have negative
10690: offsets. Interfaces have offsets that are unique throughout the
10691: system, unlike class selectors, whose offsets are only unique for the
10692: classes where the selector is available (invokable).
10693:
10694: This structure means that interface selectors have to perform one
10695: indirection more than class selectors to find their method. Their body
10696: contains the interface map pointer offset in the class method map, and
10697: the method offset in the interface method map. The
10698: @code{does>} action for an interface selector is, basically:
10699:
10700: @example
10701: ( object selector-body )
10702: 2dup selector-interface @@ ( object selector-body object interface-offset )
10703: swap object-map @@ + @@ ( object selector-body map )
10704: swap selector-offset @@ + @@ execute
10705: @end example
10706:
10707: where @code{object-map} and @code{selector-offset} are
10708: first fields and generate no code.
10709:
10710: As a concrete example, consider the following code:
10711:
10712: @example
10713: interface
10714: selector if1sel1
10715: selector if1sel2
10716: end-interface if1
10717:
10718: object class
10719: if1 implementation
10720: selector cl1sel1
10721: cell% inst-var cl1iv1
10722:
10723: ' m1 overrides construct
10724: ' m2 overrides if1sel1
10725: ' m3 overrides if1sel2
10726: ' m4 overrides cl1sel2
10727: end-class cl1
10728:
10729: create obj1 object dict-new drop
10730: create obj2 cl1 dict-new drop
10731: @end example
10732:
10733: The data structure created by this code (including the data structure
10734: for @code{object}) is shown in the
10735: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10736: @comment TODO add this diagram..
10737:
10738: @node Objects Glossary, , Objects Implementation, Objects
10739: @subsubsection @file{objects.fs} Glossary
10740: @cindex @file{objects.fs} Glossary
10741:
10742:
10743: doc---objects-bind
10744: doc---objects-<bind>
10745: doc---objects-bind'
10746: doc---objects-[bind]
10747: doc---objects-class
10748: doc---objects-class->map
10749: doc---objects-class-inst-size
10750: doc---objects-class-override!
10751: doc---objects-class-previous
10752: doc---objects-class>order
10753: doc---objects-construct
10754: doc---objects-current'
10755: doc---objects-[current]
10756: doc---objects-current-interface
10757: doc---objects-dict-new
10758: doc---objects-end-class
10759: doc---objects-end-class-noname
10760: doc---objects-end-interface
10761: doc---objects-end-interface-noname
10762: doc---objects-end-methods
10763: doc---objects-exitm
10764: doc---objects-heap-new
10765: doc---objects-implementation
10766: doc---objects-init-object
10767: doc---objects-inst-value
10768: doc---objects-inst-var
10769: doc---objects-interface
10770: doc---objects-m:
10771: doc---objects-:m
10772: doc---objects-;m
10773: doc---objects-method
10774: doc---objects-methods
10775: doc---objects-object
10776: doc---objects-overrides
10777: doc---objects-[parent]
10778: doc---objects-print
10779: doc---objects-protected
10780: doc---objects-public
10781: doc---objects-selector
10782: doc---objects-this
10783: doc---objects-<to-inst>
10784: doc---objects-[to-inst]
10785: doc---objects-to-this
10786: doc---objects-xt-new
10787:
10788:
10789: @c -------------------------------------------------------------
10790: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10791: @subsection The @file{oof.fs} model
10792: @cindex oof
10793: @cindex object-oriented programming
10794:
10795: @cindex @file{objects.fs}
10796: @cindex @file{oof.fs}
10797:
10798: This section describes the @file{oof.fs} package.
10799:
10800: The package described in this section has been used in bigFORTH since 1991, and
10801: used for two large applications: a chromatographic system used to
10802: create new medicaments, and a graphic user interface library (MINOS).
10803:
10804: You can find a description (in German) of @file{oof.fs} in @cite{Object
10805: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10806: 10(2), 1994.
10807:
10808: @menu
10809: * Properties of the OOF model::
10810: * Basic OOF Usage::
10811: * The OOF base class::
10812: * Class Declaration::
10813: * Class Implementation::
10814: @end menu
10815:
10816: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10817: @subsubsection Properties of the @file{oof.fs} model
10818: @cindex @file{oof.fs} properties
10819:
10820: @itemize @bullet
10821: @item
10822: This model combines object oriented programming with information
10823: hiding. It helps you writing large application, where scoping is
10824: necessary, because it provides class-oriented scoping.
10825:
10826: @item
10827: Named objects, object pointers, and object arrays can be created,
10828: selector invocation uses the ``object selector'' syntax. Selector invocation
10829: to objects and/or selectors on the stack is a bit less convenient, but
10830: possible.
10831:
10832: @item
10833: Selector invocation and instance variable usage of the active object is
10834: straightforward, since both make use of the active object.
10835:
10836: @item
10837: Late binding is efficient and easy to use.
10838:
10839: @item
10840: State-smart objects parse selectors. However, extensibility is provided
10841: using a (parsing) selector @code{postpone} and a selector @code{'}.
10842:
10843: @item
10844: An implementation in ANS Forth is available.
10845:
10846: @end itemize
10847:
10848:
10849: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10850: @subsubsection Basic @file{oof.fs} Usage
10851: @cindex @file{oof.fs} usage
10852:
10853: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
10854:
10855: You can define a class for graphical objects like this:
10856:
10857: @cindex @code{class} usage
10858: @cindex @code{class;} usage
10859: @cindex @code{method} usage
10860: @example
10861: object class graphical \ "object" is the parent class
10862: method draw ( x y -- )
10863: class;
10864: @end example
10865:
10866: This code defines a class @code{graphical} with an
10867: operation @code{draw}. We can perform the operation
10868: @code{draw} on any @code{graphical} object, e.g.:
10869:
10870: @example
10871: 100 100 t-rex draw
10872: @end example
10873:
10874: @noindent
10875: where @code{t-rex} is an object or object pointer, created with e.g.
10876: @code{graphical : t-rex}.
10877:
10878: @cindex abstract class
10879: How do we create a graphical object? With the present definitions,
10880: we cannot create a useful graphical object. The class
10881: @code{graphical} describes graphical objects in general, but not
10882: any concrete graphical object type (C++ users would call it an
10883: @emph{abstract class}); e.g., there is no method for the selector
10884: @code{draw} in the class @code{graphical}.
10885:
10886: For concrete graphical objects, we define child classes of the
10887: class @code{graphical}, e.g.:
10888:
10889: @example
10890: graphical class circle \ "graphical" is the parent class
10891: cell var circle-radius
10892: how:
10893: : draw ( x y -- )
10894: circle-radius @@ draw-circle ;
10895:
10896: : init ( n-radius -- )
10897: circle-radius ! ;
10898: class;
10899: @end example
10900:
10901: Here we define a class @code{circle} as a child of @code{graphical},
10902: with a field @code{circle-radius}; it defines new methods for the
10903: selectors @code{draw} and @code{init} (@code{init} is defined in
10904: @code{object}, the parent class of @code{graphical}).
10905:
10906: Now we can create a circle in the dictionary with:
10907:
10908: @example
10909: 50 circle : my-circle
10910: @end example
10911:
10912: @noindent
10913: @code{:} invokes @code{init}, thus initializing the field
10914: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10915: with:
10916:
10917: @example
10918: 100 100 my-circle draw
10919: @end example
10920:
10921: @cindex selector invocation, restrictions
10922: @cindex class definition, restrictions
10923: Note: You can only invoke a selector if the receiving object belongs to
10924: the class where the selector was defined or one of its descendents;
10925: e.g., you can invoke @code{draw} only for objects belonging to
10926: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10927: mechanism will check if you try to invoke a selector that is not
10928: defined in this class hierarchy, so you'll get an error at compilation
10929: time.
10930:
10931:
10932: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10933: @subsubsection The @file{oof.fs} base class
10934: @cindex @file{oof.fs} base class
10935:
10936: When you define a class, you have to specify a parent class. So how do
10937: you start defining classes? There is one class available from the start:
10938: @code{object}. You have to use it as ancestor for all classes. It is the
10939: only class that has no parent. Classes are also objects, except that
10940: they don't have instance variables; class manipulation such as
10941: inheritance or changing definitions of a class is handled through
10942: selectors of the class @code{object}.
10943:
10944: @code{object} provides a number of selectors:
10945:
10946: @itemize @bullet
10947: @item
10948: @code{class} for subclassing, @code{definitions} to add definitions
10949: later on, and @code{class?} to get type informations (is the class a
10950: subclass of the class passed on the stack?).
10951:
10952: doc---object-class
10953: doc---object-definitions
10954: doc---object-class?
10955:
10956:
10957: @item
10958: @code{init} and @code{dispose} as constructor and destructor of the
10959: object. @code{init} is invocated after the object's memory is allocated,
10960: while @code{dispose} also handles deallocation. Thus if you redefine
10961: @code{dispose}, you have to call the parent's dispose with @code{super
10962: dispose}, too.
10963:
10964: doc---object-init
10965: doc---object-dispose
10966:
10967:
10968: @item
10969: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10970: @code{[]} to create named and unnamed objects and object arrays or
10971: object pointers.
10972:
10973: doc---object-new
10974: doc---object-new[]
10975: doc---object-:
10976: doc---object-ptr
10977: doc---object-asptr
10978: doc---object-[]
10979:
10980:
10981: @item
10982: @code{::} and @code{super} for explicit scoping. You should use explicit
10983: scoping only for super classes or classes with the same set of instance
10984: variables. Explicitly-scoped selectors use early binding.
10985:
10986: doc---object-::
10987: doc---object-super
10988:
10989:
10990: @item
10991: @code{self} to get the address of the object
10992:
10993: doc---object-self
10994:
10995:
10996: @item
10997: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10998: pointers and instance defers.
10999:
11000: doc---object-bind
11001: doc---object-bound
11002: doc---object-link
11003: doc---object-is
11004:
11005:
11006: @item
11007: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11008: form the stack, and @code{postpone} to generate selector invocation code.
11009:
11010: doc---object-'
11011: doc---object-postpone
11012:
11013:
11014: @item
11015: @code{with} and @code{endwith} to select the active object from the
11016: stack, and enable its scope. Using @code{with} and @code{endwith}
11017: also allows you to create code using selector @code{postpone} without being
11018: trapped by the state-smart objects.
11019:
11020: doc---object-with
11021: doc---object-endwith
11022:
11023:
11024: @end itemize
11025:
11026: @node Class Declaration, Class Implementation, The OOF base class, OOF
11027: @subsubsection Class Declaration
11028: @cindex class declaration
11029:
11030: @itemize @bullet
11031: @item
11032: Instance variables
11033:
11034: doc---oof-var
11035:
11036:
11037: @item
11038: Object pointers
11039:
11040: doc---oof-ptr
11041: doc---oof-asptr
11042:
11043:
11044: @item
11045: Instance defers
11046:
11047: doc---oof-defer
11048:
11049:
11050: @item
11051: Method selectors
11052:
11053: doc---oof-early
11054: doc---oof-method
11055:
11056:
11057: @item
11058: Class-wide variables
11059:
11060: doc---oof-static
11061:
11062:
11063: @item
11064: End declaration
11065:
11066: doc---oof-how:
11067: doc---oof-class;
11068:
11069:
11070: @end itemize
11071:
11072: @c -------------------------------------------------------------
11073: @node Class Implementation, , Class Declaration, OOF
11074: @subsubsection Class Implementation
11075: @cindex class implementation
11076:
11077: @c -------------------------------------------------------------
11078: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11079: @subsection The @file{mini-oof.fs} model
11080: @cindex mini-oof
11081:
11082: Gforth's third object oriented Forth package is a 12-liner. It uses a
11083: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
11084: and reduces to the bare minimum of features. This is based on a posting
11085: of Bernd Paysan in comp.lang.forth.
11086:
11087: @menu
11088: * Basic Mini-OOF Usage::
11089: * Mini-OOF Example::
11090: * Mini-OOF Implementation::
11091: @end menu
11092:
11093: @c -------------------------------------------------------------
11094: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11095: @subsubsection Basic @file{mini-oof.fs} Usage
11096: @cindex mini-oof usage
11097:
11098: There is a base class (@code{class}, which allocates one cell for the
11099: object pointer) plus seven other words: to define a method, a variable,
11100: a class; to end a class, to resolve binding, to allocate an object and
11101: to compile a class method.
11102: @comment TODO better description of the last one
11103:
11104:
11105: doc-object
11106: doc-method
11107: doc-var
11108: doc-class
11109: doc-end-class
11110: doc-defines
11111: doc-new
11112: doc-::
11113:
11114:
11115:
11116: @c -------------------------------------------------------------
11117: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11118: @subsubsection Mini-OOF Example
11119: @cindex mini-oof example
11120:
11121: A short example shows how to use this package. This example, in slightly
11122: extended form, is supplied as @file{moof-exm.fs}
11123: @comment TODO could flesh this out with some comments from the Forthwrite article
11124:
11125: @example
11126: object class
11127: method init
11128: method draw
11129: end-class graphical
11130: @end example
11131:
11132: This code defines a class @code{graphical} with an
11133: operation @code{draw}. We can perform the operation
11134: @code{draw} on any @code{graphical} object, e.g.:
11135:
11136: @example
11137: 100 100 t-rex draw
11138: @end example
11139:
11140: where @code{t-rex} is an object or object pointer, created with e.g.
11141: @code{graphical new Constant t-rex}.
11142:
11143: For concrete graphical objects, we define child classes of the
11144: class @code{graphical}, e.g.:
11145:
11146: @example
11147: graphical class
11148: cell var circle-radius
11149: end-class circle \ "graphical" is the parent class
11150:
11151: :noname ( x y -- )
11152: circle-radius @@ draw-circle ; circle defines draw
11153: :noname ( r -- )
11154: circle-radius ! ; circle defines init
11155: @end example
11156:
11157: There is no implicit init method, so we have to define one. The creation
11158: code of the object now has to call init explicitely.
11159:
11160: @example
11161: circle new Constant my-circle
11162: 50 my-circle init
11163: @end example
11164:
11165: It is also possible to add a function to create named objects with
11166: automatic call of @code{init}, given that all objects have @code{init}
11167: on the same place:
11168:
11169: @example
11170: : new: ( .. o "name" -- )
11171: new dup Constant init ;
11172: 80 circle new: large-circle
11173: @end example
11174:
11175: We can draw this new circle at (100,100) with:
11176:
11177: @example
11178: 100 100 my-circle draw
11179: @end example
11180:
11181: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11182: @subsubsection @file{mini-oof.fs} Implementation
11183:
11184: Object-oriented systems with late binding typically use a
11185: ``vtable''-approach: the first variable in each object is a pointer to a
11186: table, which contains the methods as function pointers. The vtable
11187: may also contain other information.
11188:
11189: So first, let's declare selectors:
11190:
11191: @example
11192: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
11193: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11194: @end example
11195:
11196: During selector declaration, the number of selectors and instance
11197: variables is on the stack (in address units). @code{method} creates one
11198: selector and increments the selector number. To execute a selector, it
11199: takes the object, fetches the vtable pointer, adds the offset, and
11200: executes the method @i{xt} stored there. Each selector takes the object
11201: it is invoked with as top of stack parameter; it passes the parameters
11202: (including the object) unchanged to the appropriate method which should
11203: consume that object.
11204:
11205: Now, we also have to declare instance variables
11206:
11207: @example
11208: : var ( m v size "name" -- m v' ) Create over , +
11209: DOES> ( o -- addr ) @@ + ;
11210: @end example
11211:
11212: As before, a word is created with the current offset. Instance
11213: variables can have different sizes (cells, floats, doubles, chars), so
11214: all we do is take the size and add it to the offset. If your machine
11215: has alignment restrictions, put the proper @code{aligned} or
11216: @code{faligned} before the variable, to adjust the variable
11217: offset. That's why it is on the top of stack.
11218:
11219: We need a starting point (the base object) and some syntactic sugar:
11220:
11221: @example
11222: Create object 1 cells , 2 cells ,
11223: : class ( class -- class selectors vars ) dup 2@@ ;
11224: @end example
11225:
11226: For inheritance, the vtable of the parent object has to be
11227: copied when a new, derived class is declared. This gives all the
11228: methods of the parent class, which can be overridden, though.
11229:
11230: @example
11231: : end-class ( class selectors vars "name" -- )
11232: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11233: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11234: @end example
11235:
11236: The first line creates the vtable, initialized with
11237: @code{noop}s. The second line is the inheritance mechanism, it
11238: copies the xts from the parent vtable.
11239:
11240: We still have no way to define new methods, let's do that now:
11241:
11242: @example
11243: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11244: @end example
11245:
11246: To allocate a new object, we need a word, too:
11247:
11248: @example
11249: : new ( class -- o ) here over @@ allot swap over ! ;
11250: @end example
11251:
11252: Sometimes derived classes want to access the method of the
11253: parent object. There are two ways to achieve this with Mini-OOF:
11254: first, you could use named words, and second, you could look up the
11255: vtable of the parent object.
11256:
11257: @example
11258: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11259: @end example
11260:
11261:
11262: Nothing can be more confusing than a good example, so here is
11263: one. First let's declare a text object (called
11264: @code{button}), that stores text and position:
11265:
11266: @example
11267: object class
11268: cell var text
11269: cell var len
11270: cell var x
11271: cell var y
11272: method init
11273: method draw
11274: end-class button
11275: @end example
11276:
11277: @noindent
11278: Now, implement the two methods, @code{draw} and @code{init}:
11279:
11280: @example
11281: :noname ( o -- )
11282: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11283: button defines draw
11284: :noname ( addr u o -- )
11285: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11286: button defines init
11287: @end example
11288:
11289: @noindent
11290: To demonstrate inheritance, we define a class @code{bold-button}, with no
11291: new data and no new selectors:
11292:
11293: @example
11294: button class
11295: end-class bold-button
11296:
11297: : bold 27 emit ." [1m" ;
11298: : normal 27 emit ." [0m" ;
11299: @end example
11300:
11301: @noindent
11302: The class @code{bold-button} has a different draw method to
11303: @code{button}, but the new method is defined in terms of the draw method
11304: for @code{button}:
11305:
11306: @example
11307: :noname bold [ button :: draw ] normal ; bold-button defines draw
11308: @end example
11309:
11310: @noindent
11311: Finally, create two objects and apply selectors:
11312:
11313: @example
11314: button new Constant foo
11315: s" thin foo" foo init
11316: page
11317: foo draw
11318: bold-button new Constant bar
11319: s" fat bar" bar init
11320: 1 bar y !
11321: bar draw
11322: @end example
11323:
11324:
11325: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11326: @subsection Comparison with other object models
11327: @cindex comparison of object models
11328: @cindex object models, comparison
11329:
11330: Many object-oriented Forth extensions have been proposed (@cite{A survey
11331: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11332: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11333: relation of the object models described here to two well-known and two
11334: closely-related (by the use of method maps) models. Andras Zsoter
11335: helped us with this section.
11336:
11337: @cindex Neon model
11338: The most popular model currently seems to be the Neon model (see
11339: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11340: 1997) by Andrew McKewan) but this model has a number of limitations
11341: @footnote{A longer version of this critique can be
11342: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11343: Dimensions, May 1997) by Anton Ertl.}:
11344:
11345: @itemize @bullet
11346: @item
11347: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11348: to pass objects on the stack.
11349:
11350: @item
11351: It requires that the selector parses the input stream (at
11352: compile time); this leads to reduced extensibility and to bugs that are
11353: hard to find.
11354:
11355: @item
11356: It allows using every selector on every object; this eliminates the
11357: need for interfaces, but makes it harder to create efficient
11358: implementations.
11359: @end itemize
11360:
11361: @cindex Pountain's object-oriented model
11362: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11363: Press, London, 1987) by Dick Pountain. However, it is not really about
11364: object-oriented programming, because it hardly deals with late
11365: binding. Instead, it focuses on features like information hiding and
11366: overloading that are characteristic of modular languages like Ada (83).
11367:
11368: @cindex Zsoter's object-oriented model
11369: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11370: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11371: describes a model that makes heavy use of an active object (like
11372: @code{this} in @file{objects.fs}): The active object is not only used
11373: for accessing all fields, but also specifies the receiving object of
11374: every selector invocation; you have to change the active object
11375: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11376: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11377: the method entry point is unnecessary with Zsoter's model, because the
11378: receiving object is the active object already. On the other hand, the
11379: explicit change is absolutely necessary in that model, because otherwise
11380: no one could ever change the active object. An ANS Forth implementation
11381: of this model is available through
11382: @uref{http://www.forth.org/oopf.html}.
11383:
11384: @cindex @file{oof.fs}, differences to other models
11385: The @file{oof.fs} model combines information hiding and overloading
11386: resolution (by keeping names in various word lists) with object-oriented
11387: programming. It sets the active object implicitly on method entry, but
11388: also allows explicit changing (with @code{>o...o>} or with
11389: @code{with...endwith}). It uses parsing and state-smart objects and
11390: classes for resolving overloading and for early binding: the object or
11391: class parses the selector and determines the method from this. If the
11392: selector is not parsed by an object or class, it performs a call to the
11393: selector for the active object (late binding), like Zsoter's model.
11394: Fields are always accessed through the active object. The big
11395: disadvantage of this model is the parsing and the state-smartness, which
11396: reduces extensibility and increases the opportunities for subtle bugs;
11397: essentially, you are only safe if you never tick or @code{postpone} an
11398: object or class (Bernd disagrees, but I (Anton) am not convinced).
11399:
11400: @cindex @file{mini-oof.fs}, differences to other models
11401: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11402: version of the @file{objects.fs} model, but syntactically it is a
11403: mixture of the @file{objects.fs} and @file{oof.fs} models.
11404:
11405:
11406: @c -------------------------------------------------------------
11407: @node Programming Tools, C Interface, Object-oriented Forth, Words
11408: @section Programming Tools
11409: @cindex programming tools
11410:
11411: @c !! move this and assembler down below OO stuff.
11412:
11413: @menu
11414: * Examining:: Data and Code.
11415: * Forgetting words:: Usually before reloading.
11416: * Debugging:: Simple and quick.
11417: * Assertions:: Making your programs self-checking.
11418: * Singlestep Debugger:: Executing your program word by word.
11419: @end menu
11420:
11421: @node Examining, Forgetting words, Programming Tools, Programming Tools
11422: @subsection Examining data and code
11423: @cindex examining data and code
11424: @cindex data examination
11425: @cindex code examination
11426:
11427: The following words inspect the stack non-destructively:
11428:
11429: doc-.s
11430: doc-f.s
11431: doc-maxdepth-.s
11432:
11433: There is a word @code{.r} but it does @i{not} display the return stack!
11434: It is used for formatted numeric output (@pxref{Simple numeric output}).
11435:
11436: doc-depth
11437: doc-fdepth
11438: doc-clearstack
11439: doc-clearstacks
11440:
11441: The following words inspect memory.
11442:
11443: doc-?
11444: doc-dump
11445:
11446: And finally, @code{see} allows to inspect code:
11447:
11448: doc-see
11449: doc-xt-see
11450: doc-simple-see
11451: doc-simple-see-range
11452:
11453: @node Forgetting words, Debugging, Examining, Programming Tools
11454: @subsection Forgetting words
11455: @cindex words, forgetting
11456: @cindex forgeting words
11457:
11458: @c anton: other, maybe better places for this subsection: Defining Words;
11459: @c Dictionary allocation. At least a reference should be there.
11460:
11461: Forth allows you to forget words (and everything that was alloted in the
11462: dictonary after them) in a LIFO manner.
11463:
11464: doc-marker
11465:
11466: The most common use of this feature is during progam development: when
11467: you change a source file, forget all the words it defined and load it
11468: again (since you also forget everything defined after the source file
11469: was loaded, you have to reload that, too). Note that effects like
11470: storing to variables and destroyed system words are not undone when you
11471: forget words. With a system like Gforth, that is fast enough at
11472: starting up and compiling, I find it more convenient to exit and restart
11473: Gforth, as this gives me a clean slate.
11474:
11475: Here's an example of using @code{marker} at the start of a source file
11476: that you are debugging; it ensures that you only ever have one copy of
11477: the file's definitions compiled at any time:
11478:
11479: @example
11480: [IFDEF] my-code
11481: my-code
11482: [ENDIF]
11483:
11484: marker my-code
11485: init-included-files
11486:
11487: \ .. definitions start here
11488: \ .
11489: \ .
11490: \ end
11491: @end example
11492:
11493:
11494: @node Debugging, Assertions, Forgetting words, Programming Tools
11495: @subsection Debugging
11496: @cindex debugging
11497:
11498: Languages with a slow edit/compile/link/test development loop tend to
11499: require sophisticated tracing/stepping debuggers to facilate debugging.
11500:
11501: A much better (faster) way in fast-compiling languages is to add
11502: printing code at well-selected places, let the program run, look at
11503: the output, see where things went wrong, add more printing code, etc.,
11504: until the bug is found.
11505:
11506: The simple debugging aids provided in @file{debugs.fs}
11507: are meant to support this style of debugging.
11508:
11509: The word @code{~~} prints debugging information (by default the source
11510: location and the stack contents). It is easy to insert. If you use Emacs
11511: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11512: query-replace them with nothing). The deferred words
11513: @code{printdebugdata} and @code{.debugline} control the output of
11514: @code{~~}. The default source location output format works well with
11515: Emacs' compilation mode, so you can step through the program at the
11516: source level using @kbd{C-x `} (the advantage over a stepping debugger
11517: is that you can step in any direction and you know where the crash has
11518: happened or where the strange data has occurred).
11519:
11520: doc-~~
11521: doc-printdebugdata
11522: doc-.debugline
11523:
11524: @cindex filenames in @code{~~} output
11525: @code{~~} (and assertions) will usually print the wrong file name if a
11526: marker is executed in the same file after their occurance. They will
11527: print @samp{*somewhere*} as file name if a marker is executed in the
11528: same file before their occurance.
11529:
11530:
11531: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11532: @subsection Assertions
11533: @cindex assertions
11534:
11535: It is a good idea to make your programs self-checking, especially if you
11536: make an assumption that may become invalid during maintenance (for
11537: example, that a certain field of a data structure is never zero). Gforth
11538: supports @dfn{assertions} for this purpose. They are used like this:
11539:
11540: @example
11541: assert( @i{flag} )
11542: @end example
11543:
11544: The code between @code{assert(} and @code{)} should compute a flag, that
11545: should be true if everything is alright and false otherwise. It should
11546: not change anything else on the stack. The overall stack effect of the
11547: assertion is @code{( -- )}. E.g.
11548:
11549: @example
11550: assert( 1 1 + 2 = ) \ what we learn in school
11551: assert( dup 0<> ) \ assert that the top of stack is not zero
11552: assert( false ) \ this code should not be reached
11553: @end example
11554:
11555: The need for assertions is different at different times. During
11556: debugging, we want more checking, in production we sometimes care more
11557: for speed. Therefore, assertions can be turned off, i.e., the assertion
11558: becomes a comment. Depending on the importance of an assertion and the
11559: time it takes to check it, you may want to turn off some assertions and
11560: keep others turned on. Gforth provides several levels of assertions for
11561: this purpose:
11562:
11563:
11564: doc-assert0(
11565: doc-assert1(
11566: doc-assert2(
11567: doc-assert3(
11568: doc-assert(
11569: doc-)
11570:
11571:
11572: The variable @code{assert-level} specifies the highest assertions that
11573: are turned on. I.e., at the default @code{assert-level} of one,
11574: @code{assert0(} and @code{assert1(} assertions perform checking, while
11575: @code{assert2(} and @code{assert3(} assertions are treated as comments.
11576:
11577: The value of @code{assert-level} is evaluated at compile-time, not at
11578: run-time. Therefore you cannot turn assertions on or off at run-time;
11579: you have to set the @code{assert-level} appropriately before compiling a
11580: piece of code. You can compile different pieces of code at different
11581: @code{assert-level}s (e.g., a trusted library at level 1 and
11582: newly-written code at level 3).
11583:
11584:
11585: doc-assert-level
11586:
11587:
11588: If an assertion fails, a message compatible with Emacs' compilation mode
11589: is produced and the execution is aborted (currently with @code{ABORT"}.
11590: If there is interest, we will introduce a special throw code. But if you
11591: intend to @code{catch} a specific condition, using @code{throw} is
11592: probably more appropriate than an assertion).
11593:
11594: @cindex filenames in assertion output
11595: Assertions (and @code{~~}) will usually print the wrong file name if a
11596: marker is executed in the same file after their occurance. They will
11597: print @samp{*somewhere*} as file name if a marker is executed in the
11598: same file before their occurance.
11599:
11600: Definitions in ANS Forth for these assertion words are provided
11601: in @file{compat/assert.fs}.
11602:
11603:
11604: @node Singlestep Debugger, , Assertions, Programming Tools
11605: @subsection Singlestep Debugger
11606: @cindex singlestep Debugger
11607: @cindex debugging Singlestep
11608:
11609: The singlestep debugger works only with the engine @code{gforth-ditc}.
11610:
11611: When you create a new word there's often the need to check whether it
11612: behaves correctly or not. You can do this by typing @code{dbg
11613: badword}. A debug session might look like this:
11614:
11615: @example
11616: : badword 0 DO i . LOOP ; ok
11617: 2 dbg badword
11618: : badword
11619: Scanning code...
11620:
11621: Nesting debugger ready!
11622:
11623: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11624: 400D4740 8049F68 DO -> [ 0 ]
11625: 400D4744 804A0C8 i -> [ 1 ] 00000
11626: 400D4748 400C5E60 . -> 0 [ 0 ]
11627: 400D474C 8049D0C LOOP -> [ 0 ]
11628: 400D4744 804A0C8 i -> [ 1 ] 00001
11629: 400D4748 400C5E60 . -> 1 [ 0 ]
11630: 400D474C 8049D0C LOOP -> [ 0 ]
11631: 400D4758 804B384 ; -> ok
11632: @end example
11633:
11634: Each line displayed is one step. You always have to hit return to
11635: execute the next word that is displayed. If you don't want to execute
11636: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11637: an overview what keys are available:
11638:
11639: @table @i
11640:
11641: @item @key{RET}
11642: Next; Execute the next word.
11643:
11644: @item n
11645: Nest; Single step through next word.
11646:
11647: @item u
11648: Unnest; Stop debugging and execute rest of word. If we got to this word
11649: with nest, continue debugging with the calling word.
11650:
11651: @item d
11652: Done; Stop debugging and execute rest.
11653:
11654: @item s
11655: Stop; Abort immediately.
11656:
11657: @end table
11658:
11659: Debugging large application with this mechanism is very difficult, because
11660: you have to nest very deeply into the program before the interesting part
11661: begins. This takes a lot of time.
11662:
11663: To do it more directly put a @code{BREAK:} command into your source code.
11664: When program execution reaches @code{BREAK:} the single step debugger is
11665: invoked and you have all the features described above.
11666:
11667: If you have more than one part to debug it is useful to know where the
11668: program has stopped at the moment. You can do this by the
11669: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11670: string is typed out when the ``breakpoint'' is reached.
11671:
11672:
11673: doc-dbg
11674: doc-break:
11675: doc-break"
11676:
11677: @c ------------------------------------------------------------
11678: @node C Interface, Assembler and Code Words, Programming Tools, Words
11679: @section C Interface
11680: @cindex C interface
11681: @cindex foreign language interface
11682: @cindex interface to C functions
11683:
11684: Note that the C interface is not yet complete; a better way of
11685: declaring C functions is planned, as well as a way of declaring
11686: structs, unions, and their fields.
11687:
11688: @menu
11689: * Calling C Functions::
11690: * Declaring C Functions::
11691: * Callbacks::
11692: * Low-Level C Interface Words::
11693: @end menu
11694:
11695: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
11696: @subsection Calling C functions
11697: @cindex C functions, calls to
11698: @cindex calling C functions
11699:
11700: Once a C function is declared (see @pxref{Declaring C Functions}), you
11701: can call it as follows: You push the arguments on the stack(s), and
11702: then call the word for the C function. The arguments have to be
11703: pushed in the same order as the arguments appear in the C
11704: documentation (i.e., the first argument is deepest on the stack).
11705: Integer and pointer arguments have to be pushed on the data stack,
11706: floating-point arguments on the FP stack; these arguments are consumed
11707: by the called C function.
11708:
11709: On returning from the C function, the return value, if any, resides on
11710: the appropriate stack: an integer return value is pushed on the data
11711: stack, an FP return value on the FP stack, and a void return value
11712: results in not pushing anything. Note that most C functions have a
11713: return value, even if that is often not used in C; in Forth, you have
11714: to @code{drop} this return value explicitly if you do not use it.
11715:
11716: By default, an integer argument or return value corresponds to a
11717: single cell, and a floating-point argument or return value corresponds
11718: to a Forth float value; the C interface performs the appropriate
11719: conversions where necessary, on a best-effort basis (in some cases,
11720: there may be some loss).
11721:
11722: As an example, consider the POSIX function @code{lseek()}:
11723:
11724: @example
11725: off_t lseek(int fd, off_t offset, int whence);
11726: @end example
11727:
11728: This function takes three integer arguments, and returns an integer
11729: argument, so a Forth call for setting the current file offset to the
11730: start of the file could look like this:
11731:
11732: @example
11733: fd @@ 0 SEEK_SET lseek -1 = if
11734: ... \ error handling
11735: then
11736: @end example
11737:
11738: You might be worried that an @code{off_t} does not fit into a cell, so
11739: you could not pass larger offsets to lseek, and might get only a part
11740: of the return values. In that case, in your declaration of the
11741: function (@pxref{Declaring C Functions}) you should declare it to use
11742: double-cells for the off_t argument and return value, and maybe give
11743: the resulting Forth word a different name, like @code{dlseek}; the
11744: result could be called like this:
11745:
11746: @example
11747: fd @@ 0. SEEK_SET dlseek -1. d= if
11748: ... \ error handling
11749: then
11750: @end example
11751:
11752: Passing and returning structs or unions is currently not supported by
11753: our interface@footnote{If you know the calling convention of your C
11754: compiler, you usually can call such functions in some way, but that
11755: way is usually not portable between platforms, and sometimes not even
11756: between C compilers.}.
11757:
11758: Calling functions with a variable number of arguments (e.g.,
11759: @code{printf()}) is currently only supported by having you declare one
11760: function-calling word for each argument pattern, and calling the
11761: appropriate word for the desired pattern.
11762:
11763:
11764: @node Declaring C Functions, Callbacks, Calling C Functions, C Interface
11765: @subsection Declaring C Functions
11766: @cindex C functions, declarations
11767: @cindex declaring C functions
11768:
11769: Before you can call @code{lseek} or @code{dlseek}, you have to declare
11770: it. You have to look up in your system what the concrete type for the
11771: abstract type @code{off_t} is; let's assume it is @code{long}. Then
11772: the declarations for these words are:
11773:
11774: @example
11775: library libc libc.so.6
11776: libc lseek int long int (long) lseek ( fd noffset whence -- noffset2 )
11777: libc dlseek int dlong int (dlong) lseek ( fd doffset whence -- doffset2 )
11778: @end example
11779:
11780: The first line defines a Forth word @code{libc} for accessing the C
11781: functions in the shared library @file{libc.so.6} (the name of the
11782: shared library depends on the library and the OS; this example is the
11783: standard C library (containing most of the standard C and Unix
11784: functions) for GNU/Linux systems since about 1998).
11785:
11786: The next two lines define two Forth words for the same C function
11787: @code{lseek()}; the middle line defines @code{lseek ( n1 n2 n3 -- n
11788: )}, and the last line defines @code{dlseek ( n1 d2 n3 -- d )}.
11789:
11790: As you can see, the declarations are relatively platform-dependent
11791: (e.g., on one platform @code{off_t} may be a @code{long}, whereas on
11792: another platform it may be a @code{long long}; actually, in this case
11793: you can have this difference even on the same platform), while the
11794: resulting function-calling words are platform-independent, and calls
11795: to them are portable.
11796:
11797: At some point in the future this interface will be superseded by a
11798: more convenient one with fewer portability issues. But the resulting
11799: words for calling the C function will still have the same interface,
11800: so you will not need to change the calls.
11801:
11802: Anyway, here are the words for the current interface:
11803:
11804: doc-library
11805: doc-int
11806: doc-dint
11807: doc-uint
11808: doc-udint
11809: doc-long
11810: doc-dlong
11811: doc-ulong
11812: doc-udlong
11813: doc-longlong
11814: doc-dlonglong
11815: doc-ulonglong
11816: doc-udlonglong
11817: doc-ptr
11818: doc-cfloat
11819: doc-cdouble
11820: doc-clongdouble
11821: doc-(int)
11822: doc-(dint)
11823: doc-(uint)
11824: doc-(udint)
11825: doc-(long)
11826: doc-(dlong)
11827: doc-(ulong)
11828: doc-(udlong)
11829: doc-(longlong)
11830: doc-(dlonglong)
11831: doc-(ulonglong)
11832: doc-(udlonglong)
11833: doc-(ptr)
11834: doc-(cfloat)
11835: doc-(cdouble)
11836: doc-(clongdouble)
11837:
11838:
11839: @node Callbacks, Low-Level C Interface Words, Declaring C Functions, C Interface
11840: @subsection Callbacks
11841: @cindex Callback functions written in Forth
11842: @cindex C function pointers to Forth words
11843:
11844: In some cases you have to pass a function pointer to a C function,
11845: i.e., the library wants to call back to your application (and the
11846: pointed-to function is called a callback function). You can pass the
11847: address of an existing C function (that you get with @code{lib-sym},
11848: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
11849: function, you probably want to define the function as a Forth word.
11850:
11851: !!!
11852: @c I don't understand the existing callback interface from the example - anton
11853:
11854: doc-callback
11855: doc-callback;
11856: doc-fptr
11857:
11858: @node Low-Level C Interface Words, , Callbacks, C Interface
11859: @subsection Low-Level C Interface Words
11860:
11861: doc-open-lib
11862: doc-lib-sym
11863:
11864: @c -------------------------------------------------------------
11865: @node Assembler and Code Words, Threading Words, C Interface, Words
11866: @section Assembler and Code Words
11867: @cindex assembler
11868: @cindex code words
11869:
11870: @menu
11871: * Code and ;code::
11872: * Common Assembler:: Assembler Syntax
11873: * Common Disassembler::
11874: * 386 Assembler:: Deviations and special cases
11875: * Alpha Assembler:: Deviations and special cases
11876: * MIPS assembler:: Deviations and special cases
11877: * Other assemblers:: How to write them
11878: @end menu
11879:
11880: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11881: @subsection @code{Code} and @code{;code}
11882:
11883: Gforth provides some words for defining primitives (words written in
11884: machine code), and for defining the machine-code equivalent of
11885: @code{DOES>}-based defining words. However, the machine-independent
11886: nature of Gforth poses a few problems: First of all, Gforth runs on
11887: several architectures, so it can provide no standard assembler. What's
11888: worse is that the register allocation not only depends on the processor,
11889: but also on the @code{gcc} version and options used.
11890:
11891: The words that Gforth offers encapsulate some system dependences (e.g.,
11892: the header structure), so a system-independent assembler may be used in
11893: Gforth. If you do not have an assembler, you can compile machine code
11894: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11895: because these words emit stuff in @i{data} space; it works because
11896: Gforth has unified code/data spaces. Assembler isn't likely to be
11897: portable anyway.}.
11898:
11899:
11900: doc-assembler
11901: doc-init-asm
11902: doc-code
11903: doc-end-code
11904: doc-;code
11905: doc-flush-icache
11906:
11907:
11908: If @code{flush-icache} does not work correctly, @code{code} words
11909: etc. will not work (reliably), either.
11910:
11911: The typical usage of these @code{code} words can be shown most easily by
11912: analogy to the equivalent high-level defining words:
11913:
11914: @example
11915: : foo code foo
11916: <high-level Forth words> <assembler>
11917: ; end-code
11918:
11919: : bar : bar
11920: <high-level Forth words> <high-level Forth words>
11921: CREATE CREATE
11922: <high-level Forth words> <high-level Forth words>
11923: DOES> ;code
11924: <high-level Forth words> <assembler>
11925: ; end-code
11926: @end example
11927:
11928: @c anton: the following stuff is also in "Common Assembler", in less detail.
11929:
11930: @cindex registers of the inner interpreter
11931: In the assembly code you will want to refer to the inner interpreter's
11932: registers (e.g., the data stack pointer) and you may want to use other
11933: registers for temporary storage. Unfortunately, the register allocation
11934: is installation-dependent.
11935:
11936: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
11937: (return stack pointer) may be in different places in @code{gforth} and
11938: @code{gforth-fast}, or different installations. This means that you
11939: cannot write a @code{NEXT} routine that works reliably on both versions
11940: or different installations; so for doing @code{NEXT}, I recommend
11941: jumping to @code{' noop >code-address}, which contains nothing but a
11942: @code{NEXT}.
11943:
11944: For general accesses to the inner interpreter's registers, the easiest
11945: solution is to use explicit register declarations (@pxref{Explicit Reg
11946: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11947: all of the inner interpreter's registers: You have to compile Gforth
11948: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11949: the appropriate declarations must be present in the @code{machine.h}
11950: file (see @code{mips.h} for an example; you can find a full list of all
11951: declarable register symbols with @code{grep register engine.c}). If you
11952: give explicit registers to all variables that are declared at the
11953: beginning of @code{engine()}, you should be able to use the other
11954: caller-saved registers for temporary storage. Alternatively, you can use
11955: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11956: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11957: reserve a register (however, this restriction on register allocation may
11958: slow Gforth significantly).
11959:
11960: If this solution is not viable (e.g., because @code{gcc} does not allow
11961: you to explicitly declare all the registers you need), you have to find
11962: out by looking at the code where the inner interpreter's registers
11963: reside and which registers can be used for temporary storage. You can
11964: get an assembly listing of the engine's code with @code{make engine.s}.
11965:
11966: In any case, it is good practice to abstract your assembly code from the
11967: actual register allocation. E.g., if the data stack pointer resides in
11968: register @code{$17}, create an alias for this register called @code{sp},
11969: and use that in your assembly code.
11970:
11971: @cindex code words, portable
11972: Another option for implementing normal and defining words efficiently
11973: is to add the desired functionality to the source of Gforth. For normal
11974: words you just have to edit @file{primitives} (@pxref{Automatic
11975: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11976: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11977: @file{prims2x.fs}, and possibly @file{cross.fs}.
11978:
11979: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11980: @subsection Common Assembler
11981:
11982: The assemblers in Gforth generally use a postfix syntax, i.e., the
11983: instruction name follows the operands.
11984:
11985: The operands are passed in the usual order (the same that is used in the
11986: manual of the architecture). Since they all are Forth words, they have
11987: to be separated by spaces; you can also use Forth words to compute the
11988: operands.
11989:
11990: The instruction names usually end with a @code{,}. This makes it easier
11991: to visually separate instructions if you put several of them on one
11992: line; it also avoids shadowing other Forth words (e.g., @code{and}).
11993:
11994: Registers are usually specified by number; e.g., (decimal) @code{11}
11995: specifies registers R11 and F11 on the Alpha architecture (which one,
11996: depends on the instruction). The usual names are also available, e.g.,
11997: @code{s2} for R11 on Alpha.
11998:
11999: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12000: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12001: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12002: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12003: conditions are specified in a way specific to each assembler.
12004:
12005: Note that the register assignments of the Gforth engine can change
12006: between Gforth versions, or even between different compilations of the
12007: same Gforth version (e.g., if you use a different GCC version). So if
12008: you want to refer to Gforth's registers (e.g., the stack pointer or
12009: TOS), I recommend defining your own words for refering to these
12010: registers, and using them later on; then you can easily adapt to a
12011: changed register assignment. The stability of the register assignment
12012: is usually better if you build Gforth with @code{--enable-force-reg}.
12013:
12014: The most common use of these registers is to dispatch to the next word
12015: (the @code{next} routine). A portable way to do this is to jump to
12016: @code{' noop >code-address} (of course, this is less efficient than
12017: integrating the @code{next} code and scheduling it well).
12018:
12019: Another difference between Gforth version is that the top of stack is
12020: kept in memory in @code{gforth} and, on most platforms, in a register in
12021: @code{gforth-fast}.
12022:
12023: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12024: @subsection Common Disassembler
12025: @cindex disassembler, general
12026: @cindex gdb disassembler
12027:
12028: You can disassemble a @code{code} word with @code{see}
12029: (@pxref{Debugging}). You can disassemble a section of memory with
12030:
12031: doc-discode
12032:
12033: There are two kinds of disassembler for Gforth: The Forth disassembler
12034: (available on some CPUs) and the gdb disassembler (available on
12035: platforms with @command{gdb} and @command{mktemp}). If both are
12036: available, the Forth disassembler is used by default. If you prefer
12037: the gdb disassembler, say
12038:
12039: @example
12040: ' disasm-gdb is discode
12041: @end example
12042:
12043: If neither is available, @code{discode} performs @code{dump}.
12044:
12045: The Forth disassembler generally produces output that can be fed into the
12046: assembler (i.e., same syntax, etc.). It also includes additional
12047: information in comments. In particular, the address of the instruction
12048: is given in a comment before the instruction.
12049:
12050: The gdb disassembler produces output in the same format as the gdb
12051: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12052: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12053: the 386 and AMD64 architectures).
12054:
12055: @code{See} may display more or less than the actual code of the word,
12056: because the recognition of the end of the code is unreliable. You can
12057: use @code{discode} if it did not display enough. It may display more, if
12058: the code word is not immediately followed by a named word. If you have
12059: something else there, you can follow the word with @code{align latest ,}
12060: to ensure that the end is recognized.
12061:
12062: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12063: @subsection 386 Assembler
12064:
12065: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12066: available under GPL, and originally part of bigFORTH.
12067:
12068: The 386 disassembler included in Gforth was written by Andrew McKewan
12069: and is in the public domain.
12070:
12071: The disassembler displays code in an Intel-like prefix syntax.
12072:
12073: The assembler uses a postfix syntax with reversed parameters.
12074:
12075: The assembler includes all instruction of the Athlon, i.e. 486 core
12076: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12077: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12078: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
12079:
12080: There are several prefixes to switch between different operation sizes,
12081: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12082: double-word accesses. Addressing modes can be switched with @code{.wa}
12083: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12084: need a prefix for byte register names (@code{AL} et al).
12085:
12086: For floating point operations, the prefixes are @code{.fs} (IEEE
12087: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12088: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
12089:
12090: The MMX opcodes don't have size prefixes, they are spelled out like in
12091: the Intel assembler. Instead of move from and to memory, there are
12092: PLDQ/PLDD and PSTQ/PSTD.
12093:
12094: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12095: ax. Immediate values are indicated by postfixing them with @code{#},
12096: e.g., @code{3 #}. Here are some examples of addressing modes in various
12097: syntaxes:
12098:
12099: @example
12100: Gforth Intel (NASM) AT&T (gas) Name
12101: .w ax ax %ax register (16 bit)
12102: ax eax %eax register (32 bit)
12103: 3 # offset 3 $3 immediate
12104: 1000 #) byte ptr 1000 1000 displacement
12105: bx ) [ebx] (%ebx) base
12106: 100 di d) 100[edi] 100(%edi) base+displacement
12107: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12108: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12109: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12110: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12111: @end example
12112:
12113: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12114: @code{DI)} to enforce 32-bit displacement fields (useful for
12115: later patching).
12116:
12117: Some example of instructions are:
12118:
12119: @example
12120: ax bx mov \ move ebx,eax
12121: 3 # ax mov \ mov eax,3
12122: 100 di d) ax mov \ mov eax,100[edi]
12123: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12124: .w ax bx mov \ mov bx,ax
12125: @end example
12126:
12127: The following forms are supported for binary instructions:
12128:
12129: @example
12130: <reg> <reg> <inst>
12131: <n> # <reg> <inst>
12132: <mem> <reg> <inst>
12133: <reg> <mem> <inst>
12134: <n> # <mem> <inst>
12135: @end example
12136:
12137: The shift/rotate syntax is:
12138:
12139: @example
12140: <reg/mem> 1 # shl \ shortens to shift without immediate
12141: <reg/mem> 4 # shl
12142: <reg/mem> cl shl
12143: @end example
12144:
12145: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12146: the byte version.
12147:
12148: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12149: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12150: pc < >= <= >}. (Note that most of these words shadow some Forth words
12151: when @code{assembler} is in front of @code{forth} in the search path,
12152: e.g., in @code{code} words). Currently the control structure words use
12153: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12154: to shuffle them (you can also use @code{swap} etc.).
12155:
12156: Here is an example of a @code{code} word (assumes that the stack pointer
12157: is in esi and the TOS is in ebx):
12158:
12159: @example
12160: code my+ ( n1 n2 -- n )
12161: 4 si D) bx add
12162: 4 # si add
12163: Next
12164: end-code
12165: @end example
12166:
12167: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12168: @subsection Alpha Assembler
12169:
12170: The Alpha assembler and disassembler were originally written by Bernd
12171: Thallner.
12172:
12173: The register names @code{a0}--@code{a5} are not available to avoid
12174: shadowing hex numbers.
12175:
12176: Immediate forms of arithmetic instructions are distinguished by a
12177: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12178: does not count as arithmetic instruction).
12179:
12180: You have to specify all operands to an instruction, even those that
12181: other assemblers consider optional, e.g., the destination register for
12182: @code{br,}, or the destination register and hint for @code{jmp,}.
12183:
12184: You can specify conditions for @code{if,} by removing the first @code{b}
12185: and the trailing @code{,} from a branch with a corresponding name; e.g.,
12186:
12187: @example
12188: 11 fgt if, \ if F11>0e
12189: ...
12190: endif,
12191: @end example
12192:
12193: @code{fbgt,} gives @code{fgt}.
12194:
12195: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
12196: @subsection MIPS assembler
12197:
12198: The MIPS assembler was originally written by Christian Pirker.
12199:
12200: Currently the assembler and disassembler only cover the MIPS-I
12201: architecture (R3000), and don't support FP instructions.
12202:
12203: The register names @code{$a0}--@code{$a3} are not available to avoid
12204: shadowing hex numbers.
12205:
12206: Because there is no way to distinguish registers from immediate values,
12207: you have to explicitly use the immediate forms of instructions, i.e.,
12208: @code{addiu,}, not just @code{addu,} (@command{as} does this
12209: implicitly).
12210:
12211: If the architecture manual specifies several formats for the instruction
12212: (e.g., for @code{jalr,}), you usually have to use the one with more
12213: arguments (i.e., two for @code{jalr,}). When in doubt, see
12214: @code{arch/mips/testasm.fs} for an example of correct use.
12215:
12216: Branches and jumps in the MIPS architecture have a delay slot. You have
12217: to fill it yourself (the simplest way is to use @code{nop,}), the
12218: assembler does not do it for you (unlike @command{as}). Even
12219: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12220: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12221: and @code{then,} just specify branch targets, they are not affected.
12222:
12223: Note that you must not put branches, jumps, or @code{li,} into the delay
12224: slot: @code{li,} may expand to several instructions, and control flow
12225: instructions may not be put into the branch delay slot in any case.
12226:
12227: For branches the argument specifying the target is a relative address;
12228: You have to add the address of the delay slot to get the absolute
12229: address.
12230:
12231: The MIPS architecture also has load delay slots and restrictions on
12232: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12233: yourself to satisfy these restrictions, the assembler does not do it for
12234: you.
12235:
12236: You can specify the conditions for @code{if,} etc. by taking a
12237: conditional branch and leaving away the @code{b} at the start and the
12238: @code{,} at the end. E.g.,
12239:
12240: @example
12241: 4 5 eq if,
12242: ... \ do something if $4 equals $5
12243: then,
12244: @end example
12245:
12246: @node Other assemblers, , MIPS assembler, Assembler and Code Words
12247: @subsection Other assemblers
12248:
12249: If you want to contribute another assembler/disassembler, please contact
12250: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12251: an assembler already. If you are writing them from scratch, please use
12252: a similar syntax style as the one we use (i.e., postfix, commas at the
12253: end of the instruction names, @pxref{Common Assembler}); make the output
12254: of the disassembler be valid input for the assembler, and keep the style
12255: similar to the style we used.
12256:
12257: Hints on implementation: The most important part is to have a good test
12258: suite that contains all instructions. Once you have that, the rest is
12259: easy. For actual coding you can take a look at
12260: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12261: the assembler and disassembler, avoiding redundancy and some potential
12262: bugs. You can also look at that file (and @pxref{Advanced does> usage
12263: example}) to get ideas how to factor a disassembler.
12264:
12265: Start with the disassembler, because it's easier to reuse data from the
12266: disassembler for the assembler than the other way round.
12267:
12268: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12269: how simple it can be.
12270:
12271: @c -------------------------------------------------------------
12272: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12273: @section Threading Words
12274: @cindex threading words
12275:
12276: @cindex code address
12277: These words provide access to code addresses and other threading stuff
12278: in Gforth (and, possibly, other interpretive Forths). It more or less
12279: abstracts away the differences between direct and indirect threading
12280: (and, for direct threading, the machine dependences). However, at
12281: present this wordset is still incomplete. It is also pretty low-level;
12282: some day it will hopefully be made unnecessary by an internals wordset
12283: that abstracts implementation details away completely.
12284:
12285: The terminology used here stems from indirect threaded Forth systems; in
12286: such a system, the XT of a word is represented by the CFA (code field
12287: address) of a word; the CFA points to a cell that contains the code
12288: address. The code address is the address of some machine code that
12289: performs the run-time action of invoking the word (e.g., the
12290: @code{dovar:} routine pushes the address of the body of the word (a
12291: variable) on the stack
12292: ).
12293:
12294: @cindex code address
12295: @cindex code field address
12296: In an indirect threaded Forth, you can get the code address of @i{name}
12297: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12298: >code-address}, independent of the threading method.
12299:
12300: doc-threading-method
12301: doc->code-address
12302: doc-code-address!
12303:
12304: @cindex @code{does>}-handler
12305: @cindex @code{does>}-code
12306: For a word defined with @code{DOES>}, the code address usually points to
12307: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12308: routine (in Gforth on some platforms, it can also point to the dodoes
12309: routine itself). What you are typically interested in, though, is
12310: whether a word is a @code{DOES>}-defined word, and what Forth code it
12311: executes; @code{>does-code} tells you that.
12312:
12313: doc->does-code
12314:
12315: To create a @code{DOES>}-defined word with the following basic words,
12316: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12317: @code{/does-handler} aus behind you have to place your executable Forth
12318: code. Finally you have to create a word and modify its behaviour with
12319: @code{does-handler!}.
12320:
12321: doc-does-code!
12322: doc-does-handler!
12323: doc-/does-handler
12324:
12325: The code addresses produced by various defining words are produced by
12326: the following words:
12327:
12328: doc-docol:
12329: doc-docon:
12330: doc-dovar:
12331: doc-douser:
12332: doc-dodefer:
12333: doc-dofield:
12334:
12335: @cindex definer
12336: The following two words generalize @code{>code-address},
12337: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12338:
12339: doc->definer
12340: doc-definer!
12341:
12342: @c -------------------------------------------------------------
12343: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
12344: @section Passing Commands to the Operating System
12345: @cindex operating system - passing commands
12346: @cindex shell commands
12347:
12348: Gforth allows you to pass an arbitrary string to the host operating
12349: system shell (if such a thing exists) for execution.
12350:
12351: doc-sh
12352: doc-system
12353: doc-$?
12354: doc-getenv
12355:
12356: @c -------------------------------------------------------------
12357: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12358: @section Keeping track of Time
12359: @cindex time-related words
12360:
12361: doc-ms
12362: doc-time&date
12363: doc-utime
12364: doc-cputime
12365:
12366:
12367: @c -------------------------------------------------------------
12368: @node Miscellaneous Words, , Keeping track of Time, Words
12369: @section Miscellaneous Words
12370: @cindex miscellaneous words
12371:
12372: @comment TODO find homes for these
12373:
12374: These section lists the ANS Forth words that are not documented
12375: elsewhere in this manual. Ultimately, they all need proper homes.
12376:
12377: doc-quit
12378:
12379: The following ANS Forth words are not currently supported by Gforth
12380: (@pxref{ANS conformance}):
12381:
12382: @code{EDITOR}
12383: @code{EMIT?}
12384: @code{FORGET}
12385:
12386: @c ******************************************************************
12387: @node Error messages, Tools, Words, Top
12388: @chapter Error messages
12389: @cindex error messages
12390: @cindex backtrace
12391:
12392: A typical Gforth error message looks like this:
12393:
12394: @example
12395: in file included from \evaluated string/:-1
12396: in file included from ./yyy.fs:1
12397: ./xxx.fs:4: Invalid memory address
12398: >>>bar<<<
12399: Backtrace:
12400: $400E664C @@
12401: $400E6664 foo
12402: @end example
12403:
12404: The message identifying the error is @code{Invalid memory address}. The
12405: error happened when text-interpreting line 4 of the file
12406: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12407: word on the line where the error happened, is pointed out (with
12408: @code{>>>} and @code{<<<}).
12409:
12410: The file containing the error was included in line 1 of @file{./yyy.fs},
12411: and @file{yyy.fs} was included from a non-file (in this case, by giving
12412: @file{yyy.fs} as command-line parameter to Gforth).
12413:
12414: At the end of the error message you find a return stack dump that can be
12415: interpreted as a backtrace (possibly empty). On top you find the top of
12416: the return stack when the @code{throw} happened, and at the bottom you
12417: find the return stack entry just above the return stack of the topmost
12418: text interpreter.
12419:
12420: To the right of most return stack entries you see a guess for the word
12421: that pushed that return stack entry as its return address. This gives a
12422: backtrace. In our case we see that @code{bar} called @code{foo}, and
12423: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12424: address} exception).
12425:
12426: Note that the backtrace is not perfect: We don't know which return stack
12427: entries are return addresses (so we may get false positives); and in
12428: some cases (e.g., for @code{abort"}) we cannot determine from the return
12429: address the word that pushed the return address, so for some return
12430: addresses you see no names in the return stack dump.
12431:
12432: @cindex @code{catch} and backtraces
12433: The return stack dump represents the return stack at the time when a
12434: specific @code{throw} was executed. In programs that make use of
12435: @code{catch}, it is not necessarily clear which @code{throw} should be
12436: used for the return stack dump (e.g., consider one @code{throw} that
12437: indicates an error, which is caught, and during recovery another error
12438: happens; which @code{throw} should be used for the stack dump?). Gforth
12439: presents the return stack dump for the first @code{throw} after the last
12440: executed (not returned-to) @code{catch}; this works well in the usual
12441: case.
12442:
12443: @cindex @code{gforth-fast} and backtraces
12444: @cindex @code{gforth-fast}, difference from @code{gforth}
12445: @cindex backtraces with @code{gforth-fast}
12446: @cindex return stack dump with @code{gforth-fast}
12447: @code{Gforth} is able to do a return stack dump for throws generated
12448: from primitives (e.g., invalid memory address, stack empty etc.);
12449: @code{gforth-fast} is only able to do a return stack dump from a
12450: directly called @code{throw} (including @code{abort} etc.). Given an
12451: exception caused by a primitive in @code{gforth-fast}, you will
12452: typically see no return stack dump at all; however, if the exception is
12453: caught by @code{catch} (e.g., for restoring some state), and then
12454: @code{throw}n again, the return stack dump will be for the first such
12455: @code{throw}.
12456:
12457: @c ******************************************************************
12458: @node Tools, ANS conformance, Error messages, Top
12459: @chapter Tools
12460:
12461: @menu
12462: * ANS Report:: Report the words used, sorted by wordset.
12463: * Stack depth changes:: Where does this stack item come from?
12464: @end menu
12465:
12466: See also @ref{Emacs and Gforth}.
12467:
12468: @node ANS Report, Stack depth changes, Tools, Tools
12469: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12470: @cindex @file{ans-report.fs}
12471: @cindex report the words used in your program
12472: @cindex words used in your program
12473:
12474: If you want to label a Forth program as ANS Forth Program, you must
12475: document which wordsets the program uses; for extension wordsets, it is
12476: helpful to list the words the program requires from these wordsets
12477: (because Forth systems are allowed to provide only some words of them).
12478:
12479: The @file{ans-report.fs} tool makes it easy for you to determine which
12480: words from which wordset and which non-ANS words your application
12481: uses. You simply have to include @file{ans-report.fs} before loading the
12482: program you want to check. After loading your program, you can get the
12483: report with @code{print-ans-report}. A typical use is to run this as
12484: batch job like this:
12485: @example
12486: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12487: @end example
12488:
12489: The output looks like this (for @file{compat/control.fs}):
12490: @example
12491: The program uses the following words
12492: from CORE :
12493: : POSTPONE THEN ; immediate ?dup IF 0=
12494: from BLOCK-EXT :
12495: \
12496: from FILE :
12497: (
12498: @end example
12499:
12500: @subsection Caveats
12501:
12502: Note that @file{ans-report.fs} just checks which words are used, not whether
12503: they are used in an ANS Forth conforming way!
12504:
12505: Some words are defined in several wordsets in the
12506: standard. @file{ans-report.fs} reports them for only one of the
12507: wordsets, and not necessarily the one you expect. It depends on usage
12508: which wordset is the right one to specify. E.g., if you only use the
12509: compilation semantics of @code{S"}, it is a Core word; if you also use
12510: its interpretation semantics, it is a File word.
12511:
12512:
12513: @node Stack depth changes, , ANS Report, Tools
12514: @section Stack depth changes during interpretation
12515: @cindex @file{depth-changes.fs}
12516: @cindex depth changes during interpretation
12517: @cindex stack depth changes during interpretation
12518: @cindex items on the stack after interpretation
12519:
12520: Sometimes you notice that, after loading a file, there are items left
12521: on the stack. The tool @file{depth-changes.fs} helps you find out
12522: quickly where in the file these stack items are coming from.
12523:
12524: The simplest way of using @file{depth-changes.fs} is to include it
12525: before the file(s) you want to check, e.g.:
12526:
12527: @example
12528: gforth depth-changes.fs my-file.fs
12529: @end example
12530:
12531: This will compare the stack depths of the data and FP stack at every
12532: empty line (in interpretation state) against these depths at the last
12533: empty line (in interpretation state). If the depths are not equal,
12534: the position in the file and the stack contents are printed with
12535: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
12536: change has occured in the paragraph of non-empty lines before the
12537: indicated line. It is a good idea to leave an empty line at the end
12538: of the file, so the last paragraph is checked, too.
12539:
12540: Checking only at empty lines usually works well, but sometimes you
12541: have big blocks of non-empty lines (e.g., when building a big table),
12542: and you want to know where in this block the stack depth changed. You
12543: can check all interpreted lines with
12544:
12545: @example
12546: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12547: @end example
12548:
12549: This checks the stack depth at every end-of-line. So the depth change
12550: occured in the line reported by the @code{~~} (not in the line
12551: before).
12552:
12553: Note that, while this offers better accuracy in indicating where the
12554: stack depth changes, it will often report many intentional stack depth
12555: changes (e.g., when an interpreted computation stretches across
12556: several lines). You can suppress the checking of some lines by
12557: putting backslashes at the end of these lines (not followed by white
12558: space), and using
12559:
12560: @example
12561: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12562: @end example
12563:
12564: @c ******************************************************************
12565: @node ANS conformance, Standard vs Extensions, Tools, Top
12566: @chapter ANS conformance
12567: @cindex ANS conformance of Gforth
12568:
12569: To the best of our knowledge, Gforth is an
12570:
12571: ANS Forth System
12572: @itemize @bullet
12573: @item providing the Core Extensions word set
12574: @item providing the Block word set
12575: @item providing the Block Extensions word set
12576: @item providing the Double-Number word set
12577: @item providing the Double-Number Extensions word set
12578: @item providing the Exception word set
12579: @item providing the Exception Extensions word set
12580: @item providing the Facility word set
12581: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
12582: @item providing the File Access word set
12583: @item providing the File Access Extensions word set
12584: @item providing the Floating-Point word set
12585: @item providing the Floating-Point Extensions word set
12586: @item providing the Locals word set
12587: @item providing the Locals Extensions word set
12588: @item providing the Memory-Allocation word set
12589: @item providing the Memory-Allocation Extensions word set (that one's easy)
12590: @item providing the Programming-Tools word set
12591: @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
12592: @item providing the Search-Order word set
12593: @item providing the Search-Order Extensions word set
12594: @item providing the String word set
12595: @item providing the String Extensions word set (another easy one)
12596: @end itemize
12597:
12598: Gforth has the following environmental restrictions:
12599:
12600: @cindex environmental restrictions
12601: @itemize @bullet
12602: @item
12603: While processing the OS command line, if an exception is not caught,
12604: Gforth exits with a non-zero exit code instyead of performing QUIT.
12605:
12606: @item
12607: When an @code{throw} is performed after a @code{query}, Gforth does not
12608: allways restore the input source specification in effect at the
12609: corresponding catch.
12610:
12611: @end itemize
12612:
12613:
12614: @cindex system documentation
12615: In addition, ANS Forth systems are required to document certain
12616: implementation choices. This chapter tries to meet these
12617: requirements. In many cases it gives a way to ask the system for the
12618: information instead of providing the information directly, in
12619: particular, if the information depends on the processor, the operating
12620: system or the installation options chosen, or if they are likely to
12621: change during the maintenance of Gforth.
12622:
12623: @comment The framework for the rest has been taken from pfe.
12624:
12625: @menu
12626: * The Core Words::
12627: * The optional Block word set::
12628: * The optional Double Number word set::
12629: * The optional Exception word set::
12630: * The optional Facility word set::
12631: * The optional File-Access word set::
12632: * The optional Floating-Point word set::
12633: * The optional Locals word set::
12634: * The optional Memory-Allocation word set::
12635: * The optional Programming-Tools word set::
12636: * The optional Search-Order word set::
12637: @end menu
12638:
12639:
12640: @c =====================================================================
12641: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12642: @comment node-name, next, previous, up
12643: @section The Core Words
12644: @c =====================================================================
12645: @cindex core words, system documentation
12646: @cindex system documentation, core words
12647:
12648: @menu
12649: * core-idef:: Implementation Defined Options
12650: * core-ambcond:: Ambiguous Conditions
12651: * core-other:: Other System Documentation
12652: @end menu
12653:
12654: @c ---------------------------------------------------------------------
12655: @node core-idef, core-ambcond, The Core Words, The Core Words
12656: @subsection Implementation Defined Options
12657: @c ---------------------------------------------------------------------
12658: @cindex core words, implementation-defined options
12659: @cindex implementation-defined options, core words
12660:
12661:
12662: @table @i
12663: @item (Cell) aligned addresses:
12664: @cindex cell-aligned addresses
12665: @cindex aligned addresses
12666: processor-dependent. Gforth's alignment words perform natural alignment
12667: (e.g., an address aligned for a datum of size 8 is divisible by
12668: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12669:
12670: @item @code{EMIT} and non-graphic characters:
12671: @cindex @code{EMIT} and non-graphic characters
12672: @cindex non-graphic characters and @code{EMIT}
12673: The character is output using the C library function (actually, macro)
12674: @code{putc}.
12675:
12676: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12677: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12678: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12679: @cindex @code{ACCEPT}, editing
12680: @cindex @code{EXPECT}, editing
12681: This is modeled on the GNU readline library (@pxref{Readline
12682: Interaction, , Command Line Editing, readline, The GNU Readline
12683: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12684: producing a full word completion every time you type it (instead of
12685: producing the common prefix of all completions). @xref{Command-line editing}.
12686:
12687: @item character set:
12688: @cindex character set
12689: The character set of your computer and display device. Gforth is
12690: 8-bit-clean (but some other component in your system may make trouble).
12691:
12692: @item Character-aligned address requirements:
12693: @cindex character-aligned address requirements
12694: installation-dependent. Currently a character is represented by a C
12695: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12696: (Comments on that requested).
12697:
12698: @item character-set extensions and matching of names:
12699: @cindex character-set extensions and matching of names
12700: @cindex case-sensitivity for name lookup
12701: @cindex name lookup, case-sensitivity
12702: @cindex locale and case-sensitivity
12703: Any character except the ASCII NUL character can be used in a
12704: name. Matching is case-insensitive (except in @code{TABLE}s). The
12705: matching is performed using the C library function @code{strncasecmp}, whose
12706: function is probably influenced by the locale. E.g., the @code{C} locale
12707: does not know about accents and umlauts, so they are matched
12708: case-sensitively in that locale. For portability reasons it is best to
12709: write programs such that they work in the @code{C} locale. Then one can
12710: use libraries written by a Polish programmer (who might use words
12711: containing ISO Latin-2 encoded characters) and by a French programmer
12712: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12713: funny results for some of the words (which ones, depends on the font you
12714: are using)). Also, the locale you prefer may not be available in other
12715: operating systems. Hopefully, Unicode will solve these problems one day.
12716:
12717: @item conditions under which control characters match a space delimiter:
12718: @cindex space delimiters
12719: @cindex control characters as delimiters
12720: If @code{word} is called with the space character as a delimiter, all
12721: white-space characters (as identified by the C macro @code{isspace()})
12722: are delimiters. @code{Parse}, on the other hand, treats space like other
12723: delimiters. @code{Parse-name}, which is used by the outer
12724: interpreter (aka text interpreter) by default, treats all white-space
12725: characters as delimiters.
12726:
12727: @item format of the control-flow stack:
12728: @cindex control-flow stack, format
12729: The data stack is used as control-flow stack. The size of a control-flow
12730: stack item in cells is given by the constant @code{cs-item-size}. At the
12731: time of this writing, an item consists of a (pointer to a) locals list
12732: (third), an address in the code (second), and a tag for identifying the
12733: item (TOS). The following tags are used: @code{defstart},
12734: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12735: @code{scopestart}.
12736:
12737: @item conversion of digits > 35
12738: @cindex digits > 35
12739: The characters @code{[\]^_'} are the digits with the decimal value
12740: 36@minus{}41. There is no way to input many of the larger digits.
12741:
12742: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12743: @cindex @code{EXPECT}, display after end of input
12744: @cindex @code{ACCEPT}, display after end of input
12745: The cursor is moved to the end of the entered string. If the input is
12746: terminated using the @kbd{Return} key, a space is typed.
12747:
12748: @item exception abort sequence of @code{ABORT"}:
12749: @cindex exception abort sequence of @code{ABORT"}
12750: @cindex @code{ABORT"}, exception abort sequence
12751: The error string is stored into the variable @code{"error} and a
12752: @code{-2 throw} is performed.
12753:
12754: @item input line terminator:
12755: @cindex input line terminator
12756: @cindex line terminator on input
12757: @cindex newline character on input
12758: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12759: lines. One of these characters is typically produced when you type the
12760: @kbd{Enter} or @kbd{Return} key.
12761:
12762: @item maximum size of a counted string:
12763: @cindex maximum size of a counted string
12764: @cindex counted string, maximum size
12765: @code{s" /counted-string" environment? drop .}. Currently 255 characters
12766: on all platforms, but this may change.
12767:
12768: @item maximum size of a parsed string:
12769: @cindex maximum size of a parsed string
12770: @cindex parsed string, maximum size
12771: Given by the constant @code{/line}. Currently 255 characters.
12772:
12773: @item maximum size of a definition name, in characters:
12774: @cindex maximum size of a definition name, in characters
12775: @cindex name, maximum length
12776: MAXU/8
12777:
12778: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12779: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12780: @cindex @code{ENVIRONMENT?} string length, maximum
12781: MAXU/8
12782:
12783: @item method of selecting the user input device:
12784: @cindex user input device, method of selecting
12785: The user input device is the standard input. There is currently no way to
12786: change it from within Gforth. However, the input can typically be
12787: redirected in the command line that starts Gforth.
12788:
12789: @item method of selecting the user output device:
12790: @cindex user output device, method of selecting
12791: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
12792: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12793: output when the user output device is a terminal, otherwise the output
12794: is buffered.
12795:
12796: @item methods of dictionary compilation:
12797: What are we expected to document here?
12798:
12799: @item number of bits in one address unit:
12800: @cindex number of bits in one address unit
12801: @cindex address unit, size in bits
12802: @code{s" address-units-bits" environment? drop .}. 8 in all current
12803: platforms.
12804:
12805: @item number representation and arithmetic:
12806: @cindex number representation and arithmetic
12807: Processor-dependent. Binary two's complement on all current platforms.
12808:
12809: @item ranges for integer types:
12810: @cindex ranges for integer types
12811: @cindex integer types, ranges
12812: Installation-dependent. Make environmental queries for @code{MAX-N},
12813: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12814: unsigned (and positive) types is 0. The lower bound for signed types on
12815: two's complement and one's complement machines machines can be computed
12816: by adding 1 to the upper bound.
12817:
12818: @item read-only data space regions:
12819: @cindex read-only data space regions
12820: @cindex data-space, read-only regions
12821: The whole Forth data space is writable.
12822:
12823: @item size of buffer at @code{WORD}:
12824: @cindex size of buffer at @code{WORD}
12825: @cindex @code{WORD} buffer size
12826: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12827: shared with the pictured numeric output string. If overwriting
12828: @code{PAD} is acceptable, it is as large as the remaining dictionary
12829: space, although only as much can be sensibly used as fits in a counted
12830: string.
12831:
12832: @item size of one cell in address units:
12833: @cindex cell size
12834: @code{1 cells .}.
12835:
12836: @item size of one character in address units:
12837: @cindex char size
12838: @code{1 chars .}. 1 on all current platforms.
12839:
12840: @item size of the keyboard terminal buffer:
12841: @cindex size of the keyboard terminal buffer
12842: @cindex terminal buffer, size
12843: Varies. You can determine the size at a specific time using @code{lp@@
12844: tib - .}. It is shared with the locals stack and TIBs of files that
12845: include the current file. You can change the amount of space for TIBs
12846: and locals stack at Gforth startup with the command line option
12847: @code{-l}.
12848:
12849: @item size of the pictured numeric output buffer:
12850: @cindex size of the pictured numeric output buffer
12851: @cindex pictured numeric output buffer, size
12852: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12853: shared with @code{WORD}.
12854:
12855: @item size of the scratch area returned by @code{PAD}:
12856: @cindex size of the scratch area returned by @code{PAD}
12857: @cindex @code{PAD} size
12858: The remainder of dictionary space. @code{unused pad here - - .}.
12859:
12860: @item system case-sensitivity characteristics:
12861: @cindex case-sensitivity characteristics
12862: Dictionary searches are case-insensitive (except in
12863: @code{TABLE}s). However, as explained above under @i{character-set
12864: extensions}, the matching for non-ASCII characters is determined by the
12865: locale you are using. In the default @code{C} locale all non-ASCII
12866: characters are matched case-sensitively.
12867:
12868: @item system prompt:
12869: @cindex system prompt
12870: @cindex prompt
12871: @code{ ok} in interpret state, @code{ compiled} in compile state.
12872:
12873: @item division rounding:
12874: @cindex division rounding
12875: installation dependent. @code{s" floored" environment? drop .}. We leave
12876: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12877: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12878:
12879: @item values of @code{STATE} when true:
12880: @cindex @code{STATE} values
12881: -1.
12882:
12883: @item values returned after arithmetic overflow:
12884: On two's complement machines, arithmetic is performed modulo
12885: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12886: arithmetic (with appropriate mapping for signed types). Division by zero
12887: typically results in a @code{-55 throw} (Floating-point unidentified
12888: fault) or @code{-10 throw} (divide by zero).
12889:
12890: @item whether the current definition can be found after @t{DOES>}:
12891: @cindex @t{DOES>}, visibility of current definition
12892: No.
12893:
12894: @end table
12895:
12896: @c ---------------------------------------------------------------------
12897: @node core-ambcond, core-other, core-idef, The Core Words
12898: @subsection Ambiguous conditions
12899: @c ---------------------------------------------------------------------
12900: @cindex core words, ambiguous conditions
12901: @cindex ambiguous conditions, core words
12902:
12903: @table @i
12904:
12905: @item a name is neither a word nor a number:
12906: @cindex name not found
12907: @cindex undefined word
12908: @code{-13 throw} (Undefined word).
12909:
12910: @item a definition name exceeds the maximum length allowed:
12911: @cindex word name too long
12912: @code{-19 throw} (Word name too long)
12913:
12914: @item addressing a region not inside the various data spaces of the forth system:
12915: @cindex Invalid memory address
12916: The stacks, code space and header space are accessible. Machine code space is
12917: typically readable. Accessing other addresses gives results dependent on
12918: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12919: address).
12920:
12921: @item argument type incompatible with parameter:
12922: @cindex argument type mismatch
12923: This is usually not caught. Some words perform checks, e.g., the control
12924: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12925: mismatch).
12926:
12927: @item attempting to obtain the execution token of a word with undefined execution semantics:
12928: @cindex Interpreting a compile-only word, for @code{'} etc.
12929: @cindex execution token of words with undefined execution semantics
12930: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12931: get an execution token for @code{compile-only-error} (which performs a
12932: @code{-14 throw} when executed).
12933:
12934: @item dividing by zero:
12935: @cindex dividing by zero
12936: @cindex floating point unidentified fault, integer division
12937: On some platforms, this produces a @code{-10 throw} (Division by
12938: zero); on other systems, this typically results in a @code{-55 throw}
12939: (Floating-point unidentified fault).
12940:
12941: @item insufficient data stack or return stack space:
12942: @cindex insufficient data stack or return stack space
12943: @cindex stack overflow
12944: @cindex address alignment exception, stack overflow
12945: @cindex Invalid memory address, stack overflow
12946: Depending on the operating system, the installation, and the invocation
12947: of Gforth, this is either checked by the memory management hardware, or
12948: it is not checked. If it is checked, you typically get a @code{-3 throw}
12949: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12950: throw} (Invalid memory address) (depending on the platform and how you
12951: achieved the overflow) as soon as the overflow happens. If it is not
12952: checked, overflows typically result in mysterious illegal memory
12953: accesses, producing @code{-9 throw} (Invalid memory address) or
12954: @code{-23 throw} (Address alignment exception); they might also destroy
12955: the internal data structure of @code{ALLOCATE} and friends, resulting in
12956: various errors in these words.
12957:
12958: @item insufficient space for loop control parameters:
12959: @cindex insufficient space for loop control parameters
12960: Like other return stack overflows.
12961:
12962: @item insufficient space in the dictionary:
12963: @cindex insufficient space in the dictionary
12964: @cindex dictionary overflow
12965: If you try to allot (either directly with @code{allot}, or indirectly
12966: with @code{,}, @code{create} etc.) more memory than available in the
12967: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12968: to access memory beyond the end of the dictionary, the results are
12969: similar to stack overflows.
12970:
12971: @item interpreting a word with undefined interpretation semantics:
12972: @cindex interpreting a word with undefined interpretation semantics
12973: @cindex Interpreting a compile-only word
12974: For some words, we have defined interpretation semantics. For the
12975: others: @code{-14 throw} (Interpreting a compile-only word).
12976:
12977: @item modifying the contents of the input buffer or a string literal:
12978: @cindex modifying the contents of the input buffer or a string literal
12979: These are located in writable memory and can be modified.
12980:
12981: @item overflow of the pictured numeric output string:
12982: @cindex overflow of the pictured numeric output string
12983: @cindex pictured numeric output string, overflow
12984: @code{-17 throw} (Pictured numeric ouput string overflow).
12985:
12986: @item parsed string overflow:
12987: @cindex parsed string overflow
12988: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12989:
12990: @item producing a result out of range:
12991: @cindex result out of range
12992: On two's complement machines, arithmetic is performed modulo
12993: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12994: arithmetic (with appropriate mapping for signed types). Division by zero
12995: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12996: throw} (floating point unidentified fault). @code{convert} and
12997: @code{>number} currently overflow silently.
12998:
12999: @item reading from an empty data or return stack:
13000: @cindex stack empty
13001: @cindex stack underflow
13002: @cindex return stack underflow
13003: The data stack is checked by the outer (aka text) interpreter after
13004: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13005: underflow) is performed. Apart from that, stacks may be checked or not,
13006: depending on operating system, installation, and invocation. If they are
13007: caught by a check, they typically result in @code{-4 throw} (Stack
13008: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13009: (Invalid memory address), depending on the platform and which stack
13010: underflows and by how much. Note that even if the system uses checking
13011: (through the MMU), your program may have to underflow by a significant
13012: number of stack items to trigger the reaction (the reason for this is
13013: that the MMU, and therefore the checking, works with a page-size
13014: granularity). If there is no checking, the symptoms resulting from an
13015: underflow are similar to those from an overflow. Unbalanced return
13016: stack errors can result in a variety of symptoms, including @code{-9 throw}
13017: (Invalid memory address) and Illegal Instruction (typically @code{-260
13018: throw}).
13019:
13020: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13021: @cindex unexpected end of the input buffer
13022: @cindex zero-length string as a name
13023: @cindex Attempt to use zero-length string as a name
13024: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13025: use zero-length string as a name). Words like @code{'} probably will not
13026: find what they search. Note that it is possible to create zero-length
13027: names with @code{nextname} (should it not?).
13028:
13029: @item @code{>IN} greater than input buffer:
13030: @cindex @code{>IN} greater than input buffer
13031: The next invocation of a parsing word returns a string with length 0.
13032:
13033: @item @code{RECURSE} appears after @code{DOES>}:
13034: @cindex @code{RECURSE} appears after @code{DOES>}
13035: Compiles a recursive call to the defining word, not to the defined word.
13036:
13037: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13038: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
13039: @cindex argument type mismatch, @code{RESTORE-INPUT}
13040: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13041: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13042: the end of the file was reached), its source-id may be
13043: reused. Therefore, restoring an input source specification referencing a
13044: closed file may lead to unpredictable results instead of a @code{-12
13045: THROW}.
13046:
13047: In the future, Gforth may be able to restore input source specifications
13048: from other than the current input source.
13049:
13050: @item data space containing definitions gets de-allocated:
13051: @cindex data space containing definitions gets de-allocated
13052: Deallocation with @code{allot} is not checked. This typically results in
13053: memory access faults or execution of illegal instructions.
13054:
13055: @item data space read/write with incorrect alignment:
13056: @cindex data space read/write with incorrect alignment
13057: @cindex alignment faults
13058: @cindex address alignment exception
13059: Processor-dependent. Typically results in a @code{-23 throw} (Address
13060: alignment exception). Under Linux-Intel on a 486 or later processor with
13061: alignment turned on, incorrect alignment results in a @code{-9 throw}
13062: (Invalid memory address). There are reportedly some processors with
13063: alignment restrictions that do not report violations.
13064:
13065: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13066: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13067: Like other alignment errors.
13068:
13069: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13070: Like other stack underflows.
13071:
13072: @item loop control parameters not available:
13073: @cindex loop control parameters not available
13074: Not checked. The counted loop words simply assume that the top of return
13075: stack items are loop control parameters and behave accordingly.
13076:
13077: @item most recent definition does not have a name (@code{IMMEDIATE}):
13078: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13079: @cindex last word was headerless
13080: @code{abort" last word was headerless"}.
13081:
13082: @item name not defined by @code{VALUE} used by @code{TO}:
13083: @cindex name not defined by @code{VALUE} used by @code{TO}
13084: @cindex @code{TO} on non-@code{VALUE}s
13085: @cindex Invalid name argument, @code{TO}
13086: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13087: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13088:
13089: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13090: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
13091: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
13092: @code{-13 throw} (Undefined word)
13093:
13094: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13095: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13096: Gforth behaves as if they were of the same type. I.e., you can predict
13097: the behaviour by interpreting all parameters as, e.g., signed.
13098:
13099: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13100: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13101: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13102: compilation semantics of @code{TO}.
13103:
13104: @item String longer than a counted string returned by @code{WORD}:
13105: @cindex string longer than a counted string returned by @code{WORD}
13106: @cindex @code{WORD}, string overflow
13107: Not checked. The string will be ok, but the count will, of course,
13108: contain only the least significant bits of the length.
13109:
13110: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13111: @cindex @code{LSHIFT}, large shift counts
13112: @cindex @code{RSHIFT}, large shift counts
13113: Processor-dependent. Typical behaviours are returning 0 and using only
13114: the low bits of the shift count.
13115:
13116: @item word not defined via @code{CREATE}:
13117: @cindex @code{>BODY} of non-@code{CREATE}d words
13118: @code{>BODY} produces the PFA of the word no matter how it was defined.
13119:
13120: @cindex @code{DOES>} of non-@code{CREATE}d words
13121: @code{DOES>} changes the execution semantics of the last defined word no
13122: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13123: @code{CREATE , DOES>}.
13124:
13125: @item words improperly used outside @code{<#} and @code{#>}:
13126: Not checked. As usual, you can expect memory faults.
13127:
13128: @end table
13129:
13130:
13131: @c ---------------------------------------------------------------------
13132: @node core-other, , core-ambcond, The Core Words
13133: @subsection Other system documentation
13134: @c ---------------------------------------------------------------------
13135: @cindex other system documentation, core words
13136: @cindex core words, other system documentation
13137:
13138: @table @i
13139: @item nonstandard words using @code{PAD}:
13140: @cindex @code{PAD} use by nonstandard words
13141: None.
13142:
13143: @item operator's terminal facilities available:
13144: @cindex operator's terminal facilities available
13145: After processing the OS's command line, Gforth goes into interactive mode,
13146: and you can give commands to Gforth interactively. The actual facilities
13147: available depend on how you invoke Gforth.
13148:
13149: @item program data space available:
13150: @cindex program data space available
13151: @cindex data space available
13152: @code{UNUSED .} gives the remaining dictionary space. The total
13153: dictionary space can be specified with the @code{-m} switch
13154: (@pxref{Invoking Gforth}) when Gforth starts up.
13155:
13156: @item return stack space available:
13157: @cindex return stack space available
13158: You can compute the total return stack space in cells with
13159: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13160: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13161:
13162: @item stack space available:
13163: @cindex stack space available
13164: You can compute the total data stack space in cells with
13165: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13166: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13167:
13168: @item system dictionary space required, in address units:
13169: @cindex system dictionary space required, in address units
13170: Type @code{here forthstart - .} after startup. At the time of this
13171: writing, this gives 80080 (bytes) on a 32-bit system.
13172: @end table
13173:
13174:
13175: @c =====================================================================
13176: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13177: @section The optional Block word set
13178: @c =====================================================================
13179: @cindex system documentation, block words
13180: @cindex block words, system documentation
13181:
13182: @menu
13183: * block-idef:: Implementation Defined Options
13184: * block-ambcond:: Ambiguous Conditions
13185: * block-other:: Other System Documentation
13186: @end menu
13187:
13188:
13189: @c ---------------------------------------------------------------------
13190: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13191: @subsection Implementation Defined Options
13192: @c ---------------------------------------------------------------------
13193: @cindex implementation-defined options, block words
13194: @cindex block words, implementation-defined options
13195:
13196: @table @i
13197: @item the format for display by @code{LIST}:
13198: @cindex @code{LIST} display format
13199: First the screen number is displayed, then 16 lines of 64 characters,
13200: each line preceded by the line number.
13201:
13202: @item the length of a line affected by @code{\}:
13203: @cindex length of a line affected by @code{\}
13204: @cindex @code{\}, line length in blocks
13205: 64 characters.
13206: @end table
13207:
13208:
13209: @c ---------------------------------------------------------------------
13210: @node block-ambcond, block-other, block-idef, The optional Block word set
13211: @subsection Ambiguous conditions
13212: @c ---------------------------------------------------------------------
13213: @cindex block words, ambiguous conditions
13214: @cindex ambiguous conditions, block words
13215:
13216: @table @i
13217: @item correct block read was not possible:
13218: @cindex block read not possible
13219: Typically results in a @code{throw} of some OS-derived value (between
13220: -512 and -2048). If the blocks file was just not long enough, blanks are
13221: supplied for the missing portion.
13222:
13223: @item I/O exception in block transfer:
13224: @cindex I/O exception in block transfer
13225: @cindex block transfer, I/O exception
13226: Typically results in a @code{throw} of some OS-derived value (between
13227: -512 and -2048).
13228:
13229: @item invalid block number:
13230: @cindex invalid block number
13231: @cindex block number invalid
13232: @code{-35 throw} (Invalid block number)
13233:
13234: @item a program directly alters the contents of @code{BLK}:
13235: @cindex @code{BLK}, altering @code{BLK}
13236: The input stream is switched to that other block, at the same
13237: position. If the storing to @code{BLK} happens when interpreting
13238: non-block input, the system will get quite confused when the block ends.
13239:
13240: @item no current block buffer for @code{UPDATE}:
13241: @cindex @code{UPDATE}, no current block buffer
13242: @code{UPDATE} has no effect.
13243:
13244: @end table
13245:
13246: @c ---------------------------------------------------------------------
13247: @node block-other, , block-ambcond, The optional Block word set
13248: @subsection Other system documentation
13249: @c ---------------------------------------------------------------------
13250: @cindex other system documentation, block words
13251: @cindex block words, other system documentation
13252:
13253: @table @i
13254: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13255: No restrictions (yet).
13256:
13257: @item the number of blocks available for source and data:
13258: depends on your disk space.
13259:
13260: @end table
13261:
13262:
13263: @c =====================================================================
13264: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13265: @section The optional Double Number word set
13266: @c =====================================================================
13267: @cindex system documentation, double words
13268: @cindex double words, system documentation
13269:
13270: @menu
13271: * double-ambcond:: Ambiguous Conditions
13272: @end menu
13273:
13274:
13275: @c ---------------------------------------------------------------------
13276: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13277: @subsection Ambiguous conditions
13278: @c ---------------------------------------------------------------------
13279: @cindex double words, ambiguous conditions
13280: @cindex ambiguous conditions, double words
13281:
13282: @table @i
13283: @item @i{d} outside of range of @i{n} in @code{D>S}:
13284: @cindex @code{D>S}, @i{d} out of range of @i{n}
13285: The least significant cell of @i{d} is produced.
13286:
13287: @end table
13288:
13289:
13290: @c =====================================================================
13291: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13292: @section The optional Exception word set
13293: @c =====================================================================
13294: @cindex system documentation, exception words
13295: @cindex exception words, system documentation
13296:
13297: @menu
13298: * exception-idef:: Implementation Defined Options
13299: @end menu
13300:
13301:
13302: @c ---------------------------------------------------------------------
13303: @node exception-idef, , The optional Exception word set, The optional Exception word set
13304: @subsection Implementation Defined Options
13305: @c ---------------------------------------------------------------------
13306: @cindex implementation-defined options, exception words
13307: @cindex exception words, implementation-defined options
13308:
13309: @table @i
13310: @item @code{THROW}-codes used in the system:
13311: @cindex @code{THROW}-codes used in the system
13312: The codes -256@minus{}-511 are used for reporting signals. The mapping
13313: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
13314: codes -512@minus{}-2047 are used for OS errors (for file and memory
13315: allocation operations). The mapping from OS error numbers to throw codes
13316: is -512@minus{}@code{errno}. One side effect of this mapping is that
13317: undefined OS errors produce a message with a strange number; e.g.,
13318: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13319: @end table
13320:
13321: @c =====================================================================
13322: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13323: @section The optional Facility word set
13324: @c =====================================================================
13325: @cindex system documentation, facility words
13326: @cindex facility words, system documentation
13327:
13328: @menu
13329: * facility-idef:: Implementation Defined Options
13330: * facility-ambcond:: Ambiguous Conditions
13331: @end menu
13332:
13333:
13334: @c ---------------------------------------------------------------------
13335: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13336: @subsection Implementation Defined Options
13337: @c ---------------------------------------------------------------------
13338: @cindex implementation-defined options, facility words
13339: @cindex facility words, implementation-defined options
13340:
13341: @table @i
13342: @item encoding of keyboard events (@code{EKEY}):
13343: @cindex keyboard events, encoding in @code{EKEY}
13344: @cindex @code{EKEY}, encoding of keyboard events
13345: Keys corresponding to ASCII characters are encoded as ASCII characters.
13346: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13347: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13348: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13349: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
13350:
13351:
13352: @item duration of a system clock tick:
13353: @cindex duration of a system clock tick
13354: @cindex clock tick duration
13355: System dependent. With respect to @code{MS}, the time is specified in
13356: microseconds. How well the OS and the hardware implement this, is
13357: another question.
13358:
13359: @item repeatability to be expected from the execution of @code{MS}:
13360: @cindex repeatability to be expected from the execution of @code{MS}
13361: @cindex @code{MS}, repeatability to be expected
13362: System dependent. On Unix, a lot depends on load. If the system is
13363: lightly loaded, and the delay is short enough that Gforth does not get
13364: swapped out, the performance should be acceptable. Under MS-DOS and
13365: other single-tasking systems, it should be good.
13366:
13367: @end table
13368:
13369:
13370: @c ---------------------------------------------------------------------
13371: @node facility-ambcond, , facility-idef, The optional Facility word set
13372: @subsection Ambiguous conditions
13373: @c ---------------------------------------------------------------------
13374: @cindex facility words, ambiguous conditions
13375: @cindex ambiguous conditions, facility words
13376:
13377: @table @i
13378: @item @code{AT-XY} can't be performed on user output device:
13379: @cindex @code{AT-XY} can't be performed on user output device
13380: Largely terminal dependent. No range checks are done on the arguments.
13381: No errors are reported. You may see some garbage appearing, you may see
13382: simply nothing happen.
13383:
13384: @end table
13385:
13386:
13387: @c =====================================================================
13388: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13389: @section The optional File-Access word set
13390: @c =====================================================================
13391: @cindex system documentation, file words
13392: @cindex file words, system documentation
13393:
13394: @menu
13395: * file-idef:: Implementation Defined Options
13396: * file-ambcond:: Ambiguous Conditions
13397: @end menu
13398:
13399: @c ---------------------------------------------------------------------
13400: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13401: @subsection Implementation Defined Options
13402: @c ---------------------------------------------------------------------
13403: @cindex implementation-defined options, file words
13404: @cindex file words, implementation-defined options
13405:
13406: @table @i
13407: @item file access methods used:
13408: @cindex file access methods used
13409: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13410: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13411: @code{wb}): The file is cleared, if it exists, and created, if it does
13412: not (with both @code{open-file} and @code{create-file}). Under Unix
13413: @code{create-file} creates a file with 666 permissions modified by your
13414: umask.
13415:
13416: @item file exceptions:
13417: @cindex file exceptions
13418: The file words do not raise exceptions (except, perhaps, memory access
13419: faults when you pass illegal addresses or file-ids).
13420:
13421: @item file line terminator:
13422: @cindex file line terminator
13423: System-dependent. Gforth uses C's newline character as line
13424: terminator. What the actual character code(s) of this are is
13425: system-dependent.
13426:
13427: @item file name format:
13428: @cindex file name format
13429: System dependent. Gforth just uses the file name format of your OS.
13430:
13431: @item information returned by @code{FILE-STATUS}:
13432: @cindex @code{FILE-STATUS}, returned information
13433: @code{FILE-STATUS} returns the most powerful file access mode allowed
13434: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13435: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13436: along with the returned mode.
13437:
13438: @item input file state after an exception when including source:
13439: @cindex exception when including source
13440: All files that are left via the exception are closed.
13441:
13442: @item @i{ior} values and meaning:
13443: @cindex @i{ior} values and meaning
13444: @cindex @i{wior} values and meaning
13445: The @i{ior}s returned by the file and memory allocation words are
13446: intended as throw codes. They typically are in the range
13447: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
13448: @i{ior}s is -512@minus{}@i{errno}.
13449:
13450: @item maximum depth of file input nesting:
13451: @cindex maximum depth of file input nesting
13452: @cindex file input nesting, maximum depth
13453: limited by the amount of return stack, locals/TIB stack, and the number
13454: of open files available. This should not give you troubles.
13455:
13456: @item maximum size of input line:
13457: @cindex maximum size of input line
13458: @cindex input line size, maximum
13459: @code{/line}. Currently 255.
13460:
13461: @item methods of mapping block ranges to files:
13462: @cindex mapping block ranges to files
13463: @cindex files containing blocks
13464: @cindex blocks in files
13465: By default, blocks are accessed in the file @file{blocks.fb} in the
13466: current working directory. The file can be switched with @code{USE}.
13467:
13468: @item number of string buffers provided by @code{S"}:
13469: @cindex @code{S"}, number of string buffers
13470: 1
13471:
13472: @item size of string buffer used by @code{S"}:
13473: @cindex @code{S"}, size of string buffer
13474: @code{/line}. currently 255.
13475:
13476: @end table
13477:
13478: @c ---------------------------------------------------------------------
13479: @node file-ambcond, , file-idef, The optional File-Access word set
13480: @subsection Ambiguous conditions
13481: @c ---------------------------------------------------------------------
13482: @cindex file words, ambiguous conditions
13483: @cindex ambiguous conditions, file words
13484:
13485: @table @i
13486: @item attempting to position a file outside its boundaries:
13487: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13488: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13489: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13490:
13491: @item attempting to read from file positions not yet written:
13492: @cindex reading from file positions not yet written
13493: End-of-file, i.e., zero characters are read and no error is reported.
13494:
13495: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13496: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
13497: An appropriate exception may be thrown, but a memory fault or other
13498: problem is more probable.
13499:
13500: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13501: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13502: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13503: The @i{ior} produced by the operation, that discovered the problem, is
13504: thrown.
13505:
13506: @item named file cannot be opened (@code{INCLUDED}):
13507: @cindex @code{INCLUDED}, named file cannot be opened
13508: The @i{ior} produced by @code{open-file} is thrown.
13509:
13510: @item requesting an unmapped block number:
13511: @cindex unmapped block numbers
13512: There are no unmapped legal block numbers. On some operating systems,
13513: writing a block with a large number may overflow the file system and
13514: have an error message as consequence.
13515:
13516: @item using @code{source-id} when @code{blk} is non-zero:
13517: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13518: @code{source-id} performs its function. Typically it will give the id of
13519: the source which loaded the block. (Better ideas?)
13520:
13521: @end table
13522:
13523:
13524: @c =====================================================================
13525: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13526: @section The optional Floating-Point word set
13527: @c =====================================================================
13528: @cindex system documentation, floating-point words
13529: @cindex floating-point words, system documentation
13530:
13531: @menu
13532: * floating-idef:: Implementation Defined Options
13533: * floating-ambcond:: Ambiguous Conditions
13534: @end menu
13535:
13536:
13537: @c ---------------------------------------------------------------------
13538: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13539: @subsection Implementation Defined Options
13540: @c ---------------------------------------------------------------------
13541: @cindex implementation-defined options, floating-point words
13542: @cindex floating-point words, implementation-defined options
13543:
13544: @table @i
13545: @item format and range of floating point numbers:
13546: @cindex format and range of floating point numbers
13547: @cindex floating point numbers, format and range
13548: System-dependent; the @code{double} type of C.
13549:
13550: @item results of @code{REPRESENT} when @i{float} is out of range:
13551: @cindex @code{REPRESENT}, results when @i{float} is out of range
13552: System dependent; @code{REPRESENT} is implemented using the C library
13553: function @code{ecvt()} and inherits its behaviour in this respect.
13554:
13555: @item rounding or truncation of floating-point numbers:
13556: @cindex rounding of floating-point numbers
13557: @cindex truncation of floating-point numbers
13558: @cindex floating-point numbers, rounding or truncation
13559: System dependent; the rounding behaviour is inherited from the hosting C
13560: compiler. IEEE-FP-based (i.e., most) systems by default round to
13561: nearest, and break ties by rounding to even (i.e., such that the last
13562: bit of the mantissa is 0).
13563:
13564: @item size of floating-point stack:
13565: @cindex floating-point stack size
13566: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13567: the floating-point stack (in floats). You can specify this on startup
13568: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13569:
13570: @item width of floating-point stack:
13571: @cindex floating-point stack width
13572: @code{1 floats}.
13573:
13574: @end table
13575:
13576:
13577: @c ---------------------------------------------------------------------
13578: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13579: @subsection Ambiguous conditions
13580: @c ---------------------------------------------------------------------
13581: @cindex floating-point words, ambiguous conditions
13582: @cindex ambiguous conditions, floating-point words
13583:
13584: @table @i
13585: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13586: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13587: System-dependent. Typically results in a @code{-23 THROW} like other
13588: alignment violations.
13589:
13590: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13591: @cindex @code{f@@} used with an address that is not float aligned
13592: @cindex @code{f!} used with an address that is not float aligned
13593: System-dependent. Typically results in a @code{-23 THROW} like other
13594: alignment violations.
13595:
13596: @item floating-point result out of range:
13597: @cindex floating-point result out of range
13598: System-dependent. Can result in a @code{-43 throw} (floating point
13599: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13600: (floating point inexact result), @code{-55 THROW} (Floating-point
13601: unidentified fault), or can produce a special value representing, e.g.,
13602: Infinity.
13603:
13604: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13605: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13606: System-dependent. Typically results in an alignment fault like other
13607: alignment violations.
13608:
13609: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13610: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
13611: The floating-point number is converted into decimal nonetheless.
13612:
13613: @item Both arguments are equal to zero (@code{FATAN2}):
13614: @cindex @code{FATAN2}, both arguments are equal to zero
13615: System-dependent. @code{FATAN2} is implemented using the C library
13616: function @code{atan2()}.
13617:
13618: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13619: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13620: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
13621: because of small errors and the tan will be a very large (or very small)
13622: but finite number.
13623:
13624: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13625: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
13626: The result is rounded to the nearest float.
13627:
13628: @item dividing by zero:
13629: @cindex dividing by zero, floating-point
13630: @cindex floating-point dividing by zero
13631: @cindex floating-point unidentified fault, FP divide-by-zero
13632: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13633: (floating point divide by zero) or @code{-55 throw} (Floating-point
13634: unidentified fault).
13635:
13636: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13637: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13638: System dependent. On IEEE-FP based systems the number is converted into
13639: an infinity.
13640:
13641: @item @i{float}<1 (@code{FACOSH}):
13642: @cindex @code{FACOSH}, @i{float}<1
13643: @cindex floating-point unidentified fault, @code{FACOSH}
13644: Platform-dependent; on IEEE-FP systems typically produces a NaN.
13645:
13646: @item @i{float}=<-1 (@code{FLNP1}):
13647: @cindex @code{FLNP1}, @i{float}=<-1
13648: @cindex floating-point unidentified fault, @code{FLNP1}
13649: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13650: negative infinity for @i{float}=-1).
13651:
13652: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13653: @cindex @code{FLN}, @i{float}=<0
13654: @cindex @code{FLOG}, @i{float}=<0
13655: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
13656: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13657: negative infinity for @i{float}=0).
13658:
13659: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13660: @cindex @code{FASINH}, @i{float}<0
13661: @cindex @code{FSQRT}, @i{float}<0
13662: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
13663: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13664: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13665: C library?).
13666:
13667: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13668: @cindex @code{FACOS}, |@i{float}|>1
13669: @cindex @code{FASIN}, |@i{float}|>1
13670: @cindex @code{FATANH}, |@i{float}|>1
13671: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
13672: Platform-dependent; IEEE-FP systems typically produce a NaN.
13673:
13674: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13675: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
13676: @cindex floating-point unidentified fault, @code{F>D}
13677: Platform-dependent; typically, some double number is produced and no
13678: error is reported.
13679:
13680: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13681: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
13682: @code{Precision} characters of the numeric output area are used. If
13683: @code{precision} is too high, these words will smash the data or code
13684: close to @code{here}.
13685: @end table
13686:
13687: @c =====================================================================
13688: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13689: @section The optional Locals word set
13690: @c =====================================================================
13691: @cindex system documentation, locals words
13692: @cindex locals words, system documentation
13693:
13694: @menu
13695: * locals-idef:: Implementation Defined Options
13696: * locals-ambcond:: Ambiguous Conditions
13697: @end menu
13698:
13699:
13700: @c ---------------------------------------------------------------------
13701: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13702: @subsection Implementation Defined Options
13703: @c ---------------------------------------------------------------------
13704: @cindex implementation-defined options, locals words
13705: @cindex locals words, implementation-defined options
13706:
13707: @table @i
13708: @item maximum number of locals in a definition:
13709: @cindex maximum number of locals in a definition
13710: @cindex locals, maximum number in a definition
13711: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13712: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13713: characters. The number of locals in a definition is bounded by the size
13714: of locals-buffer, which contains the names of the locals.
13715:
13716: @end table
13717:
13718:
13719: @c ---------------------------------------------------------------------
13720: @node locals-ambcond, , locals-idef, The optional Locals word set
13721: @subsection Ambiguous conditions
13722: @c ---------------------------------------------------------------------
13723: @cindex locals words, ambiguous conditions
13724: @cindex ambiguous conditions, locals words
13725:
13726: @table @i
13727: @item executing a named local in interpretation state:
13728: @cindex local in interpretation state
13729: @cindex Interpreting a compile-only word, for a local
13730: Locals have no interpretation semantics. If you try to perform the
13731: interpretation semantics, you will get a @code{-14 throw} somewhere
13732: (Interpreting a compile-only word). If you perform the compilation
13733: semantics, the locals access will be compiled (irrespective of state).
13734:
13735: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
13736: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13737: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13738: @cindex Invalid name argument, @code{TO}
13739: @code{-32 throw} (Invalid name argument)
13740:
13741: @end table
13742:
13743:
13744: @c =====================================================================
13745: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13746: @section The optional Memory-Allocation word set
13747: @c =====================================================================
13748: @cindex system documentation, memory-allocation words
13749: @cindex memory-allocation words, system documentation
13750:
13751: @menu
13752: * memory-idef:: Implementation Defined Options
13753: @end menu
13754:
13755:
13756: @c ---------------------------------------------------------------------
13757: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13758: @subsection Implementation Defined Options
13759: @c ---------------------------------------------------------------------
13760: @cindex implementation-defined options, memory-allocation words
13761: @cindex memory-allocation words, implementation-defined options
13762:
13763: @table @i
13764: @item values and meaning of @i{ior}:
13765: @cindex @i{ior} values and meaning
13766: The @i{ior}s returned by the file and memory allocation words are
13767: intended as throw codes. They typically are in the range
13768: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
13769: @i{ior}s is -512@minus{}@i{errno}.
13770:
13771: @end table
13772:
13773: @c =====================================================================
13774: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13775: @section The optional Programming-Tools word set
13776: @c =====================================================================
13777: @cindex system documentation, programming-tools words
13778: @cindex programming-tools words, system documentation
13779:
13780: @menu
13781: * programming-idef:: Implementation Defined Options
13782: * programming-ambcond:: Ambiguous Conditions
13783: @end menu
13784:
13785:
13786: @c ---------------------------------------------------------------------
13787: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13788: @subsection Implementation Defined Options
13789: @c ---------------------------------------------------------------------
13790: @cindex implementation-defined options, programming-tools words
13791: @cindex programming-tools words, implementation-defined options
13792:
13793: @table @i
13794: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13795: @cindex @code{;CODE} ending sequence
13796: @cindex @code{CODE} ending sequence
13797: @code{END-CODE}
13798:
13799: @item manner of processing input following @code{;CODE} and @code{CODE}:
13800: @cindex @code{;CODE}, processing input
13801: @cindex @code{CODE}, processing input
13802: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13803: the input is processed by the text interpreter, (starting) in interpret
13804: state.
13805:
13806: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13807: @cindex @code{ASSEMBLER}, search order capability
13808: The ANS Forth search order word set.
13809:
13810: @item source and format of display by @code{SEE}:
13811: @cindex @code{SEE}, source and format of output
13812: The source for @code{see} is the executable code used by the inner
13813: interpreter. The current @code{see} tries to output Forth source code
13814: (and on some platforms, assembly code for primitives) as well as
13815: possible.
13816:
13817: @end table
13818:
13819: @c ---------------------------------------------------------------------
13820: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13821: @subsection Ambiguous conditions
13822: @c ---------------------------------------------------------------------
13823: @cindex programming-tools words, ambiguous conditions
13824: @cindex ambiguous conditions, programming-tools words
13825:
13826: @table @i
13827:
13828: @item deleting the compilation word list (@code{FORGET}):
13829: @cindex @code{FORGET}, deleting the compilation word list
13830: Not implemented (yet).
13831:
13832: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13833: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13834: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
13835: @cindex control-flow stack underflow
13836: This typically results in an @code{abort"} with a descriptive error
13837: message (may change into a @code{-22 throw} (Control structure mismatch)
13838: in the future). You may also get a memory access error. If you are
13839: unlucky, this ambiguous condition is not caught.
13840:
13841: @item @i{name} can't be found (@code{FORGET}):
13842: @cindex @code{FORGET}, @i{name} can't be found
13843: Not implemented (yet).
13844:
13845: @item @i{name} not defined via @code{CREATE}:
13846: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
13847: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13848: the execution semantics of the last defined word no matter how it was
13849: defined.
13850:
13851: @item @code{POSTPONE} applied to @code{[IF]}:
13852: @cindex @code{POSTPONE} applied to @code{[IF]}
13853: @cindex @code{[IF]} and @code{POSTPONE}
13854: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13855: equivalent to @code{[IF]}.
13856:
13857: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13858: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13859: Continue in the same state of conditional compilation in the next outer
13860: input source. Currently there is no warning to the user about this.
13861:
13862: @item removing a needed definition (@code{FORGET}):
13863: @cindex @code{FORGET}, removing a needed definition
13864: Not implemented (yet).
13865:
13866: @end table
13867:
13868:
13869: @c =====================================================================
13870: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13871: @section The optional Search-Order word set
13872: @c =====================================================================
13873: @cindex system documentation, search-order words
13874: @cindex search-order words, system documentation
13875:
13876: @menu
13877: * search-idef:: Implementation Defined Options
13878: * search-ambcond:: Ambiguous Conditions
13879: @end menu
13880:
13881:
13882: @c ---------------------------------------------------------------------
13883: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13884: @subsection Implementation Defined Options
13885: @c ---------------------------------------------------------------------
13886: @cindex implementation-defined options, search-order words
13887: @cindex search-order words, implementation-defined options
13888:
13889: @table @i
13890: @item maximum number of word lists in search order:
13891: @cindex maximum number of word lists in search order
13892: @cindex search order, maximum depth
13893: @code{s" wordlists" environment? drop .}. Currently 16.
13894:
13895: @item minimum search order:
13896: @cindex minimum search order
13897: @cindex search order, minimum
13898: @code{root root}.
13899:
13900: @end table
13901:
13902: @c ---------------------------------------------------------------------
13903: @node search-ambcond, , search-idef, The optional Search-Order word set
13904: @subsection Ambiguous conditions
13905: @c ---------------------------------------------------------------------
13906: @cindex search-order words, ambiguous conditions
13907: @cindex ambiguous conditions, search-order words
13908:
13909: @table @i
13910: @item changing the compilation word list (during compilation):
13911: @cindex changing the compilation word list (during compilation)
13912: @cindex compilation word list, change before definition ends
13913: The word is entered into the word list that was the compilation word list
13914: at the start of the definition. Any changes to the name field (e.g.,
13915: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13916: are applied to the latest defined word (as reported by @code{latest} or
13917: @code{latestxt}), if possible, irrespective of the compilation word list.
13918:
13919: @item search order empty (@code{previous}):
13920: @cindex @code{previous}, search order empty
13921: @cindex vocstack empty, @code{previous}
13922: @code{abort" Vocstack empty"}.
13923:
13924: @item too many word lists in search order (@code{also}):
13925: @cindex @code{also}, too many word lists in search order
13926: @cindex vocstack full, @code{also}
13927: @code{abort" Vocstack full"}.
13928:
13929: @end table
13930:
13931: @c ***************************************************************
13932: @node Standard vs Extensions, Model, ANS conformance, Top
13933: @chapter Should I use Gforth extensions?
13934: @cindex Gforth extensions
13935:
13936: As you read through the rest of this manual, you will see documentation
13937: for @i{Standard} words, and documentation for some appealing Gforth
13938: @i{extensions}. You might ask yourself the question: @i{``Should I
13939: restrict myself to the standard, or should I use the extensions?''}
13940:
13941: The answer depends on the goals you have for the program you are working
13942: on:
13943:
13944: @itemize @bullet
13945:
13946: @item Is it just for yourself or do you want to share it with others?
13947:
13948: @item
13949: If you want to share it, do the others all use Gforth?
13950:
13951: @item
13952: If it is just for yourself, do you want to restrict yourself to Gforth?
13953:
13954: @end itemize
13955:
13956: If restricting the program to Gforth is ok, then there is no reason not
13957: to use extensions. It is still a good idea to keep to the standard
13958: where it is easy, in case you want to reuse these parts in another
13959: program that you want to be portable.
13960:
13961: If you want to be able to port the program to other Forth systems, there
13962: are the following points to consider:
13963:
13964: @itemize @bullet
13965:
13966: @item
13967: Most Forth systems that are being maintained support the ANS Forth
13968: standard. So if your program complies with the standard, it will be
13969: portable among many systems.
13970:
13971: @item
13972: A number of the Gforth extensions can be implemented in ANS Forth using
13973: public-domain files provided in the @file{compat/} directory. These are
13974: mentioned in the text in passing. There is no reason not to use these
13975: extensions, your program will still be ANS Forth compliant; just include
13976: the appropriate compat files with your program.
13977:
13978: @item
13979: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13980: analyse your program and determine what non-Standard words it relies
13981: upon. However, it does not check whether you use standard words in a
13982: non-standard way.
13983:
13984: @item
13985: Some techniques are not standardized by ANS Forth, and are hard or
13986: impossible to implement in a standard way, but can be implemented in
13987: most Forth systems easily, and usually in similar ways (e.g., accessing
13988: word headers). Forth has a rich historical precedent for programmers
13989: taking advantage of implementation-dependent features of their tools
13990: (for example, relying on a knowledge of the dictionary
13991: structure). Sometimes these techniques are necessary to extract every
13992: last bit of performance from the hardware, sometimes they are just a
13993: programming shorthand.
13994:
13995: @item
13996: Does using a Gforth extension save more work than the porting this part
13997: to other Forth systems (if any) will cost?
13998:
13999: @item
14000: Is the additional functionality worth the reduction in portability and
14001: the additional porting problems?
14002:
14003: @end itemize
14004:
14005: In order to perform these consideratios, you need to know what's
14006: standard and what's not. This manual generally states if something is
14007: non-standard, but the authoritative source is the
14008: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
14009: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14010: into the thought processes of the technical committee.
14011:
14012: Note also that portability between Forth systems is not the only
14013: portability issue; there is also the issue of portability between
14014: different platforms (processor/OS combinations).
14015:
14016: @c ***************************************************************
14017: @node Model, Integrating Gforth, Standard vs Extensions, Top
14018: @chapter Model
14019:
14020: This chapter has yet to be written. It will contain information, on
14021: which internal structures you can rely.
14022:
14023: @c ***************************************************************
14024: @node Integrating Gforth, Emacs and Gforth, Model, Top
14025: @chapter Integrating Gforth into C programs
14026:
14027: This is not yet implemented.
14028:
14029: Several people like to use Forth as scripting language for applications
14030: that are otherwise written in C, C++, or some other language.
14031:
14032: The Forth system ATLAST provides facilities for embedding it into
14033: applications; unfortunately it has several disadvantages: most
14034: importantly, it is not based on ANS Forth, and it is apparently dead
14035: (i.e., not developed further and not supported). The facilities
14036: provided by Gforth in this area are inspired by ATLAST's facilities, so
14037: making the switch should not be hard.
14038:
14039: We also tried to design the interface such that it can easily be
14040: implemented by other Forth systems, so that we may one day arrive at a
14041: standardized interface. Such a standard interface would allow you to
14042: replace the Forth system without having to rewrite C code.
14043:
14044: You embed the Gforth interpreter by linking with the library
14045: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
14046: global symbols in this library that belong to the interface, have the
14047: prefix @code{forth_}. (Global symbols that are used internally have the
14048: prefix @code{gforth_}).
14049:
14050: You can include the declarations of Forth types and the functions and
14051: variables of the interface with @code{#include <forth.h>}.
14052:
14053: Types.
14054:
14055: Variables.
14056:
14057: Data and FP Stack pointer. Area sizes.
14058:
14059: functions.
14060:
14061: forth_init(imagefile)
14062: forth_evaluate(string) exceptions?
14063: forth_goto(address) (or forth_execute(xt)?)
14064: forth_continue() (a corountining mechanism)
14065:
14066: Adding primitives.
14067:
14068: No checking.
14069:
14070: Signals?
14071:
14072: Accessing the Stacks
14073:
14074: @c ******************************************************************
14075: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14076: @chapter Emacs and Gforth
14077: @cindex Emacs and Gforth
14078:
14079: @cindex @file{gforth.el}
14080: @cindex @file{forth.el}
14081: @cindex Rydqvist, Goran
14082: @cindex Kuehling, David
14083: @cindex comment editing commands
14084: @cindex @code{\}, editing with Emacs
14085: @cindex debug tracer editing commands
14086: @cindex @code{~~}, removal with Emacs
14087: @cindex Forth mode in Emacs
14088:
14089: Gforth comes with @file{gforth.el}, an improved version of
14090: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
14091: improvements are:
14092:
14093: @itemize @bullet
14094: @item
14095: A better handling of indentation.
14096: @item
14097: A custom hilighting engine for Forth-code.
14098: @item
14099: Comment paragraph filling (@kbd{M-q})
14100: @item
14101: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14102: @item
14103: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
14104: @item
14105: Support of the @code{info-lookup} feature for looking up the
14106: documentation of a word.
14107: @item
14108: Support for reading and writing blocks files.
14109: @end itemize
14110:
14111: To get a basic description of these features, enter Forth mode and
14112: type @kbd{C-h m}.
14113:
14114: @cindex source location of error or debugging output in Emacs
14115: @cindex error output, finding the source location in Emacs
14116: @cindex debugging output, finding the source location in Emacs
14117: In addition, Gforth supports Emacs quite well: The source code locations
14118: given in error messages, debugging output (from @code{~~}) and failed
14119: assertion messages are in the right format for Emacs' compilation mode
14120: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14121: Manual}) so the source location corresponding to an error or other
14122: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14123: @kbd{C-c C-c} for the error under the cursor).
14124:
14125: @cindex viewing the documentation of a word in Emacs
14126: @cindex context-sensitive help
14127: Moreover, for words documented in this manual, you can look up the
14128: glossary entry quickly by using @kbd{C-h TAB}
14129: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14130: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14131: later and does not work for words containing @code{:}.
14132:
14133: @menu
14134: * Installing gforth.el:: Making Emacs aware of Forth.
14135: * Emacs Tags:: Viewing the source of a word in Emacs.
14136: * Hilighting:: Making Forth code look prettier.
14137: * Auto-Indentation:: Customizing auto-indentation.
14138: * Blocks Files:: Reading and writing blocks files.
14139: @end menu
14140:
14141: @c ----------------------------------
14142: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
14143: @section Installing gforth.el
14144: @cindex @file{.emacs}
14145: @cindex @file{gforth.el}, installation
14146: To make the features from @file{gforth.el} available in Emacs, add
14147: the following lines to your @file{.emacs} file:
14148:
14149: @example
14150: (autoload 'forth-mode "gforth.el")
14151: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
14152: auto-mode-alist))
14153: (autoload 'forth-block-mode "gforth.el")
14154: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
14155: auto-mode-alist))
14156: (add-hook 'forth-mode-hook (function (lambda ()
14157: ;; customize variables here:
14158: (setq forth-indent-level 4)
14159: (setq forth-minor-indent-level 2)
14160: (setq forth-hilight-level 3)
14161: ;;; ...
14162: )))
14163: @end example
14164:
14165: @c ----------------------------------
14166: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14167: @section Emacs Tags
14168: @cindex @file{TAGS} file
14169: @cindex @file{etags.fs}
14170: @cindex viewing the source of a word in Emacs
14171: @cindex @code{require}, placement in files
14172: @cindex @code{include}, placement in files
14173: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14174: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
14175: contains the definitions of all words defined afterwards. You can then
14176: find the source for a word using @kbd{M-.}. Note that Emacs can use
14177: several tags files at the same time (e.g., one for the Gforth sources
14178: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14179: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14180: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
14181: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
14182: with @file{etags.fs}, you should avoid putting definitions both before
14183: and after @code{require} etc., otherwise you will see the same file
14184: visited several times by commands like @code{tags-search}.
14185:
14186: @c ----------------------------------
14187: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14188: @section Hilighting
14189: @cindex hilighting Forth code in Emacs
14190: @cindex highlighting Forth code in Emacs
14191: @file{gforth.el} comes with a custom source hilighting engine. When
14192: you open a file in @code{forth-mode}, it will be completely parsed,
14193: assigning faces to keywords, comments, strings etc. While you edit
14194: the file, modified regions get parsed and updated on-the-fly.
14195:
14196: Use the variable `forth-hilight-level' to change the level of
14197: decoration from 0 (no hilighting at all) to 3 (the default). Even if
14198: you set the hilighting level to 0, the parser will still work in the
14199: background, collecting information about whether regions of text are
14200: ``compiled'' or ``interpreted''. Those information are required for
14201: auto-indentation to work properly. Set `forth-disable-parser' to
14202: non-nil if your computer is too slow to handle parsing. This will
14203: have an impact on the smartness of the auto-indentation engine,
14204: though.
14205:
14206: Sometimes Forth sources define new features that should be hilighted,
14207: new control structures, defining-words etc. You can use the variable
14208: `forth-custom-words' to make @code{forth-mode} hilight additional
14209: words and constructs. See the docstring of `forth-words' for details
14210: (in Emacs, type @kbd{C-h v forth-words}).
14211:
14212: `forth-custom-words' is meant to be customized in your
14213: @file{.emacs} file. To customize hilighing in a file-specific manner,
14214: set `forth-local-words' in a local-variables section at the end of
14215: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14216:
14217: Example:
14218: @example
14219: 0 [IF]
14220: Local Variables:
14221: forth-local-words:
14222: ((("t:") definition-starter (font-lock-keyword-face . 1)
14223: "[ \t\n]" t name (font-lock-function-name-face . 3))
14224: ((";t") definition-ender (font-lock-keyword-face . 1)))
14225: End:
14226: [THEN]
14227: @end example
14228:
14229: @c ----------------------------------
14230: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14231: @section Auto-Indentation
14232: @cindex auto-indentation of Forth code in Emacs
14233: @cindex indentation of Forth code in Emacs
14234: @code{forth-mode} automatically tries to indent lines in a smart way,
14235: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14236:
14237: Simple customization can be achieved by setting
14238: `forth-indent-level' and `forth-minor-indent-level' in your
14239: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14240: per default by multiples of 4 columns. To use the more traditional
14241: 3-column indentation, add the following lines to your @file{.emacs}:
14242:
14243: @example
14244: (add-hook 'forth-mode-hook (function (lambda ()
14245: ;; customize variables here:
14246: (setq forth-indent-level 3)
14247: (setq forth-minor-indent-level 1)
14248: )))
14249: @end example
14250:
14251: If you want indentation to recognize non-default words, customize it
14252: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14253: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14254: v forth-indent-words}).
14255:
14256: To customize indentation in a file-specific manner, set
14257: `forth-local-indent-words' in a local-variables section at the end of
14258: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14259: Emacs Manual}).
14260:
14261: Example:
14262: @example
14263: 0 [IF]
14264: Local Variables:
14265: forth-local-indent-words:
14266: ((("t:") (0 . 2) (0 . 2))
14267: ((";t") (-2 . 0) (0 . -2)))
14268: End:
14269: [THEN]
14270: @end example
14271:
14272: @c ----------------------------------
14273: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
14274: @section Blocks Files
14275: @cindex blocks files, use with Emacs
14276: @code{forth-mode} Autodetects blocks files by checking whether the
14277: length of the first line exceeds 1023 characters. It then tries to
14278: convert the file into normal text format. When you save the file, it
14279: will be written to disk as normal stream-source file.
14280:
14281: If you want to write blocks files, use @code{forth-blocks-mode}. It
14282: inherits all the features from @code{forth-mode}, plus some additions:
14283:
14284: @itemize @bullet
14285: @item
14286: Files are written to disk in blocks file format.
14287: @item
14288: Screen numbers are displayed in the mode line (enumerated beginning
14289: with the value of `forth-block-base')
14290: @item
14291: Warnings are displayed when lines exceed 64 characters.
14292: @item
14293: The beginning of the currently edited block is marked with an
14294: overlay-arrow.
14295: @end itemize
14296:
14297: There are some restrictions you should be aware of. When you open a
14298: blocks file that contains tabulator or newline characters, these
14299: characters will be translated into spaces when the file is written
14300: back to disk. If tabs or newlines are encountered during blocks file
14301: reading, an error is output to the echo area. So have a look at the
14302: `*Messages*' buffer, when Emacs' bell rings during reading.
14303:
14304: Please consult the docstring of @code{forth-blocks-mode} for more
14305: information by typing @kbd{C-h v forth-blocks-mode}).
14306:
14307: @c ******************************************************************
14308: @node Image Files, Engine, Emacs and Gforth, Top
14309: @chapter Image Files
14310: @cindex image file
14311: @cindex @file{.fi} files
14312: @cindex precompiled Forth code
14313: @cindex dictionary in persistent form
14314: @cindex persistent form of dictionary
14315:
14316: An image file is a file containing an image of the Forth dictionary,
14317: i.e., compiled Forth code and data residing in the dictionary. By
14318: convention, we use the extension @code{.fi} for image files.
14319:
14320: @menu
14321: * Image Licensing Issues:: Distribution terms for images.
14322: * Image File Background:: Why have image files?
14323: * Non-Relocatable Image Files:: don't always work.
14324: * Data-Relocatable Image Files:: are better.
14325: * Fully Relocatable Image Files:: better yet.
14326: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
14327: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
14328: * Modifying the Startup Sequence:: and turnkey applications.
14329: @end menu
14330:
14331: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14332: @section Image Licensing Issues
14333: @cindex license for images
14334: @cindex image license
14335:
14336: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14337: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14338: original image; i.e., according to copyright law it is a derived work of
14339: the original image.
14340:
14341: Since Gforth is distributed under the GNU GPL, the newly created image
14342: falls under the GNU GPL, too. In particular, this means that if you
14343: distribute the image, you have to make all of the sources for the image
14344: available, including those you wrote. For details see @ref{Copying, ,
14345: GNU General Public License (Section 3)}.
14346:
14347: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14348: contains only code compiled from the sources you gave it; if none of
14349: these sources is under the GPL, the terms discussed above do not apply
14350: to the image. However, if your image needs an engine (a gforth binary)
14351: that is under the GPL, you should make sure that you distribute both in
14352: a way that is at most a @emph{mere aggregation}, if you don't want the
14353: terms of the GPL to apply to the image.
14354:
14355: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
14356: @section Image File Background
14357: @cindex image file background
14358:
14359: Gforth consists not only of primitives (in the engine), but also of
14360: definitions written in Forth. Since the Forth compiler itself belongs to
14361: those definitions, it is not possible to start the system with the
14362: engine and the Forth source alone. Therefore we provide the Forth
14363: code as an image file in nearly executable form. When Gforth starts up,
14364: a C routine loads the image file into memory, optionally relocates the
14365: addresses, then sets up the memory (stacks etc.) according to
14366: information in the image file, and (finally) starts executing Forth
14367: code.
14368:
14369: The image file variants represent different compromises between the
14370: goals of making it easy to generate image files and making them
14371: portable.
14372:
14373: @cindex relocation at run-time
14374: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
14375: run-time. This avoids many of the complications discussed below (image
14376: files are data relocatable without further ado), but costs performance
14377: (one addition per memory access).
14378:
14379: @cindex relocation at load-time
14380: By contrast, the Gforth loader performs relocation at image load time. The
14381: loader also has to replace tokens that represent primitive calls with the
14382: appropriate code-field addresses (or code addresses in the case of
14383: direct threading).
14384:
14385: There are three kinds of image files, with different degrees of
14386: relocatability: non-relocatable, data-relocatable, and fully relocatable
14387: image files.
14388:
14389: @cindex image file loader
14390: @cindex relocating loader
14391: @cindex loader for image files
14392: These image file variants have several restrictions in common; they are
14393: caused by the design of the image file loader:
14394:
14395: @itemize @bullet
14396: @item
14397: There is only one segment; in particular, this means, that an image file
14398: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
14399: them). The contents of the stacks are not represented, either.
14400:
14401: @item
14402: The only kinds of relocation supported are: adding the same offset to
14403: all cells that represent data addresses; and replacing special tokens
14404: with code addresses or with pieces of machine code.
14405:
14406: If any complex computations involving addresses are performed, the
14407: results cannot be represented in the image file. Several applications that
14408: use such computations come to mind:
14409: @itemize @minus
14410: @item
14411: Hashing addresses (or data structures which contain addresses) for table
14412: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14413: purpose, you will have no problem, because the hash tables are
14414: recomputed automatically when the system is started. If you use your own
14415: hash tables, you will have to do something similar.
14416:
14417: @item
14418: There's a cute implementation of doubly-linked lists that uses
14419: @code{XOR}ed addresses. You could represent such lists as singly-linked
14420: in the image file, and restore the doubly-linked representation on
14421: startup.@footnote{In my opinion, though, you should think thrice before
14422: using a doubly-linked list (whatever implementation).}
14423:
14424: @item
14425: The code addresses of run-time routines like @code{docol:} cannot be
14426: represented in the image file (because their tokens would be replaced by
14427: machine code in direct threaded implementations). As a workaround,
14428: compute these addresses at run-time with @code{>code-address} from the
14429: executions tokens of appropriate words (see the definitions of
14430: @code{docol:} and friends in @file{kernel/getdoers.fs}).
14431:
14432: @item
14433: On many architectures addresses are represented in machine code in some
14434: shifted or mangled form. You cannot put @code{CODE} words that contain
14435: absolute addresses in this form in a relocatable image file. Workarounds
14436: are representing the address in some relative form (e.g., relative to
14437: the CFA, which is present in some register), or loading the address from
14438: a place where it is stored in a non-mangled form.
14439: @end itemize
14440: @end itemize
14441:
14442: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14443: @section Non-Relocatable Image Files
14444: @cindex non-relocatable image files
14445: @cindex image file, non-relocatable
14446:
14447: These files are simple memory dumps of the dictionary. They are specific
14448: to the executable (i.e., @file{gforth} file) they were created
14449: with. What's worse, they are specific to the place on which the
14450: dictionary resided when the image was created. Now, there is no
14451: guarantee that the dictionary will reside at the same place the next
14452: time you start Gforth, so there's no guarantee that a non-relocatable
14453: image will work the next time (Gforth will complain instead of crashing,
14454: though).
14455:
14456: You can create a non-relocatable image file with
14457:
14458:
14459: doc-savesystem
14460:
14461:
14462: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14463: @section Data-Relocatable Image Files
14464: @cindex data-relocatable image files
14465: @cindex image file, data-relocatable
14466:
14467: These files contain relocatable data addresses, but fixed code addresses
14468: (instead of tokens). They are specific to the executable (i.e.,
14469: @file{gforth} file) they were created with. For direct threading on some
14470: architectures (e.g., the i386), data-relocatable images do not work. You
14471: get a data-relocatable image, if you use @file{gforthmi} with a
14472: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14473: Relocatable Image Files}).
14474:
14475: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14476: @section Fully Relocatable Image Files
14477: @cindex fully relocatable image files
14478: @cindex image file, fully relocatable
14479:
14480: @cindex @file{kern*.fi}, relocatability
14481: @cindex @file{gforth.fi}, relocatability
14482: These image files have relocatable data addresses, and tokens for code
14483: addresses. They can be used with different binaries (e.g., with and
14484: without debugging) on the same machine, and even across machines with
14485: the same data formats (byte order, cell size, floating point
14486: format). However, they are usually specific to the version of Gforth
14487: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14488: are fully relocatable.
14489:
14490: There are two ways to create a fully relocatable image file:
14491:
14492: @menu
14493: * gforthmi:: The normal way
14494: * cross.fs:: The hard way
14495: @end menu
14496:
14497: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14498: @subsection @file{gforthmi}
14499: @cindex @file{comp-i.fs}
14500: @cindex @file{gforthmi}
14501:
14502: You will usually use @file{gforthmi}. If you want to create an
14503: image @i{file} that contains everything you would load by invoking
14504: Gforth with @code{gforth @i{options}}, you simply say:
14505: @example
14506: gforthmi @i{file} @i{options}
14507: @end example
14508:
14509: E.g., if you want to create an image @file{asm.fi} that has the file
14510: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14511: like this:
14512:
14513: @example
14514: gforthmi asm.fi asm.fs
14515: @end example
14516:
14517: @file{gforthmi} is implemented as a sh script and works like this: It
14518: produces two non-relocatable images for different addresses and then
14519: compares them. Its output reflects this: first you see the output (if
14520: any) of the two Gforth invocations that produce the non-relocatable image
14521: files, then you see the output of the comparing program: It displays the
14522: offset used for data addresses and the offset used for code addresses;
14523: moreover, for each cell that cannot be represented correctly in the
14524: image files, it displays a line like this:
14525:
14526: @example
14527: 78DC BFFFFA50 BFFFFA40
14528: @end example
14529:
14530: This means that at offset $78dc from @code{forthstart}, one input image
14531: contains $bffffa50, and the other contains $bffffa40. Since these cells
14532: cannot be represented correctly in the output image, you should examine
14533: these places in the dictionary and verify that these cells are dead
14534: (i.e., not read before they are written).
14535:
14536: @cindex --application, @code{gforthmi} option
14537: If you insert the option @code{--application} in front of the image file
14538: name, you will get an image that uses the @code{--appl-image} option
14539: instead of the @code{--image-file} option (@pxref{Invoking
14540: Gforth}). When you execute such an image on Unix (by typing the image
14541: name as command), the Gforth engine will pass all options to the image
14542: instead of trying to interpret them as engine options.
14543:
14544: If you type @file{gforthmi} with no arguments, it prints some usage
14545: instructions.
14546:
14547: @cindex @code{savesystem} during @file{gforthmi}
14548: @cindex @code{bye} during @file{gforthmi}
14549: @cindex doubly indirect threaded code
14550: @cindex environment variables
14551: @cindex @code{GFORTHD} -- environment variable
14552: @cindex @code{GFORTH} -- environment variable
14553: @cindex @code{gforth-ditc}
14554: There are a few wrinkles: After processing the passed @i{options}, the
14555: words @code{savesystem} and @code{bye} must be visible. A special doubly
14556: indirect threaded version of the @file{gforth} executable is used for
14557: creating the non-relocatable images; you can pass the exact filename of
14558: this executable through the environment variable @code{GFORTHD}
14559: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14560: indirect threaded, you will not get a fully relocatable image, but a
14561: data-relocatable image (because there is no code address offset). The
14562: normal @file{gforth} executable is used for creating the relocatable
14563: image; you can pass the exact filename of this executable through the
14564: environment variable @code{GFORTH}.
14565:
14566: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14567: @subsection @file{cross.fs}
14568: @cindex @file{cross.fs}
14569: @cindex cross-compiler
14570: @cindex metacompiler
14571: @cindex target compiler
14572:
14573: You can also use @code{cross}, a batch compiler that accepts a Forth-like
14574: programming language (@pxref{Cross Compiler}).
14575:
14576: @code{cross} allows you to create image files for machines with
14577: different data sizes and data formats than the one used for generating
14578: the image file. You can also use it to create an application image that
14579: does not contain a Forth compiler. These features are bought with
14580: restrictions and inconveniences in programming. E.g., addresses have to
14581: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14582: order to make the code relocatable.
14583:
14584:
14585: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14586: @section Stack and Dictionary Sizes
14587: @cindex image file, stack and dictionary sizes
14588: @cindex dictionary size default
14589: @cindex stack size default
14590:
14591: If you invoke Gforth with a command line flag for the size
14592: (@pxref{Invoking Gforth}), the size you specify is stored in the
14593: dictionary. If you save the dictionary with @code{savesystem} or create
14594: an image with @file{gforthmi}, this size will become the default
14595: for the resulting image file. E.g., the following will create a
14596: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
14597:
14598: @example
14599: gforthmi gforth.fi -m 1M
14600: @end example
14601:
14602: In other words, if you want to set the default size for the dictionary
14603: and the stacks of an image, just invoke @file{gforthmi} with the
14604: appropriate options when creating the image.
14605:
14606: @cindex stack size, cache-friendly
14607: Note: For cache-friendly behaviour (i.e., good performance), you should
14608: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14609: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14610: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14611:
14612: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14613: @section Running Image Files
14614: @cindex running image files
14615: @cindex invoking image files
14616: @cindex image file invocation
14617:
14618: @cindex -i, invoke image file
14619: @cindex --image file, invoke image file
14620: You can invoke Gforth with an image file @i{image} instead of the
14621: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14622: @example
14623: gforth -i @i{image}
14624: @end example
14625:
14626: @cindex executable image file
14627: @cindex image file, executable
14628: If your operating system supports starting scripts with a line of the
14629: form @code{#! ...}, you just have to type the image file name to start
14630: Gforth with this image file (note that the file extension @code{.fi} is
14631: just a convention). I.e., to run Gforth with the image file @i{image},
14632: you can just type @i{image} instead of @code{gforth -i @i{image}}.
14633: This works because every @code{.fi} file starts with a line of this
14634: format:
14635:
14636: @example
14637: #! /usr/local/bin/gforth-0.4.0 -i
14638: @end example
14639:
14640: The file and pathname for the Gforth engine specified on this line is
14641: the specific Gforth executable that it was built against; i.e. the value
14642: of the environment variable @code{GFORTH} at the time that
14643: @file{gforthmi} was executed.
14644:
14645: You can make use of the same shell capability to make a Forth source
14646: file into an executable. For example, if you place this text in a file:
14647:
14648: @example
14649: #! /usr/local/bin/gforth
14650:
14651: ." Hello, world" CR
14652: bye
14653: @end example
14654:
14655: @noindent
14656: and then make the file executable (chmod +x in Unix), you can run it
14657: directly from the command line. The sequence @code{#!} is used in two
14658: ways; firstly, it is recognised as a ``magic sequence'' by the operating
14659: system@footnote{The Unix kernel actually recognises two types of files:
14660: executable files and files of data, where the data is processed by an
14661: interpreter that is specified on the ``interpreter line'' -- the first
14662: line of the file, starting with the sequence #!. There may be a small
14663: limit (e.g., 32) on the number of characters that may be specified on
14664: the interpreter line.} secondly it is treated as a comment character by
14665: Gforth. Because of the second usage, a space is required between
14666: @code{#!} and the path to the executable (moreover, some Unixes
14667: require the sequence @code{#! /}).
14668:
14669: The disadvantage of this latter technique, compared with using
14670: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14671: compiled on-the-fly, each time the program is invoked.
14672:
14673: doc-#!
14674:
14675:
14676: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14677: @section Modifying the Startup Sequence
14678: @cindex startup sequence for image file
14679: @cindex image file initialization sequence
14680: @cindex initialization sequence of image file
14681:
14682: You can add your own initialization to the startup sequence of an image
14683: through the deferred word @code{'cold}. @code{'cold} is invoked just
14684: before the image-specific command line processing (i.e., loading files
14685: and evaluating (@code{-e}) strings) starts.
14686:
14687: A sequence for adding your initialization usually looks like this:
14688:
14689: @example
14690: :noname
14691: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14692: ... \ your stuff
14693: ; IS 'cold
14694: @end example
14695:
14696: After @code{'cold}, Gforth processes the image options
14697: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
14698: another deferred word. This normally prints Gforth's startup message
14699: and does nothing else.
14700:
14701: @cindex turnkey image files
14702: @cindex image file, turnkey applications
14703: So, if you want to make a turnkey image (i.e., an image for an
14704: application instead of an extended Forth system), you can do this in
14705: two ways:
14706:
14707: @itemize @bullet
14708:
14709: @item
14710: If you want to do your interpretation of the OS command-line
14711: arguments, hook into @code{'cold}. In that case you probably also
14712: want to build the image with @code{gforthmi --application}
14713: (@pxref{gforthmi}) to keep the engine from processing OS command line
14714: options. You can then do your own command-line processing with
14715: @code{next-arg}
14716:
14717: @item
14718: If you want to have the normal Gforth processing of OS command-line
14719: arguments, hook into @code{bootmessage}.
14720:
14721: @end itemize
14722:
14723: In either case, you probably do not want the word that you execute in
14724: these hooks to exit normally, but use @code{bye} or @code{throw}.
14725: Otherwise the Gforth startup process would continue and eventually
14726: present the Forth command line to the user.
14727:
14728: doc-'cold
14729: doc-bootmessage
14730:
14731: @c ******************************************************************
14732: @node Engine, Cross Compiler, Image Files, Top
14733: @chapter Engine
14734: @cindex engine
14735: @cindex virtual machine
14736:
14737: Reading this chapter is not necessary for programming with Gforth. It
14738: may be helpful for finding your way in the Gforth sources.
14739:
14740: The ideas in this section have also been published in the following
14741: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14742: Forth-Tagung '93; M. Anton Ertl,
14743: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14744: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14745: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14746: Threaded code variations and optimizations (extended version)}},
14747: Forth-Tagung '02.
14748:
14749: @menu
14750: * Portability::
14751: * Threading::
14752: * Primitives::
14753: * Performance::
14754: @end menu
14755:
14756: @node Portability, Threading, Engine, Engine
14757: @section Portability
14758: @cindex engine portability
14759:
14760: An important goal of the Gforth Project is availability across a wide
14761: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14762: achieved this goal by manually coding the engine in assembly language
14763: for several then-popular processors. This approach is very
14764: labor-intensive and the results are short-lived due to progress in
14765: computer architecture.
14766:
14767: @cindex C, using C for the engine
14768: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14769: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14770: particularly popular for UNIX-based Forths due to the large variety of
14771: architectures of UNIX machines. Unfortunately an implementation in C
14772: does not mix well with the goals of efficiency and with using
14773: traditional techniques: Indirect or direct threading cannot be expressed
14774: in C, and switch threading, the fastest technique available in C, is
14775: significantly slower. Another problem with C is that it is very
14776: cumbersome to express double integer arithmetic.
14777:
14778: @cindex GNU C for the engine
14779: @cindex long long
14780: Fortunately, there is a portable language that does not have these
14781: limitations: GNU C, the version of C processed by the GNU C compiler
14782: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14783: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14784: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14785: threading possible, its @code{long long} type (@pxref{Long Long, ,
14786: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
14787: double numbers on many systems. GNU C is freely available on all
14788: important (and many unimportant) UNIX machines, VMS, 80386s running
14789: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14790: on all these machines.
14791:
14792: Writing in a portable language has the reputation of producing code that
14793: is slower than assembly. For our Forth engine we repeatedly looked at
14794: the code produced by the compiler and eliminated most compiler-induced
14795: inefficiencies by appropriate changes in the source code.
14796:
14797: @cindex explicit register declarations
14798: @cindex --enable-force-reg, configuration flag
14799: @cindex -DFORCE_REG
14800: However, register allocation cannot be portably influenced by the
14801: programmer, leading to some inefficiencies on register-starved
14802: machines. We use explicit register declarations (@pxref{Explicit Reg
14803: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14804: improve the speed on some machines. They are turned on by using the
14805: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14806: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14807: machine, but also on the compiler version: On some machines some
14808: compiler versions produce incorrect code when certain explicit register
14809: declarations are used. So by default @code{-DFORCE_REG} is not used.
14810:
14811: @node Threading, Primitives, Portability, Engine
14812: @section Threading
14813: @cindex inner interpreter implementation
14814: @cindex threaded code implementation
14815:
14816: @cindex labels as values
14817: GNU C's labels as values extension (available since @code{gcc-2.0},
14818: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
14819: makes it possible to take the address of @i{label} by writing
14820: @code{&&@i{label}}. This address can then be used in a statement like
14821: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
14822: @code{goto x}.
14823:
14824: @cindex @code{NEXT}, indirect threaded
14825: @cindex indirect threaded inner interpreter
14826: @cindex inner interpreter, indirect threaded
14827: With this feature an indirect threaded @code{NEXT} looks like:
14828: @example
14829: cfa = *ip++;
14830: ca = *cfa;
14831: goto *ca;
14832: @end example
14833: @cindex instruction pointer
14834: For those unfamiliar with the names: @code{ip} is the Forth instruction
14835: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14836: execution token and points to the code field of the next word to be
14837: executed; The @code{ca} (code address) fetched from there points to some
14838: executable code, e.g., a primitive or the colon definition handler
14839: @code{docol}.
14840:
14841: @cindex @code{NEXT}, direct threaded
14842: @cindex direct threaded inner interpreter
14843: @cindex inner interpreter, direct threaded
14844: Direct threading is even simpler:
14845: @example
14846: ca = *ip++;
14847: goto *ca;
14848: @end example
14849:
14850: Of course we have packaged the whole thing neatly in macros called
14851: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
14852:
14853: @menu
14854: * Scheduling::
14855: * Direct or Indirect Threaded?::
14856: * Dynamic Superinstructions::
14857: * DOES>::
14858: @end menu
14859:
14860: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14861: @subsection Scheduling
14862: @cindex inner interpreter optimization
14863:
14864: There is a little complication: Pipelined and superscalar processors,
14865: i.e., RISC and some modern CISC machines can process independent
14866: instructions while waiting for the results of an instruction. The
14867: compiler usually reorders (schedules) the instructions in a way that
14868: achieves good usage of these delay slots. However, on our first tries
14869: the compiler did not do well on scheduling primitives. E.g., for
14870: @code{+} implemented as
14871: @example
14872: n=sp[0]+sp[1];
14873: sp++;
14874: sp[0]=n;
14875: NEXT;
14876: @end example
14877: the @code{NEXT} comes strictly after the other code, i.e., there is
14878: nearly no scheduling. After a little thought the problem becomes clear:
14879: The compiler cannot know that @code{sp} and @code{ip} point to different
14880: addresses (and the version of @code{gcc} we used would not know it even
14881: if it was possible), so it could not move the load of the cfa above the
14882: store to the TOS. Indeed the pointers could be the same, if code on or
14883: very near the top of stack were executed. In the interest of speed we
14884: chose to forbid this probably unused ``feature'' and helped the compiler
14885: in scheduling: @code{NEXT} is divided into several parts:
14886: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14887: like:
14888: @example
14889: NEXT_P0;
14890: n=sp[0]+sp[1];
14891: sp++;
14892: NEXT_P1;
14893: sp[0]=n;
14894: NEXT_P2;
14895: @end example
14896:
14897: There are various schemes that distribute the different operations of
14898: NEXT between these parts in several ways; in general, different schemes
14899: perform best on different processors. We use a scheme for most
14900: architectures that performs well for most processors of this
14901: architecture; in the future we may switch to benchmarking and chosing
14902: the scheme on installation time.
14903:
14904:
14905: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
14906: @subsection Direct or Indirect Threaded?
14907: @cindex threading, direct or indirect?
14908:
14909: Threaded forth code consists of references to primitives (simple machine
14910: code routines like @code{+}) and to non-primitives (e.g., colon
14911: definitions, variables, constants); for a specific class of
14912: non-primitives (e.g., variables) there is one code routine (e.g.,
14913: @code{dovar}), but each variable needs a separate reference to its data.
14914:
14915: Traditionally Forth has been implemented as indirect threaded code,
14916: because this allows to use only one cell to reference a non-primitive
14917: (basically you point to the data, and find the code address there).
14918:
14919: @cindex primitive-centric threaded code
14920: However, threaded code in Gforth (since 0.6.0) uses two cells for
14921: non-primitives, one for the code address, and one for the data address;
14922: the data pointer is an immediate argument for the virtual machine
14923: instruction represented by the code address. We call this
14924: @emph{primitive-centric} threaded code, because all code addresses point
14925: to simple primitives. E.g., for a variable, the code address is for
14926: @code{lit} (also used for integer literals like @code{99}).
14927:
14928: Primitive-centric threaded code allows us to use (faster) direct
14929: threading as dispatch method, completely portably (direct threaded code
14930: in Gforth before 0.6.0 required architecture-specific code). It also
14931: eliminates the performance problems related to I-cache consistency that
14932: 386 implementations have with direct threaded code, and allows
14933: additional optimizations.
14934:
14935: @cindex hybrid direct/indirect threaded code
14936: There is a catch, however: the @var{xt} parameter of @code{execute} can
14937: occupy only one cell, so how do we pass non-primitives with their code
14938: @emph{and} data addresses to them? Our answer is to use indirect
14939: threaded dispatch for @code{execute} and other words that use a
14940: single-cell xt. So, normal threaded code in colon definitions uses
14941: direct threading, and @code{execute} and similar words, which dispatch
14942: to xts on the data stack, use indirect threaded code. We call this
14943: @emph{hybrid direct/indirect} threaded code.
14944:
14945: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14946: @cindex gforth engine
14947: @cindex gforth-fast engine
14948: The engines @command{gforth} and @command{gforth-fast} use hybrid
14949: direct/indirect threaded code. This means that with these engines you
14950: cannot use @code{,} to compile an xt. Instead, you have to use
14951: @code{compile,}.
14952:
14953: @cindex gforth-itc engine
14954: If you want to compile xts with @code{,}, use @command{gforth-itc}.
14955: This engine uses plain old indirect threaded code. It still compiles in
14956: a primitive-centric style, so you cannot use @code{compile,} instead of
14957: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
14958: ... [}). If you want to do that, you have to use @command{gforth-itc}
14959: and execute @code{' , is compile,}. Your program can check if it is
14960: running on a hybrid direct/indirect threaded engine or a pure indirect
14961: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14962:
14963:
14964: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14965: @subsection Dynamic Superinstructions
14966: @cindex Dynamic superinstructions with replication
14967: @cindex Superinstructions
14968: @cindex Replication
14969:
14970: The engines @command{gforth} and @command{gforth-fast} use another
14971: optimization: Dynamic superinstructions with replication. As an
14972: example, consider the following colon definition:
14973:
14974: @example
14975: : squared ( n1 -- n2 )
14976: dup * ;
14977: @end example
14978:
14979: Gforth compiles this into the threaded code sequence
14980:
14981: @example
14982: dup
14983: *
14984: ;s
14985: @end example
14986:
14987: In normal direct threaded code there is a code address occupying one
14988: cell for each of these primitives. Each code address points to a
14989: machine code routine, and the interpreter jumps to this machine code in
14990: order to execute the primitive. The routines for these three
14991: primitives are (in @command{gforth-fast} on the 386):
14992:
14993: @example
14994: Code dup
14995: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
14996: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
14997: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14998: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14999: end-code
15000: Code *
15001: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15002: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
15003: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
15004: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
15005: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15006: end-code
15007: Code ;s
15008: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
15009: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
15010: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15011: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15012: end-code
15013: @end example
15014:
15015: With dynamic superinstructions and replication the compiler does not
15016: just lay down the threaded code, but also copies the machine code
15017: fragments, usually without the jump at the end.
15018:
15019: @example
15020: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
15021: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
15022: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15023: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15024: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
15025: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
15026: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
15027: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
15028: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
15029: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15030: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15031: @end example
15032:
15033: Only when a threaded-code control-flow change happens (e.g., in
15034: @code{;s}), the jump is appended. This optimization eliminates many of
15035: these jumps and makes the rest much more predictable. The speedup
15036: depends on the processor and the application; on the Athlon and Pentium
15037: III this optimization typically produces a speedup by a factor of 2.
15038:
15039: The code addresses in the direct-threaded code are set to point to the
15040: appropriate points in the copied machine code, in this example like
15041: this:
15042:
15043: @example
15044: primitive code address
15045: dup $4057D27D
15046: * $4057D286
15047: ;s $4057D292
15048: @end example
15049:
15050: Thus there can be threaded-code jumps to any place in this piece of
15051: code. This also simplifies decompilation quite a bit.
15052:
15053: @cindex --no-dynamic command-line option
15054: @cindex --no-super command-line option
15055: You can disable this optimization with @option{--no-dynamic}. You can
15056: use the copying without eliminating the jumps (i.e., dynamic
15057: replication, but without superinstructions) with @option{--no-super};
15058: this gives the branch prediction benefit alone; the effect on
15059: performance depends on the CPU; on the Athlon and Pentium III the
15060: speedup is a little less than for dynamic superinstructions with
15061: replication.
15062:
15063: @cindex patching threaded code
15064: One use of these options is if you want to patch the threaded code.
15065: With superinstructions, many of the dispatch jumps are eliminated, so
15066: patching often has no effect. These options preserve all the dispatch
15067: jumps.
15068:
15069: @cindex --dynamic command-line option
15070: On some machines dynamic superinstructions are disabled by default,
15071: because it is unsafe on these machines. However, if you feel
15072: adventurous, you can enable it with @option{--dynamic}.
15073:
15074: @node DOES>, , Dynamic Superinstructions, Threading
15075: @subsection DOES>
15076: @cindex @code{DOES>} implementation
15077:
15078: @cindex @code{dodoes} routine
15079: @cindex @code{DOES>}-code
15080: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15081: the chunk of code executed by every word defined by a
15082: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15083: this is only needed if the xt of the word is @code{execute}d. The main
15084: problem here is: How to find the Forth code to be executed, i.e. the
15085: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15086: solutions:
15087:
15088: In fig-Forth the code field points directly to the @code{dodoes} and the
15089: @code{DOES>}-code address is stored in the cell after the code address
15090: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15091: illegal in the Forth-79 and all later standards, because in fig-Forth
15092: this address lies in the body (which is illegal in these
15093: standards). However, by making the code field larger for all words this
15094: solution becomes legal again. We use this approach. Leaving a cell
15095: unused in most words is a bit wasteful, but on the machines we are
15096: targeting this is hardly a problem.
15097:
15098:
15099: @node Primitives, Performance, Threading, Engine
15100: @section Primitives
15101: @cindex primitives, implementation
15102: @cindex virtual machine instructions, implementation
15103:
15104: @menu
15105: * Automatic Generation::
15106: * TOS Optimization::
15107: * Produced code::
15108: @end menu
15109:
15110: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15111: @subsection Automatic Generation
15112: @cindex primitives, automatic generation
15113:
15114: @cindex @file{prims2x.fs}
15115:
15116: Since the primitives are implemented in a portable language, there is no
15117: longer any need to minimize the number of primitives. On the contrary,
15118: having many primitives has an advantage: speed. In order to reduce the
15119: number of errors in primitives and to make programming them easier, we
15120: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15121: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15122: generates most (and sometimes all) of the C code for a primitive from
15123: the stack effect notation. The source for a primitive has the following
15124: form:
15125:
15126: @cindex primitive source format
15127: @format
15128: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
15129: [@code{""}@i{glossary entry}@code{""}]
15130: @i{C code}
15131: [@code{:}
15132: @i{Forth code}]
15133: @end format
15134:
15135: The items in brackets are optional. The category and glossary fields
15136: are there for generating the documentation, the Forth code is there
15137: for manual implementations on machines without GNU C. E.g., the source
15138: for the primitive @code{+} is:
15139: @example
15140: + ( n1 n2 -- n ) core plus
15141: n = n1+n2;
15142: @end example
15143:
15144: This looks like a specification, but in fact @code{n = n1+n2} is C
15145: code. Our primitive generation tool extracts a lot of information from
15146: the stack effect notations@footnote{We use a one-stack notation, even
15147: though we have separate data and floating-point stacks; The separate
15148: notation can be generated easily from the unified notation.}: The number
15149: of items popped from and pushed on the stack, their type, and by what
15150: name they are referred to in the C code. It then generates a C code
15151: prelude and postlude for each primitive. The final C code for @code{+}
15152: looks like this:
15153:
15154: @example
15155: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
15156: /* */ /* documentation */
15157: NAME("+") /* debugging output (with -DDEBUG) */
15158: @{
15159: DEF_CA /* definition of variable ca (indirect threading) */
15160: Cell n1; /* definitions of variables */
15161: Cell n2;
15162: Cell n;
15163: NEXT_P0; /* NEXT part 0 */
15164: n1 = (Cell) sp[1]; /* input */
15165: n2 = (Cell) TOS;
15166: sp += 1; /* stack adjustment */
15167: @{
15168: n = n1+n2; /* C code taken from the source */
15169: @}
15170: NEXT_P1; /* NEXT part 1 */
15171: TOS = (Cell)n; /* output */
15172: NEXT_P2; /* NEXT part 2 */
15173: @}
15174: @end example
15175:
15176: This looks long and inefficient, but the GNU C compiler optimizes quite
15177: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15178: HP RISC machines: Defining the @code{n}s does not produce any code, and
15179: using them as intermediate storage also adds no cost.
15180:
15181: There are also other optimizations that are not illustrated by this
15182: example: assignments between simple variables are usually for free (copy
15183: propagation). If one of the stack items is not used by the primitive
15184: (e.g. in @code{drop}), the compiler eliminates the load from the stack
15185: (dead code elimination). On the other hand, there are some things that
15186: the compiler does not do, therefore they are performed by
15187: @file{prims2x.fs}: The compiler does not optimize code away that stores
15188: a stack item to the place where it just came from (e.g., @code{over}).
15189:
15190: While programming a primitive is usually easy, there are a few cases
15191: where the programmer has to take the actions of the generator into
15192: account, most notably @code{?dup}, but also words that do not (always)
15193: fall through to @code{NEXT}.
15194:
15195: For more information
15196:
15197: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15198: @subsection TOS Optimization
15199: @cindex TOS optimization for primitives
15200: @cindex primitives, keeping the TOS in a register
15201:
15202: An important optimization for stack machine emulators, e.g., Forth
15203: engines, is keeping one or more of the top stack items in
15204: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
15205: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
15206: @itemize @bullet
15207: @item
15208: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
15209: due to fewer loads from and stores to the stack.
15210: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15211: @i{y<n}, due to additional moves between registers.
15212: @end itemize
15213:
15214: @cindex -DUSE_TOS
15215: @cindex -DUSE_NO_TOS
15216: In particular, keeping one item in a register is never a disadvantage,
15217: if there are enough registers. Keeping two items in registers is a
15218: disadvantage for frequent words like @code{?branch}, constants,
15219: variables, literals and @code{i}. Therefore our generator only produces
15220: code that keeps zero or one items in registers. The generated C code
15221: covers both cases; the selection between these alternatives is made at
15222: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15223: code for @code{+} is just a simple variable name in the one-item case,
15224: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15225: GNU C compiler tries to keep simple variables like @code{TOS} in
15226: registers, and it usually succeeds, if there are enough registers.
15227:
15228: @cindex -DUSE_FTOS
15229: @cindex -DUSE_NO_FTOS
15230: The primitive generator performs the TOS optimization for the
15231: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15232: operations the benefit of this optimization is even larger:
15233: floating-point operations take quite long on most processors, but can be
15234: performed in parallel with other operations as long as their results are
15235: not used. If the FP-TOS is kept in a register, this works. If
15236: it is kept on the stack, i.e., in memory, the store into memory has to
15237: wait for the result of the floating-point operation, lengthening the
15238: execution time of the primitive considerably.
15239:
15240: The TOS optimization makes the automatic generation of primitives a
15241: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15242: @code{TOS} is not sufficient. There are some special cases to
15243: consider:
15244: @itemize @bullet
15245: @item In the case of @code{dup ( w -- w w )} the generator must not
15246: eliminate the store to the original location of the item on the stack,
15247: if the TOS optimization is turned on.
15248: @item Primitives with stack effects of the form @code{--}
15249: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15250: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
15251: must load the TOS from the stack at the end. But for the null stack
15252: effect @code{--} no stores or loads should be generated.
15253: @end itemize
15254:
15255: @node Produced code, , TOS Optimization, Primitives
15256: @subsection Produced code
15257: @cindex primitives, assembly code listing
15258:
15259: @cindex @file{engine.s}
15260: To see what assembly code is produced for the primitives on your machine
15261: with your compiler and your flag settings, type @code{make engine.s} and
15262: look at the resulting file @file{engine.s}. Alternatively, you can also
15263: disassemble the code of primitives with @code{see} on some architectures.
15264:
15265: @node Performance, , Primitives, Engine
15266: @section Performance
15267: @cindex performance of some Forth interpreters
15268: @cindex engine performance
15269: @cindex benchmarking Forth systems
15270: @cindex Gforth performance
15271:
15272: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
15273: impossible to write a significantly faster threaded-code engine.
15274:
15275: On register-starved machines like the 386 architecture processors
15276: improvements are possible, because @code{gcc} does not utilize the
15277: registers as well as a human, even with explicit register declarations;
15278: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15279: and hand-tuned it for the 486; this system is 1.19 times faster on the
15280: Sieve benchmark on a 486DX2/66 than Gforth compiled with
15281: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15282: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15283: registers fit in real registers (and we can even afford to use the TOS
15284: optimization), resulting in a speedup of 1.14 on the sieve over the
15285: earlier results. And dynamic superinstructions provide another speedup
15286: (but only around a factor 1.2 on the 486).
15287:
15288: @cindex Win32Forth performance
15289: @cindex NT Forth performance
15290: @cindex eforth performance
15291: @cindex ThisForth performance
15292: @cindex PFE performance
15293: @cindex TILE performance
15294: The potential advantage of assembly language implementations is not
15295: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
15296: (direct threaded, compiled with @code{gcc-2.95.1} and
15297: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15298: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15299: (with and without peephole (aka pinhole) optimization of the threaded
15300: code); all these systems were written in assembly language. We also
15301: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15302: with @code{gcc-2.6.3} with the default configuration for Linux:
15303: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15304: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15305: employs peephole optimization of the threaded code) and TILE (compiled
15306: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15307: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15308: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15309: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15310: then extended it to run the benchmarks, added the peephole optimizer,
15311: ran the benchmarks and reported the results.
15312:
15313: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15314: matrix multiplication come from the Stanford integer benchmarks and have
15315: been translated into Forth by Martin Fraeman; we used the versions
15316: included in the TILE Forth package, but with bigger data set sizes; and
15317: a recursive Fibonacci number computation for benchmarking calling
15318: performance. The following table shows the time taken for the benchmarks
15319: scaled by the time taken by Gforth (in other words, it shows the speedup
15320: factor that Gforth achieved over the other systems).
15321:
15322: @example
15323: relative Win32- NT eforth This-
15324: time Gforth Forth Forth eforth +opt PFE Forth TILE
15325: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15326: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15327: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15328: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
15329: @end example
15330:
15331: You may be quite surprised by the good performance of Gforth when
15332: compared with systems written in assembly language. One important reason
15333: for the disappointing performance of these other systems is probably
15334: that they are not written optimally for the 486 (e.g., they use the
15335: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15336: but costly method for relocating the Forth image: like @code{cforth}, it
15337: computes the actual addresses at run time, resulting in two address
15338: computations per @code{NEXT} (@pxref{Image File Background}).
15339:
15340: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15341: explained with the self-imposed restriction of the latter systems to
15342: standard C, which makes efficient threading impossible (however, the
15343: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
15344: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15345: Moreover, current C compilers have a hard time optimizing other aspects
15346: of the ThisForth and the TILE source.
15347:
15348: The performance of Gforth on 386 architecture processors varies widely
15349: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15350: allocate any of the virtual machine registers into real machine
15351: registers by itself and would not work correctly with explicit register
15352: declarations, giving a significantly slower engine (on a 486DX2/66
15353: running the Sieve) than the one measured above.
15354:
15355: Note that there have been several releases of Win32Forth since the
15356: release presented here, so the results presented above may have little
15357: predictive value for the performance of Win32Forth today (results for
15358: the current release on an i486DX2/66 are welcome).
15359:
15360: @cindex @file{Benchres}
15361: In
15362: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15363: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
15364: Maierhofer (presented at EuroForth '95), an indirect threaded version of
15365: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15366: several native code systems; that version of Gforth is slower on a 486
15367: than the version used here. You can find a newer version of these
15368: measurements at
15369: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
15370: find numbers for Gforth on various machines in @file{Benchres}.
15371:
15372: @c ******************************************************************
15373: @c @node Binding to System Library, Cross Compiler, Engine, Top
15374: @c @chapter Binding to System Library
15375:
15376: @c ****************************************************************
15377: @node Cross Compiler, Bugs, Engine, Top
15378: @chapter Cross Compiler
15379: @cindex @file{cross.fs}
15380: @cindex cross-compiler
15381: @cindex metacompiler
15382: @cindex target compiler
15383:
15384: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15385: mostly written in Forth, including crucial parts like the outer
15386: interpreter and compiler, it needs compiled Forth code to get
15387: started. The cross compiler allows to create new images for other
15388: architectures, even running under another Forth system.
15389:
15390: @menu
15391: * Using the Cross Compiler::
15392: * How the Cross Compiler Works::
15393: @end menu
15394:
15395: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
15396: @section Using the Cross Compiler
15397:
15398: The cross compiler uses a language that resembles Forth, but isn't. The
15399: main difference is that you can execute Forth code after definition,
15400: while you usually can't execute the code compiled by cross, because the
15401: code you are compiling is typically for a different computer than the
15402: one you are compiling on.
15403:
15404: @c anton: This chapter is somewhat different from waht I would expect: I
15405: @c would expect an explanation of the cross language and how to create an
15406: @c application image with it. The section explains some aspects of
15407: @c creating a Gforth kernel.
15408:
15409: The Makefile is already set up to allow you to create kernels for new
15410: architectures with a simple make command. The generic kernels using the
15411: GCC compiled virtual machine are created in the normal build process
15412: with @code{make}. To create a embedded Gforth executable for e.g. the
15413: 8086 processor (running on a DOS machine), type
15414:
15415: @example
15416: make kernl-8086.fi
15417: @end example
15418:
15419: This will use the machine description from the @file{arch/8086}
15420: directory to create a new kernel. A machine file may look like that:
15421:
15422: @example
15423: \ Parameter for target systems 06oct92py
15424:
15425: 4 Constant cell \ cell size in bytes
15426: 2 Constant cell<< \ cell shift to bytes
15427: 5 Constant cell>bit \ cell shift to bits
15428: 8 Constant bits/char \ bits per character
15429: 8 Constant bits/byte \ bits per byte [default: 8]
15430: 8 Constant float \ bytes per float
15431: 8 Constant /maxalign \ maximum alignment in bytes
15432: false Constant bigendian \ byte order
15433: ( true=big, false=little )
15434:
15435: include machpc.fs \ feature list
15436: @end example
15437:
15438: This part is obligatory for the cross compiler itself, the feature list
15439: is used by the kernel to conditionally compile some features in and out,
15440: depending on whether the target supports these features.
15441:
15442: There are some optional features, if you define your own primitives,
15443: have an assembler, or need special, nonstandard preparation to make the
15444: boot process work. @code{asm-include} includes an assembler,
15445: @code{prims-include} includes primitives, and @code{>boot} prepares for
15446: booting.
15447:
15448: @example
15449: : asm-include ." Include assembler" cr
15450: s" arch/8086/asm.fs" included ;
15451:
15452: : prims-include ." Include primitives" cr
15453: s" arch/8086/prim.fs" included ;
15454:
15455: : >boot ." Prepare booting" cr
15456: s" ' boot >body into-forth 1+ !" evaluate ;
15457: @end example
15458:
15459: These words are used as sort of macro during the cross compilation in
15460: the file @file{kernel/main.fs}. Instead of using these macros, it would
15461: be possible --- but more complicated --- to write a new kernel project
15462: file, too.
15463:
15464: @file{kernel/main.fs} expects the machine description file name on the
15465: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15466: @code{mach-file} leaves a counted string on the stack, or
15467: @code{machine-file} leaves an address, count pair of the filename on the
15468: stack.
15469:
15470: The feature list is typically controlled using @code{SetValue}, generic
15471: files that are used by several projects can use @code{DefaultValue}
15472: instead. Both functions work like @code{Value}, when the value isn't
15473: defined, but @code{SetValue} works like @code{to} if the value is
15474: defined, and @code{DefaultValue} doesn't set anything, if the value is
15475: defined.
15476:
15477: @example
15478: \ generic mach file for pc gforth 03sep97jaw
15479:
15480: true DefaultValue NIL \ relocating
15481:
15482: >ENVIRON
15483:
15484: true DefaultValue file \ controls the presence of the
15485: \ file access wordset
15486: true DefaultValue OS \ flag to indicate a operating system
15487:
15488: true DefaultValue prims \ true: primitives are c-code
15489:
15490: true DefaultValue floating \ floating point wordset is present
15491:
15492: true DefaultValue glocals \ gforth locals are present
15493: \ will be loaded
15494: true DefaultValue dcomps \ double number comparisons
15495:
15496: true DefaultValue hash \ hashing primitives are loaded/present
15497:
15498: true DefaultValue xconds \ used together with glocals,
15499: \ special conditionals supporting gforths'
15500: \ local variables
15501: true DefaultValue header \ save a header information
15502:
15503: true DefaultValue backtrace \ enables backtrace code
15504:
15505: false DefaultValue ec
15506: false DefaultValue crlf
15507:
15508: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15509:
15510: &16 KB DefaultValue stack-size
15511: &15 KB &512 + DefaultValue fstack-size
15512: &15 KB DefaultValue rstack-size
15513: &14 KB &512 + DefaultValue lstack-size
15514: @end example
15515:
15516: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
15517: @section How the Cross Compiler Works
15518:
15519: @node Bugs, Origin, Cross Compiler, Top
15520: @appendix Bugs
15521: @cindex bug reporting
15522:
15523: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
15524:
15525: If you find a bug, please submit a bug report through
15526: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
15527:
15528: @itemize @bullet
15529: @item
15530: A program (or a sequence of keyboard commands) that reproduces the bug.
15531: @item
15532: A description of what you think constitutes the buggy behaviour.
15533: @item
15534: The Gforth version used (it is announced at the start of an
15535: interactive Gforth session).
15536: @item
15537: The machine and operating system (on Unix
15538: systems @code{uname -a} will report this information).
15539: @item
15540: The installation options (you can find the configure options at the
15541: start of @file{config.status}) and configuration (@code{configure}
15542: output or @file{config.cache}).
15543: @item
15544: A complete list of changes (if any) you (or your installer) have made to the
15545: Gforth sources.
15546: @end itemize
15547:
15548: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15549: to Report Bugs, gcc.info, GNU C Manual}.
15550:
15551:
15552: @node Origin, Forth-related information, Bugs, Top
15553: @appendix Authors and Ancestors of Gforth
15554:
15555: @section Authors and Contributors
15556: @cindex authors of Gforth
15557: @cindex contributors to Gforth
15558:
15559: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
15560: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15561: lot to the manual. Assemblers and disassemblers were contributed by
15562: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
15563: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15564: inspired us with their continuous feedback. Lennart Benshop contributed
15565: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15566: support for calling C libraries. Helpful comments also came from Paul
15567: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
15568: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert
15569: Epprecht, Dennis Ruffer and David N. Williams. Since the release of
15570: Gforth-0.2.1 there were also helpful comments from many others; thank
15571: you all, sorry for not listing you here (but digging through my mailbox
15572: to extract your names is on my to-do list).
15573:
15574: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15575: and autoconf, among others), and to the creators of the Internet: Gforth
15576: was developed across the Internet, and its authors did not meet
15577: physically for the first 4 years of development.
15578:
15579: @section Pedigree
15580: @cindex pedigree of Gforth
15581:
15582: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15583: significant part of the design of Gforth was prescribed by ANS Forth.
15584:
15585: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
15586: 32 bit native code version of VolksForth for the Atari ST, written
15587: mostly by Dietrich Weineck.
15588:
15589: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15590: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
15591: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
15592:
15593: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15594: @c Forth-83 standard. !! Pedigree? When?
15595:
15596: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15597: 1979. Robert Selzer and Bill Ragsdale developed the original
15598: implementation of fig-Forth for the 6502 based on microForth.
15599:
15600: The principal architect of microForth was Dean Sanderson. microForth was
15601: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15602: the 1802, and subsequently implemented on the 8080, the 6800 and the
15603: Z80.
15604:
15605: All earlier Forth systems were custom-made, usually by Charles Moore,
15606: who discovered (as he puts it) Forth during the late 60s. The first full
15607: Forth existed in 1971.
15608:
15609: A part of the information in this section comes from
15610: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15611: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
15612: Charles H. Moore, presented at the HOPL-II conference and preprinted
15613: in SIGPLAN Notices 28(3), 1993. You can find more historical and
15614: genealogical information about Forth there. For a more general (and
15615: graphical) Forth family tree look see
15616: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
15617: Forth Family Tree and Timeline}.
15618:
15619: @c ------------------------------------------------------------------
15620: @node Forth-related information, Licenses, Origin, Top
15621: @appendix Other Forth-related information
15622: @cindex Forth-related information
15623:
15624: @c anton: I threw most of this stuff out, because it can be found through
15625: @c the FAQ and the FAQ is more likely to be up-to-date.
15626:
15627: @cindex comp.lang.forth
15628: @cindex frequently asked questions
15629: There is an active news group (comp.lang.forth) discussing Forth
15630: (including Gforth) and Forth-related issues. Its
15631: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15632: (frequently asked questions and their answers) contains a lot of
15633: information on Forth. You should read it before posting to
15634: comp.lang.forth.
15635:
15636: The ANS Forth standard is most usable in its
15637: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
15638:
15639: @c ---------------------------------------------------
15640: @node Licenses, Word Index, Forth-related information, Top
15641: @appendix Licenses
15642:
15643: @menu
15644: * GNU Free Documentation License:: License for copying this manual.
15645: * Copying:: GPL (for copying this software).
15646: @end menu
15647:
15648: @include fdl.texi
15649:
15650: @include gpl.texi
15651:
15652:
15653:
15654: @c ------------------------------------------------------------------
15655: @node Word Index, Concept Index, Licenses, Top
15656: @unnumbered Word Index
15657:
15658: This index is a list of Forth words that have ``glossary'' entries
15659: within this manual. Each word is listed with its stack effect and
15660: wordset.
15661:
15662: @printindex fn
15663:
15664: @c anton: the name index seems superfluous given the word and concept indices.
15665:
15666: @c @node Name Index, Concept Index, Word Index, Top
15667: @c @unnumbered Name Index
15668:
15669: @c This index is a list of Forth words that have ``glossary'' entries
15670: @c within this manual.
15671:
15672: @c @printindex ky
15673:
15674: @c -------------------------------------------------------
15675: @node Concept Index, , Word Index, Top
15676: @unnumbered Concept and Word Index
15677:
15678: Not all entries listed in this index are present verbatim in the
15679: text. This index also duplicates, in abbreviated form, all of the words
15680: listed in the Word Index (only the names are listed for the words here).
15681:
15682: @printindex cp
15683:
15684: @bye
15685:
15686:
15687:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>