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
60: (version @value{VERSION}, @value{UPDATED}),
61: a fast and portable implementation of the ANS Forth language
62:
63: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003 Free Software Foundation, Inc.
64:
65: @quotation
66: Permission is granted to copy, distribute and/or modify this document
67: under the terms of the GNU Free Documentation License, Version 1.1 or
68: any later version published by the Free Software Foundation; with no
69: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
70: and with the Back-Cover Texts as in (a) below. A copy of the
71: license is included in the section entitled ``GNU Free Documentation
72: License.''
73:
74: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
75: this GNU Manual, like GNU software. Copies published by the Free
76: Software Foundation raise funds for GNU development.''
77: @end quotation
78: @end copying
79:
80: @dircategory Software development
81: @direntry
82: * Gforth: (gforth). A fast interpreter for the Forth language.
83: @end direntry
84: @c The Texinfo manual also recommends doing this, but for Gforth it may
85: @c not make much sense
86: @c @dircategory Individual utilities
87: @c @direntry
88: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
89: @c @end direntry
90:
91: @titlepage
92: @title Gforth
93: @subtitle for version @value{VERSION}, @value{UPDATED}
94: @author Neal Crook
95: @author Anton Ertl
96: @author David Kuehling
97: @author Bernd Paysan
98: @author Jens Wilke
99: @page
100: @vskip 0pt plus 1filll
101: @insertcopying
102: @end titlepage
103:
104: @contents
105:
106: @ifnottex
107: @node Top, Goals, (dir), (dir)
108: @top Gforth
109:
110: @insertcopying
111: @end ifnottex
112:
113: @menu
114: * Goals:: About the Gforth Project
115: * Gforth Environment:: Starting (and exiting) Gforth
116: * Tutorial:: Hands-on Forth Tutorial
117: * Introduction:: An introduction to ANS Forth
118: * Words:: Forth words available in Gforth
119: * Error messages:: How to interpret them
120: * Tools:: Programming tools
121: * ANS conformance:: Implementation-defined options etc.
122: * Standard vs Extensions:: Should I use extensions?
123: * Model:: The abstract machine of Gforth
124: * Integrating Gforth:: Forth as scripting language for applications
125: * Emacs and Gforth:: The Gforth Mode
126: * Image Files:: @code{.fi} files contain compiled code
127: * Engine:: The inner interpreter and the primitives
128: * Cross Compiler:: The Cross Compiler
129: * Bugs:: How to report them
130: * Origin:: Authors and ancestors of Gforth
131: * Forth-related information:: Books and places to look on the WWW
132: * Licenses::
133: * Word Index:: An item for each Forth word
134: * Concept Index:: A menu covering many topics
135:
136: @detailmenu
137: --- The Detailed Node Listing ---
138:
139: Gforth Environment
140:
141: * Invoking Gforth:: Getting in
142: * Leaving Gforth:: Getting out
143: * Command-line editing::
144: * Environment variables:: that affect how Gforth starts up
145: * Gforth Files:: What gets installed and where
146: * Gforth in pipes::
147: * Startup speed:: When 35ms is not fast enough ...
148:
149: Forth Tutorial
150:
151: * Starting Gforth Tutorial::
152: * Syntax Tutorial::
153: * Crash Course Tutorial::
154: * Stack Tutorial::
155: * Arithmetics Tutorial::
156: * Stack Manipulation Tutorial::
157: * Using files for Forth code Tutorial::
158: * Comments Tutorial::
159: * Colon Definitions Tutorial::
160: * Decompilation Tutorial::
161: * Stack-Effect Comments Tutorial::
162: * Types Tutorial::
163: * Factoring Tutorial::
164: * Designing the stack effect Tutorial::
165: * Local Variables Tutorial::
166: * Conditional execution Tutorial::
167: * Flags and Comparisons Tutorial::
168: * General Loops Tutorial::
169: * Counted loops Tutorial::
170: * Recursion Tutorial::
171: * Leaving definitions or loops Tutorial::
172: * Return Stack Tutorial::
173: * Memory Tutorial::
174: * Characters and Strings Tutorial::
175: * Alignment Tutorial::
176: * Files Tutorial::
177: * Interpretation and Compilation Semantics and Immediacy Tutorial::
178: * Execution Tokens Tutorial::
179: * Exceptions Tutorial::
180: * Defining Words Tutorial::
181: * Arrays and Records Tutorial::
182: * POSTPONE Tutorial::
183: * Literal Tutorial::
184: * Advanced macros Tutorial::
185: * Compilation Tokens Tutorial::
186: * Wordlists and Search Order Tutorial::
187:
188: An Introduction to ANS Forth
189:
190: * Introducing the Text Interpreter::
191: * Stacks and Postfix notation::
192: * Your first definition::
193: * How does that work?::
194: * Forth is written in Forth::
195: * Review - elements of a Forth system::
196: * Where to go next::
197: * Exercises::
198:
199: Forth Words
200:
201: * Notation::
202: * Case insensitivity::
203: * Comments::
204: * Boolean Flags::
205: * Arithmetic::
206: * Stack Manipulation::
207: * Memory::
208: * Control Structures::
209: * Defining Words::
210: * Interpretation and Compilation Semantics::
211: * Tokens for Words::
212: * Compiling words::
213: * The Text Interpreter::
214: * The Input Stream::
215: * Word Lists::
216: * Environmental Queries::
217: * Files::
218: * Blocks::
219: * Other I/O::
220: * OS command line arguments::
221: * Locals::
222: * Structures::
223: * Object-oriented Forth::
224: * Programming Tools::
225: * Assembler and Code Words::
226: * Threading Words::
227: * Passing Commands to the OS::
228: * Keeping track of Time::
229: * Miscellaneous Words::
230:
231: Arithmetic
232:
233: * Single precision::
234: * Double precision:: Double-cell integer arithmetic
235: * Bitwise operations::
236: * Numeric comparison::
237: * Mixed precision:: Operations with single and double-cell integers
238: * Floating Point::
239:
240: Stack Manipulation
241:
242: * Data stack::
243: * Floating point stack::
244: * Return stack::
245: * Locals stack::
246: * Stack pointer manipulation::
247:
248: Memory
249:
250: * Memory model::
251: * Dictionary allocation::
252: * Heap Allocation::
253: * Memory Access::
254: * Address arithmetic::
255: * Memory Blocks::
256:
257: Control Structures
258:
259: * Selection:: IF ... ELSE ... ENDIF
260: * Simple Loops:: BEGIN ...
261: * Counted Loops:: DO
262: * Arbitrary control structures::
263: * Calls and returns::
264: * Exception Handling::
265:
266: Defining Words
267:
268: * CREATE::
269: * Variables:: Variables and user variables
270: * Constants::
271: * Values:: Initialised variables
272: * Colon Definitions::
273: * Anonymous Definitions:: Definitions without names
274: * Supplying names:: Passing definition names as strings
275: * User-defined Defining Words::
276: * Deferred words:: Allow forward references
277: * Aliases::
278:
279: User-defined Defining Words
280:
281: * CREATE..DOES> applications::
282: * CREATE..DOES> details::
283: * Advanced does> usage example::
284: * @code{Const-does>}::
285:
286: Interpretation and Compilation Semantics
287:
288: * Combined words::
289:
290: Tokens for Words
291:
292: * Execution token:: represents execution/interpretation semantics
293: * Compilation token:: represents compilation semantics
294: * Name token:: represents named words
295:
296: Compiling words
297:
298: * Literals:: Compiling data values
299: * Macros:: Compiling words
300:
301: The Text Interpreter
302:
303: * Input Sources::
304: * Number Conversion::
305: * Interpret/Compile states::
306: * Interpreter Directives::
307:
308: Word Lists
309:
310: * Vocabularies::
311: * Why use word lists?::
312: * Word list example::
313:
314: Files
315:
316: * Forth source files::
317: * General files::
318: * Search Paths::
319:
320: Search Paths
321:
322: * Source Search Paths::
323: * General Search Paths::
324:
325: Other I/O
326:
327: * Simple numeric output:: Predefined formats
328: * Formatted numeric output:: Formatted (pictured) output
329: * String Formats:: How Forth stores strings in memory
330: * Displaying characters and strings:: Other stuff
331: * Input:: Input
332: * Pipes:: How to create your own pipes
333:
334: Locals
335:
336: * Gforth locals::
337: * ANS Forth locals::
338:
339: Gforth locals
340:
341: * Where are locals visible by name?::
342: * How long do locals live?::
343: * Locals programming style::
344: * Locals implementation::
345:
346: Structures
347:
348: * Why explicit structure support?::
349: * Structure Usage::
350: * Structure Naming Convention::
351: * Structure Implementation::
352: * Structure Glossary::
353:
354: Object-oriented Forth
355:
356: * Why object-oriented programming?::
357: * Object-Oriented Terminology::
358: * Objects::
359: * OOF::
360: * Mini-OOF::
361: * Comparison with other object models::
362:
363: The @file{objects.fs} model
364:
365: * Properties of the Objects model::
366: * Basic Objects Usage::
367: * The Objects base class::
368: * Creating objects::
369: * Object-Oriented Programming Style::
370: * Class Binding::
371: * Method conveniences::
372: * Classes and Scoping::
373: * Dividing classes::
374: * Object Interfaces::
375: * Objects Implementation::
376: * Objects Glossary::
377:
378: The @file{oof.fs} model
379:
380: * Properties of the OOF model::
381: * Basic OOF Usage::
382: * The OOF base class::
383: * Class Declaration::
384: * Class Implementation::
385:
386: The @file{mini-oof.fs} model
387:
388: * Basic Mini-OOF Usage::
389: * Mini-OOF Example::
390: * Mini-OOF Implementation::
391:
392: Programming Tools
393:
394: * Examining::
395: * Forgetting words::
396: * Debugging:: Simple and quick.
397: * Assertions:: Making your programs self-checking.
398: * Singlestep Debugger:: Executing your program word by word.
399:
400: Assembler and Code Words
401:
402: * Code and ;code::
403: * Common Assembler:: Assembler Syntax
404: * Common Disassembler::
405: * 386 Assembler:: Deviations and special cases
406: * Alpha Assembler:: Deviations and special cases
407: * MIPS assembler:: Deviations and special cases
408: * Other assemblers:: How to write them
409:
410: Tools
411:
412: * ANS Report:: Report the words used, sorted by wordset.
413:
414: ANS conformance
415:
416: * The Core Words::
417: * The optional Block word set::
418: * The optional Double Number word set::
419: * The optional Exception word set::
420: * The optional Facility word set::
421: * The optional File-Access word set::
422: * The optional Floating-Point word set::
423: * The optional Locals word set::
424: * The optional Memory-Allocation word set::
425: * The optional Programming-Tools word set::
426: * The optional Search-Order word set::
427:
428: The Core Words
429:
430: * core-idef:: Implementation Defined Options
431: * core-ambcond:: Ambiguous Conditions
432: * core-other:: Other System Documentation
433:
434: The optional Block word set
435:
436: * block-idef:: Implementation Defined Options
437: * block-ambcond:: Ambiguous Conditions
438: * block-other:: Other System Documentation
439:
440: The optional Double Number word set
441:
442: * double-ambcond:: Ambiguous Conditions
443:
444: The optional Exception word set
445:
446: * exception-idef:: Implementation Defined Options
447:
448: The optional Facility word set
449:
450: * facility-idef:: Implementation Defined Options
451: * facility-ambcond:: Ambiguous Conditions
452:
453: The optional File-Access word set
454:
455: * file-idef:: Implementation Defined Options
456: * file-ambcond:: Ambiguous Conditions
457:
458: The optional Floating-Point word set
459:
460: * floating-idef:: Implementation Defined Options
461: * floating-ambcond:: Ambiguous Conditions
462:
463: The optional Locals word set
464:
465: * locals-idef:: Implementation Defined Options
466: * locals-ambcond:: Ambiguous Conditions
467:
468: The optional Memory-Allocation word set
469:
470: * memory-idef:: Implementation Defined Options
471:
472: The optional Programming-Tools word set
473:
474: * programming-idef:: Implementation Defined Options
475: * programming-ambcond:: Ambiguous Conditions
476:
477: The optional Search-Order word set
478:
479: * search-idef:: Implementation Defined Options
480: * search-ambcond:: Ambiguous Conditions
481:
482: Emacs and Gforth
483:
484: * Installing gforth.el:: Making Emacs aware of Forth.
485: * Emacs Tags:: Viewing the source of a word in Emacs.
486: * Hilighting:: Making Forth code look prettier.
487: * Auto-Indentation:: Customizing auto-indentation.
488: * Blocks Files:: Reading and writing blocks files.
489:
490: Image Files
491:
492: * Image Licensing Issues:: Distribution terms for images.
493: * Image File Background:: Why have image files?
494: * Non-Relocatable Image Files:: don't always work.
495: * Data-Relocatable Image Files:: are better.
496: * Fully Relocatable Image Files:: better yet.
497: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
498: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
499: * Modifying the Startup Sequence:: and turnkey applications.
500:
501: Fully Relocatable Image Files
502:
503: * gforthmi:: The normal way
504: * cross.fs:: The hard way
505:
506: Engine
507:
508: * Portability::
509: * Threading::
510: * Primitives::
511: * Performance::
512:
513: Threading
514:
515: * Scheduling::
516: * Direct or Indirect Threaded?::
517: * Dynamic Superinstructions::
518: * DOES>::
519:
520: Primitives
521:
522: * Automatic Generation::
523: * TOS Optimization::
524: * Produced code::
525:
526: Cross Compiler
527:
528: * Using the Cross Compiler::
529: * How the Cross Compiler Works::
530:
531: Licenses
532:
533: * GNU Free Documentation License:: License for copying this manual.
534: * Copying:: GPL (for copying this software).
535:
536: @end detailmenu
537: @end menu
538:
539: @c ----------------------------------------------------------
540: @iftex
541: @unnumbered Preface
542: @cindex Preface
543: This manual documents Gforth. Some introductory material is provided for
544: readers who are unfamiliar with Forth or who are migrating to Gforth
545: from other Forth compilers. However, this manual is primarily a
546: reference manual.
547: @end iftex
548:
549: @comment TODO much more blurb here.
550:
551: @c ******************************************************************
552: @node Goals, Gforth Environment, Top, Top
553: @comment node-name, next, previous, up
554: @chapter Goals of Gforth
555: @cindex goals of the Gforth project
556: The goal of the Gforth Project is to develop a standard model for
557: ANS Forth. This can be split into several subgoals:
558:
559: @itemize @bullet
560: @item
561: Gforth should conform to the ANS Forth Standard.
562: @item
563: It should be a model, i.e. it should define all the
564: implementation-dependent things.
565: @item
566: It should become standard, i.e. widely accepted and used. This goal
567: is the most difficult one.
568: @end itemize
569:
570: To achieve these goals Gforth should be
571: @itemize @bullet
572: @item
573: Similar to previous models (fig-Forth, F83)
574: @item
575: Powerful. It should provide for all the things that are considered
576: necessary today and even some that are not yet considered necessary.
577: @item
578: Efficient. It should not get the reputation of being exceptionally
579: slow.
580: @item
581: Free.
582: @item
583: Available on many machines/easy to port.
584: @end itemize
585:
586: Have we achieved these goals? Gforth conforms to the ANS Forth
587: standard. It may be considered a model, but we have not yet documented
588: which parts of the model are stable and which parts we are likely to
589: change. It certainly has not yet become a de facto standard, but it
590: appears to be quite popular. It has some similarities to and some
591: differences from previous models. It has some powerful features, but not
592: yet everything that we envisioned. We certainly have achieved our
593: execution speed goals (@pxref{Performance})@footnote{However, in 1998
594: the bar was raised when the major commercial Forth vendors switched to
595: native code compilers.}. It is free and available on many machines.
596:
597: @c ******************************************************************
598: @node Gforth Environment, Tutorial, Goals, Top
599: @chapter Gforth Environment
600: @cindex Gforth environment
601:
602: Note: ultimately, the Gforth man page will be auto-generated from the
603: material in this chapter.
604:
605: @menu
606: * Invoking Gforth:: Getting in
607: * Leaving Gforth:: Getting out
608: * Command-line editing::
609: * Environment variables:: that affect how Gforth starts up
610: * Gforth Files:: What gets installed and where
611: * Gforth in pipes::
612: * Startup speed:: When 35ms is not fast enough ...
613: @end menu
614:
615: For related information about the creation of images see @ref{Image Files}.
616:
617: @comment ----------------------------------------------
618: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
619: @section Invoking Gforth
620: @cindex invoking Gforth
621: @cindex running Gforth
622: @cindex command-line options
623: @cindex options on the command line
624: @cindex flags on the command line
625:
626: Gforth is made up of two parts; an executable ``engine'' (named
627: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
628: will usually just say @code{gforth} -- this automatically loads the
629: default image file @file{gforth.fi}. In many other cases the default
630: Gforth image will be invoked like this:
631: @example
632: gforth [file | -e forth-code] ...
633: @end example
634: @noindent
635: This interprets the contents of the files and the Forth code in the order they
636: are given.
637:
638: In addition to the @command{gforth} engine, there is also an engine
639: called @command{gforth-fast}, which is faster, but gives less
640: informative error messages (@pxref{Error messages}) and may catch some
641: stack underflows later or not at all. You should use it for debugged,
642: performance-critical programs.
643:
644: Moreover, there is an engine called @command{gforth-itc}, which is
645: useful in some backwards-compatibility situations (@pxref{Direct or
646: Indirect Threaded?}).
647:
648: In general, the command line looks like this:
649:
650: @example
651: gforth[-fast] [engine options] [image options]
652: @end example
653:
654: The engine options must come before the rest of the command
655: line. They are:
656:
657: @table @code
658: @cindex -i, command-line option
659: @cindex --image-file, command-line option
660: @item --image-file @i{file}
661: @itemx -i @i{file}
662: Loads the Forth image @i{file} instead of the default
663: @file{gforth.fi} (@pxref{Image Files}).
664:
665: @cindex --appl-image, command-line option
666: @item --appl-image @i{file}
667: Loads the image @i{file} and leaves all further command-line arguments
668: to the image (instead of processing them as engine options). This is
669: useful for building executable application images on Unix, built with
670: @code{gforthmi --application ...}.
671:
672: @cindex --path, command-line option
673: @cindex -p, command-line option
674: @item --path @i{path}
675: @itemx -p @i{path}
676: Uses @i{path} for searching the image file and Forth source code files
677: instead of the default in the environment variable @code{GFORTHPATH} or
678: the path specified at installation time (e.g.,
679: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
680: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
681:
682: @cindex --dictionary-size, command-line option
683: @cindex -m, command-line option
684: @cindex @i{size} parameters for command-line options
685: @cindex size of the dictionary and the stacks
686: @item --dictionary-size @i{size}
687: @itemx -m @i{size}
688: Allocate @i{size} space for the Forth dictionary space instead of
689: using the default specified in the image (typically 256K). The
690: @i{size} specification for this and subsequent options consists of
691: an integer and a unit (e.g.,
692: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
693: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
694: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
695: @code{e} is used.
696:
697: @cindex --data-stack-size, command-line option
698: @cindex -d, command-line option
699: @item --data-stack-size @i{size}
700: @itemx -d @i{size}
701: Allocate @i{size} space for the data stack instead of using the
702: default specified in the image (typically 16K).
703:
704: @cindex --return-stack-size, command-line option
705: @cindex -r, command-line option
706: @item --return-stack-size @i{size}
707: @itemx -r @i{size}
708: Allocate @i{size} space for the return stack instead of using the
709: default specified in the image (typically 15K).
710:
711: @cindex --fp-stack-size, command-line option
712: @cindex -f, command-line option
713: @item --fp-stack-size @i{size}
714: @itemx -f @i{size}
715: Allocate @i{size} space for the floating point stack instead of
716: using the default specified in the image (typically 15.5K). In this case
717: the unit specifier @code{e} refers to floating point numbers.
718:
719: @cindex --locals-stack-size, command-line option
720: @cindex -l, command-line option
721: @item --locals-stack-size @i{size}
722: @itemx -l @i{size}
723: Allocate @i{size} space for the locals stack instead of using the
724: default specified in the image (typically 14.5K).
725:
726: @cindex -h, command-line option
727: @cindex --help, command-line option
728: @item --help
729: @itemx -h
730: Print a message about the command-line options
731:
732: @cindex -v, command-line option
733: @cindex --version, command-line option
734: @item --version
735: @itemx -v
736: Print version and exit
737:
738: @cindex --debug, command-line option
739: @item --debug
740: Print some information useful for debugging on startup.
741:
742: @cindex --offset-image, command-line option
743: @item --offset-image
744: Start the dictionary at a slightly different position than would be used
745: otherwise (useful for creating data-relocatable images,
746: @pxref{Data-Relocatable Image Files}).
747:
748: @cindex --no-offset-im, command-line option
749: @item --no-offset-im
750: Start the dictionary at the normal position.
751:
752: @cindex --clear-dictionary, command-line option
753: @item --clear-dictionary
754: Initialize all bytes in the dictionary to 0 before loading the image
755: (@pxref{Data-Relocatable Image Files}).
756:
757: @cindex --die-on-signal, command-line-option
758: @item --die-on-signal
759: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
760: or the segmentation violation SIGSEGV) by translating it into a Forth
761: @code{THROW}. With this option, Gforth exits if it receives such a
762: signal. This option is useful when the engine and/or the image might be
763: severely broken (such that it causes another signal before recovering
764: from the first); this option avoids endless loops in such cases.
765:
766: @cindex --no-dynamic, command-line option
767: @cindex --dynamic, command-line option
768: @item --no-dynamic
769: @item --dynamic
770: Disable or enable dynamic superinstructions with replication
771: (@pxref{Dynamic Superinstructions}).
772:
773: @cindex --no-super, command-line option
774: @item --no-super
775: Disable dynamic superinstructions, use just dynamic replication; this is
776: useful if you want to patch threaded code (@pxref{Dynamic
777: Superinstructions}).
778:
779: @cindex --ss-number, command-line option
780: @item --ss-number=@var{N}
781: Use only the first @var{N} static superinstructions compiled into the
782: engine (default: use them all; note that only @code{gforth-fast} has
783: any). This option is useful for measuring the performance impact of
784: static superinstructions.
785:
786: @cindex --ss-min-..., command-line options
787: @item --ss-min-codesize
788: @item --ss-min-ls
789: @item --ss-min-lsu
790: @item --ss-min-nexts
791: Use specified metric for determining the cost of a primitive or static
792: superinstruction for static superinstruction selection. @code{Codesize}
793: is the native code size of the primive or static superinstruction,
794: @code{ls} is the number of loads and stores, @code{lsu} is the number of
795: loads, stores, and updates, and @code{nexts} is the number of dispatches
796: (not taking dynamic superinstructions into account), i.e. every
797: primitive or static superinstruction has cost 1. Default:
798: @code{codesize} if you use dynamic code generation, otherwise
799: @code{nexts}.
800:
801: @cindex --ss-greedy, command-line option
802: @item --ss-greedy
803: This option is useful for measuring the performance impact of static
804: superinstructions. By default, an optimal shortest-path algorithm is
805: used for selecting static superinstructions. With @option{--ss-greedy}
806: this algorithm is modified to assume that anything after the static
807: superinstruction currently under consideration is not combined into
808: static superinstructions. With @option{--ss-min-nexts} this produces
809: the same result as a greedy algorithm that always selects the longest
810: superinstruction available at the moment. E.g., if there are
811: superinstructions AB and BCD, then for the sequence A B C D the optimal
812: algorithm will select A BCD and the greedy algorithm will select AB C D.
813:
814: @cindex --print-metrics, command-line option
815: @item --print-metrics
816: Prints some metrics used during static superinstruction selection:
817: @code{code size} is the actual size of the dynamically generated code.
818: @code{Metric codesize} is the sum of the codesize metrics as seen by
819: static superinstruction selection; there is a difference from @code{code
820: size}, because not all primitives and static superinstructions are
821: compiled into dynamically generated code, and because of markers. The
822: other metrics correspond to the @option{ss-min-...} options. This
823: option is useful for evaluating the effects of the @option{--ss-...}
824: options.
825:
826: @end table
827:
828: @cindex loading files at startup
829: @cindex executing code on startup
830: @cindex batch processing with Gforth
831: As explained above, the image-specific command-line arguments for the
832: default image @file{gforth.fi} consist of a sequence of filenames and
833: @code{-e @var{forth-code}} options that are interpreted in the sequence
834: in which they are given. The @code{-e @var{forth-code}} or
835: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
836: option takes only one argument; if you want to evaluate more Forth
837: words, you have to quote them or use @code{-e} several times. To exit
838: after processing the command line (instead of entering interactive mode)
839: append @code{-e bye} to the command line. You can also process the
840: command-line arguments with a Forth program (@pxref{OS command line
841: arguments}).
842:
843: @cindex versions, invoking other versions of Gforth
844: If you have several versions of Gforth installed, @code{gforth} will
845: invoke the version that was installed last. @code{gforth-@i{version}}
846: invokes a specific version. If your environment contains the variable
847: @code{GFORTHPATH}, you may want to override it by using the
848: @code{--path} option.
849:
850: Not yet implemented:
851: On startup the system first executes the system initialization file
852: (unless the option @code{--no-init-file} is given; note that the system
853: resulting from using this option may not be ANS Forth conformant). Then
854: the user initialization file @file{.gforth.fs} is executed, unless the
855: option @code{--no-rc} is given; this file is searched for in @file{.},
856: then in @file{~}, then in the normal path (see above).
857:
858:
859:
860: @comment ----------------------------------------------
861: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
862: @section Leaving Gforth
863: @cindex Gforth - leaving
864: @cindex leaving Gforth
865:
866: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
867: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
868: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
869: data are discarded. For ways of saving the state of the system before
870: leaving Gforth see @ref{Image Files}.
871:
872: doc-bye
873:
874:
875: @comment ----------------------------------------------
876: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
877: @section Command-line editing
878: @cindex command-line editing
879:
880: Gforth maintains a history file that records every line that you type to
881: the text interpreter. This file is preserved between sessions, and is
882: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
883: repeatedly you can recall successively older commands from this (or
884: previous) session(s). The full list of command-line editing facilities is:
885:
886: @itemize @bullet
887: @item
888: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
889: commands from the history buffer.
890: @item
891: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
892: from the history buffer.
893: @item
894: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
895: @item
896: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
897: @item
898: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
899: closing up the line.
900: @item
901: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
902: @item
903: @kbd{Ctrl-a} to move the cursor to the start of the line.
904: @item
905: @kbd{Ctrl-e} to move the cursor to the end of the line.
906: @item
907: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
908: line.
909: @item
910: @key{TAB} to step through all possible full-word completions of the word
911: currently being typed.
912: @item
913: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
914: using @code{bye}).
915: @item
916: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
917: character under the cursor.
918: @end itemize
919:
920: When editing, displayable characters are inserted to the left of the
921: cursor position; the line is always in ``insert'' (as opposed to
922: ``overstrike'') mode.
923:
924: @cindex history file
925: @cindex @file{.gforth-history}
926: On Unix systems, the history file is @file{~/.gforth-history} by
927: default@footnote{i.e. it is stored in the user's home directory.}. You
928: can find out the name and location of your history file using:
929:
930: @example
931: history-file type \ Unix-class systems
932:
933: history-file type \ Other systems
934: history-dir type
935: @end example
936:
937: If you enter long definitions by hand, you can use a text editor to
938: paste them out of the history file into a Forth source file for reuse at
939: a later time.
940:
941: Gforth never trims the size of the history file, so you should do this
942: periodically, if necessary.
943:
944: @comment this is all defined in history.fs
945: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
946: @comment chosen?
947:
948:
949: @comment ----------------------------------------------
950: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
951: @section Environment variables
952: @cindex environment variables
953:
954: Gforth uses these environment variables:
955:
956: @itemize @bullet
957: @item
958: @cindex @code{GFORTHHIST} -- environment variable
959: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
960: open/create the history file, @file{.gforth-history}. Default:
961: @code{$HOME}.
962:
963: @item
964: @cindex @code{GFORTHPATH} -- environment variable
965: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
966: for Forth source-code files.
967:
968: @item
969: @cindex @code{GFORTH} -- environment variable
970: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
971:
972: @item
973: @cindex @code{GFORTHD} -- environment variable
974: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
975:
976: @item
977: @cindex @code{TMP}, @code{TEMP} - environment variable
978: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
979: location for the history file.
980: @end itemize
981:
982: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
983: @comment mentioning these.
984:
985: All the Gforth environment variables default to sensible values if they
986: are not set.
987:
988:
989: @comment ----------------------------------------------
990: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
991: @section Gforth files
992: @cindex Gforth files
993:
994: When you install Gforth on a Unix system, it installs files in these
995: locations by default:
996:
997: @itemize @bullet
998: @item
999: @file{/usr/local/bin/gforth}
1000: @item
1001: @file{/usr/local/bin/gforthmi}
1002: @item
1003: @file{/usr/local/man/man1/gforth.1} - man page.
1004: @item
1005: @file{/usr/local/info} - the Info version of this manual.
1006: @item
1007: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1008: @item
1009: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1010: @item
1011: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1012: @item
1013: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1014: @end itemize
1015:
1016: You can select different places for installation by using
1017: @code{configure} options (listed with @code{configure --help}).
1018:
1019: @comment ----------------------------------------------
1020: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1021: @section Gforth in pipes
1022: @cindex pipes, Gforth as part of
1023:
1024: Gforth can be used in pipes created elsewhere (described here). It can
1025: also create pipes on its own (@pxref{Pipes}).
1026:
1027: @cindex input from pipes
1028: If you pipe into Gforth, your program should read with @code{read-file}
1029: or @code{read-line} from @code{stdin} (@pxref{General files}).
1030: @code{Key} does not recognize the end of input. Words like
1031: @code{accept} echo the input and are therefore usually not useful for
1032: reading from a pipe. You have to invoke the Forth program with an OS
1033: command-line option, as you have no chance to use the Forth command line
1034: (the text interpreter would try to interpret the pipe input).
1035:
1036: @cindex output in pipes
1037: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1038:
1039: @cindex silent exiting from Gforth
1040: When you write to a pipe that has been closed at the other end, Gforth
1041: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1042: into the exception @code{broken-pipe-error}. If your application does
1043: not catch that exception, the system catches it and exits, usually
1044: silently (unless you were working on the Forth command line; then it
1045: prints an error message and exits). This is usually the desired
1046: behaviour.
1047:
1048: If you do not like this behaviour, you have to catch the exception
1049: yourself, and react to it.
1050:
1051: Here's an example of an invocation of Gforth that is usable in a pipe:
1052:
1053: @example
1054: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1055: type repeat ; foo bye"
1056: @end example
1057:
1058: This example just copies the input verbatim to the output. A very
1059: simple pipe containing this example looks like this:
1060:
1061: @example
1062: cat startup.fs |
1063: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1064: type repeat ; foo bye"|
1065: head
1066: @end example
1067:
1068: @cindex stderr and pipes
1069: Pipes involving Gforth's @code{stderr} output do not work.
1070:
1071: @comment ----------------------------------------------
1072: @node Startup speed, , Gforth in pipes, Gforth Environment
1073: @section Startup speed
1074: @cindex Startup speed
1075: @cindex speed, startup
1076:
1077: If Gforth is used for CGI scripts or in shell scripts, its startup
1078: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1079: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1080: system time.
1081:
1082: If startup speed is a problem, you may consider the following ways to
1083: improve it; or you may consider ways to reduce the number of startups
1084: (for example, by using Fast-CGI).
1085:
1086: An easy step that influences Gforth startup speed is the use of the
1087: @option{--no-dynamic} option; this decreases image loading speed, but
1088: increases compile-time and run-time.
1089:
1090: Another step to improve startup speed is to statically link Gforth, by
1091: building it with @code{XLDFLAGS=-static}. This requires more memory for
1092: the code and will therefore slow down the first invocation, but
1093: subsequent invocations avoid the dynamic linking overhead. Another
1094: disadvantage is that Gforth won't profit from library upgrades. As a
1095: result, @code{gforth-static -e bye} takes about 17.1ms user and
1096: 8.2ms system time.
1097:
1098: The next step to improve startup speed is to use a non-relocatable image
1099: (@pxref{Non-Relocatable Image Files}). You can create this image with
1100: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1101: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1102: and a part of the copy-on-write overhead. The disadvantage is that the
1103: non-relocatable image does not work if the OS gives Gforth a different
1104: address for the dictionary, for whatever reason; so you better provide a
1105: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1106: bye} takes about 15.3ms user and 7.5ms system time.
1107:
1108: The final step is to disable dictionary hashing in Gforth. Gforth
1109: builds the hash table on startup, which takes much of the startup
1110: overhead. You can do this by commenting out the @code{include hash.fs}
1111: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1112: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1113: The disadvantages are that functionality like @code{table} and
1114: @code{ekey} is missing and that text interpretation (e.g., compiling)
1115: now takes much longer. So, you should only use this method if there is
1116: no significant text interpretation to perform (the script should be
1117: compiled into the image, amongst other things). @code{gforth-static -i
1118: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1119:
1120: @c ******************************************************************
1121: @node Tutorial, Introduction, Gforth Environment, Top
1122: @chapter Forth Tutorial
1123: @cindex Tutorial
1124: @cindex Forth Tutorial
1125:
1126: @c Topics from nac's Introduction that could be mentioned:
1127: @c press <ret> after each line
1128: @c Prompt
1129: @c numbers vs. words in dictionary on text interpretation
1130: @c what happens on redefinition
1131: @c parsing words (in particular, defining words)
1132:
1133: The difference of this chapter from the Introduction
1134: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1135: be used while sitting in front of a computer, and covers much more
1136: material, but does not explain how the Forth system works.
1137:
1138: This tutorial can be used with any ANS-compliant Forth; any
1139: Gforth-specific features are marked as such and you can skip them if you
1140: work with another Forth. This tutorial does not explain all features of
1141: Forth, just enough to get you started and give you some ideas about the
1142: facilities available in Forth. Read the rest of the manual and the
1143: standard when you are through this.
1144:
1145: The intended way to use this tutorial is that you work through it while
1146: sitting in front of the console, take a look at the examples and predict
1147: what they will do, then try them out; if the outcome is not as expected,
1148: find out why (e.g., by trying out variations of the example), so you
1149: understand what's going on. There are also some assignments that you
1150: should solve.
1151:
1152: This tutorial assumes that you have programmed before and know what,
1153: e.g., a loop is.
1154:
1155: @c !! explain compat library
1156:
1157: @menu
1158: * Starting Gforth Tutorial::
1159: * Syntax Tutorial::
1160: * Crash Course Tutorial::
1161: * Stack Tutorial::
1162: * Arithmetics Tutorial::
1163: * Stack Manipulation Tutorial::
1164: * Using files for Forth code Tutorial::
1165: * Comments Tutorial::
1166: * Colon Definitions Tutorial::
1167: * Decompilation Tutorial::
1168: * Stack-Effect Comments Tutorial::
1169: * Types Tutorial::
1170: * Factoring Tutorial::
1171: * Designing the stack effect Tutorial::
1172: * Local Variables Tutorial::
1173: * Conditional execution Tutorial::
1174: * Flags and Comparisons Tutorial::
1175: * General Loops Tutorial::
1176: * Counted loops Tutorial::
1177: * Recursion Tutorial::
1178: * Leaving definitions or loops Tutorial::
1179: * Return Stack Tutorial::
1180: * Memory Tutorial::
1181: * Characters and Strings Tutorial::
1182: * Alignment Tutorial::
1183: * Files Tutorial::
1184: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1185: * Execution Tokens Tutorial::
1186: * Exceptions Tutorial::
1187: * Defining Words Tutorial::
1188: * Arrays and Records Tutorial::
1189: * POSTPONE Tutorial::
1190: * Literal Tutorial::
1191: * Advanced macros Tutorial::
1192: * Compilation Tokens Tutorial::
1193: * Wordlists and Search Order Tutorial::
1194: @end menu
1195:
1196: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1197: @section Starting Gforth
1198: @cindex starting Gforth tutorial
1199: You can start Gforth by typing its name:
1200:
1201: @example
1202: gforth
1203: @end example
1204:
1205: That puts you into interactive mode; you can leave Gforth by typing
1206: @code{bye}. While in Gforth, you can edit the command line and access
1207: the command line history with cursor keys, similar to bash.
1208:
1209:
1210: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1211: @section Syntax
1212: @cindex syntax tutorial
1213:
1214: A @dfn{word} is a sequence of arbitrary characters (expcept white
1215: space). Words are separated by white space. E.g., each of the
1216: following lines contains exactly one word:
1217:
1218: @example
1219: word
1220: !@@#$%^&*()
1221: 1234567890
1222: 5!a
1223: @end example
1224:
1225: A frequent beginner's error is to leave away necessary white space,
1226: resulting in an error like @samp{Undefined word}; so if you see such an
1227: error, check if you have put spaces wherever necessary.
1228:
1229: @example
1230: ." hello, world" \ correct
1231: ."hello, world" \ gives an "Undefined word" error
1232: @end example
1233:
1234: Gforth and most other Forth systems ignore differences in case (they are
1235: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1236: your system is case-sensitive, you may have to type all the examples
1237: given here in upper case.
1238:
1239:
1240: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1241: @section Crash Course
1242:
1243: Type
1244:
1245: @example
1246: 0 0 !
1247: here execute
1248: ' catch >body 20 erase abort
1249: ' (quit) >body 20 erase
1250: @end example
1251:
1252: The last two examples are guaranteed to destroy parts of Gforth (and
1253: most other systems), so you better leave Gforth afterwards (if it has
1254: not finished by itself). On some systems you may have to kill gforth
1255: from outside (e.g., in Unix with @code{kill}).
1256:
1257: Now that you know how to produce crashes (and that there's not much to
1258: them), let's learn how to produce meaningful programs.
1259:
1260:
1261: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1262: @section Stack
1263: @cindex stack tutorial
1264:
1265: The most obvious feature of Forth is the stack. When you type in a
1266: number, it is pushed on the stack. You can display the content of the
1267: stack with @code{.s}.
1268:
1269: @example
1270: 1 2 .s
1271: 3 .s
1272: @end example
1273:
1274: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1275: appear in @code{.s} output as they appeared in the input.
1276:
1277: You can print the top of stack element with @code{.}.
1278:
1279: @example
1280: 1 2 3 . . .
1281: @end example
1282:
1283: In general, words consume their stack arguments (@code{.s} is an
1284: exception).
1285:
1286: @assignment
1287: What does the stack contain after @code{5 6 7 .}?
1288: @endassignment
1289:
1290:
1291: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1292: @section Arithmetics
1293: @cindex arithmetics tutorial
1294:
1295: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1296: operate on the top two stack items:
1297:
1298: @example
1299: 2 2 .s
1300: + .s
1301: .
1302: 2 1 - .
1303: 7 3 mod .
1304: @end example
1305:
1306: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1307: as in the corresponding infix expression (this is generally the case in
1308: Forth).
1309:
1310: Parentheses are superfluous (and not available), because the order of
1311: the words unambiguously determines the order of evaluation and the
1312: operands:
1313:
1314: @example
1315: 3 4 + 5 * .
1316: 3 4 5 * + .
1317: @end example
1318:
1319: @assignment
1320: What are the infix expressions corresponding to the Forth code above?
1321: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1322: known as Postfix or RPN (Reverse Polish Notation).}.
1323: @endassignment
1324:
1325: To change the sign, use @code{negate}:
1326:
1327: @example
1328: 2 negate .
1329: @end example
1330:
1331: @assignment
1332: Convert -(-3)*4-5 to Forth.
1333: @endassignment
1334:
1335: @code{/mod} performs both @code{/} and @code{mod}.
1336:
1337: @example
1338: 7 3 /mod . .
1339: @end example
1340:
1341: Reference: @ref{Arithmetic}.
1342:
1343:
1344: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1345: @section Stack Manipulation
1346: @cindex stack manipulation tutorial
1347:
1348: Stack manipulation words rearrange the data on the stack.
1349:
1350: @example
1351: 1 .s drop .s
1352: 1 .s dup .s drop drop .s
1353: 1 2 .s over .s drop drop drop
1354: 1 2 .s swap .s drop drop
1355: 1 2 3 .s rot .s drop drop drop
1356: @end example
1357:
1358: These are the most important stack manipulation words. There are also
1359: variants that manipulate twice as many stack items:
1360:
1361: @example
1362: 1 2 3 4 .s 2swap .s 2drop 2drop
1363: @end example
1364:
1365: Two more stack manipulation words are:
1366:
1367: @example
1368: 1 2 .s nip .s drop
1369: 1 2 .s tuck .s 2drop drop
1370: @end example
1371:
1372: @assignment
1373: Replace @code{nip} and @code{tuck} with combinations of other stack
1374: manipulation words.
1375:
1376: @example
1377: Given: How do you get:
1378: 1 2 3 3 2 1
1379: 1 2 3 1 2 3 2
1380: 1 2 3 1 2 3 3
1381: 1 2 3 1 3 3
1382: 1 2 3 2 1 3
1383: 1 2 3 4 4 3 2 1
1384: 1 2 3 1 2 3 1 2 3
1385: 1 2 3 4 1 2 3 4 1 2
1386: 1 2 3
1387: 1 2 3 1 2 3 4
1388: 1 2 3 1 3
1389: @end example
1390: @endassignment
1391:
1392: @example
1393: 5 dup * .
1394: @end example
1395:
1396: @assignment
1397: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1398: Write a piece of Forth code that expects two numbers on the stack
1399: (@var{a} and @var{b}, with @var{b} on top) and computes
1400: @code{(a-b)(a+1)}.
1401: @endassignment
1402:
1403: Reference: @ref{Stack Manipulation}.
1404:
1405:
1406: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1407: @section Using files for Forth code
1408: @cindex loading Forth code, tutorial
1409: @cindex files containing Forth code, tutorial
1410:
1411: While working at the Forth command line is convenient for one-line
1412: examples and short one-off code, you probably want to store your source
1413: code in files for convenient editing and persistence. You can use your
1414: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1415: Gforth}) to create @var{file.fs} and use
1416:
1417: @example
1418: s" @var{file.fs}" included
1419: @end example
1420:
1421: to load it into your Forth system. The file name extension I use for
1422: Forth files is @samp{.fs}.
1423:
1424: You can easily start Gforth with some files loaded like this:
1425:
1426: @example
1427: gforth @var{file1.fs} @var{file2.fs}
1428: @end example
1429:
1430: If an error occurs during loading these files, Gforth terminates,
1431: whereas an error during @code{INCLUDED} within Gforth usually gives you
1432: a Gforth command line. Starting the Forth system every time gives you a
1433: clean start every time, without interference from the results of earlier
1434: tries.
1435:
1436: I often put all the tests in a file, then load the code and run the
1437: tests with
1438:
1439: @example
1440: gforth @var{code.fs} @var{tests.fs} -e bye
1441: @end example
1442:
1443: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1444: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1445: restart this command without ado.
1446:
1447: The advantage of this approach is that the tests can be repeated easily
1448: every time the program ist changed, making it easy to catch bugs
1449: introduced by the change.
1450:
1451: Reference: @ref{Forth source files}.
1452:
1453:
1454: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1455: @section Comments
1456: @cindex comments tutorial
1457:
1458: @example
1459: \ That's a comment; it ends at the end of the line
1460: ( Another comment; it ends here: ) .s
1461: @end example
1462:
1463: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1464: separated with white space from the following text.
1465:
1466: @example
1467: \This gives an "Undefined word" error
1468: @end example
1469:
1470: The first @code{)} ends a comment started with @code{(}, so you cannot
1471: nest @code{(}-comments; and you cannot comment out text containing a
1472: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1473: avoid @code{)} in word names.}.
1474:
1475: I use @code{\}-comments for descriptive text and for commenting out code
1476: of one or more line; I use @code{(}-comments for describing the stack
1477: effect, the stack contents, or for commenting out sub-line pieces of
1478: code.
1479:
1480: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1481: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1482: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1483: with @kbd{M-q}.
1484:
1485: Reference: @ref{Comments}.
1486:
1487:
1488: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1489: @section Colon Definitions
1490: @cindex colon definitions, tutorial
1491: @cindex definitions, tutorial
1492: @cindex procedures, tutorial
1493: @cindex functions, tutorial
1494:
1495: are similar to procedures and functions in other programming languages.
1496:
1497: @example
1498: : squared ( n -- n^2 )
1499: dup * ;
1500: 5 squared .
1501: 7 squared .
1502: @end example
1503:
1504: @code{:} starts the colon definition; its name is @code{squared}. The
1505: following comment describes its stack effect. The words @code{dup *}
1506: are not executed, but compiled into the definition. @code{;} ends the
1507: colon definition.
1508:
1509: The newly-defined word can be used like any other word, including using
1510: it in other definitions:
1511:
1512: @example
1513: : cubed ( n -- n^3 )
1514: dup squared * ;
1515: -5 cubed .
1516: : fourth-power ( n -- n^4 )
1517: squared squared ;
1518: 3 fourth-power .
1519: @end example
1520:
1521: @assignment
1522: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1523: @code{/mod} in terms of other Forth words, and check if they work (hint:
1524: test your tests on the originals first). Don't let the
1525: @samp{redefined}-Messages spook you, they are just warnings.
1526: @endassignment
1527:
1528: Reference: @ref{Colon Definitions}.
1529:
1530:
1531: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1532: @section Decompilation
1533: @cindex decompilation tutorial
1534: @cindex see tutorial
1535:
1536: You can decompile colon definitions with @code{see}:
1537:
1538: @example
1539: see squared
1540: see cubed
1541: @end example
1542:
1543: In Gforth @code{see} shows you a reconstruction of the source code from
1544: the executable code. Informations that were present in the source, but
1545: not in the executable code, are lost (e.g., comments).
1546:
1547: You can also decompile the predefined words:
1548:
1549: @example
1550: see .
1551: see +
1552: @end example
1553:
1554:
1555: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1556: @section Stack-Effect Comments
1557: @cindex stack-effect comments, tutorial
1558: @cindex --, tutorial
1559: By convention the comment after the name of a definition describes the
1560: stack effect: The part in from of the @samp{--} describes the state of
1561: the stack before the execution of the definition, i.e., the parameters
1562: that are passed into the colon definition; the part behind the @samp{--}
1563: is the state of the stack after the execution of the definition, i.e.,
1564: the results of the definition. The stack comment only shows the top
1565: stack items that the definition accesses and/or changes.
1566:
1567: You should put a correct stack effect on every definition, even if it is
1568: just @code{( -- )}. You should also add some descriptive comment to
1569: more complicated words (I usually do this in the lines following
1570: @code{:}). If you don't do this, your code becomes unreadable (because
1571: you have to work through every definition before you can understand
1572: any).
1573:
1574: @assignment
1575: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1576: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1577: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1578: are done, you can compare your stack effects to those in this manual
1579: (@pxref{Word Index}).
1580: @endassignment
1581:
1582: Sometimes programmers put comments at various places in colon
1583: definitions that describe the contents of the stack at that place (stack
1584: comments); i.e., they are like the first part of a stack-effect
1585: comment. E.g.,
1586:
1587: @example
1588: : cubed ( n -- n^3 )
1589: dup squared ( n n^2 ) * ;
1590: @end example
1591:
1592: In this case the stack comment is pretty superfluous, because the word
1593: is simple enough. If you think it would be a good idea to add such a
1594: comment to increase readability, you should also consider factoring the
1595: word into several simpler words (@pxref{Factoring Tutorial,,
1596: Factoring}), which typically eliminates the need for the stack comment;
1597: however, if you decide not to refactor it, then having such a comment is
1598: better than not having it.
1599:
1600: The names of the stack items in stack-effect and stack comments in the
1601: standard, in this manual, and in many programs specify the type through
1602: a type prefix, similar to Fortran and Hungarian notation. The most
1603: frequent prefixes are:
1604:
1605: @table @code
1606: @item n
1607: signed integer
1608: @item u
1609: unsigned integer
1610: @item c
1611: character
1612: @item f
1613: Boolean flags, i.e. @code{false} or @code{true}.
1614: @item a-addr,a-
1615: Cell-aligned address
1616: @item c-addr,c-
1617: Char-aligned address (note that a Char may have two bytes in Windows NT)
1618: @item xt
1619: Execution token, same size as Cell
1620: @item w,x
1621: Cell, can contain an integer or an address. It usually takes 32, 64 or
1622: 16 bits (depending on your platform and Forth system). A cell is more
1623: commonly known as machine word, but the term @emph{word} already means
1624: something different in Forth.
1625: @item d
1626: signed double-cell integer
1627: @item ud
1628: unsigned double-cell integer
1629: @item r
1630: Float (on the FP stack)
1631: @end table
1632:
1633: You can find a more complete list in @ref{Notation}.
1634:
1635: @assignment
1636: Write stack-effect comments for all definitions you have written up to
1637: now.
1638: @endassignment
1639:
1640:
1641: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1642: @section Types
1643: @cindex types tutorial
1644:
1645: In Forth the names of the operations are not overloaded; so similar
1646: operations on different types need different names; e.g., @code{+} adds
1647: integers, and you have to use @code{f+} to add floating-point numbers.
1648: The following prefixes are often used for related operations on
1649: different types:
1650:
1651: @table @code
1652: @item (none)
1653: signed integer
1654: @item u
1655: unsigned integer
1656: @item c
1657: character
1658: @item d
1659: signed double-cell integer
1660: @item ud, du
1661: unsigned double-cell integer
1662: @item 2
1663: two cells (not-necessarily double-cell numbers)
1664: @item m, um
1665: mixed single-cell and double-cell operations
1666: @item f
1667: floating-point (note that in stack comments @samp{f} represents flags,
1668: and @samp{r} represents FP numbers).
1669: @end table
1670:
1671: If there are no differences between the signed and the unsigned variant
1672: (e.g., for @code{+}), there is only the prefix-less variant.
1673:
1674: Forth does not perform type checking, neither at compile time, nor at
1675: run time. If you use the wrong oeration, the data are interpreted
1676: incorrectly:
1677:
1678: @example
1679: -1 u.
1680: @end example
1681:
1682: If you have only experience with type-checked languages until now, and
1683: have heard how important type-checking is, don't panic! In my
1684: experience (and that of other Forthers), type errors in Forth code are
1685: usually easy to find (once you get used to it), the increased vigilance
1686: of the programmer tends to catch some harder errors in addition to most
1687: type errors, and you never have to work around the type system, so in
1688: most situations the lack of type-checking seems to be a win (projects to
1689: add type checking to Forth have not caught on).
1690:
1691:
1692: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1693: @section Factoring
1694: @cindex factoring tutorial
1695:
1696: If you try to write longer definitions, you will soon find it hard to
1697: keep track of the stack contents. Therefore, good Forth programmers
1698: tend to write only short definitions (e.g., three lines). The art of
1699: finding meaningful short definitions is known as factoring (as in
1700: factoring polynomials).
1701:
1702: Well-factored programs offer additional advantages: smaller, more
1703: general words, are easier to test and debug and can be reused more and
1704: better than larger, specialized words.
1705:
1706: So, if you run into difficulties with stack management, when writing
1707: code, try to define meaningful factors for the word, and define the word
1708: in terms of those. Even if a factor contains only two words, it is
1709: often helpful.
1710:
1711: Good factoring is not easy, and it takes some practice to get the knack
1712: for it; but even experienced Forth programmers often don't find the
1713: right solution right away, but only when rewriting the program. So, if
1714: you don't come up with a good solution immediately, keep trying, don't
1715: despair.
1716:
1717: @c example !!
1718:
1719:
1720: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1721: @section Designing the stack effect
1722: @cindex Stack effect design, tutorial
1723: @cindex design of stack effects, tutorial
1724:
1725: In other languages you can use an arbitrary order of parameters for a
1726: function; and since there is only one result, you don't have to deal with
1727: the order of results, either.
1728:
1729: In Forth (and other stack-based languages, e.g., PostScript) the
1730: parameter and result order of a definition is important and should be
1731: designed well. The general guideline is to design the stack effect such
1732: that the word is simple to use in most cases, even if that complicates
1733: the implementation of the word. Some concrete rules are:
1734:
1735: @itemize @bullet
1736:
1737: @item
1738: Words consume all of their parameters (e.g., @code{.}).
1739:
1740: @item
1741: If there is a convention on the order of parameters (e.g., from
1742: mathematics or another programming language), stick with it (e.g.,
1743: @code{-}).
1744:
1745: @item
1746: If one parameter usually requires only a short computation (e.g., it is
1747: a constant), pass it on the top of the stack. Conversely, parameters
1748: that usually require a long sequence of code to compute should be passed
1749: as the bottom (i.e., first) parameter. This makes the code easier to
1750: read, because reader does not need to keep track of the bottom item
1751: through a long sequence of code (or, alternatively, through stack
1752: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1753: address on top of the stack because it is usually simpler to compute
1754: than the stored value (often the address is just a variable).
1755:
1756: @item
1757: Similarly, results that are usually consumed quickly should be returned
1758: on the top of stack, whereas a result that is often used in long
1759: computations should be passed as bottom result. E.g., the file words
1760: like @code{open-file} return the error code on the top of stack, because
1761: it is usually consumed quickly by @code{throw}; moreover, the error code
1762: has to be checked before doing anything with the other results.
1763:
1764: @end itemize
1765:
1766: These rules are just general guidelines, don't lose sight of the overall
1767: goal to make the words easy to use. E.g., if the convention rule
1768: conflicts with the computation-length rule, you might decide in favour
1769: of the convention if the word will be used rarely, and in favour of the
1770: computation-length rule if the word will be used frequently (because
1771: with frequent use the cost of breaking the computation-length rule would
1772: be quite high, and frequent use makes it easier to remember an
1773: unconventional order).
1774:
1775: @c example !! structure package
1776:
1777:
1778: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1779: @section Local Variables
1780: @cindex local variables, tutorial
1781:
1782: You can define local variables (@emph{locals}) in a colon definition:
1783:
1784: @example
1785: : swap @{ a b -- b a @}
1786: b a ;
1787: 1 2 swap .s 2drop
1788: @end example
1789:
1790: (If your Forth system does not support this syntax, include
1791: @file{compat/anslocals.fs} first).
1792:
1793: In this example @code{@{ a b -- b a @}} is the locals definition; it
1794: takes two cells from the stack, puts the top of stack in @code{b} and
1795: the next stack element in @code{a}. @code{--} starts a comment ending
1796: with @code{@}}. After the locals definition, using the name of the
1797: local will push its value on the stack. You can leave the comment
1798: part (@code{-- b a}) away:
1799:
1800: @example
1801: : swap ( x1 x2 -- x2 x1 )
1802: @{ a b @} b a ;
1803: @end example
1804:
1805: In Gforth you can have several locals definitions, anywhere in a colon
1806: definition; in contrast, in a standard program you can have only one
1807: locals definition per colon definition, and that locals definition must
1808: be outside any controll structure.
1809:
1810: With locals you can write slightly longer definitions without running
1811: into stack trouble. However, I recommend trying to write colon
1812: definitions without locals for exercise purposes to help you gain the
1813: essential factoring skills.
1814:
1815: @assignment
1816: Rewrite your definitions until now with locals
1817: @endassignment
1818:
1819: Reference: @ref{Locals}.
1820:
1821:
1822: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1823: @section Conditional execution
1824: @cindex conditionals, tutorial
1825: @cindex if, tutorial
1826:
1827: In Forth you can use control structures only inside colon definitions.
1828: An @code{if}-structure looks like this:
1829:
1830: @example
1831: : abs ( n1 -- +n2 )
1832: dup 0 < if
1833: negate
1834: endif ;
1835: 5 abs .
1836: -5 abs .
1837: @end example
1838:
1839: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1840: the following code is performed, otherwise execution continues after the
1841: @code{endif} (or @code{else}). @code{<} compares the top two stack
1842: elements and prioduces a flag:
1843:
1844: @example
1845: 1 2 < .
1846: 2 1 < .
1847: 1 1 < .
1848: @end example
1849:
1850: Actually the standard name for @code{endif} is @code{then}. This
1851: tutorial presents the examples using @code{endif}, because this is often
1852: less confusing for people familiar with other programming languages
1853: where @code{then} has a different meaning. If your system does not have
1854: @code{endif}, define it with
1855:
1856: @example
1857: : endif postpone then ; immediate
1858: @end example
1859:
1860: You can optionally use an @code{else}-part:
1861:
1862: @example
1863: : min ( n1 n2 -- n )
1864: 2dup < if
1865: drop
1866: else
1867: nip
1868: endif ;
1869: 2 3 min .
1870: 3 2 min .
1871: @end example
1872:
1873: @assignment
1874: Write @code{min} without @code{else}-part (hint: what's the definition
1875: of @code{nip}?).
1876: @endassignment
1877:
1878: Reference: @ref{Selection}.
1879:
1880:
1881: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1882: @section Flags and Comparisons
1883: @cindex flags tutorial
1884: @cindex comparison tutorial
1885:
1886: In a false-flag all bits are clear (0 when interpreted as integer). In
1887: a canonical true-flag all bits are set (-1 as a twos-complement signed
1888: integer); in many contexts (e.g., @code{if}) any non-zero value is
1889: treated as true flag.
1890:
1891: @example
1892: false .
1893: true .
1894: true hex u. decimal
1895: @end example
1896:
1897: Comparison words produce canonical flags:
1898:
1899: @example
1900: 1 1 = .
1901: 1 0= .
1902: 0 1 < .
1903: 0 0 < .
1904: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1905: -1 1 < .
1906: @end example
1907:
1908: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1909: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1910: these combinations are standard (for details see the standard,
1911: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1912:
1913: You can use @code{and or xor invert} can be used as operations on
1914: canonical flags. Actually they are bitwise operations:
1915:
1916: @example
1917: 1 2 and .
1918: 1 2 or .
1919: 1 3 xor .
1920: 1 invert .
1921: @end example
1922:
1923: You can convert a zero/non-zero flag into a canonical flag with
1924: @code{0<>} (and complement it on the way with @code{0=}).
1925:
1926: @example
1927: 1 0= .
1928: 1 0<> .
1929: @end example
1930:
1931: You can use the all-bits-set feature of canonical flags and the bitwise
1932: operation of the Boolean operations to avoid @code{if}s:
1933:
1934: @example
1935: : foo ( n1 -- n2 )
1936: 0= if
1937: 14
1938: else
1939: 0
1940: endif ;
1941: 0 foo .
1942: 1 foo .
1943:
1944: : foo ( n1 -- n2 )
1945: 0= 14 and ;
1946: 0 foo .
1947: 1 foo .
1948: @end example
1949:
1950: @assignment
1951: Write @code{min} without @code{if}.
1952: @endassignment
1953:
1954: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
1955: @ref{Bitwise operations}.
1956:
1957:
1958: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
1959: @section General Loops
1960: @cindex loops, indefinite, tutorial
1961:
1962: The endless loop is the most simple one:
1963:
1964: @example
1965: : endless ( -- )
1966: 0 begin
1967: dup . 1+
1968: again ;
1969: endless
1970: @end example
1971:
1972: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
1973: does nothing at run-time, @code{again} jumps back to @code{begin}.
1974:
1975: A loop with one exit at any place looks like this:
1976:
1977: @example
1978: : log2 ( +n1 -- n2 )
1979: \ logarithmus dualis of n1>0, rounded down to the next integer
1980: assert( dup 0> )
1981: 2/ 0 begin
1982: over 0> while
1983: 1+ swap 2/ swap
1984: repeat
1985: nip ;
1986: 7 log2 .
1987: 8 log2 .
1988: @end example
1989:
1990: At run-time @code{while} consumes a flag; if it is 0, execution
1991: continues behind the @code{repeat}; if the flag is non-zero, execution
1992: continues behind the @code{while}. @code{Repeat} jumps back to
1993: @code{begin}, just like @code{again}.
1994:
1995: In Forth there are many combinations/abbreviations, like @code{1+}.
1996: However, @code{2/} is not one of them; it shifts its argument right by
1997: one bit (arithmetic shift right):
1998:
1999: @example
2000: -5 2 / .
2001: -5 2/ .
2002: @end example
2003:
2004: @code{assert(} is no standard word, but you can get it on systems other
2005: then Gforth by including @file{compat/assert.fs}. You can see what it
2006: does by trying
2007:
2008: @example
2009: 0 log2 .
2010: @end example
2011:
2012: Here's a loop with an exit at the end:
2013:
2014: @example
2015: : log2 ( +n1 -- n2 )
2016: \ logarithmus dualis of n1>0, rounded down to the next integer
2017: assert( dup 0 > )
2018: -1 begin
2019: 1+ swap 2/ swap
2020: over 0 <=
2021: until
2022: nip ;
2023: @end example
2024:
2025: @code{Until} consumes a flag; if it is non-zero, execution continues at
2026: the @code{begin}, otherwise after the @code{until}.
2027:
2028: @assignment
2029: Write a definition for computing the greatest common divisor.
2030: @endassignment
2031:
2032: Reference: @ref{Simple Loops}.
2033:
2034:
2035: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2036: @section Counted loops
2037: @cindex loops, counted, tutorial
2038:
2039: @example
2040: : ^ ( n1 u -- n )
2041: \ n = the uth power of u1
2042: 1 swap 0 u+do
2043: over *
2044: loop
2045: nip ;
2046: 3 2 ^ .
2047: 4 3 ^ .
2048: @end example
2049:
2050: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2051: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2052: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2053: times (or not at all, if @code{u3-u4<0}).
2054:
2055: You can see the stack effect design rules at work in the stack effect of
2056: the loop start words: Since the start value of the loop is more
2057: frequently constant than the end value, the start value is passed on
2058: the top-of-stack.
2059:
2060: You can access the counter of a counted loop with @code{i}:
2061:
2062: @example
2063: : fac ( u -- u! )
2064: 1 swap 1+ 1 u+do
2065: i *
2066: loop ;
2067: 5 fac .
2068: 7 fac .
2069: @end example
2070:
2071: There is also @code{+do}, which expects signed numbers (important for
2072: deciding whether to enter the loop).
2073:
2074: @assignment
2075: Write a definition for computing the nth Fibonacci number.
2076: @endassignment
2077:
2078: You can also use increments other than 1:
2079:
2080: @example
2081: : up2 ( n1 n2 -- )
2082: +do
2083: i .
2084: 2 +loop ;
2085: 10 0 up2
2086:
2087: : down2 ( n1 n2 -- )
2088: -do
2089: i .
2090: 2 -loop ;
2091: 0 10 down2
2092: @end example
2093:
2094: Reference: @ref{Counted Loops}.
2095:
2096:
2097: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2098: @section Recursion
2099: @cindex recursion tutorial
2100:
2101: Usually the name of a definition is not visible in the definition; but
2102: earlier definitions are usually visible:
2103:
2104: @example
2105: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2106: : / ( n1 n2 -- n )
2107: dup 0= if
2108: -10 throw \ report division by zero
2109: endif
2110: / \ old version
2111: ;
2112: 1 0 /
2113: @end example
2114:
2115: For recursive definitions you can use @code{recursive} (non-standard) or
2116: @code{recurse}:
2117:
2118: @example
2119: : fac1 ( n -- n! ) recursive
2120: dup 0> if
2121: dup 1- fac1 *
2122: else
2123: drop 1
2124: endif ;
2125: 7 fac1 .
2126:
2127: : fac2 ( n -- n! )
2128: dup 0> if
2129: dup 1- recurse *
2130: else
2131: drop 1
2132: endif ;
2133: 8 fac2 .
2134: @end example
2135:
2136: @assignment
2137: Write a recursive definition for computing the nth Fibonacci number.
2138: @endassignment
2139:
2140: Reference (including indirect recursion): @xref{Calls and returns}.
2141:
2142:
2143: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2144: @section Leaving definitions or loops
2145: @cindex leaving definitions, tutorial
2146: @cindex leaving loops, tutorial
2147:
2148: @code{EXIT} exits the current definition right away. For every counted
2149: loop that is left in this way, an @code{UNLOOP} has to be performed
2150: before the @code{EXIT}:
2151:
2152: @c !! real examples
2153: @example
2154: : ...
2155: ... u+do
2156: ... if
2157: ... unloop exit
2158: endif
2159: ...
2160: loop
2161: ... ;
2162: @end example
2163:
2164: @code{LEAVE} leaves the innermost counted loop right away:
2165:
2166: @example
2167: : ...
2168: ... u+do
2169: ... if
2170: ... leave
2171: endif
2172: ...
2173: loop
2174: ... ;
2175: @end example
2176:
2177: @c !! example
2178:
2179: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2180:
2181:
2182: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2183: @section Return Stack
2184: @cindex return stack tutorial
2185:
2186: In addition to the data stack Forth also has a second stack, the return
2187: stack; most Forth systems store the return addresses of procedure calls
2188: there (thus its name). Programmers can also use this stack:
2189:
2190: @example
2191: : foo ( n1 n2 -- )
2192: .s
2193: >r .s
2194: r@@ .
2195: >r .s
2196: r@@ .
2197: r> .
2198: r@@ .
2199: r> . ;
2200: 1 2 foo
2201: @end example
2202:
2203: @code{>r} takes an element from the data stack and pushes it onto the
2204: return stack; conversely, @code{r>} moves an elementm from the return to
2205: the data stack; @code{r@@} pushes a copy of the top of the return stack
2206: on the return stack.
2207:
2208: Forth programmers usually use the return stack for storing data
2209: temporarily, if using the data stack alone would be too complex, and
2210: factoring and locals are not an option:
2211:
2212: @example
2213: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2214: rot >r rot r> ;
2215: @end example
2216:
2217: The return address of the definition and the loop control parameters of
2218: counted loops usually reside on the return stack, so you have to take
2219: all items, that you have pushed on the return stack in a colon
2220: definition or counted loop, from the return stack before the definition
2221: or loop ends. You cannot access items that you pushed on the return
2222: stack outside some definition or loop within the definition of loop.
2223:
2224: If you miscount the return stack items, this usually ends in a crash:
2225:
2226: @example
2227: : crash ( n -- )
2228: >r ;
2229: 5 crash
2230: @end example
2231:
2232: You cannot mix using locals and using the return stack (according to the
2233: standard; Gforth has no problem). However, they solve the same
2234: problems, so this shouldn't be an issue.
2235:
2236: @assignment
2237: Can you rewrite any of the definitions you wrote until now in a better
2238: way using the return stack?
2239: @endassignment
2240:
2241: Reference: @ref{Return stack}.
2242:
2243:
2244: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2245: @section Memory
2246: @cindex memory access/allocation tutorial
2247:
2248: You can create a global variable @code{v} with
2249:
2250: @example
2251: variable v ( -- addr )
2252: @end example
2253:
2254: @code{v} pushes the address of a cell in memory on the stack. This cell
2255: was reserved by @code{variable}. You can use @code{!} (store) to store
2256: values into this cell and @code{@@} (fetch) to load the value from the
2257: stack into memory:
2258:
2259: @example
2260: v .
2261: 5 v ! .s
2262: v @@ .
2263: @end example
2264:
2265: You can see a raw dump of memory with @code{dump}:
2266:
2267: @example
2268: v 1 cells .s dump
2269: @end example
2270:
2271: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2272: generally, address units (aus)) that @code{n1 cells} occupy. You can
2273: also reserve more memory:
2274:
2275: @example
2276: create v2 20 cells allot
2277: v2 20 cells dump
2278: @end example
2279:
2280: creates a word @code{v2} and reserves 20 uninitialized cells; the
2281: address pushed by @code{v2} points to the start of these 20 cells. You
2282: can use address arithmetic to access these cells:
2283:
2284: @example
2285: 3 v2 5 cells + !
2286: v2 20 cells dump
2287: @end example
2288:
2289: You can reserve and initialize memory with @code{,}:
2290:
2291: @example
2292: create v3
2293: 5 , 4 , 3 , 2 , 1 ,
2294: v3 @@ .
2295: v3 cell+ @@ .
2296: v3 2 cells + @@ .
2297: v3 5 cells dump
2298: @end example
2299:
2300: @assignment
2301: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2302: @code{u} cells, with the first of these cells at @code{addr}, the next
2303: one at @code{addr cell+} etc.
2304: @endassignment
2305:
2306: You can also reserve memory without creating a new word:
2307:
2308: @example
2309: here 10 cells allot .
2310: here .
2311: @end example
2312:
2313: @code{Here} pushes the start address of the memory area. You should
2314: store it somewhere, or you will have a hard time finding the memory area
2315: again.
2316:
2317: @code{Allot} manages dictionary memory. The dictionary memory contains
2318: the system's data structures for words etc. on Gforth and most other
2319: Forth systems. It is managed like a stack: You can free the memory that
2320: you have just @code{allot}ed with
2321:
2322: @example
2323: -10 cells allot
2324: here .
2325: @end example
2326:
2327: Note that you cannot do this if you have created a new word in the
2328: meantime (because then your @code{allot}ed memory is no longer on the
2329: top of the dictionary ``stack'').
2330:
2331: Alternatively, you can use @code{allocate} and @code{free} which allow
2332: freeing memory in any order:
2333:
2334: @example
2335: 10 cells allocate throw .s
2336: 20 cells allocate throw .s
2337: swap
2338: free throw
2339: free throw
2340: @end example
2341:
2342: The @code{throw}s deal with errors (e.g., out of memory).
2343:
2344: And there is also a
2345: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2346: garbage collector}, which eliminates the need to @code{free} memory
2347: explicitly.
2348:
2349: Reference: @ref{Memory}.
2350:
2351:
2352: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2353: @section Characters and Strings
2354: @cindex strings tutorial
2355: @cindex characters tutorial
2356:
2357: On the stack characters take up a cell, like numbers. In memory they
2358: have their own size (one 8-bit byte on most systems), and therefore
2359: require their own words for memory access:
2360:
2361: @example
2362: create v4
2363: 104 c, 97 c, 108 c, 108 c, 111 c,
2364: v4 4 chars + c@@ .
2365: v4 5 chars dump
2366: @end example
2367:
2368: The preferred representation of strings on the stack is @code{addr
2369: u-count}, where @code{addr} is the address of the first character and
2370: @code{u-count} is the number of characters in the string.
2371:
2372: @example
2373: v4 5 type
2374: @end example
2375:
2376: You get a string constant with
2377:
2378: @example
2379: s" hello, world" .s
2380: type
2381: @end example
2382:
2383: Make sure you have a space between @code{s"} and the string; @code{s"}
2384: is a normal Forth word and must be delimited with white space (try what
2385: happens when you remove the space).
2386:
2387: However, this interpretive use of @code{s"} is quite restricted: the
2388: string exists only until the next call of @code{s"} (some Forth systems
2389: keep more than one of these strings, but usually they still have a
2390: limited lifetime).
2391:
2392: @example
2393: s" hello," s" world" .s
2394: type
2395: type
2396: @end example
2397:
2398: You can also use @code{s"} in a definition, and the resulting
2399: strings then live forever (well, for as long as the definition):
2400:
2401: @example
2402: : foo s" hello," s" world" ;
2403: foo .s
2404: type
2405: type
2406: @end example
2407:
2408: @assignment
2409: @code{Emit ( c -- )} types @code{c} as character (not a number).
2410: Implement @code{type ( addr u -- )}.
2411: @endassignment
2412:
2413: Reference: @ref{Memory Blocks}.
2414:
2415:
2416: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
2417: @section Alignment
2418: @cindex alignment tutorial
2419: @cindex memory alignment tutorial
2420:
2421: On many processors cells have to be aligned in memory, if you want to
2422: access them with @code{@@} and @code{!} (and even if the processor does
2423: not require alignment, access to aligned cells is faster).
2424:
2425: @code{Create} aligns @code{here} (i.e., the place where the next
2426: allocation will occur, and that the @code{create}d word points to).
2427: Likewise, the memory produced by @code{allocate} starts at an aligned
2428: address. Adding a number of @code{cells} to an aligned address produces
2429: another aligned address.
2430:
2431: However, address arithmetic involving @code{char+} and @code{chars} can
2432: create an address that is not cell-aligned. @code{Aligned ( addr --
2433: a-addr )} produces the next aligned address:
2434:
2435: @example
2436: v3 char+ aligned .s @@ .
2437: v3 char+ .s @@ .
2438: @end example
2439:
2440: Similarly, @code{align} advances @code{here} to the next aligned
2441: address:
2442:
2443: @example
2444: create v5 97 c,
2445: here .
2446: align here .
2447: 1000 ,
2448: @end example
2449:
2450: Note that you should use aligned addresses even if your processor does
2451: not require them, if you want your program to be portable.
2452:
2453: Reference: @ref{Address arithmetic}.
2454:
2455:
2456: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2457: @section Files
2458: @cindex files tutorial
2459:
2460: This section gives a short introduction into how to use files inside
2461: Forth. It's broken up into five easy steps:
2462:
2463: @enumerate 1
2464: @item Opened an ASCII text file for input
2465: @item Opened a file for output
2466: @item Read input file until string matched (or some other condition matched)
2467: @item Wrote some lines from input ( modified or not) to output
2468: @item Closed the files.
2469: @end enumerate
2470:
2471: @subsection Open file for input
2472:
2473: @example
2474: s" foo.in" r/o open-file throw Value fd-in
2475: @end example
2476:
2477: @subsection Create file for output
2478:
2479: @example
2480: s" foo.out" w/o create-file throw Value fd-out
2481: @end example
2482:
2483: The available file modes are r/o for read-only access, r/w for
2484: read-write access, and w/o for write-only access. You could open both
2485: files with r/w, too, if you like. All file words return error codes; for
2486: most applications, it's best to pass there error codes with @code{throw}
2487: to the outer error handler.
2488:
2489: If you want words for opening and assigning, define them as follows:
2490:
2491: @example
2492: 0 Value fd-in
2493: 0 Value fd-out
2494: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2495: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2496: @end example
2497:
2498: Usage example:
2499:
2500: @example
2501: s" foo.in" open-input
2502: s" foo.out" open-output
2503: @end example
2504:
2505: @subsection Scan file for a particular line
2506:
2507: @example
2508: 256 Constant max-line
2509: Create line-buffer max-line 2 + allot
2510:
2511: : scan-file ( addr u -- )
2512: begin
2513: line-buffer max-line fd-in read-line throw
2514: while
2515: >r 2dup line-buffer r> compare 0=
2516: until
2517: else
2518: drop
2519: then
2520: 2drop ;
2521: @end example
2522:
2523: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
2524: the buffer at addr, and returns the number of bytes read, a flag that is
2525: false when the end of file is reached, and an error code.
2526:
2527: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2528: returns zero if both strings are equal. It returns a positive number if
2529: the first string is lexically greater, a negative if the second string
2530: is lexically greater.
2531:
2532: We haven't seen this loop here; it has two exits. Since the @code{while}
2533: exits with the number of bytes read on the stack, we have to clean up
2534: that separately; that's after the @code{else}.
2535:
2536: Usage example:
2537:
2538: @example
2539: s" The text I search is here" scan-file
2540: @end example
2541:
2542: @subsection Copy input to output
2543:
2544: @example
2545: : copy-file ( -- )
2546: begin
2547: line-buffer max-line fd-in read-line throw
2548: while
2549: line-buffer swap fd-out write-file throw
2550: repeat ;
2551: @end example
2552:
2553: @subsection Close files
2554:
2555: @example
2556: fd-in close-file throw
2557: fd-out close-file throw
2558: @end example
2559:
2560: Likewise, you can put that into definitions, too:
2561:
2562: @example
2563: : close-input ( -- ) fd-in close-file throw ;
2564: : close-output ( -- ) fd-out close-file throw ;
2565: @end example
2566:
2567: @assignment
2568: How could you modify @code{copy-file} so that it copies until a second line is
2569: matched? Can you write a program that extracts a section of a text file,
2570: given the line that starts and the line that terminates that section?
2571: @endassignment
2572:
2573: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
2574: @section Interpretation and Compilation Semantics and Immediacy
2575: @cindex semantics tutorial
2576: @cindex interpretation semantics tutorial
2577: @cindex compilation semantics tutorial
2578: @cindex immediate, tutorial
2579:
2580: When a word is compiled, it behaves differently from being interpreted.
2581: E.g., consider @code{+}:
2582:
2583: @example
2584: 1 2 + .
2585: : foo + ;
2586: @end example
2587:
2588: These two behaviours are known as compilation and interpretation
2589: semantics. For normal words (e.g., @code{+}), the compilation semantics
2590: is to append the interpretation semantics to the currently defined word
2591: (@code{foo} in the example above). I.e., when @code{foo} is executed
2592: later, the interpretation semantics of @code{+} (i.e., adding two
2593: numbers) will be performed.
2594:
2595: However, there are words with non-default compilation semantics, e.g.,
2596: the control-flow words like @code{if}. You can use @code{immediate} to
2597: change the compilation semantics of the last defined word to be equal to
2598: the interpretation semantics:
2599:
2600: @example
2601: : [FOO] ( -- )
2602: 5 . ; immediate
2603:
2604: [FOO]
2605: : bar ( -- )
2606: [FOO] ;
2607: bar
2608: see bar
2609: @end example
2610:
2611: Two conventions to mark words with non-default compilation semnatics are
2612: names with brackets (more frequently used) and to write them all in
2613: upper case (less frequently used).
2614:
2615: In Gforth (and many other systems) you can also remove the
2616: interpretation semantics with @code{compile-only} (the compilation
2617: semantics is derived from the original interpretation semantics):
2618:
2619: @example
2620: : flip ( -- )
2621: 6 . ; compile-only \ but not immediate
2622: flip
2623:
2624: : flop ( -- )
2625: flip ;
2626: flop
2627: @end example
2628:
2629: In this example the interpretation semantics of @code{flop} is equal to
2630: the original interpretation semantics of @code{flip}.
2631:
2632: The text interpreter has two states: in interpret state, it performs the
2633: interpretation semantics of words it encounters; in compile state, it
2634: performs the compilation semantics of these words.
2635:
2636: Among other things, @code{:} switches into compile state, and @code{;}
2637: switches back to interpret state. They contain the factors @code{]}
2638: (switch to compile state) and @code{[} (switch to interpret state), that
2639: do nothing but switch the state.
2640:
2641: @example
2642: : xxx ( -- )
2643: [ 5 . ]
2644: ;
2645:
2646: xxx
2647: see xxx
2648: @end example
2649:
2650: These brackets are also the source of the naming convention mentioned
2651: above.
2652:
2653: Reference: @ref{Interpretation and Compilation Semantics}.
2654:
2655:
2656: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2657: @section Execution Tokens
2658: @cindex execution tokens tutorial
2659: @cindex XT tutorial
2660:
2661: @code{' word} gives you the execution token (XT) of a word. The XT is a
2662: cell representing the interpretation semantics of a word. You can
2663: execute this semantics with @code{execute}:
2664:
2665: @example
2666: ' + .s
2667: 1 2 rot execute .
2668: @end example
2669:
2670: The XT is similar to a function pointer in C. However, parameter
2671: passing through the stack makes it a little more flexible:
2672:
2673: @example
2674: : map-array ( ... addr u xt -- ... )
2675: \ executes xt ( ... x -- ... ) for every element of the array starting
2676: \ at addr and containing u elements
2677: @{ xt @}
2678: cells over + swap ?do
2679: i @@ xt execute
2680: 1 cells +loop ;
2681:
2682: create a 3 , 4 , 2 , -1 , 4 ,
2683: a 5 ' . map-array .s
2684: 0 a 5 ' + map-array .
2685: s" max-n" environment? drop .s
2686: a 5 ' min map-array .
2687: @end example
2688:
2689: You can use map-array with the XTs of words that consume one element
2690: more than they produce. In theory you can also use it with other XTs,
2691: but the stack effect then depends on the size of the array, which is
2692: hard to understand.
2693:
2694: Since XTs are cell-sized, you can store them in memory and manipulate
2695: them on the stack like other cells. You can also compile the XT into a
2696: word with @code{compile,}:
2697:
2698: @example
2699: : foo1 ( n1 n2 -- n )
2700: [ ' + compile, ] ;
2701: see foo
2702: @end example
2703:
2704: This is non-standard, because @code{compile,} has no compilation
2705: semantics in the standard, but it works in good Forth systems. For the
2706: broken ones, use
2707:
2708: @example
2709: : [compile,] compile, ; immediate
2710:
2711: : foo1 ( n1 n2 -- n )
2712: [ ' + ] [compile,] ;
2713: see foo
2714: @end example
2715:
2716: @code{'} is a word with default compilation semantics; it parses the
2717: next word when its interpretation semantics are executed, not during
2718: compilation:
2719:
2720: @example
2721: : foo ( -- xt )
2722: ' ;
2723: see foo
2724: : bar ( ... "word" -- ... )
2725: ' execute ;
2726: see bar
2727: 1 2 bar + .
2728: @end example
2729:
2730: You often want to parse a word during compilation and compile its XT so
2731: it will be pushed on the stack at run-time. @code{[']} does this:
2732:
2733: @example
2734: : xt-+ ( -- xt )
2735: ['] + ;
2736: see xt-+
2737: 1 2 xt-+ execute .
2738: @end example
2739:
2740: Many programmers tend to see @code{'} and the word it parses as one
2741: unit, and expect it to behave like @code{[']} when compiled, and are
2742: confused by the actual behaviour. If you are, just remember that the
2743: Forth system just takes @code{'} as one unit and has no idea that it is
2744: a parsing word (attempts to convenience programmers in this issue have
2745: usually resulted in even worse pitfalls, see
2746: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2747: @code{State}-smartness---Why it is evil and How to Exorcise it}).
2748:
2749: Note that the state of the interpreter does not come into play when
2750: creating and executing XTs. I.e., even when you execute @code{'} in
2751: compile state, it still gives you the interpretation semantics. And
2752: whatever that state is, @code{execute} performs the semantics
2753: represented by the XT (i.e., for XTs produced with @code{'} the
2754: interpretation semantics).
2755:
2756: Reference: @ref{Tokens for Words}.
2757:
2758:
2759: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2760: @section Exceptions
2761: @cindex exceptions tutorial
2762:
2763: @code{throw ( n -- )} causes an exception unless n is zero.
2764:
2765: @example
2766: 100 throw .s
2767: 0 throw .s
2768: @end example
2769:
2770: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2771: it catches exceptions and pushes the number of the exception on the
2772: stack (or 0, if the xt executed without exception). If there was an
2773: exception, the stacks have the same depth as when entering @code{catch}:
2774:
2775: @example
2776: .s
2777: 3 0 ' / catch .s
2778: 3 2 ' / catch .s
2779: @end example
2780:
2781: @assignment
2782: Try the same with @code{execute} instead of @code{catch}.
2783: @endassignment
2784:
2785: @code{Throw} always jumps to the dynamically next enclosing
2786: @code{catch}, even if it has to leave several call levels to achieve
2787: this:
2788:
2789: @example
2790: : foo 100 throw ;
2791: : foo1 foo ." after foo" ;
2792: : bar ['] foo1 catch ;
2793: bar .
2794: @end example
2795:
2796: It is often important to restore a value upon leaving a definition, even
2797: if the definition is left through an exception. You can ensure this
2798: like this:
2799:
2800: @example
2801: : ...
2802: save-x
2803: ['] word-changing-x catch ( ... n )
2804: restore-x
2805: ( ... n ) throw ;
2806: @end example
2807:
2808: Gforth provides an alternative syntax in addition to @code{catch}:
2809: @code{try ... recover ... endtry}. If the code between @code{try} and
2810: @code{recover} has an exception, the stack depths are restored, the
2811: exception number is pushed on the stack, and the code between
2812: @code{recover} and @code{endtry} is performed. E.g., the definition for
2813: @code{catch} is
2814:
2815: @example
2816: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
2817: try
2818: execute 0
2819: recover
2820: nip
2821: endtry ;
2822: @end example
2823:
2824: The equivalent to the restoration code above is
2825:
2826: @example
2827: : ...
2828: save-x
2829: try
2830: word-changing-x 0
2831: recover endtry
2832: restore-x
2833: throw ;
2834: @end example
2835:
2836: This works if @code{word-changing-x} does not change the stack depth,
2837: otherwise you should add some code between @code{recover} and
2838: @code{endtry} to balance the stack.
2839:
2840: Reference: @ref{Exception Handling}.
2841:
2842:
2843: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2844: @section Defining Words
2845: @cindex defining words tutorial
2846: @cindex does> tutorial
2847: @cindex create...does> tutorial
2848:
2849: @c before semantics?
2850:
2851: @code{:}, @code{create}, and @code{variable} are definition words: They
2852: define other words. @code{Constant} is another definition word:
2853:
2854: @example
2855: 5 constant foo
2856: foo .
2857: @end example
2858:
2859: You can also use the prefixes @code{2} (double-cell) and @code{f}
2860: (floating point) with @code{variable} and @code{constant}.
2861:
2862: You can also define your own defining words. E.g.:
2863:
2864: @example
2865: : variable ( "name" -- )
2866: create 0 , ;
2867: @end example
2868:
2869: You can also define defining words that create words that do something
2870: other than just producing their address:
2871:
2872: @example
2873: : constant ( n "name" -- )
2874: create ,
2875: does> ( -- n )
2876: ( addr ) @@ ;
2877:
2878: 5 constant foo
2879: foo .
2880: @end example
2881:
2882: The definition of @code{constant} above ends at the @code{does>}; i.e.,
2883: @code{does>} replaces @code{;}, but it also does something else: It
2884: changes the last defined word such that it pushes the address of the
2885: body of the word and then performs the code after the @code{does>}
2886: whenever it is called.
2887:
2888: In the example above, @code{constant} uses @code{,} to store 5 into the
2889: body of @code{foo}. When @code{foo} executes, it pushes the address of
2890: the body onto the stack, then (in the code after the @code{does>})
2891: fetches the 5 from there.
2892:
2893: The stack comment near the @code{does>} reflects the stack effect of the
2894: defined word, not the stack effect of the code after the @code{does>}
2895: (the difference is that the code expects the address of the body that
2896: the stack comment does not show).
2897:
2898: You can use these definition words to do factoring in cases that involve
2899: (other) definition words. E.g., a field offset is always added to an
2900: address. Instead of defining
2901:
2902: @example
2903: 2 cells constant offset-field1
2904: @end example
2905:
2906: and using this like
2907:
2908: @example
2909: ( addr ) offset-field1 +
2910: @end example
2911:
2912: you can define a definition word
2913:
2914: @example
2915: : simple-field ( n "name" -- )
2916: create ,
2917: does> ( n1 -- n1+n )
2918: ( addr ) @@ + ;
2919: @end example
2920:
2921: Definition and use of field offsets now look like this:
2922:
2923: @example
2924: 2 cells simple-field field1
2925: create mystruct 4 cells allot
2926: mystruct .s field1 .s drop
2927: @end example
2928:
2929: If you want to do something with the word without performing the code
2930: after the @code{does>}, you can access the body of a @code{create}d word
2931: with @code{>body ( xt -- addr )}:
2932:
2933: @example
2934: : value ( n "name" -- )
2935: create ,
2936: does> ( -- n1 )
2937: @@ ;
2938: : to ( n "name" -- )
2939: ' >body ! ;
2940:
2941: 5 value foo
2942: foo .
2943: 7 to foo
2944: foo .
2945: @end example
2946:
2947: @assignment
2948: Define @code{defer ( "name" -- )}, which creates a word that stores an
2949: XT (at the start the XT of @code{abort}), and upon execution
2950: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
2951: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
2952: recursion is one application of @code{defer}.
2953: @endassignment
2954:
2955: Reference: @ref{User-defined Defining Words}.
2956:
2957:
2958: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
2959: @section Arrays and Records
2960: @cindex arrays tutorial
2961: @cindex records tutorial
2962: @cindex structs tutorial
2963:
2964: Forth has no standard words for defining data structures such as arrays
2965: and records (structs in C terminology), but you can build them yourself
2966: based on address arithmetic. You can also define words for defining
2967: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
2968:
2969: One of the first projects a Forth newcomer sets out upon when learning
2970: about defining words is an array defining word (possibly for
2971: n-dimensional arrays). Go ahead and do it, I did it, too; you will
2972: learn something from it. However, don't be disappointed when you later
2973: learn that you have little use for these words (inappropriate use would
2974: be even worse). I have not yet found a set of useful array words yet;
2975: the needs are just too diverse, and named, global arrays (the result of
2976: naive use of defining words) are often not flexible enough (e.g.,
2977: consider how to pass them as parameters). Another such project is a set
2978: of words to help dealing with strings.
2979:
2980: On the other hand, there is a useful set of record words, and it has
2981: been defined in @file{compat/struct.fs}; these words are predefined in
2982: Gforth. They are explained in depth elsewhere in this manual (see
2983: @pxref{Structures}). The @code{simple-field} example above is
2984: simplified variant of fields in this package.
2985:
2986:
2987: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
2988: @section @code{POSTPONE}
2989: @cindex postpone tutorial
2990:
2991: You can compile the compilation semantics (instead of compiling the
2992: interpretation semantics) of a word with @code{POSTPONE}:
2993:
2994: @example
2995: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
2996: POSTPONE + ; immediate
2997: : foo ( n1 n2 -- n )
2998: MY-+ ;
2999: 1 2 foo .
3000: see foo
3001: @end example
3002:
3003: During the definition of @code{foo} the text interpreter performs the
3004: compilation semantics of @code{MY-+}, which performs the compilation
3005: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3006:
3007: This example also displays separate stack comments for the compilation
3008: semantics and for the stack effect of the compiled code. For words with
3009: default compilation semantics these stack effects are usually not
3010: displayed; the stack effect of the compilation semantics is always
3011: @code{( -- )} for these words, the stack effect for the compiled code is
3012: the stack effect of the interpretation semantics.
3013:
3014: Note that the state of the interpreter does not come into play when
3015: performing the compilation semantics in this way. You can also perform
3016: it interpretively, e.g.:
3017:
3018: @example
3019: : foo2 ( n1 n2 -- n )
3020: [ MY-+ ] ;
3021: 1 2 foo .
3022: see foo
3023: @end example
3024:
3025: However, there are some broken Forth systems where this does not always
3026: work, and therefore this practice was been declared non-standard in
3027: 1999.
3028: @c !! repair.fs
3029:
3030: Here is another example for using @code{POSTPONE}:
3031:
3032: @example
3033: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3034: POSTPONE negate POSTPONE + ; immediate compile-only
3035: : bar ( n1 n2 -- n )
3036: MY-- ;
3037: 2 1 bar .
3038: see bar
3039: @end example
3040:
3041: You can define @code{ENDIF} in this way:
3042:
3043: @example
3044: : ENDIF ( Compilation: orig -- )
3045: POSTPONE then ; immediate
3046: @end example
3047:
3048: @assignment
3049: Write @code{MY-2DUP} that has compilation semantics equivalent to
3050: @code{2dup}, but compiles @code{over over}.
3051: @endassignment
3052:
3053: @c !! @xref{Macros} for reference
3054:
3055:
3056: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3057: @section @code{Literal}
3058: @cindex literal tutorial
3059:
3060: You cannot @code{POSTPONE} numbers:
3061:
3062: @example
3063: : [FOO] POSTPONE 500 ; immediate
3064: @end example
3065:
3066: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
3067:
3068: @example
3069: : [FOO] ( compilation: --; run-time: -- n )
3070: 500 POSTPONE literal ; immediate
3071:
3072: : flip [FOO] ;
3073: flip .
3074: see flip
3075: @end example
3076:
3077: @code{LITERAL} consumes a number at compile-time (when it's compilation
3078: semantics are executed) and pushes it at run-time (when the code it
3079: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3080: number computed at compile time into the current word:
3081:
3082: @example
3083: : bar ( -- n )
3084: [ 2 2 + ] literal ;
3085: see bar
3086: @end example
3087:
3088: @assignment
3089: Write @code{]L} which allows writing the example above as @code{: bar (
3090: -- n ) [ 2 2 + ]L ;}
3091: @endassignment
3092:
3093: @c !! @xref{Macros} for reference
3094:
3095:
3096: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3097: @section Advanced macros
3098: @cindex macros, advanced tutorial
3099: @cindex run-time code generation, tutorial
3100:
3101: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3102: Execution Tokens}. It frequently performs @code{execute}, a relatively
3103: expensive operation in some Forth implementations. You can use
3104: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3105: and produce a word that contains the word to be performed directly:
3106:
3107: @c use ]] ... [[
3108: @example
3109: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3110: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3111: \ array beginning at addr and containing u elements
3112: @{ xt @}
3113: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
3114: POSTPONE i POSTPONE @@ xt compile,
3115: 1 cells POSTPONE literal POSTPONE +loop ;
3116:
3117: : sum-array ( addr u -- n )
3118: 0 rot rot [ ' + compile-map-array ] ;
3119: see sum-array
3120: a 5 sum-array .
3121: @end example
3122:
3123: You can use the full power of Forth for generating the code; here's an
3124: example where the code is generated in a loop:
3125:
3126: @example
3127: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3128: \ n2=n1+(addr1)*n, addr2=addr1+cell
3129: POSTPONE tuck POSTPONE @@
3130: POSTPONE literal POSTPONE * POSTPONE +
3131: POSTPONE swap POSTPONE cell+ ;
3132:
3133: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
3134: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
3135: 0 postpone literal postpone swap
3136: [ ' compile-vmul-step compile-map-array ]
3137: postpone drop ;
3138: see compile-vmul
3139:
3140: : a-vmul ( addr -- n )
3141: \ n=a*v, where v is a vector that's as long as a and starts at addr
3142: [ a 5 compile-vmul ] ;
3143: see a-vmul
3144: a a-vmul .
3145: @end example
3146:
3147: This example uses @code{compile-map-array} to show off, but you could
3148: also use @code{map-array} instead (try it now!).
3149:
3150: You can use this technique for efficient multiplication of large
3151: matrices. In matrix multiplication, you multiply every line of one
3152: matrix with every column of the other matrix. You can generate the code
3153: for one line once, and use it for every column. The only downside of
3154: this technique is that it is cumbersome to recover the memory consumed
3155: by the generated code when you are done (and in more complicated cases
3156: it is not possible portably).
3157:
3158: @c !! @xref{Macros} for reference
3159:
3160:
3161: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3162: @section Compilation Tokens
3163: @cindex compilation tokens, tutorial
3164: @cindex CT, tutorial
3165:
3166: This section is Gforth-specific. You can skip it.
3167:
3168: @code{' word compile,} compiles the interpretation semantics. For words
3169: with default compilation semantics this is the same as performing the
3170: compilation semantics. To represent the compilation semantics of other
3171: words (e.g., words like @code{if} that have no interpretation
3172: semantics), Gforth has the concept of a compilation token (CT,
3173: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3174: You can perform the compilation semantics represented by a CT with
3175: @code{execute}:
3176:
3177: @example
3178: : foo2 ( n1 n2 -- n )
3179: [ comp' + execute ] ;
3180: see foo
3181: @end example
3182:
3183: You can compile the compilation semantics represented by a CT with
3184: @code{postpone,}:
3185:
3186: @example
3187: : foo3 ( -- )
3188: [ comp' + postpone, ] ;
3189: see foo3
3190: @end example
3191:
3192: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
3193: @code{comp'} is particularly useful for words that have no
3194: interpretation semantics:
3195:
3196: @example
3197: ' if
3198: comp' if .s 2drop
3199: @end example
3200:
3201: Reference: @ref{Tokens for Words}.
3202:
3203:
3204: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3205: @section Wordlists and Search Order
3206: @cindex wordlists tutorial
3207: @cindex search order, tutorial
3208:
3209: The dictionary is not just a memory area that allows you to allocate
3210: memory with @code{allot}, it also contains the Forth words, arranged in
3211: several wordlists. When searching for a word in a wordlist,
3212: conceptually you start searching at the youngest and proceed towards
3213: older words (in reality most systems nowadays use hash-tables); i.e., if
3214: you define a word with the same name as an older word, the new word
3215: shadows the older word.
3216:
3217: Which wordlists are searched in which order is determined by the search
3218: order. You can display the search order with @code{order}. It displays
3219: first the search order, starting with the wordlist searched first, then
3220: it displays the wordlist that will contain newly defined words.
3221:
3222: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
3223:
3224: @example
3225: wordlist constant mywords
3226: @end example
3227:
3228: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3229: defined words (the @emph{current} wordlist):
3230:
3231: @example
3232: mywords set-current
3233: order
3234: @end example
3235:
3236: Gforth does not display a name for the wordlist in @code{mywords}
3237: because this wordlist was created anonymously with @code{wordlist}.
3238:
3239: You can get the current wordlist with @code{get-current ( -- wid)}. If
3240: you want to put something into a specific wordlist without overall
3241: effect on the current wordlist, this typically looks like this:
3242:
3243: @example
3244: get-current mywords set-current ( wid )
3245: create someword
3246: ( wid ) set-current
3247: @end example
3248:
3249: You can write the search order with @code{set-order ( wid1 .. widn n --
3250: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3251: searched wordlist is topmost.
3252:
3253: @example
3254: get-order mywords swap 1+ set-order
3255: order
3256: @end example
3257:
3258: Yes, the order of wordlists in the output of @code{order} is reversed
3259: from stack comments and the output of @code{.s} and thus unintuitive.
3260:
3261: @assignment
3262: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3263: wordlist to the search order. Define @code{previous ( -- )}, which
3264: removes the first searched wordlist from the search order. Experiment
3265: with boundary conditions (you will see some crashes or situations that
3266: are hard or impossible to leave).
3267: @endassignment
3268:
3269: The search order is a powerful foundation for providing features similar
3270: to Modula-2 modules and C++ namespaces. However, trying to modularize
3271: programs in this way has disadvantages for debugging and reuse/factoring
3272: that overcome the advantages in my experience (I don't do huge projects,
3273: though). These disadvantages are not so clear in other
3274: languages/programming environments, because these languages are not so
3275: strong in debugging and reuse.
3276:
3277: @c !! example
3278:
3279: Reference: @ref{Word Lists}.
3280:
3281: @c ******************************************************************
3282: @node Introduction, Words, Tutorial, Top
3283: @comment node-name, next, previous, up
3284: @chapter An Introduction to ANS Forth
3285: @cindex Forth - an introduction
3286:
3287: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3288: that it is slower-paced in its examples, but uses them to dive deep into
3289: explaining Forth internals (not covered by the Tutorial). Apart from
3290: that, this chapter covers far less material. It is suitable for reading
3291: without using a computer.
3292:
3293: The primary purpose of this manual is to document Gforth. However, since
3294: Forth is not a widely-known language and there is a lack of up-to-date
3295: teaching material, it seems worthwhile to provide some introductory
3296: material. For other sources of Forth-related
3297: information, see @ref{Forth-related information}.
3298:
3299: The examples in this section should work on any ANS Forth; the
3300: output shown was produced using Gforth. Each example attempts to
3301: reproduce the exact output that Gforth produces. If you try out the
3302: examples (and you should), what you should type is shown @kbd{like this}
3303: and Gforth's response is shown @code{like this}. The single exception is
3304: that, where the example shows @key{RET} it means that you should
3305: press the ``carriage return'' key. Unfortunately, some output formats for
3306: this manual cannot show the difference between @kbd{this} and
3307: @code{this} which will make trying out the examples harder (but not
3308: impossible).
3309:
3310: Forth is an unusual language. It provides an interactive development
3311: environment which includes both an interpreter and compiler. Forth
3312: programming style encourages you to break a problem down into many
3313: @cindex factoring
3314: small fragments (@dfn{factoring}), and then to develop and test each
3315: fragment interactively. Forth advocates assert that breaking the
3316: edit-compile-test cycle used by conventional programming languages can
3317: lead to great productivity improvements.
3318:
3319: @menu
3320: * Introducing the Text Interpreter::
3321: * Stacks and Postfix notation::
3322: * Your first definition::
3323: * How does that work?::
3324: * Forth is written in Forth::
3325: * Review - elements of a Forth system::
3326: * Where to go next::
3327: * Exercises::
3328: @end menu
3329:
3330: @comment ----------------------------------------------
3331: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3332: @section Introducing the Text Interpreter
3333: @cindex text interpreter
3334: @cindex outer interpreter
3335:
3336: @c IMO this is too detailed and the pace is too slow for
3337: @c an introduction. If you know German, take a look at
3338: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3339: @c to see how I do it - anton
3340:
3341: @c nac-> Where I have accepted your comments 100% and modified the text
3342: @c accordingly, I have deleted your comments. Elsewhere I have added a
3343: @c response like this to attempt to rationalise what I have done. Of
3344: @c course, this is a very clumsy mechanism for something that would be
3345: @c done far more efficiently over a beer. Please delete any dialogue
3346: @c you consider closed.
3347:
3348: When you invoke the Forth image, you will see a startup banner printed
3349: and nothing else (if you have Gforth installed on your system, try
3350: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
3351: its command line interpreter, which is called the @dfn{Text Interpreter}
3352: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
3353: about the text interpreter as you read through this chapter, for more
3354: detail @pxref{The Text Interpreter}).
3355:
3356: Although it's not obvious, Forth is actually waiting for your
3357: input. Type a number and press the @key{RET} key:
3358:
3359: @example
3360: @kbd{45@key{RET}} ok
3361: @end example
3362:
3363: Rather than give you a prompt to invite you to input something, the text
3364: interpreter prints a status message @i{after} it has processed a line
3365: of input. The status message in this case (``@code{ ok}'' followed by
3366: carriage-return) indicates that the text interpreter was able to process
3367: all of your input successfully. Now type something illegal:
3368:
3369: @example
3370: @kbd{qwer341@key{RET}}
3371: :1: Undefined word
3372: qwer341
3373: ^^^^^^^
3374: $400D2BA8 Bounce
3375: $400DBDA8 no.extensions
3376: @end example
3377:
3378: The exact text, other than the ``Undefined word'' may differ slightly on
3379: your system, but the effect is the same; when the text interpreter
3380: detects an error, it discards any remaining text on a line, resets
3381: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
3382: messages}.
3383:
3384: The text interpreter waits for you to press carriage-return, and then
3385: processes your input line. Starting at the beginning of the line, it
3386: breaks the line into groups of characters separated by spaces. For each
3387: group of characters in turn, it makes two attempts to do something:
3388:
3389: @itemize @bullet
3390: @item
3391: @cindex name dictionary
3392: It tries to treat it as a command. It does this by searching a @dfn{name
3393: dictionary}. If the group of characters matches an entry in the name
3394: dictionary, the name dictionary provides the text interpreter with
3395: information that allows the text interpreter perform some actions. In
3396: Forth jargon, we say that the group
3397: @cindex word
3398: @cindex definition
3399: @cindex execution token
3400: @cindex xt
3401: of characters names a @dfn{word}, that the dictionary search returns an
3402: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3403: word, and that the text interpreter executes the xt. Often, the terms
3404: @dfn{word} and @dfn{definition} are used interchangeably.
3405: @item
3406: If the text interpreter fails to find a match in the name dictionary, it
3407: tries to treat the group of characters as a number in the current number
3408: base (when you start up Forth, the current number base is base 10). If
3409: the group of characters legitimately represents a number, the text
3410: interpreter pushes the number onto a stack (we'll learn more about that
3411: in the next section).
3412: @end itemize
3413:
3414: If the text interpreter is unable to do either of these things with any
3415: group of characters, it discards the group of characters and the rest of
3416: the line, then prints an error message. If the text interpreter reaches
3417: the end of the line without error, it prints the status message ``@code{ ok}''
3418: followed by carriage-return.
3419:
3420: This is the simplest command we can give to the text interpreter:
3421:
3422: @example
3423: @key{RET} ok
3424: @end example
3425:
3426: The text interpreter did everything we asked it to do (nothing) without
3427: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3428: command:
3429:
3430: @example
3431: @kbd{12 dup fred dup@key{RET}}
3432: :1: Undefined word
3433: 12 dup fred dup
3434: ^^^^
3435: $400D2BA8 Bounce
3436: $400DBDA8 no.extensions
3437: @end example
3438:
3439: When you press the carriage-return key, the text interpreter starts to
3440: work its way along the line:
3441:
3442: @itemize @bullet
3443: @item
3444: When it gets to the space after the @code{2}, it takes the group of
3445: characters @code{12} and looks them up in the name
3446: dictionary@footnote{We can't tell if it found them or not, but assume
3447: for now that it did not}. There is no match for this group of characters
3448: in the name dictionary, so it tries to treat them as a number. It is
3449: able to do this successfully, so it puts the number, 12, ``on the stack''
3450: (whatever that means).
3451: @item
3452: The text interpreter resumes scanning the line and gets the next group
3453: of characters, @code{dup}. It looks it up in the name dictionary and
3454: (you'll have to take my word for this) finds it, and executes the word
3455: @code{dup} (whatever that means).
3456: @item
3457: Once again, the text interpreter resumes scanning the line and gets the
3458: group of characters @code{fred}. It looks them up in the name
3459: dictionary, but can't find them. It tries to treat them as a number, but
3460: they don't represent any legal number.
3461: @end itemize
3462:
3463: At this point, the text interpreter gives up and prints an error
3464: message. The error message shows exactly how far the text interpreter
3465: got in processing the line. In particular, it shows that the text
3466: interpreter made no attempt to do anything with the final character
3467: group, @code{dup}, even though we have good reason to believe that the
3468: text interpreter would have no problem looking that word up and
3469: executing it a second time.
3470:
3471:
3472: @comment ----------------------------------------------
3473: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3474: @section Stacks, postfix notation and parameter passing
3475: @cindex text interpreter
3476: @cindex outer interpreter
3477:
3478: In procedural programming languages (like C and Pascal), the
3479: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3480: functions or procedures are called with @dfn{explicit parameters}. For
3481: example, in C we might write:
3482:
3483: @example
3484: total = total + new_volume(length,height,depth);
3485: @end example
3486:
3487: @noindent
3488: where new_volume is a function-call to another piece of code, and total,
3489: length, height and depth are all variables. length, height and depth are
3490: parameters to the function-call.
3491:
3492: In Forth, the equivalent of the function or procedure is the
3493: @dfn{definition} and parameters are implicitly passed between
3494: definitions using a shared stack that is visible to the
3495: programmer. Although Forth does support variables, the existence of the
3496: stack means that they are used far less often than in most other
3497: programming languages. When the text interpreter encounters a number, it
3498: will place (@dfn{push}) it on the stack. There are several stacks (the
3499: actual number is implementation-dependent ...) and the particular stack
3500: used for any operation is implied unambiguously by the operation being
3501: performed. The stack used for all integer operations is called the @dfn{data
3502: stack} and, since this is the stack used most commonly, references to
3503: ``the data stack'' are often abbreviated to ``the stack''.
3504:
3505: The stacks have a last-in, first-out (LIFO) organisation. If you type:
3506:
3507: @example
3508: @kbd{1 2 3@key{RET}} ok
3509: @end example
3510:
3511: Then this instructs the text interpreter to placed three numbers on the
3512: (data) stack. An analogy for the behaviour of the stack is to take a
3513: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3514: the table. The 3 was the last card onto the pile (``last-in'') and if
3515: you take a card off the pile then, unless you're prepared to fiddle a
3516: bit, the card that you take off will be the 3 (``first-out''). The
3517: number that will be first-out of the stack is called the @dfn{top of
3518: stack}, which
3519: @cindex TOS definition
3520: is often abbreviated to @dfn{TOS}.
3521:
3522: To understand how parameters are passed in Forth, consider the
3523: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3524: be surprised to learn that this definition performs addition. More
3525: precisely, it adds two number together and produces a result. Where does
3526: it get the two numbers from? It takes the top two numbers off the
3527: stack. Where does it place the result? On the stack. You can act-out the
3528: behaviour of @code{+} with your playing cards like this:
3529:
3530: @itemize @bullet
3531: @item
3532: Pick up two cards from the stack on the table
3533: @item
3534: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3535: numbers''
3536: @item
3537: Decide that the answer is 5
3538: @item
3539: Shuffle the two cards back into the pack and find a 5
3540: @item
3541: Put a 5 on the remaining ace that's on the table.
3542: @end itemize
3543:
3544: If you don't have a pack of cards handy but you do have Forth running,
3545: you can use the definition @code{.s} to show the current state of the stack,
3546: without affecting the stack. Type:
3547:
3548: @example
3549: @kbd{clearstacks 1 2 3@key{RET}} ok
3550: @kbd{.s@key{RET}} <3> 1 2 3 ok
3551: @end example
3552:
3553: The text interpreter looks up the word @code{clearstacks} and executes
3554: it; it tidies up the stacks and removes any entries that may have been
3555: left on it by earlier examples. The text interpreter pushes each of the
3556: three numbers in turn onto the stack. Finally, the text interpreter
3557: looks up the word @code{.s} and executes it. The effect of executing
3558: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3559: followed by a list of all the items on the stack; the item on the far
3560: right-hand side is the TOS.
3561:
3562: You can now type:
3563:
3564: @example
3565: @kbd{+ .s@key{RET}} <2> 1 5 ok
3566: @end example
3567:
3568: @noindent
3569: which is correct; there are now 2 items on the stack and the result of
3570: the addition is 5.
3571:
3572: If you're playing with cards, try doing a second addition: pick up the
3573: two cards, work out that their sum is 6, shuffle them into the pack,
3574: look for a 6 and place that on the table. You now have just one item on
3575: the stack. What happens if you try to do a third addition? Pick up the
3576: first card, pick up the second card -- ah! There is no second card. This
3577: is called a @dfn{stack underflow} and consitutes an error. If you try to
3578: do the same thing with Forth it often reports an error (probably a Stack
3579: Underflow or an Invalid Memory Address error).
3580:
3581: The opposite situation to a stack underflow is a @dfn{stack overflow},
3582: which simply accepts that there is a finite amount of storage space
3583: reserved for the stack. To stretch the playing card analogy, if you had
3584: enough packs of cards and you piled the cards up on the table, you would
3585: eventually be unable to add another card; you'd hit the ceiling. Gforth
3586: allows you to set the maximum size of the stacks. In general, the only
3587: time that you will get a stack overflow is because a definition has a
3588: bug in it and is generating data on the stack uncontrollably.
3589:
3590: There's one final use for the playing card analogy. If you model your
3591: stack using a pack of playing cards, the maximum number of items on
3592: your stack will be 52 (I assume you didn't use the Joker). The maximum
3593: @i{value} of any item on the stack is 13 (the King). In fact, the only
3594: possible numbers are positive integer numbers 1 through 13; you can't
3595: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3596: think about some of the cards, you can accommodate different
3597: numbers. For example, you could think of the Jack as representing 0,
3598: the Queen as representing -1 and the King as representing -2. Your
3599: @i{range} remains unchanged (you can still only represent a total of 13
3600: numbers) but the numbers that you can represent are -2 through 10.
3601:
3602: In that analogy, the limit was the amount of information that a single
3603: stack entry could hold, and Forth has a similar limit. In Forth, the
3604: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3605: implementation dependent and affects the maximum value that a stack
3606: entry can hold. A Standard Forth provides a cell size of at least
3607: 16-bits, and most desktop systems use a cell size of 32-bits.
3608:
3609: Forth does not do any type checking for you, so you are free to
3610: manipulate and combine stack items in any way you wish. A convenient way
3611: of treating stack items is as 2's complement signed integers, and that
3612: is what Standard words like @code{+} do. Therefore you can type:
3613:
3614: @example
3615: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
3616: @end example
3617:
3618: If you use numbers and definitions like @code{+} in order to turn Forth
3619: into a great big pocket calculator, you will realise that it's rather
3620: different from a normal calculator. Rather than typing 2 + 3 = you had
3621: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3622: result). The terminology used to describe this difference is to say that
3623: your calculator uses @dfn{Infix Notation} (parameters and operators are
3624: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3625: operators are separate), also called @dfn{Reverse Polish Notation}.
3626:
3627: Whilst postfix notation might look confusing to begin with, it has
3628: several important advantages:
3629:
3630: @itemize @bullet
3631: @item
3632: it is unambiguous
3633: @item
3634: it is more concise
3635: @item
3636: it fits naturally with a stack-based system
3637: @end itemize
3638:
3639: To examine these claims in more detail, consider these sums:
3640:
3641: @example
3642: 6 + 5 * 4 =
3643: 4 * 5 + 6 =
3644: @end example
3645:
3646: If you're just learning maths or your maths is very rusty, you will
3647: probably come up with the answer 44 for the first and 26 for the
3648: second. If you are a bit of a whizz at maths you will remember the
3649: @i{convention} that multiplication takes precendence over addition, and
3650: you'd come up with the answer 26 both times. To explain the answer 26
3651: to someone who got the answer 44, you'd probably rewrite the first sum
3652: like this:
3653:
3654: @example
3655: 6 + (5 * 4) =
3656: @end example
3657:
3658: If what you really wanted was to perform the addition before the
3659: multiplication, you would have to use parentheses to force it.
3660:
3661: If you did the first two sums on a pocket calculator you would probably
3662: get the right answers, unless you were very cautious and entered them using
3663: these keystroke sequences:
3664:
3665: 6 + 5 = * 4 =
3666: 4 * 5 = + 6 =
3667:
3668: Postfix notation is unambiguous because the order that the operators
3669: are applied is always explicit; that also means that parentheses are
3670: never required. The operators are @i{active} (the act of quoting the
3671: operator makes the operation occur) which removes the need for ``=''.
3672:
3673: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3674: equivalent ways:
3675:
3676: @example
3677: 6 5 4 * + or:
3678: 5 4 * 6 +
3679: @end example
3680:
3681: An important thing that you should notice about this notation is that
3682: the @i{order} of the numbers does not change; if you want to subtract
3683: 2 from 10 you type @code{10 2 -}.
3684:
3685: The reason that Forth uses postfix notation is very simple to explain: it
3686: makes the implementation extremely simple, and it follows naturally from
3687: using the stack as a mechanism for passing parameters. Another way of
3688: thinking about this is to realise that all Forth definitions are
3689: @i{active}; they execute as they are encountered by the text
3690: interpreter. The result of this is that the syntax of Forth is trivially
3691: simple.
3692:
3693:
3694:
3695: @comment ----------------------------------------------
3696: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3697: @section Your first Forth definition
3698: @cindex first definition
3699:
3700: Until now, the examples we've seen have been trivial; we've just been
3701: using Forth as a bigger-than-pocket calculator. Also, each calculation
3702: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3703: again@footnote{That's not quite true. If you press the up-arrow key on
3704: your keyboard you should be able to scroll back to any earlier command,
3705: edit it and re-enter it.} In this section we'll see how to add new
3706: words to Forth's vocabulary.
3707:
3708: The easiest way to create a new word is to use a @dfn{colon
3709: definition}. We'll define a few and try them out before worrying too
3710: much about how they work. Try typing in these examples; be careful to
3711: copy the spaces accurately:
3712:
3713: @example
3714: : add-two 2 + . ;
3715: : greet ." Hello and welcome" ;
3716: : demo 5 add-two ;
3717: @end example
3718:
3719: @noindent
3720: Now try them out:
3721:
3722: @example
3723: @kbd{greet@key{RET}} Hello and welcome ok
3724: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3725: @kbd{4 add-two@key{RET}} 6 ok
3726: @kbd{demo@key{RET}} 7 ok
3727: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
3728: @end example
3729:
3730: The first new thing that we've introduced here is the pair of words
3731: @code{:} and @code{;}. These are used to start and terminate a new
3732: definition, respectively. The first word after the @code{:} is the name
3733: for the new definition.
3734:
3735: As you can see from the examples, a definition is built up of words that
3736: have already been defined; Forth makes no distinction between
3737: definitions that existed when you started the system up, and those that
3738: you define yourself.
3739:
3740: The examples also introduce the words @code{.} (dot), @code{."}
3741: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3742: the stack and displays it. It's like @code{.s} except that it only
3743: displays the top item of the stack and it is destructive; after it has
3744: executed, the number is no longer on the stack. There is always one
3745: space printed after the number, and no spaces before it. Dot-quote
3746: defines a string (a sequence of characters) that will be printed when
3747: the word is executed. The string can contain any printable characters
3748: except @code{"}. A @code{"} has a special function; it is not a Forth
3749: word but it acts as a delimiter (the way that delimiters work is
3750: described in the next section). Finally, @code{dup} duplicates the value
3751: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
3752:
3753: We already know that the text interpreter searches through the
3754: dictionary to locate names. If you've followed the examples earlier, you
3755: will already have a definition called @code{add-two}. Lets try modifying
3756: it by typing in a new definition:
3757:
3758: @example
3759: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
3760: @end example
3761:
3762: Forth recognised that we were defining a word that already exists, and
3763: printed a message to warn us of that fact. Let's try out the new
3764: definition:
3765:
3766: @example
3767: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
3768: @end example
3769:
3770: @noindent
3771: All that we've actually done here, though, is to create a new
3772: definition, with a particular name. The fact that there was already a
3773: definition with the same name did not make any difference to the way
3774: that the new definition was created (except that Forth printed a warning
3775: message). The old definition of add-two still exists (try @code{demo}
3776: again to see that this is true). Any new definition will use the new
3777: definition of @code{add-two}, but old definitions continue to use the
3778: version that already existed at the time that they were @code{compiled}.
3779:
3780: Before you go on to the next section, try defining and redefining some
3781: words of your own.
3782:
3783: @comment ----------------------------------------------
3784: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3785: @section How does that work?
3786: @cindex parsing words
3787:
3788: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3789:
3790: @c Is it a good idea to talk about the interpretation semantics of a
3791: @c number? We don't have an xt to go along with it. - anton
3792:
3793: @c Now that I have eliminated execution semantics, I wonder if it would not
3794: @c be better to keep them (or add run-time semantics), to make it easier to
3795: @c explain what compilation semantics usually does. - anton
3796:
3797: @c nac-> I removed the term ``default compilation sematics'' from the
3798: @c introductory chapter. Removing ``execution semantics'' was making
3799: @c everything simpler to explain, then I think the use of this term made
3800: @c everything more complex again. I replaced it with ``default
3801: @c semantics'' (which is used elsewhere in the manual) by which I mean
3802: @c ``a definition that has neither the immediate nor the compile-only
3803: @c flag set''.
3804:
3805: @c anton: I have eliminated default semantics (except in one place where it
3806: @c means "default interpretation and compilation semantics"), because it
3807: @c makes no sense in the presence of combined words. I reverted to
3808: @c "execution semantics" where necessary.
3809:
3810: @c nac-> I reworded big chunks of the ``how does that work''
3811: @c section (and, unusually for me, I think I even made it shorter!). See
3812: @c what you think -- I know I have not addressed your primary concern
3813: @c that it is too heavy-going for an introduction. From what I understood
3814: @c of your course notes it looks as though they might be a good framework.
3815: @c Things that I've tried to capture here are some things that came as a
3816: @c great revelation here when I first understood them. Also, I like the
3817: @c fact that a very simple code example shows up almost all of the issues
3818: @c that you need to understand to see how Forth works. That's unique and
3819: @c worthwhile to emphasise.
3820:
3821: @c anton: I think it's a good idea to present the details, especially those
3822: @c that you found to be a revelation, and probably the tutorial tries to be
3823: @c too superficial and does not get some of the things across that make
3824: @c Forth special. I do believe that most of the time these things should
3825: @c be discussed at the end of a section or in separate sections instead of
3826: @c in the middle of a section (e.g., the stuff you added in "User-defined
3827: @c defining words" leads in a completely different direction from the rest
3828: @c of the section).
3829:
3830: Now we're going to take another look at the definition of @code{add-two}
3831: from the previous section. From our knowledge of the way that the text
3832: interpreter works, we would have expected this result when we tried to
3833: define @code{add-two}:
3834:
3835: @example
3836: @kbd{: add-two 2 + . ;@key{RET}}
3837: ^^^^^^^
3838: Error: Undefined word
3839: @end example
3840:
3841: The reason that this didn't happen is bound up in the way that @code{:}
3842: works. The word @code{:} does two special things. The first special
3843: thing that it does prevents the text interpreter from ever seeing the
3844: characters @code{add-two}. The text interpreter uses a variable called
3845: @cindex modifying >IN
3846: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
3847: input line. When it encounters the word @code{:} it behaves in exactly
3848: the same way as it does for any other word; it looks it up in the name
3849: dictionary, finds its xt and executes it. When @code{:} executes, it
3850: looks at the input buffer, finds the word @code{add-two} and advances the
3851: value of @code{>IN} to point past it. It then does some other stuff
3852: associated with creating the new definition (including creating an entry
3853: for @code{add-two} in the name dictionary). When the execution of @code{:}
3854: completes, control returns to the text interpreter, which is oblivious
3855: to the fact that it has been tricked into ignoring part of the input
3856: line.
3857:
3858: @cindex parsing words
3859: Words like @code{:} -- words that advance the value of @code{>IN} and so
3860: prevent the text interpreter from acting on the whole of the input line
3861: -- are called @dfn{parsing words}.
3862:
3863: @cindex @code{state} - effect on the text interpreter
3864: @cindex text interpreter - effect of state
3865: The second special thing that @code{:} does is change the value of a
3866: variable called @code{state}, which affects the way that the text
3867: interpreter behaves. When Gforth starts up, @code{state} has the value
3868: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3869: colon definition (started with @code{:}), @code{state} is set to -1 and
3870: the text interpreter is said to be @dfn{compiling}.
3871:
3872: In this example, the text interpreter is compiling when it processes the
3873: string ``@code{2 + . ;}''. It still breaks the string down into
3874: character sequences in the same way. However, instead of pushing the
3875: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
3876: into the definition of @code{add-two} that will make the number @code{2} get
3877: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
3878: the behaviours of @code{+} and @code{.} are also compiled into the
3879: definition.
3880:
3881: One category of words don't get compiled. These so-called @dfn{immediate
3882: words} get executed (performed @i{now}) regardless of whether the text
3883: interpreter is interpreting or compiling. The word @code{;} is an
3884: immediate word. Rather than being compiled into the definition, it
3885: executes. Its effect is to terminate the current definition, which
3886: includes changing the value of @code{state} back to 0.
3887:
3888: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
3889: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
3890: definition.
3891:
3892: In Forth, every word or number can be described in terms of two
3893: properties:
3894:
3895: @itemize @bullet
3896: @item
3897: @cindex interpretation semantics
3898: Its @dfn{interpretation semantics} describe how it will behave when the
3899: text interpreter encounters it in @dfn{interpret} state. The
3900: interpretation semantics of a word are represented by an @dfn{execution
3901: token}.
3902: @item
3903: @cindex compilation semantics
3904: Its @dfn{compilation semantics} describe how it will behave when the
3905: text interpreter encounters it in @dfn{compile} state. The compilation
3906: semantics of a word are represented in an implementation-dependent way;
3907: Gforth uses a @dfn{compilation token}.
3908: @end itemize
3909:
3910: @noindent
3911: Numbers are always treated in a fixed way:
3912:
3913: @itemize @bullet
3914: @item
3915: When the number is @dfn{interpreted}, its behaviour is to push the
3916: number onto the stack.
3917: @item
3918: When the number is @dfn{compiled}, a piece of code is appended to the
3919: current definition that pushes the number when it runs. (In other words,
3920: the compilation semantics of a number are to postpone its interpretation
3921: semantics until the run-time of the definition that it is being compiled
3922: into.)
3923: @end itemize
3924:
3925: Words don't behave in such a regular way, but most have @i{default
3926: semantics} which means that they behave like this:
3927:
3928: @itemize @bullet
3929: @item
3930: The @dfn{interpretation semantics} of the word are to do something useful.
3931: @item
3932: The @dfn{compilation semantics} of the word are to append its
3933: @dfn{interpretation semantics} to the current definition (so that its
3934: run-time behaviour is to do something useful).
3935: @end itemize
3936:
3937: @cindex immediate words
3938: The actual behaviour of any particular word can be controlled by using
3939: the words @code{immediate} and @code{compile-only} when the word is
3940: defined. These words set flags in the name dictionary entry of the most
3941: recently defined word, and these flags are retrieved by the text
3942: interpreter when it finds the word in the name dictionary.
3943:
3944: A word that is marked as @dfn{immediate} has compilation semantics that
3945: are identical to its interpretation semantics. In other words, it
3946: behaves like this:
3947:
3948: @itemize @bullet
3949: @item
3950: The @dfn{interpretation semantics} of the word are to do something useful.
3951: @item
3952: The @dfn{compilation semantics} of the word are to do something useful
3953: (and actually the same thing); i.e., it is executed during compilation.
3954: @end itemize
3955:
3956: Marking a word as @dfn{compile-only} prohibits the text interpreter from
3957: performing the interpretation semantics of the word directly; an attempt
3958: to do so will generate an error. It is never necessary to use
3959: @code{compile-only} (and it is not even part of ANS Forth, though it is
3960: provided by many implementations) but it is good etiquette to apply it
3961: to a word that will not behave correctly (and might have unexpected
3962: side-effects) in interpret state. For example, it is only legal to use
3963: the conditional word @code{IF} within a definition. If you forget this
3964: and try to use it elsewhere, the fact that (in Gforth) it is marked as
3965: @code{compile-only} allows the text interpreter to generate a helpful
3966: error message rather than subjecting you to the consequences of your
3967: folly.
3968:
3969: This example shows the difference between an immediate and a
3970: non-immediate word:
3971:
3972: @example
3973: : show-state state @@ . ;
3974: : show-state-now show-state ; immediate
3975: : word1 show-state ;
3976: : word2 show-state-now ;
3977: @end example
3978:
3979: The word @code{immediate} after the definition of @code{show-state-now}
3980: makes that word an immediate word. These definitions introduce a new
3981: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
3982: variable, and leaves it on the stack. Therefore, the behaviour of
3983: @code{show-state} is to print a number that represents the current value
3984: of @code{state}.
3985:
3986: When you execute @code{word1}, it prints the number 0, indicating that
3987: the system is interpreting. When the text interpreter compiled the
3988: definition of @code{word1}, it encountered @code{show-state} whose
3989: compilation semantics are to append its interpretation semantics to the
3990: current definition. When you execute @code{word1}, it performs the
3991: interpretation semantics of @code{show-state}. At the time that @code{word1}
3992: (and therefore @code{show-state}) are executed, the system is
3993: interpreting.
3994:
3995: When you pressed @key{RET} after entering the definition of @code{word2},
3996: you should have seen the number -1 printed, followed by ``@code{
3997: ok}''. When the text interpreter compiled the definition of
3998: @code{word2}, it encountered @code{show-state-now}, an immediate word,
3999: whose compilation semantics are therefore to perform its interpretation
4000: semantics. It is executed straight away (even before the text
4001: interpreter has moved on to process another group of characters; the
4002: @code{;} in this example). The effect of executing it are to display the
4003: value of @code{state} @i{at the time that the definition of}
4004: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4005: system is compiling at this time. If you execute @code{word2} it does
4006: nothing at all.
4007:
4008: @cindex @code{."}, how it works
4009: Before leaving the subject of immediate words, consider the behaviour of
4010: @code{."} in the definition of @code{greet}, in the previous
4011: section. This word is both a parsing word and an immediate word. Notice
4012: that there is a space between @code{."} and the start of the text
4013: @code{Hello and welcome}, but that there is no space between the last
4014: letter of @code{welcome} and the @code{"} character. The reason for this
4015: is that @code{."} is a Forth word; it must have a space after it so that
4016: the text interpreter can identify it. The @code{"} is not a Forth word;
4017: it is a @dfn{delimiter}. The examples earlier show that, when the string
4018: is displayed, there is neither a space before the @code{H} nor after the
4019: @code{e}. Since @code{."} is an immediate word, it executes at the time
4020: that @code{greet} is defined. When it executes, its behaviour is to
4021: search forward in the input line looking for the delimiter. When it
4022: finds the delimiter, it updates @code{>IN} to point past the
4023: delimiter. It also compiles some magic code into the definition of
4024: @code{greet}; the xt of a run-time routine that prints a text string. It
4025: compiles the string @code{Hello and welcome} into memory so that it is
4026: available to be printed later. When the text interpreter gains control,
4027: the next word it finds in the input stream is @code{;} and so it
4028: terminates the definition of @code{greet}.
4029:
4030:
4031: @comment ----------------------------------------------
4032: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4033: @section Forth is written in Forth
4034: @cindex structure of Forth programs
4035:
4036: When you start up a Forth compiler, a large number of definitions
4037: already exist. In Forth, you develop a new application using bottom-up
4038: programming techniques to create new definitions that are defined in
4039: terms of existing definitions. As you create each definition you can
4040: test and debug it interactively.
4041:
4042: If you have tried out the examples in this section, you will probably
4043: have typed them in by hand; when you leave Gforth, your definitions will
4044: be lost. You can avoid this by using a text editor to enter Forth source
4045: code into a file, and then loading code from the file using
4046: @code{include} (@pxref{Forth source files}). A Forth source file is
4047: processed by the text interpreter, just as though you had typed it in by
4048: hand@footnote{Actually, there are some subtle differences -- see
4049: @ref{The Text Interpreter}.}.
4050:
4051: Gforth also supports the traditional Forth alternative to using text
4052: files for program entry (@pxref{Blocks}).
4053:
4054: In common with many, if not most, Forth compilers, most of Gforth is
4055: actually written in Forth. All of the @file{.fs} files in the
4056: installation directory@footnote{For example,
4057: @file{/usr/local/share/gforth...}} are Forth source files, which you can
4058: study to see examples of Forth programming.
4059:
4060: Gforth maintains a history file that records every line that you type to
4061: the text interpreter. This file is preserved between sessions, and is
4062: used to provide a command-line recall facility. If you enter long
4063: definitions by hand, you can use a text editor to paste them out of the
4064: history file into a Forth source file for reuse at a later time
4065: (for more information @pxref{Command-line editing}).
4066:
4067:
4068: @comment ----------------------------------------------
4069: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4070: @section Review - elements of a Forth system
4071: @cindex elements of a Forth system
4072:
4073: To summarise this chapter:
4074:
4075: @itemize @bullet
4076: @item
4077: Forth programs use @dfn{factoring} to break a problem down into small
4078: fragments called @dfn{words} or @dfn{definitions}.
4079: @item
4080: Forth program development is an interactive process.
4081: @item
4082: The main command loop that accepts input, and controls both
4083: interpretation and compilation, is called the @dfn{text interpreter}
4084: (also known as the @dfn{outer interpreter}).
4085: @item
4086: Forth has a very simple syntax, consisting of words and numbers
4087: separated by spaces or carriage-return characters. Any additional syntax
4088: is imposed by @dfn{parsing words}.
4089: @item
4090: Forth uses a stack to pass parameters between words. As a result, it
4091: uses postfix notation.
4092: @item
4093: To use a word that has previously been defined, the text interpreter
4094: searches for the word in the @dfn{name dictionary}.
4095: @item
4096: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
4097: @item
4098: The text interpreter uses the value of @code{state} to select between
4099: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4100: semantics} of a word that it encounters.
4101: @item
4102: The relationship between the @dfn{interpretation semantics} and
4103: @dfn{compilation semantics} for a word
4104: depend upon the way in which the word was defined (for example, whether
4105: it is an @dfn{immediate} word).
4106: @item
4107: Forth definitions can be implemented in Forth (called @dfn{high-level
4108: definitions}) or in some other way (usually a lower-level language and
4109: as a result often called @dfn{low-level definitions}, @dfn{code
4110: definitions} or @dfn{primitives}).
4111: @item
4112: Many Forth systems are implemented mainly in Forth.
4113: @end itemize
4114:
4115:
4116: @comment ----------------------------------------------
4117: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
4118: @section Where To Go Next
4119: @cindex where to go next
4120:
4121: Amazing as it may seem, if you have read (and understood) this far, you
4122: know almost all the fundamentals about the inner workings of a Forth
4123: system. You certainly know enough to be able to read and understand the
4124: rest of this manual and the ANS Forth document, to learn more about the
4125: facilities that Forth in general and Gforth in particular provide. Even
4126: scarier, you know almost enough to implement your own Forth system.
4127: However, that's not a good idea just yet... better to try writing some
4128: programs in Gforth.
4129:
4130: Forth has such a rich vocabulary that it can be hard to know where to
4131: start in learning it. This section suggests a few sets of words that are
4132: enough to write small but useful programs. Use the word index in this
4133: document to learn more about each word, then try it out and try to write
4134: small definitions using it. Start by experimenting with these words:
4135:
4136: @itemize @bullet
4137: @item
4138: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4139: @item
4140: Comparison: @code{MIN MAX =}
4141: @item
4142: Logic: @code{AND OR XOR NOT}
4143: @item
4144: Stack manipulation: @code{DUP DROP SWAP OVER}
4145: @item
4146: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
4147: @item
4148: Input/Output: @code{. ." EMIT CR KEY}
4149: @item
4150: Defining words: @code{: ; CREATE}
4151: @item
4152: Memory allocation words: @code{ALLOT ,}
4153: @item
4154: Tools: @code{SEE WORDS .S MARKER}
4155: @end itemize
4156:
4157: When you have mastered those, go on to:
4158:
4159: @itemize @bullet
4160: @item
4161: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
4162: @item
4163: Memory access: @code{@@ !}
4164: @end itemize
4165:
4166: When you have mastered these, there's nothing for it but to read through
4167: the whole of this manual and find out what you've missed.
4168:
4169: @comment ----------------------------------------------
4170: @node Exercises, , Where to go next, Introduction
4171: @section Exercises
4172: @cindex exercises
4173:
4174: TODO: provide a set of programming excercises linked into the stuff done
4175: already and into other sections of the manual. Provide solutions to all
4176: the exercises in a .fs file in the distribution.
4177:
4178: @c Get some inspiration from Starting Forth and Kelly&Spies.
4179:
4180: @c excercises:
4181: @c 1. take inches and convert to feet and inches.
4182: @c 2. take temperature and convert from fahrenheight to celcius;
4183: @c may need to care about symmetric vs floored??
4184: @c 3. take input line and do character substitution
4185: @c to encipher or decipher
4186: @c 4. as above but work on a file for in and out
4187: @c 5. take input line and convert to pig-latin
4188: @c
4189: @c thing of sets of things to exercise then come up with
4190: @c problems that need those things.
4191:
4192:
4193: @c ******************************************************************
4194: @node Words, Error messages, Introduction, Top
4195: @chapter Forth Words
4196: @cindex words
4197:
4198: @menu
4199: * Notation::
4200: * Case insensitivity::
4201: * Comments::
4202: * Boolean Flags::
4203: * Arithmetic::
4204: * Stack Manipulation::
4205: * Memory::
4206: * Control Structures::
4207: * Defining Words::
4208: * Interpretation and Compilation Semantics::
4209: * Tokens for Words::
4210: * Compiling words::
4211: * The Text Interpreter::
4212: * The Input Stream::
4213: * Word Lists::
4214: * Environmental Queries::
4215: * Files::
4216: * Blocks::
4217: * Other I/O::
4218: * OS command line arguments::
4219: * Locals::
4220: * Structures::
4221: * Object-oriented Forth::
4222: * Programming Tools::
4223: * Assembler and Code Words::
4224: * Threading Words::
4225: * Passing Commands to the OS::
4226: * Keeping track of Time::
4227: * Miscellaneous Words::
4228: @end menu
4229:
4230: @node Notation, Case insensitivity, Words, Words
4231: @section Notation
4232: @cindex notation of glossary entries
4233: @cindex format of glossary entries
4234: @cindex glossary notation format
4235: @cindex word glossary entry format
4236:
4237: The Forth words are described in this section in the glossary notation
4238: that has become a de-facto standard for Forth texts:
4239:
4240: @format
4241: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
4242: @end format
4243: @i{Description}
4244:
4245: @table @var
4246: @item word
4247: The name of the word.
4248:
4249: @item Stack effect
4250: @cindex stack effect
4251: The stack effect is written in the notation @code{@i{before} --
4252: @i{after}}, where @i{before} and @i{after} describe the top of
4253: stack entries before and after the execution of the word. The rest of
4254: the stack is not touched by the word. The top of stack is rightmost,
4255: i.e., a stack sequence is written as it is typed in. Note that Gforth
4256: uses a separate floating point stack, but a unified stack
4257: notation. Also, return stack effects are not shown in @i{stack
4258: effect}, but in @i{Description}. The name of a stack item describes
4259: the type and/or the function of the item. See below for a discussion of
4260: the types.
4261:
4262: All words have two stack effects: A compile-time stack effect and a
4263: run-time stack effect. The compile-time stack-effect of most words is
4264: @i{ -- }. If the compile-time stack-effect of a word deviates from
4265: this standard behaviour, or the word does other unusual things at
4266: compile time, both stack effects are shown; otherwise only the run-time
4267: stack effect is shown.
4268:
4269: @cindex pronounciation of words
4270: @item pronunciation
4271: How the word is pronounced.
4272:
4273: @cindex wordset
4274: @cindex environment wordset
4275: @item wordset
4276: The ANS Forth standard is divided into several word sets. A standard
4277: system need not support all of them. Therefore, in theory, the fewer
4278: word sets your program uses the more portable it will be. However, we
4279: suspect that most ANS Forth systems on personal machines will feature
4280: all word sets. Words that are not defined in ANS Forth have
4281: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
4282: describes words that will work in future releases of Gforth;
4283: @code{gforth-internal} words are more volatile. Environmental query
4284: strings are also displayed like words; you can recognize them by the
4285: @code{environment} in the word set field.
4286:
4287: @item Description
4288: A description of the behaviour of the word.
4289: @end table
4290:
4291: @cindex types of stack items
4292: @cindex stack item types
4293: The type of a stack item is specified by the character(s) the name
4294: starts with:
4295:
4296: @table @code
4297: @item f
4298: @cindex @code{f}, stack item type
4299: Boolean flags, i.e. @code{false} or @code{true}.
4300: @item c
4301: @cindex @code{c}, stack item type
4302: Char
4303: @item w
4304: @cindex @code{w}, stack item type
4305: Cell, can contain an integer or an address
4306: @item n
4307: @cindex @code{n}, stack item type
4308: signed integer
4309: @item u
4310: @cindex @code{u}, stack item type
4311: unsigned integer
4312: @item d
4313: @cindex @code{d}, stack item type
4314: double sized signed integer
4315: @item ud
4316: @cindex @code{ud}, stack item type
4317: double sized unsigned integer
4318: @item r
4319: @cindex @code{r}, stack item type
4320: Float (on the FP stack)
4321: @item a-
4322: @cindex @code{a_}, stack item type
4323: Cell-aligned address
4324: @item c-
4325: @cindex @code{c_}, stack item type
4326: Char-aligned address (note that a Char may have two bytes in Windows NT)
4327: @item f-
4328: @cindex @code{f_}, stack item type
4329: Float-aligned address
4330: @item df-
4331: @cindex @code{df_}, stack item type
4332: Address aligned for IEEE double precision float
4333: @item sf-
4334: @cindex @code{sf_}, stack item type
4335: Address aligned for IEEE single precision float
4336: @item xt
4337: @cindex @code{xt}, stack item type
4338: Execution token, same size as Cell
4339: @item wid
4340: @cindex @code{wid}, stack item type
4341: Word list ID, same size as Cell
4342: @item ior, wior
4343: @cindex ior type description
4344: @cindex wior type description
4345: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
4346: @item f83name
4347: @cindex @code{f83name}, stack item type
4348: Pointer to a name structure
4349: @item "
4350: @cindex @code{"}, stack item type
4351: string in the input stream (not on the stack). The terminating character
4352: is a blank by default. If it is not a blank, it is shown in @code{<>}
4353: quotes.
4354: @end table
4355:
4356: @comment ----------------------------------------------
4357: @node Case insensitivity, Comments, Notation, Words
4358: @section Case insensitivity
4359: @cindex case sensitivity
4360: @cindex upper and lower case
4361:
4362: Gforth is case-insensitive; you can enter definitions and invoke
4363: Standard words using upper, lower or mixed case (however,
4364: @pxref{core-idef, Implementation-defined options, Implementation-defined
4365: options}).
4366:
4367: ANS Forth only @i{requires} implementations to recognise Standard words
4368: when they are typed entirely in upper case. Therefore, a Standard
4369: program must use upper case for all Standard words. You can use whatever
4370: case you like for words that you define, but in a Standard program you
4371: have to use the words in the same case that you defined them.
4372:
4373: Gforth supports case sensitivity through @code{table}s (case-sensitive
4374: wordlists, @pxref{Word Lists}).
4375:
4376: Two people have asked how to convert Gforth to be case-sensitive; while
4377: we think this is a bad idea, you can change all wordlists into tables
4378: like this:
4379:
4380: @example
4381: ' table-find forth-wordlist wordlist-map @ !
4382: @end example
4383:
4384: Note that you now have to type the predefined words in the same case
4385: that we defined them, which are varying. You may want to convert them
4386: to your favourite case before doing this operation (I won't explain how,
4387: because if you are even contemplating doing this, you'd better have
4388: enough knowledge of Forth systems to know this already).
4389:
4390: @node Comments, Boolean Flags, Case insensitivity, Words
4391: @section Comments
4392: @cindex comments
4393:
4394: Forth supports two styles of comment; the traditional @i{in-line} comment,
4395: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
4396:
4397:
4398: doc-(
4399: doc-\
4400: doc-\G
4401:
4402:
4403: @node Boolean Flags, Arithmetic, Comments, Words
4404: @section Boolean Flags
4405: @cindex Boolean flags
4406:
4407: A Boolean flag is cell-sized. A cell with all bits clear represents the
4408: flag @code{false} and a flag with all bits set represents the flag
4409: @code{true}. Words that check a flag (for example, @code{IF}) will treat
4410: a cell that has @i{any} bit set as @code{true}.
4411: @c on and off to Memory?
4412: @c true and false to "Bitwise operations" or "Numeric comparison"?
4413:
4414: doc-true
4415: doc-false
4416: doc-on
4417: doc-off
4418:
4419:
4420: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
4421: @section Arithmetic
4422: @cindex arithmetic words
4423:
4424: @cindex division with potentially negative operands
4425: Forth arithmetic is not checked, i.e., you will not hear about integer
4426: overflow on addition or multiplication, you may hear about division by
4427: zero if you are lucky. The operator is written after the operands, but
4428: the operands are still in the original order. I.e., the infix @code{2-1}
4429: corresponds to @code{2 1 -}. Forth offers a variety of division
4430: operators. If you perform division with potentially negative operands,
4431: you do not want to use @code{/} or @code{/mod} with its undefined
4432: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4433: former, @pxref{Mixed precision}).
4434: @comment TODO discuss the different division forms and the std approach
4435:
4436: @menu
4437: * Single precision::
4438: * Double precision:: Double-cell integer arithmetic
4439: * Bitwise operations::
4440: * Numeric comparison::
4441: * Mixed precision:: Operations with single and double-cell integers
4442: * Floating Point::
4443: @end menu
4444:
4445: @node Single precision, Double precision, Arithmetic, Arithmetic
4446: @subsection Single precision
4447: @cindex single precision arithmetic words
4448:
4449: @c !! cell undefined
4450:
4451: By default, numbers in Forth are single-precision integers that are one
4452: cell in size. They can be signed or unsigned, depending upon how you
4453: treat them. For the rules used by the text interpreter for recognising
4454: single-precision integers see @ref{Number Conversion}.
4455:
4456: These words are all defined for signed operands, but some of them also
4457: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4458: @code{*}.
4459:
4460: doc-+
4461: doc-1+
4462: doc--
4463: doc-1-
4464: doc-*
4465: doc-/
4466: doc-mod
4467: doc-/mod
4468: doc-negate
4469: doc-abs
4470: doc-min
4471: doc-max
4472: doc-floored
4473:
4474:
4475: @node Double precision, Bitwise operations, Single precision, Arithmetic
4476: @subsection Double precision
4477: @cindex double precision arithmetic words
4478:
4479: For the rules used by the text interpreter for
4480: recognising double-precision integers, see @ref{Number Conversion}.
4481:
4482: A double precision number is represented by a cell pair, with the most
4483: significant cell at the TOS. It is trivial to convert an unsigned single
4484: to a double: simply push a @code{0} onto the TOS. Since numbers are
4485: represented by Gforth using 2's complement arithmetic, converting a
4486: signed single to a (signed) double requires sign-extension across the
4487: most significant cell. This can be achieved using @code{s>d}. The moral
4488: of the story is that you cannot convert a number without knowing whether
4489: it represents an unsigned or a signed number.
4490:
4491: These words are all defined for signed operands, but some of them also
4492: work for unsigned numbers: @code{d+}, @code{d-}.
4493:
4494: doc-s>d
4495: doc-d>s
4496: doc-d+
4497: doc-d-
4498: doc-dnegate
4499: doc-dabs
4500: doc-dmin
4501: doc-dmax
4502:
4503:
4504: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4505: @subsection Bitwise operations
4506: @cindex bitwise operation words
4507:
4508:
4509: doc-and
4510: doc-or
4511: doc-xor
4512: doc-invert
4513: doc-lshift
4514: doc-rshift
4515: doc-2*
4516: doc-d2*
4517: doc-2/
4518: doc-d2/
4519:
4520:
4521: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
4522: @subsection Numeric comparison
4523: @cindex numeric comparison words
4524:
4525: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4526: d0= d0<>}) work for for both signed and unsigned numbers.
4527:
4528: doc-<
4529: doc-<=
4530: doc-<>
4531: doc-=
4532: doc->
4533: doc->=
4534:
4535: doc-0<
4536: doc-0<=
4537: doc-0<>
4538: doc-0=
4539: doc-0>
4540: doc-0>=
4541:
4542: doc-u<
4543: doc-u<=
4544: @c u<> and u= exist but are the same as <> and =
4545: @c doc-u<>
4546: @c doc-u=
4547: doc-u>
4548: doc-u>=
4549:
4550: doc-within
4551:
4552: doc-d<
4553: doc-d<=
4554: doc-d<>
4555: doc-d=
4556: doc-d>
4557: doc-d>=
4558:
4559: doc-d0<
4560: doc-d0<=
4561: doc-d0<>
4562: doc-d0=
4563: doc-d0>
4564: doc-d0>=
4565:
4566: doc-du<
4567: doc-du<=
4568: @c du<> and du= exist but are the same as d<> and d=
4569: @c doc-du<>
4570: @c doc-du=
4571: doc-du>
4572: doc-du>=
4573:
4574:
4575: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
4576: @subsection Mixed precision
4577: @cindex mixed precision arithmetic words
4578:
4579:
4580: doc-m+
4581: doc-*/
4582: doc-*/mod
4583: doc-m*
4584: doc-um*
4585: doc-m*/
4586: doc-um/mod
4587: doc-fm/mod
4588: doc-sm/rem
4589:
4590:
4591: @node Floating Point, , Mixed precision, Arithmetic
4592: @subsection Floating Point
4593: @cindex floating point arithmetic words
4594:
4595: For the rules used by the text interpreter for
4596: recognising floating-point numbers see @ref{Number Conversion}.
4597:
4598: Gforth has a separate floating point stack, but the documentation uses
4599: the unified notation.@footnote{It's easy to generate the separate
4600: notation from that by just separating the floating-point numbers out:
4601: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4602: r3 )}.}
4603:
4604: @cindex floating-point arithmetic, pitfalls
4605: Floating point numbers have a number of unpleasant surprises for the
4606: unwary (e.g., floating point addition is not associative) and even a few
4607: for the wary. You should not use them unless you know what you are doing
4608: or you don't care that the results you get are totally bogus. If you
4609: want to learn about the problems of floating point numbers (and how to
4610: avoid them), you might start with @cite{David Goldberg,
4611: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4612: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4613: Surveys 23(1):5@minus{}48, March 1991}.
4614:
4615:
4616: doc-d>f
4617: doc-f>d
4618: doc-f+
4619: doc-f-
4620: doc-f*
4621: doc-f/
4622: doc-fnegate
4623: doc-fabs
4624: doc-fmax
4625: doc-fmin
4626: doc-floor
4627: doc-fround
4628: doc-f**
4629: doc-fsqrt
4630: doc-fexp
4631: doc-fexpm1
4632: doc-fln
4633: doc-flnp1
4634: doc-flog
4635: doc-falog
4636: doc-f2*
4637: doc-f2/
4638: doc-1/f
4639: doc-precision
4640: doc-set-precision
4641:
4642: @cindex angles in trigonometric operations
4643: @cindex trigonometric operations
4644: Angles in floating point operations are given in radians (a full circle
4645: has 2 pi radians).
4646:
4647: doc-fsin
4648: doc-fcos
4649: doc-fsincos
4650: doc-ftan
4651: doc-fasin
4652: doc-facos
4653: doc-fatan
4654: doc-fatan2
4655: doc-fsinh
4656: doc-fcosh
4657: doc-ftanh
4658: doc-fasinh
4659: doc-facosh
4660: doc-fatanh
4661: doc-pi
4662:
4663: @cindex equality of floats
4664: @cindex floating-point comparisons
4665: One particular problem with floating-point arithmetic is that comparison
4666: for equality often fails when you would expect it to succeed. For this
4667: reason approximate equality is often preferred (but you still have to
4668: know what you are doing). Also note that IEEE NaNs may compare
4669: differently from what you might expect. The comparison words are:
4670:
4671: doc-f~rel
4672: doc-f~abs
4673: doc-f~
4674: doc-f=
4675: doc-f<>
4676:
4677: doc-f<
4678: doc-f<=
4679: doc-f>
4680: doc-f>=
4681:
4682: doc-f0<
4683: doc-f0<=
4684: doc-f0<>
4685: doc-f0=
4686: doc-f0>
4687: doc-f0>=
4688:
4689:
4690: @node Stack Manipulation, Memory, Arithmetic, Words
4691: @section Stack Manipulation
4692: @cindex stack manipulation words
4693:
4694: @cindex floating-point stack in the standard
4695: Gforth maintains a number of separate stacks:
4696:
4697: @cindex data stack
4698: @cindex parameter stack
4699: @itemize @bullet
4700: @item
4701: A data stack (also known as the @dfn{parameter stack}) -- for
4702: characters, cells, addresses, and double cells.
4703:
4704: @cindex floating-point stack
4705: @item
4706: A floating point stack -- for holding floating point (FP) numbers.
4707:
4708: @cindex return stack
4709: @item
4710: A return stack -- for holding the return addresses of colon
4711: definitions and other (non-FP) data.
4712:
4713: @cindex locals stack
4714: @item
4715: A locals stack -- for holding local variables.
4716: @end itemize
4717:
4718: @menu
4719: * Data stack::
4720: * Floating point stack::
4721: * Return stack::
4722: * Locals stack::
4723: * Stack pointer manipulation::
4724: @end menu
4725:
4726: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4727: @subsection Data stack
4728: @cindex data stack manipulation words
4729: @cindex stack manipulations words, data stack
4730:
4731:
4732: doc-drop
4733: doc-nip
4734: doc-dup
4735: doc-over
4736: doc-tuck
4737: doc-swap
4738: doc-pick
4739: doc-rot
4740: doc--rot
4741: doc-?dup
4742: doc-roll
4743: doc-2drop
4744: doc-2nip
4745: doc-2dup
4746: doc-2over
4747: doc-2tuck
4748: doc-2swap
4749: doc-2rot
4750:
4751:
4752: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4753: @subsection Floating point stack
4754: @cindex floating-point stack manipulation words
4755: @cindex stack manipulation words, floating-point stack
4756:
4757: Whilst every sane Forth has a separate floating-point stack, it is not
4758: strictly required; an ANS Forth system could theoretically keep
4759: floating-point numbers on the data stack. As an additional difficulty,
4760: you don't know how many cells a floating-point number takes. It is
4761: reportedly possible to write words in a way that they work also for a
4762: unified stack model, but we do not recommend trying it. Instead, just
4763: say that your program has an environmental dependency on a separate
4764: floating-point stack.
4765:
4766: doc-floating-stack
4767:
4768: doc-fdrop
4769: doc-fnip
4770: doc-fdup
4771: doc-fover
4772: doc-ftuck
4773: doc-fswap
4774: doc-fpick
4775: doc-frot
4776:
4777:
4778: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4779: @subsection Return stack
4780: @cindex return stack manipulation words
4781: @cindex stack manipulation words, return stack
4782:
4783: @cindex return stack and locals
4784: @cindex locals and return stack
4785: A Forth system is allowed to keep local variables on the
4786: return stack. This is reasonable, as local variables usually eliminate
4787: the need to use the return stack explicitly. So, if you want to produce
4788: a standard compliant program and you are using local variables in a
4789: word, forget about return stack manipulations in that word (refer to the
4790: standard document for the exact rules).
4791:
4792: doc->r
4793: doc-r>
4794: doc-r@
4795: doc-rdrop
4796: doc-2>r
4797: doc-2r>
4798: doc-2r@
4799: doc-2rdrop
4800:
4801:
4802: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4803: @subsection Locals stack
4804:
4805: Gforth uses an extra locals stack. It is described, along with the
4806: reasons for its existence, in @ref{Locals implementation}.
4807:
4808: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4809: @subsection Stack pointer manipulation
4810: @cindex stack pointer manipulation words
4811:
4812: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
4813: doc-sp0
4814: doc-sp@
4815: doc-sp!
4816: doc-fp0
4817: doc-fp@
4818: doc-fp!
4819: doc-rp0
4820: doc-rp@
4821: doc-rp!
4822: doc-lp0
4823: doc-lp@
4824: doc-lp!
4825:
4826:
4827: @node Memory, Control Structures, Stack Manipulation, Words
4828: @section Memory
4829: @cindex memory words
4830:
4831: @menu
4832: * Memory model::
4833: * Dictionary allocation::
4834: * Heap Allocation::
4835: * Memory Access::
4836: * Address arithmetic::
4837: * Memory Blocks::
4838: @end menu
4839:
4840: In addition to the standard Forth memory allocation words, there is also
4841: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4842: garbage collector}.
4843:
4844: @node Memory model, Dictionary allocation, Memory, Memory
4845: @subsection ANS Forth and Gforth memory models
4846:
4847: @c The ANS Forth description is a mess (e.g., is the heap part of
4848: @c the dictionary?), so let's not stick to closely with it.
4849:
4850: ANS Forth considers a Forth system as consisting of several address
4851: spaces, of which only @dfn{data space} is managed and accessible with
4852: the memory words. Memory not necessarily in data space includes the
4853: stacks, the code (called code space) and the headers (called name
4854: space). In Gforth everything is in data space, but the code for the
4855: primitives is usually read-only.
4856:
4857: Data space is divided into a number of areas: The (data space portion of
4858: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4859: refer to the search data structure embodied in word lists and headers,
4860: because it is used for looking up names, just as you would in a
4861: conventional dictionary.}, the heap, and a number of system-allocated
4862: buffers.
4863:
4864: @cindex address arithmetic restrictions, ANS vs. Gforth
4865: @cindex contiguous regions, ANS vs. Gforth
4866: In ANS Forth data space is also divided into contiguous regions. You
4867: can only use address arithmetic within a contiguous region, not between
4868: them. Usually each allocation gives you one contiguous region, but the
4869: dictionary allocation words have additional rules (@pxref{Dictionary
4870: allocation}).
4871:
4872: Gforth provides one big address space, and address arithmetic can be
4873: performed between any addresses. However, in the dictionary headers or
4874: code are interleaved with data, so almost the only contiguous data space
4875: regions there are those described by ANS Forth as contiguous; but you
4876: can be sure that the dictionary is allocated towards increasing
4877: addresses even between contiguous regions. The memory order of
4878: allocations in the heap is platform-dependent (and possibly different
4879: from one run to the next).
4880:
4881:
4882: @node Dictionary allocation, Heap Allocation, Memory model, Memory
4883: @subsection Dictionary allocation
4884: @cindex reserving data space
4885: @cindex data space - reserving some
4886:
4887: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
4888: you want to deallocate X, you also deallocate everything
4889: allocated after X.
4890:
4891: @cindex contiguous regions in dictionary allocation
4892: The allocations using the words below are contiguous and grow the region
4893: towards increasing addresses. Other words that allocate dictionary
4894: memory of any kind (i.e., defining words including @code{:noname}) end
4895: the contiguous region and start a new one.
4896:
4897: In ANS Forth only @code{create}d words are guaranteed to produce an
4898: address that is the start of the following contiguous region. In
4899: particular, the cell allocated by @code{variable} is not guaranteed to
4900: be contiguous with following @code{allot}ed memory.
4901:
4902: You can deallocate memory by using @code{allot} with a negative argument
4903: (with some restrictions, see @code{allot}). For larger deallocations use
4904: @code{marker}.
4905:
4906:
4907: doc-here
4908: doc-unused
4909: doc-allot
4910: doc-c,
4911: doc-f,
4912: doc-,
4913: doc-2,
4914:
4915: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
4916: course you should allocate memory in an aligned way, too. I.e., before
4917: allocating allocating a cell, @code{here} must be cell-aligned, etc.
4918: The words below align @code{here} if it is not already. Basically it is
4919: only already aligned for a type, if the last allocation was a multiple
4920: of the size of this type and if @code{here} was aligned for this type
4921: before.
4922:
4923: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
4924: ANS Forth (@code{maxalign}ed in Gforth).
4925:
4926: doc-align
4927: doc-falign
4928: doc-sfalign
4929: doc-dfalign
4930: doc-maxalign
4931: doc-cfalign
4932:
4933:
4934: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
4935: @subsection Heap allocation
4936: @cindex heap allocation
4937: @cindex dynamic allocation of memory
4938: @cindex memory-allocation word set
4939:
4940: @cindex contiguous regions and heap allocation
4941: Heap allocation supports deallocation of allocated memory in any
4942: order. Dictionary allocation is not affected by it (i.e., it does not
4943: end a contiguous region). In Gforth, these words are implemented using
4944: the standard C library calls malloc(), free() and resize().
4945:
4946: The memory region produced by one invocation of @code{allocate} or
4947: @code{resize} is internally contiguous. There is no contiguity between
4948: such a region and any other region (including others allocated from the
4949: heap).
4950:
4951: doc-allocate
4952: doc-free
4953: doc-resize
4954:
4955:
4956: @node Memory Access, Address arithmetic, Heap Allocation, Memory
4957: @subsection Memory Access
4958: @cindex memory access words
4959:
4960: doc-@
4961: doc-!
4962: doc-+!
4963: doc-c@
4964: doc-c!
4965: doc-2@
4966: doc-2!
4967: doc-f@
4968: doc-f!
4969: doc-sf@
4970: doc-sf!
4971: doc-df@
4972: doc-df!
4973:
4974:
4975: @node Address arithmetic, Memory Blocks, Memory Access, Memory
4976: @subsection Address arithmetic
4977: @cindex address arithmetic words
4978:
4979: Address arithmetic is the foundation on which you can build data
4980: structures like arrays, records (@pxref{Structures}) and objects
4981: (@pxref{Object-oriented Forth}).
4982:
4983: @cindex address unit
4984: @cindex au (address unit)
4985: ANS Forth does not specify the sizes of the data types. Instead, it
4986: offers a number of words for computing sizes and doing address
4987: arithmetic. Address arithmetic is performed in terms of address units
4988: (aus); on most systems the address unit is one byte. Note that a
4989: character may have more than one au, so @code{chars} is no noop (on
4990: platforms where it is a noop, it compiles to nothing).
4991:
4992: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
4993: you have the address of a cell, perform @code{1 cells +}, and you will
4994: have the address of the next cell.
4995:
4996: @cindex contiguous regions and address arithmetic
4997: In ANS Forth you can perform address arithmetic only within a contiguous
4998: region, i.e., if you have an address into one region, you can only add
4999: and subtract such that the result is still within the region; you can
5000: only subtract or compare addresses from within the same contiguous
5001: region. Reasons: several contiguous regions can be arranged in memory
5002: in any way; on segmented systems addresses may have unusual
5003: representations, such that address arithmetic only works within a
5004: region. Gforth provides a few more guarantees (linear address space,
5005: dictionary grows upwards), but in general I have found it easy to stay
5006: within contiguous regions (exception: computing and comparing to the
5007: address just beyond the end of an array).
5008:
5009: @cindex alignment of addresses for types
5010: ANS Forth also defines words for aligning addresses for specific
5011: types. Many computers require that accesses to specific data types
5012: must only occur at specific addresses; e.g., that cells may only be
5013: accessed at addresses divisible by 4. Even if a machine allows unaligned
5014: accesses, it can usually perform aligned accesses faster.
5015:
5016: For the performance-conscious: alignment operations are usually only
5017: necessary during the definition of a data structure, not during the
5018: (more frequent) accesses to it.
5019:
5020: ANS Forth defines no words for character-aligning addresses. This is not
5021: an oversight, but reflects the fact that addresses that are not
5022: char-aligned have no use in the standard and therefore will not be
5023: created.
5024:
5025: @cindex @code{CREATE} and alignment
5026: ANS Forth guarantees that addresses returned by @code{CREATE}d words
5027: are cell-aligned; in addition, Gforth guarantees that these addresses
5028: are aligned for all purposes.
5029:
5030: Note that the ANS Forth word @code{char} has nothing to do with address
5031: arithmetic.
5032:
5033:
5034: doc-chars
5035: doc-char+
5036: doc-cells
5037: doc-cell+
5038: doc-cell
5039: doc-aligned
5040: doc-floats
5041: doc-float+
5042: doc-float
5043: doc-faligned
5044: doc-sfloats
5045: doc-sfloat+
5046: doc-sfaligned
5047: doc-dfloats
5048: doc-dfloat+
5049: doc-dfaligned
5050: doc-maxaligned
5051: doc-cfaligned
5052: doc-address-unit-bits
5053:
5054:
5055: @node Memory Blocks, , Address arithmetic, Memory
5056: @subsection Memory Blocks
5057: @cindex memory block words
5058: @cindex character strings - moving and copying
5059:
5060: Memory blocks often represent character strings; For ways of storing
5061: character strings in memory see @ref{String Formats}. For other
5062: string-processing words see @ref{Displaying characters and strings}.
5063:
5064: A few of these words work on address unit blocks. In that case, you
5065: usually have to insert @code{CHARS} before the word when working on
5066: character strings. Most words work on character blocks, and expect a
5067: char-aligned address.
5068:
5069: When copying characters between overlapping memory regions, use
5070: @code{chars move} or choose carefully between @code{cmove} and
5071: @code{cmove>}.
5072:
5073: doc-move
5074: doc-erase
5075: doc-cmove
5076: doc-cmove>
5077: doc-fill
5078: doc-blank
5079: doc-compare
5080: doc-str=
5081: doc-str<
5082: doc-string-prefix?
5083: doc-search
5084: doc--trailing
5085: doc-/string
5086: doc-bounds
5087:
5088:
5089: @comment TODO examples
5090:
5091:
5092: @node Control Structures, Defining Words, Memory, Words
5093: @section Control Structures
5094: @cindex control structures
5095:
5096: Control structures in Forth cannot be used interpretively, only in a
5097: colon definition@footnote{To be precise, they have no interpretation
5098: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5099: not like this limitation, but have not seen a satisfying way around it
5100: yet, although many schemes have been proposed.
5101:
5102: @menu
5103: * Selection:: IF ... ELSE ... ENDIF
5104: * Simple Loops:: BEGIN ...
5105: * Counted Loops:: DO
5106: * Arbitrary control structures::
5107: * Calls and returns::
5108: * Exception Handling::
5109: @end menu
5110:
5111: @node Selection, Simple Loops, Control Structures, Control Structures
5112: @subsection Selection
5113: @cindex selection control structures
5114: @cindex control structures for selection
5115:
5116: @cindex @code{IF} control structure
5117: @example
5118: @i{flag}
5119: IF
5120: @i{code}
5121: ENDIF
5122: @end example
5123: @noindent
5124:
5125: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5126: with any bit set represents truth) @i{code} is executed.
5127:
5128: @example
5129: @i{flag}
5130: IF
5131: @i{code1}
5132: ELSE
5133: @i{code2}
5134: ENDIF
5135: @end example
5136:
5137: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5138: executed.
5139:
5140: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5141: standard, and @code{ENDIF} is not, although it is quite popular. We
5142: recommend using @code{ENDIF}, because it is less confusing for people
5143: who also know other languages (and is not prone to reinforcing negative
5144: prejudices against Forth in these people). Adding @code{ENDIF} to a
5145: system that only supplies @code{THEN} is simple:
5146: @example
5147: : ENDIF POSTPONE then ; immediate
5148: @end example
5149:
5150: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5151: (adv.)} has the following meanings:
5152: @quotation
5153: ... 2b: following next after in order ... 3d: as a necessary consequence
5154: (if you were there, then you saw them).
5155: @end quotation
5156: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5157: and many other programming languages has the meaning 3d.]
5158:
5159: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
5160: you can avoid using @code{?dup}. Using these alternatives is also more
5161: efficient than using @code{?dup}. Definitions in ANS Forth
5162: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5163: @file{compat/control.fs}.
5164:
5165: @cindex @code{CASE} control structure
5166: @example
5167: @i{n}
5168: CASE
5169: @i{n1} OF @i{code1} ENDOF
5170: @i{n2} OF @i{code2} ENDOF
5171: @dots{}
5172: ( n ) @i{default-code} ( n )
5173: ENDCASE
5174: @end example
5175:
5176: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If no
5177: @i{ni} matches, the optional @i{default-code} is executed. The optional
5178: default case can be added by simply writing the code after the last
5179: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
5180: not consume it.
5181:
5182: @progstyle
5183: To keep the code understandable, you should ensure that on all paths
5184: through a selection construct the stack is changed in the same way
5185: (wrt. number and types of stack items consumed and pushed).
5186:
5187: @node Simple Loops, Counted Loops, Selection, Control Structures
5188: @subsection Simple Loops
5189: @cindex simple loops
5190: @cindex loops without count
5191:
5192: @cindex @code{WHILE} loop
5193: @example
5194: BEGIN
5195: @i{code1}
5196: @i{flag}
5197: WHILE
5198: @i{code2}
5199: REPEAT
5200: @end example
5201:
5202: @i{code1} is executed and @i{flag} is computed. If it is true,
5203: @i{code2} is executed and the loop is restarted; If @i{flag} is
5204: false, execution continues after the @code{REPEAT}.
5205:
5206: @cindex @code{UNTIL} loop
5207: @example
5208: BEGIN
5209: @i{code}
5210: @i{flag}
5211: UNTIL
5212: @end example
5213:
5214: @i{code} is executed. The loop is restarted if @code{flag} is false.
5215:
5216: @progstyle
5217: To keep the code understandable, a complete iteration of the loop should
5218: not change the number and types of the items on the stacks.
5219:
5220: @cindex endless loop
5221: @cindex loops, endless
5222: @example
5223: BEGIN
5224: @i{code}
5225: AGAIN
5226: @end example
5227:
5228: This is an endless loop.
5229:
5230: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5231: @subsection Counted Loops
5232: @cindex counted loops
5233: @cindex loops, counted
5234: @cindex @code{DO} loops
5235:
5236: The basic counted loop is:
5237: @example
5238: @i{limit} @i{start}
5239: ?DO
5240: @i{body}
5241: LOOP
5242: @end example
5243:
5244: This performs one iteration for every integer, starting from @i{start}
5245: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
5246: accessed with @code{i}. For example, the loop:
5247: @example
5248: 10 0 ?DO
5249: i .
5250: LOOP
5251: @end example
5252: @noindent
5253: prints @code{0 1 2 3 4 5 6 7 8 9}
5254:
5255: The index of the innermost loop can be accessed with @code{i}, the index
5256: of the next loop with @code{j}, and the index of the third loop with
5257: @code{k}.
5258:
5259:
5260: doc-i
5261: doc-j
5262: doc-k
5263:
5264:
5265: The loop control data are kept on the return stack, so there are some
5266: restrictions on mixing return stack accesses and counted loop words. In
5267: particuler, if you put values on the return stack outside the loop, you
5268: cannot read them inside the loop@footnote{well, not in a way that is
5269: portable.}. If you put values on the return stack within a loop, you
5270: have to remove them before the end of the loop and before accessing the
5271: index of the loop.
5272:
5273: There are several variations on the counted loop:
5274:
5275: @itemize @bullet
5276: @item
5277: @code{LEAVE} leaves the innermost counted loop immediately; execution
5278: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5279:
5280: @example
5281: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5282: @end example
5283: prints @code{0 1 2 3}
5284:
5285:
5286: @item
5287: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5288: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5289: return stack so @code{EXIT} can get to its return address. For example:
5290:
5291: @example
5292: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5293: @end example
5294: prints @code{0 1 2 3}
5295:
5296:
5297: @item
5298: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
5299: (and @code{LOOP} iterates until they become equal by wrap-around
5300: arithmetic). This behaviour is usually not what you want. Therefore,
5301: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
5302: @code{?DO}), which do not enter the loop if @i{start} is greater than
5303: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
5304: unsigned loop parameters.
5305:
5306: @item
5307: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5308: the loop, independent of the loop parameters. Do not use @code{DO}, even
5309: if you know that the loop is entered in any case. Such knowledge tends
5310: to become invalid during maintenance of a program, and then the
5311: @code{DO} will make trouble.
5312:
5313: @item
5314: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5315: index by @i{n} instead of by 1. The loop is terminated when the border
5316: between @i{limit-1} and @i{limit} is crossed. E.g.:
5317:
5318: @example
5319: 4 0 +DO i . 2 +LOOP
5320: @end example
5321: @noindent
5322: prints @code{0 2}
5323:
5324: @example
5325: 4 1 +DO i . 2 +LOOP
5326: @end example
5327: @noindent
5328: prints @code{1 3}
5329:
5330: @item
5331: @cindex negative increment for counted loops
5332: @cindex counted loops with negative increment
5333: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
5334:
5335: @example
5336: -1 0 ?DO i . -1 +LOOP
5337: @end example
5338: @noindent
5339: prints @code{0 -1}
5340:
5341: @example
5342: 0 0 ?DO i . -1 +LOOP
5343: @end example
5344: prints nothing.
5345:
5346: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5347: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5348: index by @i{u} each iteration. The loop is terminated when the border
5349: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
5350: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5351:
5352: @example
5353: -2 0 -DO i . 1 -LOOP
5354: @end example
5355: @noindent
5356: prints @code{0 -1}
5357:
5358: @example
5359: -1 0 -DO i . 1 -LOOP
5360: @end example
5361: @noindent
5362: prints @code{0}
5363:
5364: @example
5365: 0 0 -DO i . 1 -LOOP
5366: @end example
5367: @noindent
5368: prints nothing.
5369:
5370: @end itemize
5371:
5372: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
5373: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5374: for these words that uses only standard words is provided in
5375: @file{compat/loops.fs}.
5376:
5377:
5378: @cindex @code{FOR} loops
5379: Another counted loop is:
5380: @example
5381: @i{n}
5382: FOR
5383: @i{body}
5384: NEXT
5385: @end example
5386: This is the preferred loop of native code compiler writers who are too
5387: lazy to optimize @code{?DO} loops properly. This loop structure is not
5388: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5389: @code{i} produces values starting with @i{n} and ending with 0. Other
5390: Forth systems may behave differently, even if they support @code{FOR}
5391: loops. To avoid problems, don't use @code{FOR} loops.
5392:
5393: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5394: @subsection Arbitrary control structures
5395: @cindex control structures, user-defined
5396:
5397: @cindex control-flow stack
5398: ANS Forth permits and supports using control structures in a non-nested
5399: way. Information about incomplete control structures is stored on the
5400: control-flow stack. This stack may be implemented on the Forth data
5401: stack, and this is what we have done in Gforth.
5402:
5403: @cindex @code{orig}, control-flow stack item
5404: @cindex @code{dest}, control-flow stack item
5405: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5406: entry represents a backward branch target. A few words are the basis for
5407: building any control structure possible (except control structures that
5408: need storage, like calls, coroutines, and backtracking).
5409:
5410:
5411: doc-if
5412: doc-ahead
5413: doc-then
5414: doc-begin
5415: doc-until
5416: doc-again
5417: doc-cs-pick
5418: doc-cs-roll
5419:
5420:
5421: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5422: manipulate the control-flow stack in a portable way. Without them, you
5423: would need to know how many stack items are occupied by a control-flow
5424: entry (many systems use one cell. In Gforth they currently take three,
5425: but this may change in the future).
5426:
5427: Some standard control structure words are built from these words:
5428:
5429:
5430: doc-else
5431: doc-while
5432: doc-repeat
5433:
5434:
5435: @noindent
5436: Gforth adds some more control-structure words:
5437:
5438:
5439: doc-endif
5440: doc-?dup-if
5441: doc-?dup-0=-if
5442:
5443:
5444: @noindent
5445: Counted loop words constitute a separate group of words:
5446:
5447:
5448: doc-?do
5449: doc-+do
5450: doc-u+do
5451: doc--do
5452: doc-u-do
5453: doc-do
5454: doc-for
5455: doc-loop
5456: doc-+loop
5457: doc--loop
5458: doc-next
5459: doc-leave
5460: doc-?leave
5461: doc-unloop
5462: doc-done
5463:
5464:
5465: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5466: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
5467: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5468: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5469: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5470: resolved (by using one of the loop-ending words or @code{DONE}).
5471:
5472: @noindent
5473: Another group of control structure words are:
5474:
5475:
5476: doc-case
5477: doc-endcase
5478: doc-of
5479: doc-endof
5480:
5481:
5482: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5483: @code{CS-ROLL}.
5484:
5485: @subsubsection Programming Style
5486: @cindex control structures programming style
5487: @cindex programming style, arbitrary control structures
5488:
5489: In order to ensure readability we recommend that you do not create
5490: arbitrary control structures directly, but define new control structure
5491: words for the control structure you want and use these words in your
5492: program. For example, instead of writing:
5493:
5494: @example
5495: BEGIN
5496: ...
5497: IF [ 1 CS-ROLL ]
5498: ...
5499: AGAIN THEN
5500: @end example
5501:
5502: @noindent
5503: we recommend defining control structure words, e.g.,
5504:
5505: @example
5506: : WHILE ( DEST -- ORIG DEST )
5507: POSTPONE IF
5508: 1 CS-ROLL ; immediate
5509:
5510: : REPEAT ( orig dest -- )
5511: POSTPONE AGAIN
5512: POSTPONE THEN ; immediate
5513: @end example
5514:
5515: @noindent
5516: and then using these to create the control structure:
5517:
5518: @example
5519: BEGIN
5520: ...
5521: WHILE
5522: ...
5523: REPEAT
5524: @end example
5525:
5526: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5527: @code{WHILE} are predefined, so in this example it would not be
5528: necessary to define them.
5529:
5530: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5531: @subsection Calls and returns
5532: @cindex calling a definition
5533: @cindex returning from a definition
5534:
5535: @cindex recursive definitions
5536: A definition can be called simply be writing the name of the definition
5537: to be called. Normally a definition is invisible during its own
5538: definition. If you want to write a directly recursive definition, you
5539: can use @code{recursive} to make the current definition visible, or
5540: @code{recurse} to call the current definition directly.
5541:
5542:
5543: doc-recursive
5544: doc-recurse
5545:
5546:
5547: @comment TODO add example of the two recursion methods
5548: @quotation
5549: @progstyle
5550: I prefer using @code{recursive} to @code{recurse}, because calling the
5551: definition by name is more descriptive (if the name is well-chosen) than
5552: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5553: implementation, it is much better to read (and think) ``now sort the
5554: partitions'' than to read ``now do a recursive call''.
5555: @end quotation
5556:
5557: For mutual recursion, use @code{Defer}red words, like this:
5558:
5559: @example
5560: Defer foo
5561:
5562: : bar ( ... -- ... )
5563: ... foo ... ;
5564:
5565: :noname ( ... -- ... )
5566: ... bar ... ;
5567: IS foo
5568: @end example
5569:
5570: Deferred words are discussed in more detail in @ref{Deferred words}.
5571:
5572: The current definition returns control to the calling definition when
5573: the end of the definition is reached or @code{EXIT} is encountered.
5574:
5575: doc-exit
5576: doc-;s
5577:
5578:
5579: @node Exception Handling, , Calls and returns, Control Structures
5580: @subsection Exception Handling
5581: @cindex exceptions
5582:
5583: @c quit is a very bad idea for error handling,
5584: @c because it does not translate into a THROW
5585: @c it also does not belong into this chapter
5586:
5587: If a word detects an error condition that it cannot handle, it can
5588: @code{throw} an exception. In the simplest case, this will terminate
5589: your program, and report an appropriate error.
5590:
5591: doc-throw
5592:
5593: @code{Throw} consumes a cell-sized error number on the stack. There are
5594: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5595: Gforth (and most other systems) you can use the iors produced by various
5596: words as error numbers (e.g., a typical use of @code{allocate} is
5597: @code{allocate throw}). Gforth also provides the word @code{exception}
5598: to define your own error numbers (with decent error reporting); an ANS
5599: Forth version of this word (but without the error messages) is available
5600: in @code{compat/except.fs}. And finally, you can use your own error
5601: numbers (anything outside the range -4095..0), but won't get nice error
5602: messages, only numbers. For example, try:
5603:
5604: @example
5605: -10 throw \ ANS defined
5606: -267 throw \ system defined
5607: s" my error" exception throw \ user defined
5608: 7 throw \ arbitrary number
5609: @end example
5610:
5611: doc---exception-exception
5612:
5613: A common idiom to @code{THROW} a specific error if a flag is true is
5614: this:
5615:
5616: @example
5617: @code{( flag ) 0<> @i{errno} and throw}
5618: @end example
5619:
5620: Your program can provide exception handlers to catch exceptions. An
5621: exception handler can be used to correct the problem, or to clean up
5622: some data structures and just throw the exception to the next exception
5623: handler. Note that @code{throw} jumps to the dynamically innermost
5624: exception handler. The system's exception handler is outermost, and just
5625: prints an error and restarts command-line interpretation (or, in batch
5626: mode (i.e., while processing the shell command line), leaves Gforth).
5627:
5628: The ANS Forth way to catch exceptions is @code{catch}:
5629:
5630: doc-catch
5631:
5632: The most common use of exception handlers is to clean up the state when
5633: an error happens. E.g.,
5634:
5635: @example
5636: base @ >r hex \ actually the hex should be inside foo, or we h
5637: ['] foo catch ( nerror|0 )
5638: r> base !
5639: ( nerror|0 ) throw \ pass it on
5640: @end example
5641:
5642: A use of @code{catch} for handling the error @code{myerror} might look
5643: like this:
5644:
5645: @example
5646: ['] foo catch
5647: CASE
5648: myerror OF ... ( do something about it ) ENDOF
5649: dup throw \ default: pass other errors on, do nothing on non-errors
5650: ENDCASE
5651: @end example
5652:
5653: Having to wrap the code into a separate word is often cumbersome,
5654: therefore Gforth provides an alternative syntax:
5655:
5656: @example
5657: TRY
5658: @i{code1}
5659: RECOVER \ optional
5660: @i{code2} \ optional
5661: ENDTRY
5662: @end example
5663:
5664: This performs @i{Code1}. If @i{code1} completes normally, execution
5665: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5666: reset to the state during @code{try}, the throw value is pushed on the
5667: data stack, and execution constinues at @i{code2}, and finally falls
5668: through the @code{endtry} into the following code.
5669:
5670: doc-try
5671: doc-recover
5672: doc-endtry
5673:
5674: The cleanup example from above in this syntax:
5675:
5676: @example
5677: base @ >r TRY
5678: hex foo \ now the hex is placed correctly
5679: 0 \ value for throw
5680: RECOVER ENDTRY
5681: r> base ! throw
5682: @end example
5683:
5684: And here's the error handling example:
5685:
5686: @example
5687: TRY
5688: foo
5689: RECOVER
5690: CASE
5691: myerror OF ... ( do something about it ) ENDOF
5692: throw \ pass other errors on
5693: ENDCASE
5694: ENDTRY
5695: @end example
5696:
5697: @progstyle
5698: As usual, you should ensure that the stack depth is statically known at
5699: the end: either after the @code{throw} for passing on errors, or after
5700: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5701: selection construct for handling the error).
5702:
5703: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5704: and you can provide an error message. @code{Abort} just produces an
5705: ``Aborted'' error.
5706:
5707: The problem with these words is that exception handlers cannot
5708: differentiate between different @code{abort"}s; they just look like
5709: @code{-2 throw} to them (the error message cannot be accessed by
5710: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5711: exception handlers.
5712:
5713: doc-abort"
5714: doc-abort
5715:
5716:
5717:
5718: @c -------------------------------------------------------------
5719: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
5720: @section Defining Words
5721: @cindex defining words
5722:
5723: Defining words are used to extend Forth by creating new entries in the dictionary.
5724:
5725: @menu
5726: * CREATE::
5727: * Variables:: Variables and user variables
5728: * Constants::
5729: * Values:: Initialised variables
5730: * Colon Definitions::
5731: * Anonymous Definitions:: Definitions without names
5732: * Supplying names:: Passing definition names as strings
5733: * User-defined Defining Words::
5734: * Deferred words:: Allow forward references
5735: * Aliases::
5736: @end menu
5737:
5738: @node CREATE, Variables, Defining Words, Defining Words
5739: @subsection @code{CREATE}
5740: @cindex simple defining words
5741: @cindex defining words, simple
5742:
5743: Defining words are used to create new entries in the dictionary. The
5744: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5745: this:
5746:
5747: @example
5748: CREATE new-word1
5749: @end example
5750:
5751: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5752: input stream (@code{new-word1} in our example). It generates a
5753: dictionary entry for @code{new-word1}. When @code{new-word1} is
5754: executed, all that it does is leave an address on the stack. The address
5755: represents the value of the data space pointer (@code{HERE}) at the time
5756: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5757: associating a name with the address of a region of memory.
5758:
5759: doc-create
5760:
5761: Note that in ANS Forth guarantees only for @code{create} that its body
5762: is in dictionary data space (i.e., where @code{here}, @code{allot}
5763: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5764: @code{create}d words can be modified with @code{does>}
5765: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5766: can only be applied to @code{create}d words.
5767:
5768: By extending this example to reserve some memory in data space, we end
5769: up with something like a @i{variable}. Here are two different ways to do
5770: it:
5771:
5772: @example
5773: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5774: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5775: @end example
5776:
5777: The variable can be examined and modified using @code{@@} (``fetch'') and
5778: @code{!} (``store'') like this:
5779:
5780: @example
5781: new-word2 @@ . \ get address, fetch from it and display
5782: 1234 new-word2 ! \ new value, get address, store to it
5783: @end example
5784:
5785: @cindex arrays
5786: A similar mechanism can be used to create arrays. For example, an
5787: 80-character text input buffer:
5788:
5789: @example
5790: CREATE text-buf 80 chars allot
5791:
5792: text-buf 0 chars c@@ \ the 1st character (offset 0)
5793: text-buf 3 chars c@@ \ the 4th character (offset 3)
5794: @end example
5795:
5796: You can build arbitrarily complex data structures by allocating
5797: appropriate areas of memory. For further discussions of this, and to
5798: learn about some Gforth tools that make it easier,
5799: @xref{Structures}.
5800:
5801:
5802: @node Variables, Constants, CREATE, Defining Words
5803: @subsection Variables
5804: @cindex variables
5805:
5806: The previous section showed how a sequence of commands could be used to
5807: generate a variable. As a final refinement, the whole code sequence can
5808: be wrapped up in a defining word (pre-empting the subject of the next
5809: section), making it easier to create new variables:
5810:
5811: @example
5812: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5813: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5814:
5815: myvariableX foo \ variable foo starts off with an unknown value
5816: myvariable0 joe \ whilst joe is initialised to 0
5817:
5818: 45 3 * foo ! \ set foo to 135
5819: 1234 joe ! \ set joe to 1234
5820: 3 joe +! \ increment joe by 3.. to 1237
5821: @end example
5822:
5823: Not surprisingly, there is no need to define @code{myvariable}, since
5824: Forth already has a definition @code{Variable}. ANS Forth does not
5825: guarantee that a @code{Variable} is initialised when it is created
5826: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5827: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5828: like @code{myvariable0}). Forth also provides @code{2Variable} and
5829: @code{fvariable} for double and floating-point variables, respectively
5830: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
5831: store a boolean, you can use @code{on} and @code{off} to toggle its
5832: state.
5833:
5834: doc-variable
5835: doc-2variable
5836: doc-fvariable
5837:
5838: @cindex user variables
5839: @cindex user space
5840: The defining word @code{User} behaves in the same way as @code{Variable}.
5841: The difference is that it reserves space in @i{user (data) space} rather
5842: than normal data space. In a Forth system that has a multi-tasker, each
5843: task has its own set of user variables.
5844:
5845: doc-user
5846: @c doc-udp
5847: @c doc-uallot
5848:
5849: @comment TODO is that stuff about user variables strictly correct? Is it
5850: @comment just terminal tasks that have user variables?
5851: @comment should document tasker.fs (with some examples) elsewhere
5852: @comment in this manual, then expand on user space and user variables.
5853:
5854: @node Constants, Values, Variables, Defining Words
5855: @subsection Constants
5856: @cindex constants
5857:
5858: @code{Constant} allows you to declare a fixed value and refer to it by
5859: name. For example:
5860:
5861: @example
5862: 12 Constant INCHES-PER-FOOT
5863: 3E+08 fconstant SPEED-O-LIGHT
5864: @end example
5865:
5866: A @code{Variable} can be both read and written, so its run-time
5867: behaviour is to supply an address through which its current value can be
5868: manipulated. In contrast, the value of a @code{Constant} cannot be
5869: changed once it has been declared@footnote{Well, often it can be -- but
5870: not in a Standard, portable way. It's safer to use a @code{Value} (read
5871: on).} so it's not necessary to supply the address -- it is more
5872: efficient to return the value of the constant directly. That's exactly
5873: what happens; the run-time effect of a constant is to put its value on
5874: the top of the stack (You can find one
5875: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
5876:
5877: Forth also provides @code{2Constant} and @code{fconstant} for defining
5878: double and floating-point constants, respectively.
5879:
5880: doc-constant
5881: doc-2constant
5882: doc-fconstant
5883:
5884: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
5885: @c nac-> How could that not be true in an ANS Forth? You can't define a
5886: @c constant, use it and then delete the definition of the constant..
5887:
5888: @c anton->An ANS Forth system can compile a constant to a literal; On
5889: @c decompilation you would see only the number, just as if it had been used
5890: @c in the first place. The word will stay, of course, but it will only be
5891: @c used by the text interpreter (no run-time duties, except when it is
5892: @c POSTPONEd or somesuch).
5893:
5894: @c nac:
5895: @c I agree that it's rather deep, but IMO it is an important difference
5896: @c relative to other programming languages.. often it's annoying: it
5897: @c certainly changes my programming style relative to C.
5898:
5899: @c anton: In what way?
5900:
5901: Constants in Forth behave differently from their equivalents in other
5902: programming languages. In other languages, a constant (such as an EQU in
5903: assembler or a #define in C) only exists at compile-time; in the
5904: executable program the constant has been translated into an absolute
5905: number and, unless you are using a symbolic debugger, it's impossible to
5906: know what abstract thing that number represents. In Forth a constant has
5907: an entry in the header space and remains there after the code that uses
5908: it has been defined. In fact, it must remain in the dictionary since it
5909: has run-time duties to perform. For example:
5910:
5911: @example
5912: 12 Constant INCHES-PER-FOOT
5913: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
5914: @end example
5915:
5916: @cindex in-lining of constants
5917: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
5918: associated with the constant @code{INCHES-PER-FOOT}. If you use
5919: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
5920: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
5921: attempt to optimise constants by in-lining them where they are used. You
5922: can force Gforth to in-line a constant like this:
5923:
5924: @example
5925: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
5926: @end example
5927:
5928: If you use @code{see} to decompile @i{this} version of
5929: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
5930: longer present. To understand how this works, read
5931: @ref{Interpret/Compile states}, and @ref{Literals}.
5932:
5933: In-lining constants in this way might improve execution time
5934: fractionally, and can ensure that a constant is now only referenced at
5935: compile-time. However, the definition of the constant still remains in
5936: the dictionary. Some Forth compilers provide a mechanism for controlling
5937: a second dictionary for holding transient words such that this second
5938: dictionary can be deleted later in order to recover memory
5939: space. However, there is no standard way of doing this.
5940:
5941:
5942: @node Values, Colon Definitions, Constants, Defining Words
5943: @subsection Values
5944: @cindex values
5945:
5946: A @code{Value} behaves like a @code{Constant}, but it can be changed.
5947: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
5948: (not in ANS Forth) you can access (and change) a @code{value} also with
5949: @code{>body}.
5950:
5951: Here are some
5952: examples:
5953:
5954: @example
5955: 12 Value APPLES \ Define APPLES with an initial value of 12
5956: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
5957: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
5958: APPLES \ puts 35 on the top of the stack.
5959: @end example
5960:
5961: doc-value
5962: doc-to
5963:
5964:
5965:
5966: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
5967: @subsection Colon Definitions
5968: @cindex colon definitions
5969:
5970: @example
5971: : name ( ... -- ... )
5972: word1 word2 word3 ;
5973: @end example
5974:
5975: @noindent
5976: Creates a word called @code{name} that, upon execution, executes
5977: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
5978:
5979: The explanation above is somewhat superficial. For simple examples of
5980: colon definitions see @ref{Your first definition}. For an in-depth
5981: discussion of some of the issues involved, @xref{Interpretation and
5982: Compilation Semantics}.
5983:
5984: doc-:
5985: doc-;
5986:
5987:
5988: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
5989: @subsection Anonymous Definitions
5990: @cindex colon definitions
5991: @cindex defining words without name
5992:
5993: Sometimes you want to define an @dfn{anonymous word}; a word without a
5994: name. You can do this with:
5995:
5996: doc-:noname
5997:
5998: This leaves the execution token for the word on the stack after the
5999: closing @code{;}. Here's an example in which a deferred word is
6000: initialised with an @code{xt} from an anonymous colon definition:
6001:
6002: @example
6003: Defer deferred
6004: :noname ( ... -- ... )
6005: ... ;
6006: IS deferred
6007: @end example
6008:
6009: @noindent
6010: Gforth provides an alternative way of doing this, using two separate
6011: words:
6012:
6013: doc-noname
6014: @cindex execution token of last defined word
6015: doc-latestxt
6016:
6017: @noindent
6018: The previous example can be rewritten using @code{noname} and
6019: @code{latestxt}:
6020:
6021: @example
6022: Defer deferred
6023: noname : ( ... -- ... )
6024: ... ;
6025: latestxt IS deferred
6026: @end example
6027:
6028: @noindent
6029: @code{noname} works with any defining word, not just @code{:}.
6030:
6031: @code{latestxt} also works when the last word was not defined as
6032: @code{noname}. It does not work for combined words, though. It also has
6033: the useful property that is is valid as soon as the header for a
6034: definition has been built. Thus:
6035:
6036: @example
6037: latestxt . : foo [ latestxt . ] ; ' foo .
6038: @end example
6039:
6040: @noindent
6041: prints 3 numbers; the last two are the same.
6042:
6043: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6044: @subsection Supplying the name of a defined word
6045: @cindex names for defined words
6046: @cindex defining words, name given in a string
6047:
6048: By default, a defining word takes the name for the defined word from the
6049: input stream. Sometimes you want to supply the name from a string. You
6050: can do this with:
6051:
6052: doc-nextname
6053:
6054: For example:
6055:
6056: @example
6057: s" foo" nextname create
6058: @end example
6059:
6060: @noindent
6061: is equivalent to:
6062:
6063: @example
6064: create foo
6065: @end example
6066:
6067: @noindent
6068: @code{nextname} works with any defining word.
6069:
6070:
6071: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
6072: @subsection User-defined Defining Words
6073: @cindex user-defined defining words
6074: @cindex defining words, user-defined
6075:
6076: You can create a new defining word by wrapping defining-time code around
6077: an existing defining word and putting the sequence in a colon
6078: definition.
6079:
6080: @c anton: This example is very complex and leads in a quite different
6081: @c direction from the CREATE-DOES> stuff that follows. It should probably
6082: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6083: @c subsection of Defining Words)
6084:
6085: For example, suppose that you have a word @code{stats} that
6086: gathers statistics about colon definitions given the @i{xt} of the
6087: definition, and you want every colon definition in your application to
6088: make a call to @code{stats}. You can define and use a new version of
6089: @code{:} like this:
6090:
6091: @example
6092: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6093: ... ; \ other code
6094:
6095: : my: : latestxt postpone literal ['] stats compile, ;
6096:
6097: my: foo + - ;
6098: @end example
6099:
6100: When @code{foo} is defined using @code{my:} these steps occur:
6101:
6102: @itemize @bullet
6103: @item
6104: @code{my:} is executed.
6105: @item
6106: The @code{:} within the definition (the one between @code{my:} and
6107: @code{latestxt}) is executed, and does just what it always does; it parses
6108: the input stream for a name, builds a dictionary header for the name
6109: @code{foo} and switches @code{state} from interpret to compile.
6110: @item
6111: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
6112: being defined -- @code{foo} -- onto the stack.
6113: @item
6114: The code that was produced by @code{postpone literal} is executed; this
6115: causes the value on the stack to be compiled as a literal in the code
6116: area of @code{foo}.
6117: @item
6118: The code @code{['] stats} compiles a literal into the definition of
6119: @code{my:}. When @code{compile,} is executed, that literal -- the
6120: execution token for @code{stats} -- is layed down in the code area of
6121: @code{foo} , following the literal@footnote{Strictly speaking, the
6122: mechanism that @code{compile,} uses to convert an @i{xt} into something
6123: in the code area is implementation-dependent. A threaded implementation
6124: might spit out the execution token directly whilst another
6125: implementation might spit out a native code sequence.}.
6126: @item
6127: At this point, the execution of @code{my:} is complete, and control
6128: returns to the text interpreter. The text interpreter is in compile
6129: state, so subsequent text @code{+ -} is compiled into the definition of
6130: @code{foo} and the @code{;} terminates the definition as always.
6131: @end itemize
6132:
6133: You can use @code{see} to decompile a word that was defined using
6134: @code{my:} and see how it is different from a normal @code{:}
6135: definition. For example:
6136:
6137: @example
6138: : bar + - ; \ like foo but using : rather than my:
6139: see bar
6140: : bar
6141: + - ;
6142: see foo
6143: : foo
6144: 107645672 stats + - ;
6145:
6146: \ use ' stats . to show that 107645672 is the xt for stats
6147: @end example
6148:
6149: You can use techniques like this to make new defining words in terms of
6150: @i{any} existing defining word.
6151:
6152:
6153: @cindex defining defining words
6154: @cindex @code{CREATE} ... @code{DOES>}
6155: If you want the words defined with your defining words to behave
6156: differently from words defined with standard defining words, you can
6157: write your defining word like this:
6158:
6159: @example
6160: : def-word ( "name" -- )
6161: CREATE @i{code1}
6162: DOES> ( ... -- ... )
6163: @i{code2} ;
6164:
6165: def-word name
6166: @end example
6167:
6168: @cindex child words
6169: This fragment defines a @dfn{defining word} @code{def-word} and then
6170: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6171: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6172: is not executed at this time. The word @code{name} is sometimes called a
6173: @dfn{child} of @code{def-word}.
6174:
6175: When you execute @code{name}, the address of the body of @code{name} is
6176: put on the data stack and @i{code2} is executed (the address of the body
6177: of @code{name} is the address @code{HERE} returns immediately after the
6178: @code{CREATE}, i.e., the address a @code{create}d word returns by
6179: default).
6180:
6181: @c anton:
6182: @c www.dictionary.com says:
6183: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6184: @c several generations of absence, usually caused by the chance
6185: @c recombination of genes. 2.An individual or a part that exhibits
6186: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6187: @c of previous behavior after a period of absence.
6188: @c
6189: @c Doesn't seem to fit.
6190:
6191: @c @cindex atavism in child words
6192: You can use @code{def-word} to define a set of child words that behave
6193: similarly; they all have a common run-time behaviour determined by
6194: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6195: body of the child word. The structure of the data is common to all
6196: children of @code{def-word}, but the data values are specific -- and
6197: private -- to each child word. When a child word is executed, the
6198: address of its private data area is passed as a parameter on TOS to be
6199: used and manipulated@footnote{It is legitimate both to read and write to
6200: this data area.} by @i{code2}.
6201:
6202: The two fragments of code that make up the defining words act (are
6203: executed) at two completely separate times:
6204:
6205: @itemize @bullet
6206: @item
6207: At @i{define time}, the defining word executes @i{code1} to generate a
6208: child word
6209: @item
6210: At @i{child execution time}, when a child word is invoked, @i{code2}
6211: is executed, using parameters (data) that are private and specific to
6212: the child word.
6213: @end itemize
6214:
6215: Another way of understanding the behaviour of @code{def-word} and
6216: @code{name} is to say that, if you make the following definitions:
6217: @example
6218: : def-word1 ( "name" -- )
6219: CREATE @i{code1} ;
6220:
6221: : action1 ( ... -- ... )
6222: @i{code2} ;
6223:
6224: def-word1 name1
6225: @end example
6226:
6227: @noindent
6228: Then using @code{name1 action1} is equivalent to using @code{name}.
6229:
6230: The classic example is that you can define @code{CONSTANT} in this way:
6231:
6232: @example
6233: : CONSTANT ( w "name" -- )
6234: CREATE ,
6235: DOES> ( -- w )
6236: @@ ;
6237: @end example
6238:
6239: @comment There is a beautiful description of how this works and what
6240: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6241: @comment commentary on the Counting Fruits problem.
6242:
6243: When you create a constant with @code{5 CONSTANT five}, a set of
6244: define-time actions take place; first a new word @code{five} is created,
6245: then the value 5 is laid down in the body of @code{five} with
6246: @code{,}. When @code{five} is executed, the address of the body is put on
6247: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6248: no code of its own; it simply contains a data field and a pointer to the
6249: code that follows @code{DOES>} in its defining word. That makes words
6250: created in this way very compact.
6251:
6252: The final example in this section is intended to remind you that space
6253: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6254: both read and written by a Standard program@footnote{Exercise: use this
6255: example as a starting point for your own implementation of @code{Value}
6256: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6257: @code{[']}.}:
6258:
6259: @example
6260: : foo ( "name" -- )
6261: CREATE -1 ,
6262: DOES> ( -- )
6263: @@ . ;
6264:
6265: foo first-word
6266: foo second-word
6267:
6268: 123 ' first-word >BODY !
6269: @end example
6270:
6271: If @code{first-word} had been a @code{CREATE}d word, we could simply
6272: have executed it to get the address of its data field. However, since it
6273: was defined to have @code{DOES>} actions, its execution semantics are to
6274: perform those @code{DOES>} actions. To get the address of its data field
6275: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6276: translate the xt into the address of the data field. When you execute
6277: @code{first-word}, it will display @code{123}. When you execute
6278: @code{second-word} it will display @code{-1}.
6279:
6280: @cindex stack effect of @code{DOES>}-parts
6281: @cindex @code{DOES>}-parts, stack effect
6282: In the examples above the stack comment after the @code{DOES>} specifies
6283: the stack effect of the defined words, not the stack effect of the
6284: following code (the following code expects the address of the body on
6285: the top of stack, which is not reflected in the stack comment). This is
6286: the convention that I use and recommend (it clashes a bit with using
6287: locals declarations for stack effect specification, though).
6288:
6289: @menu
6290: * CREATE..DOES> applications::
6291: * CREATE..DOES> details::
6292: * Advanced does> usage example::
6293: * @code{Const-does>}::
6294: @end menu
6295:
6296: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
6297: @subsubsection Applications of @code{CREATE..DOES>}
6298: @cindex @code{CREATE} ... @code{DOES>}, applications
6299:
6300: You may wonder how to use this feature. Here are some usage patterns:
6301:
6302: @cindex factoring similar colon definitions
6303: When you see a sequence of code occurring several times, and you can
6304: identify a meaning, you will factor it out as a colon definition. When
6305: you see similar colon definitions, you can factor them using
6306: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6307: that look very similar:
6308: @example
6309: : ori, ( reg-target reg-source n -- )
6310: 0 asm-reg-reg-imm ;
6311: : andi, ( reg-target reg-source n -- )
6312: 1 asm-reg-reg-imm ;
6313: @end example
6314:
6315: @noindent
6316: This could be factored with:
6317: @example
6318: : reg-reg-imm ( op-code -- )
6319: CREATE ,
6320: DOES> ( reg-target reg-source n -- )
6321: @@ asm-reg-reg-imm ;
6322:
6323: 0 reg-reg-imm ori,
6324: 1 reg-reg-imm andi,
6325: @end example
6326:
6327: @cindex currying
6328: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6329: supply a part of the parameters for a word (known as @dfn{currying} in
6330: the functional language community). E.g., @code{+} needs two
6331: parameters. Creating versions of @code{+} with one parameter fixed can
6332: be done like this:
6333:
6334: @example
6335: : curry+ ( n1 "name" -- )
6336: CREATE ,
6337: DOES> ( n2 -- n1+n2 )
6338: @@ + ;
6339:
6340: 3 curry+ 3+
6341: -2 curry+ 2-
6342: @end example
6343:
6344:
6345: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
6346: @subsubsection The gory details of @code{CREATE..DOES>}
6347: @cindex @code{CREATE} ... @code{DOES>}, details
6348:
6349: doc-does>
6350:
6351: @cindex @code{DOES>} in a separate definition
6352: This means that you need not use @code{CREATE} and @code{DOES>} in the
6353: same definition; you can put the @code{DOES>}-part in a separate
6354: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
6355: @example
6356: : does1
6357: DOES> ( ... -- ... )
6358: ... ;
6359:
6360: : does2
6361: DOES> ( ... -- ... )
6362: ... ;
6363:
6364: : def-word ( ... -- ... )
6365: create ...
6366: IF
6367: does1
6368: ELSE
6369: does2
6370: ENDIF ;
6371: @end example
6372:
6373: In this example, the selection of whether to use @code{does1} or
6374: @code{does2} is made at definition-time; at the time that the child word is
6375: @code{CREATE}d.
6376:
6377: @cindex @code{DOES>} in interpretation state
6378: In a standard program you can apply a @code{DOES>}-part only if the last
6379: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6380: will override the behaviour of the last word defined in any case. In a
6381: standard program, you can use @code{DOES>} only in a colon
6382: definition. In Gforth, you can also use it in interpretation state, in a
6383: kind of one-shot mode; for example:
6384: @example
6385: CREATE name ( ... -- ... )
6386: @i{initialization}
6387: DOES>
6388: @i{code} ;
6389: @end example
6390:
6391: @noindent
6392: is equivalent to the standard:
6393: @example
6394: :noname
6395: DOES>
6396: @i{code} ;
6397: CREATE name EXECUTE ( ... -- ... )
6398: @i{initialization}
6399: @end example
6400:
6401: doc->body
6402:
6403: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
6404: @subsubsection Advanced does> usage example
6405:
6406: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6407: for disassembling instructions, that follow a very repetetive scheme:
6408:
6409: @example
6410: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6411: @var{entry-num} cells @var{table} + !
6412: @end example
6413:
6414: Of course, this inspires the idea to factor out the commonalities to
6415: allow a definition like
6416:
6417: @example
6418: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6419: @end example
6420:
6421: The parameters @var{disasm-operands} and @var{table} are usually
6422: correlated. Moreover, before I wrote the disassembler, there already
6423: existed code that defines instructions like this:
6424:
6425: @example
6426: @var{entry-num} @var{inst-format} @var{inst-name}
6427: @end example
6428:
6429: This code comes from the assembler and resides in
6430: @file{arch/mips/insts.fs}.
6431:
6432: So I had to define the @var{inst-format} words that performed the scheme
6433: above when executed. At first I chose to use run-time code-generation:
6434:
6435: @example
6436: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6437: :noname Postpone @var{disasm-operands}
6438: name Postpone sliteral Postpone type Postpone ;
6439: swap cells @var{table} + ! ;
6440: @end example
6441:
6442: Note that this supplies the other two parameters of the scheme above.
6443:
6444: An alternative would have been to write this using
6445: @code{create}/@code{does>}:
6446:
6447: @example
6448: : @var{inst-format} ( entry-num "name" -- )
6449: here name string, ( entry-num c-addr ) \ parse and save "name"
6450: noname create , ( entry-num )
6451: latestxt swap cells @var{table} + !
6452: does> ( addr w -- )
6453: \ disassemble instruction w at addr
6454: @@ >r
6455: @var{disasm-operands}
6456: r> count type ;
6457: @end example
6458:
6459: Somehow the first solution is simpler, mainly because it's simpler to
6460: shift a string from definition-time to use-time with @code{sliteral}
6461: than with @code{string,} and friends.
6462:
6463: I wrote a lot of words following this scheme and soon thought about
6464: factoring out the commonalities among them. Note that this uses a
6465: two-level defining word, i.e., a word that defines ordinary defining
6466: words.
6467:
6468: This time a solution involving @code{postpone} and friends seemed more
6469: difficult (try it as an exercise), so I decided to use a
6470: @code{create}/@code{does>} word; since I was already at it, I also used
6471: @code{create}/@code{does>} for the lower level (try using
6472: @code{postpone} etc. as an exercise), resulting in the following
6473: definition:
6474:
6475: @example
6476: : define-format ( disasm-xt table-xt -- )
6477: \ define an instruction format that uses disasm-xt for
6478: \ disassembling and enters the defined instructions into table
6479: \ table-xt
6480: create 2,
6481: does> ( u "inst" -- )
6482: \ defines an anonymous word for disassembling instruction inst,
6483: \ and enters it as u-th entry into table-xt
6484: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6485: noname create 2, \ define anonymous word
6486: execute latestxt swap ! \ enter xt of defined word into table-xt
6487: does> ( addr w -- )
6488: \ disassemble instruction w at addr
6489: 2@@ >r ( addr w disasm-xt R: c-addr )
6490: execute ( R: c-addr ) \ disassemble operands
6491: r> count type ; \ print name
6492: @end example
6493:
6494: Note that the tables here (in contrast to above) do the @code{cells +}
6495: by themselves (that's why you have to pass an xt). This word is used in
6496: the following way:
6497:
6498: @example
6499: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6500: @end example
6501:
6502: As shown above, the defined instruction format is then used like this:
6503:
6504: @example
6505: @var{entry-num} @var{inst-format} @var{inst-name}
6506: @end example
6507:
6508: In terms of currying, this kind of two-level defining word provides the
6509: parameters in three stages: first @var{disasm-operands} and @var{table},
6510: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6511: the instruction to be disassembled.
6512:
6513: Of course this did not quite fit all the instruction format names used
6514: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6515: the parameters into the right form.
6516:
6517: If you have trouble following this section, don't worry. First, this is
6518: involved and takes time (and probably some playing around) to
6519: understand; second, this is the first two-level
6520: @code{create}/@code{does>} word I have written in seventeen years of
6521: Forth; and if I did not have @file{insts.fs} to start with, I may well
6522: have elected to use just a one-level defining word (with some repeating
6523: of parameters when using the defining word). So it is not necessary to
6524: understand this, but it may improve your understanding of Forth.
6525:
6526:
6527: @node @code{Const-does>}, , Advanced does> usage example, User-defined Defining Words
6528: @subsubsection @code{Const-does>}
6529:
6530: A frequent use of @code{create}...@code{does>} is for transferring some
6531: values from definition-time to run-time. Gforth supports this use with
6532:
6533: doc-const-does>
6534:
6535: A typical use of this word is:
6536:
6537: @example
6538: : curry+ ( n1 "name" -- )
6539: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6540: + ;
6541:
6542: 3 curry+ 3+
6543: @end example
6544:
6545: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6546: definition to run-time.
6547:
6548: The advantages of using @code{const-does>} are:
6549:
6550: @itemize
6551:
6552: @item
6553: You don't have to deal with storing and retrieving the values, i.e.,
6554: your program becomes more writable and readable.
6555:
6556: @item
6557: When using @code{does>}, you have to introduce a @code{@@} that cannot
6558: be optimized away (because you could change the data using
6559: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6560:
6561: @end itemize
6562:
6563: An ANS Forth implementation of @code{const-does>} is available in
6564: @file{compat/const-does.fs}.
6565:
6566:
6567: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6568: @subsection Deferred words
6569: @cindex deferred words
6570:
6571: The defining word @code{Defer} allows you to define a word by name
6572: without defining its behaviour; the definition of its behaviour is
6573: deferred. Here are two situation where this can be useful:
6574:
6575: @itemize @bullet
6576: @item
6577: Where you want to allow the behaviour of a word to be altered later, and
6578: for all precompiled references to the word to change when its behaviour
6579: is changed.
6580: @item
6581: For mutual recursion; @xref{Calls and returns}.
6582: @end itemize
6583:
6584: In the following example, @code{foo} always invokes the version of
6585: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6586: always invokes the version that prints ``@code{Hello}''. There is no way
6587: of getting @code{foo} to use the later version without re-ordering the
6588: source code and recompiling it.
6589:
6590: @example
6591: : greet ." Good morning" ;
6592: : foo ... greet ... ;
6593: : greet ." Hello" ;
6594: : bar ... greet ... ;
6595: @end example
6596:
6597: This problem can be solved by defining @code{greet} as a @code{Defer}red
6598: word. The behaviour of a @code{Defer}red word can be defined and
6599: redefined at any time by using @code{IS} to associate the xt of a
6600: previously-defined word with it. The previous example becomes:
6601:
6602: @example
6603: Defer greet ( -- )
6604: : foo ... greet ... ;
6605: : bar ... greet ... ;
6606: : greet1 ( -- ) ." Good morning" ;
6607: : greet2 ( -- ) ." Hello" ;
6608: ' greet2 <IS> greet \ make greet behave like greet2
6609: @end example
6610:
6611: @progstyle
6612: You should write a stack comment for every deferred word, and put only
6613: XTs into deferred words that conform to this stack effect. Otherwise
6614: it's too difficult to use the deferred word.
6615:
6616: A deferred word can be used to improve the statistics-gathering example
6617: from @ref{User-defined Defining Words}; rather than edit the
6618: application's source code to change every @code{:} to a @code{my:}, do
6619: this:
6620:
6621: @example
6622: : real: : ; \ retain access to the original
6623: defer : \ redefine as a deferred word
6624: ' my: <IS> : \ use special version of :
6625: \
6626: \ load application here
6627: \
6628: ' real: <IS> : \ go back to the original
6629: @end example
6630:
6631:
6632: One thing to note is that @code{<IS>} consumes its name when it is
6633: executed. If you want to specify the name at compile time, use
6634: @code{[IS]}:
6635:
6636: @example
6637: : set-greet ( xt -- )
6638: [IS] greet ;
6639:
6640: ' greet1 set-greet
6641: @end example
6642:
6643: A deferred word can only inherit execution semantics from the xt
6644: (because that is all that an xt can represent -- for more discussion of
6645: this @pxref{Tokens for Words}); by default it will have default
6646: interpretation and compilation semantics deriving from this execution
6647: semantics. However, you can change the interpretation and compilation
6648: semantics of the deferred word in the usual ways:
6649:
6650: @example
6651: : bar .... ; compile-only
6652: Defer fred immediate
6653: Defer jim
6654:
6655: ' bar <IS> jim \ jim has default semantics
6656: ' bar <IS> fred \ fred is immediate
6657: @end example
6658:
6659: doc-defer
6660: doc-<is>
6661: doc-[is]
6662: doc-is
6663: @comment TODO document these: what's defers [is]
6664: doc-what's
6665: doc-defers
6666:
6667: @c Use @code{words-deferred} to see a list of deferred words.
6668:
6669: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
6670: are provided in @file{compat/defer.fs}.
6671:
6672:
6673: @node Aliases, , Deferred words, Defining Words
6674: @subsection Aliases
6675: @cindex aliases
6676:
6677: The defining word @code{Alias} allows you to define a word by name that
6678: has the same behaviour as some other word. Here are two situation where
6679: this can be useful:
6680:
6681: @itemize @bullet
6682: @item
6683: When you want access to a word's definition from a different word list
6684: (for an example of this, see the definition of the @code{Root} word list
6685: in the Gforth source).
6686: @item
6687: When you want to create a synonym; a definition that can be known by
6688: either of two names (for example, @code{THEN} and @code{ENDIF} are
6689: aliases).
6690: @end itemize
6691:
6692: Like deferred words, an alias has default compilation and interpretation
6693: semantics at the beginning (not the modifications of the other word),
6694: but you can change them in the usual ways (@code{immediate},
6695: @code{compile-only}). For example:
6696:
6697: @example
6698: : foo ... ; immediate
6699:
6700: ' foo Alias bar \ bar is not an immediate word
6701: ' foo Alias fooby immediate \ fooby is an immediate word
6702: @end example
6703:
6704: Words that are aliases have the same xt, different headers in the
6705: dictionary, and consequently different name tokens (@pxref{Tokens for
6706: Words}) and possibly different immediate flags. An alias can only have
6707: default or immediate compilation semantics; you can define aliases for
6708: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
6709:
6710: doc-alias
6711:
6712:
6713: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6714: @section Interpretation and Compilation Semantics
6715: @cindex semantics, interpretation and compilation
6716:
6717: @c !! state and ' are used without explanation
6718: @c example for immediate/compile-only? or is the tutorial enough
6719:
6720: @cindex interpretation semantics
6721: The @dfn{interpretation semantics} of a (named) word are what the text
6722: interpreter does when it encounters the word in interpret state. It also
6723: appears in some other contexts, e.g., the execution token returned by
6724: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6725: (in other words, @code{' @i{word} execute} is equivalent to
6726: interpret-state text interpretation of @code{@i{word}}).
6727:
6728: @cindex compilation semantics
6729: The @dfn{compilation semantics} of a (named) word are what the text
6730: interpreter does when it encounters the word in compile state. It also
6731: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6732: compiles@footnote{In standard terminology, ``appends to the current
6733: definition''.} the compilation semantics of @i{word}.
6734:
6735: @cindex execution semantics
6736: The standard also talks about @dfn{execution semantics}. They are used
6737: only for defining the interpretation and compilation semantics of many
6738: words. By default, the interpretation semantics of a word are to
6739: @code{execute} its execution semantics, and the compilation semantics of
6740: a word are to @code{compile,} its execution semantics.@footnote{In
6741: standard terminology: The default interpretation semantics are its
6742: execution semantics; the default compilation semantics are to append its
6743: execution semantics to the execution semantics of the current
6744: definition.}
6745:
6746: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6747: the text interpreter, ticked, or @code{postpone}d, so they have no
6748: interpretation or compilation semantics. Their behaviour is represented
6749: by their XT (@pxref{Tokens for Words}), and we call it execution
6750: semantics, too.
6751:
6752: @comment TODO expand, make it co-operate with new sections on text interpreter.
6753:
6754: @cindex immediate words
6755: @cindex compile-only words
6756: You can change the semantics of the most-recently defined word:
6757:
6758:
6759: doc-immediate
6760: doc-compile-only
6761: doc-restrict
6762:
6763: By convention, words with non-default compilation semantics (e.g.,
6764: immediate words) often have names surrounded with brackets (e.g.,
6765: @code{[']}, @pxref{Execution token}).
6766:
6767: Note that ticking (@code{'}) a compile-only word gives an error
6768: (``Interpreting a compile-only word'').
6769:
6770: @menu
6771: * Combined words::
6772: @end menu
6773:
6774:
6775: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
6776: @subsection Combined Words
6777: @cindex combined words
6778:
6779: Gforth allows you to define @dfn{combined words} -- words that have an
6780: arbitrary combination of interpretation and compilation semantics.
6781:
6782: doc-interpret/compile:
6783:
6784: This feature was introduced for implementing @code{TO} and @code{S"}. I
6785: recommend that you do not define such words, as cute as they may be:
6786: they make it hard to get at both parts of the word in some contexts.
6787: E.g., assume you want to get an execution token for the compilation
6788: part. Instead, define two words, one that embodies the interpretation
6789: part, and one that embodies the compilation part. Once you have done
6790: that, you can define a combined word with @code{interpret/compile:} for
6791: the convenience of your users.
6792:
6793: You might try to use this feature to provide an optimizing
6794: implementation of the default compilation semantics of a word. For
6795: example, by defining:
6796: @example
6797: :noname
6798: foo bar ;
6799: :noname
6800: POSTPONE foo POSTPONE bar ;
6801: interpret/compile: opti-foobar
6802: @end example
6803:
6804: @noindent
6805: as an optimizing version of:
6806:
6807: @example
6808: : foobar
6809: foo bar ;
6810: @end example
6811:
6812: Unfortunately, this does not work correctly with @code{[compile]},
6813: because @code{[compile]} assumes that the compilation semantics of all
6814: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
6815: opti-foobar} would compile compilation semantics, whereas
6816: @code{[compile] foobar} would compile interpretation semantics.
6817:
6818: @cindex state-smart words (are a bad idea)
6819: @anchor{state-smartness}
6820: Some people try to use @dfn{state-smart} words to emulate the feature provided
6821: by @code{interpret/compile:} (words are state-smart if they check
6822: @code{STATE} during execution). E.g., they would try to code
6823: @code{foobar} like this:
6824:
6825: @example
6826: : foobar
6827: STATE @@
6828: IF ( compilation state )
6829: POSTPONE foo POSTPONE bar
6830: ELSE
6831: foo bar
6832: ENDIF ; immediate
6833: @end example
6834:
6835: Although this works if @code{foobar} is only processed by the text
6836: interpreter, it does not work in other contexts (like @code{'} or
6837: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6838: for a state-smart word, not for the interpretation semantics of the
6839: original @code{foobar}; when you execute this execution token (directly
6840: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6841: state, the result will not be what you expected (i.e., it will not
6842: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6843: write them@footnote{For a more detailed discussion of this topic, see
6844: M. Anton Ertl,
6845: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6846: it is Evil and How to Exorcise it}}, EuroForth '98.}!
6847:
6848: @cindex defining words with arbitrary semantics combinations
6849: It is also possible to write defining words that define words with
6850: arbitrary combinations of interpretation and compilation semantics. In
6851: general, they look like this:
6852:
6853: @example
6854: : def-word
6855: create-interpret/compile
6856: @i{code1}
6857: interpretation>
6858: @i{code2}
6859: <interpretation
6860: compilation>
6861: @i{code3}
6862: <compilation ;
6863: @end example
6864:
6865: For a @i{word} defined with @code{def-word}, the interpretation
6866: semantics are to push the address of the body of @i{word} and perform
6867: @i{code2}, and the compilation semantics are to push the address of
6868: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
6869: can also be defined like this (except that the defined constants don't
6870: behave correctly when @code{[compile]}d):
6871:
6872: @example
6873: : constant ( n "name" -- )
6874: create-interpret/compile
6875: ,
6876: interpretation> ( -- n )
6877: @@
6878: <interpretation
6879: compilation> ( compilation. -- ; run-time. -- n )
6880: @@ postpone literal
6881: <compilation ;
6882: @end example
6883:
6884:
6885: doc-create-interpret/compile
6886: doc-interpretation>
6887: doc-<interpretation
6888: doc-compilation>
6889: doc-<compilation
6890:
6891:
6892: Words defined with @code{interpret/compile:} and
6893: @code{create-interpret/compile} have an extended header structure that
6894: differs from other words; however, unless you try to access them with
6895: plain address arithmetic, you should not notice this. Words for
6896: accessing the header structure usually know how to deal with this; e.g.,
6897: @code{'} @i{word} @code{>body} also gives you the body of a word created
6898: with @code{create-interpret/compile}.
6899:
6900:
6901: @c -------------------------------------------------------------
6902: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
6903: @section Tokens for Words
6904: @cindex tokens for words
6905:
6906: This section describes the creation and use of tokens that represent
6907: words.
6908:
6909: @menu
6910: * Execution token:: represents execution/interpretation semantics
6911: * Compilation token:: represents compilation semantics
6912: * Name token:: represents named words
6913: @end menu
6914:
6915: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
6916: @subsection Execution token
6917:
6918: @cindex xt
6919: @cindex execution token
6920: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
6921: You can use @code{execute} to invoke this behaviour.
6922:
6923: @cindex tick (')
6924: You can use @code{'} to get an execution token that represents the
6925: interpretation semantics of a named word:
6926:
6927: @example
6928: 5 ' . ( n xt )
6929: execute ( ) \ execute the xt (i.e., ".")
6930: @end example
6931:
6932: doc-'
6933:
6934: @code{'} parses at run-time; there is also a word @code{[']} that parses
6935: when it is compiled, and compiles the resulting XT:
6936:
6937: @example
6938: : foo ['] . execute ;
6939: 5 foo
6940: : bar ' execute ; \ by contrast,
6941: 5 bar . \ ' parses "." when bar executes
6942: @end example
6943:
6944: doc-[']
6945:
6946: If you want the execution token of @i{word}, write @code{['] @i{word}}
6947: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
6948: @code{'} and @code{[']} behave somewhat unusually by complaining about
6949: compile-only words (because these words have no interpretation
6950: semantics). You might get what you want by using @code{COMP' @i{word}
6951: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
6952: token}).
6953:
6954: Another way to get an XT is @code{:noname} or @code{latestxt}
6955: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
6956: for the only behaviour the word has (the execution semantics). For
6957: named words, @code{latestxt} produces an XT for the same behaviour it
6958: would produce if the word was defined anonymously.
6959:
6960: @example
6961: :noname ." hello" ;
6962: execute
6963: @end example
6964:
6965: An XT occupies one cell and can be manipulated like any other cell.
6966:
6967: @cindex code field address
6968: @cindex CFA
6969: In ANS Forth the XT is just an abstract data type (i.e., defined by the
6970: operations that produce or consume it). For old hands: In Gforth, the
6971: XT is implemented as a code field address (CFA).
6972:
6973: doc-execute
6974: doc-perform
6975:
6976: @node Compilation token, Name token, Execution token, Tokens for Words
6977: @subsection Compilation token
6978:
6979: @cindex compilation token
6980: @cindex CT (compilation token)
6981: Gforth represents the compilation semantics of a named word by a
6982: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
6983: @i{xt} is an execution token. The compilation semantics represented by
6984: the compilation token can be performed with @code{execute}, which
6985: consumes the whole compilation token, with an additional stack effect
6986: determined by the represented compilation semantics.
6987:
6988: At present, the @i{w} part of a compilation token is an execution token,
6989: and the @i{xt} part represents either @code{execute} or
6990: @code{compile,}@footnote{Depending upon the compilation semantics of the
6991: word. If the word has default compilation semantics, the @i{xt} will
6992: represent @code{compile,}. Otherwise (e.g., for immediate words), the
6993: @i{xt} will represent @code{execute}.}. However, don't rely on that
6994: knowledge, unless necessary; future versions of Gforth may introduce
6995: unusual compilation tokens (e.g., a compilation token that represents
6996: the compilation semantics of a literal).
6997:
6998: You can perform the compilation semantics represented by the compilation
6999: token with @code{execute}. You can compile the compilation semantics
7000: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7001: equivalent to @code{postpone @i{word}}.
7002:
7003: doc-[comp']
7004: doc-comp'
7005: doc-postpone,
7006:
7007: @node Name token, , Compilation token, Tokens for Words
7008: @subsection Name token
7009:
7010: @cindex name token
7011: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7012: token is an abstract data type that occurs as argument or result of the
7013: words below.
7014:
7015: @c !! put this elswhere?
7016: @cindex name field address
7017: @cindex NFA
7018: The closest thing to the nt in older Forth systems is the name field
7019: address (NFA), but there are significant differences: in older Forth
7020: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7021: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7022: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7023: is a link field in the structure identified by the name token, but
7024: searching usually uses a hash table external to these structures; the
7025: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7026: implemented as the address of that count field.
7027:
7028: doc-find-name
7029: doc-latest
7030: doc->name
7031: doc-name>int
7032: doc-name?int
7033: doc-name>comp
7034: doc-name>string
7035: doc-id.
7036: doc-.name
7037: doc-.id
7038:
7039: @c ----------------------------------------------------------
7040: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7041: @section Compiling words
7042: @cindex compiling words
7043: @cindex macros
7044:
7045: In contrast to most other languages, Forth has no strict boundary
7046: between compilation and run-time. E.g., you can run arbitrary code
7047: between defining words (or for computing data used by defining words
7048: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7049: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7050: running arbitrary code while compiling a colon definition (exception:
7051: you must not allot dictionary space).
7052:
7053: @menu
7054: * Literals:: Compiling data values
7055: * Macros:: Compiling words
7056: @end menu
7057:
7058: @node Literals, Macros, Compiling words, Compiling words
7059: @subsection Literals
7060: @cindex Literals
7061:
7062: The simplest and most frequent example is to compute a literal during
7063: compilation. E.g., the following definition prints an array of strings,
7064: one string per line:
7065:
7066: @example
7067: : .strings ( addr u -- ) \ gforth
7068: 2* cells bounds U+DO
7069: cr i 2@@ type
7070: 2 cells +LOOP ;
7071: @end example
7072:
7073: With a simple-minded compiler like Gforth's, this computes @code{2
7074: cells} on every loop iteration. You can compute this value once and for
7075: all at compile time and compile it into the definition like this:
7076:
7077: @example
7078: : .strings ( addr u -- ) \ gforth
7079: 2* cells bounds U+DO
7080: cr i 2@@ type
7081: [ 2 cells ] literal +LOOP ;
7082: @end example
7083:
7084: @code{[} switches the text interpreter to interpret state (you will get
7085: an @code{ok} prompt if you type this example interactively and insert a
7086: newline between @code{[} and @code{]}), so it performs the
7087: interpretation semantics of @code{2 cells}; this computes a number.
7088: @code{]} switches the text interpreter back into compile state. It then
7089: performs @code{Literal}'s compilation semantics, which are to compile
7090: this number into the current word. You can decompile the word with
7091: @code{see .strings} to see the effect on the compiled code.
7092:
7093: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7094: *} in this way.
7095:
7096: doc-[
7097: doc-]
7098: doc-literal
7099: doc-]L
7100:
7101: There are also words for compiling other data types than single cells as
7102: literals:
7103:
7104: doc-2literal
7105: doc-fliteral
7106: doc-sliteral
7107:
7108: @cindex colon-sys, passing data across @code{:}
7109: @cindex @code{:}, passing data across
7110: You might be tempted to pass data from outside a colon definition to the
7111: inside on the data stack. This does not work, because @code{:} puhes a
7112: colon-sys, making stuff below unaccessible. E.g., this does not work:
7113:
7114: @example
7115: 5 : foo literal ; \ error: "unstructured"
7116: @end example
7117:
7118: Instead, you have to pass the value in some other way, e.g., through a
7119: variable:
7120:
7121: @example
7122: variable temp
7123: 5 temp !
7124: : foo [ temp @@ ] literal ;
7125: @end example
7126:
7127:
7128: @node Macros, , Literals, Compiling words
7129: @subsection Macros
7130: @cindex Macros
7131: @cindex compiling compilation semantics
7132:
7133: @code{Literal} and friends compile data values into the current
7134: definition. You can also write words that compile other words into the
7135: current definition. E.g.,
7136:
7137: @example
7138: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7139: POSTPONE + ;
7140:
7141: : foo ( n1 n2 -- n )
7142: [ compile-+ ] ;
7143: 1 2 foo .
7144: @end example
7145:
7146: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7147: What happens in this example? @code{Postpone} compiles the compilation
7148: semantics of @code{+} into @code{compile-+}; later the text interpreter
7149: executes @code{compile-+} and thus the compilation semantics of +, which
7150: compile (the execution semantics of) @code{+} into
7151: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7152: should only be executed in compile state, so this example is not
7153: guaranteed to work on all standard systems, but on any decent system it
7154: will work.}
7155:
7156: doc-postpone
7157: doc-[compile]
7158:
7159: Compiling words like @code{compile-+} are usually immediate (or similar)
7160: so you do not have to switch to interpret state to execute them;
7161: mopifying the last example accordingly produces:
7162:
7163: @example
7164: : [compile-+] ( compilation: --; interpretation: -- )
7165: \ compiled code: ( n1 n2 -- n )
7166: POSTPONE + ; immediate
7167:
7168: : foo ( n1 n2 -- n )
7169: [compile-+] ;
7170: 1 2 foo .
7171: @end example
7172:
7173: Immediate compiling words are similar to macros in other languages (in
7174: particular, Lisp). The important differences to macros in, e.g., C are:
7175:
7176: @itemize @bullet
7177:
7178: @item
7179: You use the same language for defining and processing macros, not a
7180: separate preprocessing language and processor.
7181:
7182: @item
7183: Consequently, the full power of Forth is available in macro definitions.
7184: E.g., you can perform arbitrarily complex computations, or generate
7185: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7186: Tutorial}). This power is very useful when writing a parser generators
7187: or other code-generating software.
7188:
7189: @item
7190: Macros defined using @code{postpone} etc. deal with the language at a
7191: higher level than strings; name binding happens at macro definition
7192: time, so you can avoid the pitfalls of name collisions that can happen
7193: in C macros. Of course, Forth is a liberal language and also allows to
7194: shoot yourself in the foot with text-interpreted macros like
7195:
7196: @example
7197: : [compile-+] s" +" evaluate ; immediate
7198: @end example
7199:
7200: Apart from binding the name at macro use time, using @code{evaluate}
7201: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7202: @end itemize
7203:
7204: You may want the macro to compile a number into a word. The word to do
7205: it is @code{literal}, but you have to @code{postpone} it, so its
7206: compilation semantics take effect when the macro is executed, not when
7207: it is compiled:
7208:
7209: @example
7210: : [compile-5] ( -- ) \ compiled code: ( -- n )
7211: 5 POSTPONE literal ; immediate
7212:
7213: : foo [compile-5] ;
7214: foo .
7215: @end example
7216:
7217: You may want to pass parameters to a macro, that the macro should
7218: compile into the current definition. If the parameter is a number, then
7219: you can use @code{postpone literal} (similar for other values).
7220:
7221: If you want to pass a word that is to be compiled, the usual way is to
7222: pass an execution token and @code{compile,} it:
7223:
7224: @example
7225: : twice1 ( xt -- ) \ compiled code: ... -- ...
7226: dup compile, compile, ;
7227:
7228: : 2+ ( n1 -- n2 )
7229: [ ' 1+ twice1 ] ;
7230: @end example
7231:
7232: doc-compile,
7233:
7234: An alternative available in Gforth, that allows you to pass compile-only
7235: words as parameters is to use the compilation token (@pxref{Compilation
7236: token}). The same example in this technique:
7237:
7238: @example
7239: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7240: 2dup 2>r execute 2r> execute ;
7241:
7242: : 2+ ( n1 -- n2 )
7243: [ comp' 1+ twice ] ;
7244: @end example
7245:
7246: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7247: works even if the executed compilation semantics has an effect on the
7248: data stack.
7249:
7250: You can also define complete definitions with these words; this provides
7251: an alternative to using @code{does>} (@pxref{User-defined Defining
7252: Words}). E.g., instead of
7253:
7254: @example
7255: : curry+ ( n1 "name" -- )
7256: CREATE ,
7257: DOES> ( n2 -- n1+n2 )
7258: @@ + ;
7259: @end example
7260:
7261: you could define
7262:
7263: @example
7264: : curry+ ( n1 "name" -- )
7265: \ name execution: ( n2 -- n1+n2 )
7266: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
7267:
7268: -3 curry+ 3-
7269: see 3-
7270: @end example
7271:
7272: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7273: colon-sys on the data stack that makes everything below it unaccessible.
7274:
7275: This way of writing defining words is sometimes more, sometimes less
7276: convenient than using @code{does>} (@pxref{Advanced does> usage
7277: example}). One advantage of this method is that it can be optimized
7278: better, because the compiler knows that the value compiled with
7279: @code{literal} is fixed, whereas the data associated with a
7280: @code{create}d word can be changed.
7281:
7282: @c ----------------------------------------------------------
7283: @node The Text Interpreter, The Input Stream, Compiling words, Words
7284: @section The Text Interpreter
7285: @cindex interpreter - outer
7286: @cindex text interpreter
7287: @cindex outer interpreter
7288:
7289: @c Should we really describe all these ugly details? IMO the text
7290: @c interpreter should be much cleaner, but that may not be possible within
7291: @c ANS Forth. - anton
7292: @c nac-> I wanted to explain how it works to show how you can exploit
7293: @c it in your own programs. When I was writing a cross-compiler, figuring out
7294: @c some of these gory details was very helpful to me. None of the textbooks
7295: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7296: @c seems to positively avoid going into too much detail for some of
7297: @c the internals.
7298:
7299: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7300: @c it is; for the ugly details, I would prefer another place. I wonder
7301: @c whether we should have a chapter before "Words" that describes some
7302: @c basic concepts referred to in words, and a chapter after "Words" that
7303: @c describes implementation details.
7304:
7305: The text interpreter@footnote{This is an expanded version of the
7306: material in @ref{Introducing the Text Interpreter}.} is an endless loop
7307: that processes input from the current input device. It is also called
7308: the outer interpreter, in contrast to the inner interpreter
7309: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7310: implementations.
7311:
7312: @cindex interpret state
7313: @cindex compile state
7314: The text interpreter operates in one of two states: @dfn{interpret
7315: state} and @dfn{compile state}. The current state is defined by the
7316: aptly-named variable @code{state}.
7317:
7318: This section starts by describing how the text interpreter behaves when
7319: it is in interpret state, processing input from the user input device --
7320: the keyboard. This is the mode that a Forth system is in after it starts
7321: up.
7322:
7323: @cindex input buffer
7324: @cindex terminal input buffer
7325: The text interpreter works from an area of memory called the @dfn{input
7326: buffer}@footnote{When the text interpreter is processing input from the
7327: keyboard, this area of memory is called the @dfn{terminal input buffer}
7328: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7329: @code{#TIB}.}, which stores your keyboard input when you press the
7330: @key{RET} key. Starting at the beginning of the input buffer, it skips
7331: leading spaces (called @dfn{delimiters}) then parses a string (a
7332: sequence of non-space characters) until it reaches either a space
7333: character or the end of the buffer. Having parsed a string, it makes two
7334: attempts to process it:
7335:
7336: @cindex dictionary
7337: @itemize @bullet
7338: @item
7339: It looks for the string in a @dfn{dictionary} of definitions. If the
7340: string is found, the string names a @dfn{definition} (also known as a
7341: @dfn{word}) and the dictionary search returns information that allows
7342: the text interpreter to perform the word's @dfn{interpretation
7343: semantics}. In most cases, this simply means that the word will be
7344: executed.
7345: @item
7346: If the string is not found in the dictionary, the text interpreter
7347: attempts to treat it as a number, using the rules described in
7348: @ref{Number Conversion}. If the string represents a legal number in the
7349: current radix, the number is pushed onto a parameter stack (the data
7350: stack for integers, the floating-point stack for floating-point
7351: numbers).
7352: @end itemize
7353:
7354: If both attempts fail, or if the word is found in the dictionary but has
7355: no interpretation semantics@footnote{This happens if the word was
7356: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7357: remainder of the input buffer, issues an error message and waits for
7358: more input. If one of the attempts succeeds, the text interpreter
7359: repeats the parsing process until the whole of the input buffer has been
7360: processed, at which point it prints the status message ``@code{ ok}''
7361: and waits for more input.
7362:
7363: @c anton: this should be in the input stream subsection (or below it)
7364:
7365: @cindex parse area
7366: The text interpreter keeps track of its position in the input buffer by
7367: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7368: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7369: of the input buffer. The region from offset @code{>IN @@} to the end of
7370: the input buffer is called the @dfn{parse area}@footnote{In other words,
7371: the text interpreter processes the contents of the input buffer by
7372: parsing strings from the parse area until the parse area is empty.}.
7373: This example shows how @code{>IN} changes as the text interpreter parses
7374: the input buffer:
7375:
7376: @example
7377: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7378: CR ." ->" TYPE ." <-" ; IMMEDIATE
7379:
7380: 1 2 3 remaining + remaining .
7381:
7382: : foo 1 2 3 remaining SWAP remaining ;
7383: @end example
7384:
7385: @noindent
7386: The result is:
7387:
7388: @example
7389: ->+ remaining .<-
7390: ->.<-5 ok
7391:
7392: ->SWAP remaining ;-<
7393: ->;<- ok
7394: @end example
7395:
7396: @cindex parsing words
7397: The value of @code{>IN} can also be modified by a word in the input
7398: buffer that is executed by the text interpreter. This means that a word
7399: can ``trick'' the text interpreter into either skipping a section of the
7400: input buffer@footnote{This is how parsing words work.} or into parsing a
7401: section twice. For example:
7402:
7403: @example
7404: : lat ." <<foo>>" ;
7405: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
7406: @end example
7407:
7408: @noindent
7409: When @code{flat} is executed, this output is produced@footnote{Exercise
7410: for the reader: what would happen if the @code{3} were replaced with
7411: @code{4}?}:
7412:
7413: @example
7414: <<bar>><<foo>>
7415: @end example
7416:
7417: This technique can be used to work around some of the interoperability
7418: problems of parsing words. Of course, it's better to avoid parsing
7419: words where possible.
7420:
7421: @noindent
7422: Two important notes about the behaviour of the text interpreter:
7423:
7424: @itemize @bullet
7425: @item
7426: It processes each input string to completion before parsing additional
7427: characters from the input buffer.
7428: @item
7429: It treats the input buffer as a read-only region (and so must your code).
7430: @end itemize
7431:
7432: @noindent
7433: When the text interpreter is in compile state, its behaviour changes in
7434: these ways:
7435:
7436: @itemize @bullet
7437: @item
7438: If a parsed string is found in the dictionary, the text interpreter will
7439: perform the word's @dfn{compilation semantics}. In most cases, this
7440: simply means that the execution semantics of the word will be appended
7441: to the current definition.
7442: @item
7443: When a number is encountered, it is compiled into the current definition
7444: (as a literal) rather than being pushed onto a parameter stack.
7445: @item
7446: If an error occurs, @code{state} is modified to put the text interpreter
7447: back into interpret state.
7448: @item
7449: Each time a line is entered from the keyboard, Gforth prints
7450: ``@code{ compiled}'' rather than `` @code{ok}''.
7451: @end itemize
7452:
7453: @cindex text interpreter - input sources
7454: When the text interpreter is using an input device other than the
7455: keyboard, its behaviour changes in these ways:
7456:
7457: @itemize @bullet
7458: @item
7459: When the parse area is empty, the text interpreter attempts to refill
7460: the input buffer from the input source. When the input source is
7461: exhausted, the input source is set back to the previous input source.
7462: @item
7463: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7464: time the parse area is emptied.
7465: @item
7466: If an error occurs, the input source is set back to the user input
7467: device.
7468: @end itemize
7469:
7470: You can read about this in more detail in @ref{Input Sources}.
7471:
7472: doc->in
7473: doc-source
7474:
7475: doc-tib
7476: doc-#tib
7477:
7478:
7479: @menu
7480: * Input Sources::
7481: * Number Conversion::
7482: * Interpret/Compile states::
7483: * Interpreter Directives::
7484: @end menu
7485:
7486: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7487: @subsection Input Sources
7488: @cindex input sources
7489: @cindex text interpreter - input sources
7490:
7491: By default, the text interpreter processes input from the user input
7492: device (the keyboard) when Forth starts up. The text interpreter can
7493: process input from any of these sources:
7494:
7495: @itemize @bullet
7496: @item
7497: The user input device -- the keyboard.
7498: @item
7499: A file, using the words described in @ref{Forth source files}.
7500: @item
7501: A block, using the words described in @ref{Blocks}.
7502: @item
7503: A text string, using @code{evaluate}.
7504: @end itemize
7505:
7506: A program can identify the current input device from the values of
7507: @code{source-id} and @code{blk}.
7508:
7509:
7510: doc-source-id
7511: doc-blk
7512:
7513: doc-save-input
7514: doc-restore-input
7515:
7516: doc-evaluate
7517: doc-query
7518:
7519:
7520:
7521: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
7522: @subsection Number Conversion
7523: @cindex number conversion
7524: @cindex double-cell numbers, input format
7525: @cindex input format for double-cell numbers
7526: @cindex single-cell numbers, input format
7527: @cindex input format for single-cell numbers
7528: @cindex floating-point numbers, input format
7529: @cindex input format for floating-point numbers
7530:
7531: This section describes the rules that the text interpreter uses when it
7532: tries to convert a string into a number.
7533:
7534: Let <digit> represent any character that is a legal digit in the current
7535: number base@footnote{For example, 0-9 when the number base is decimal or
7536: 0-9, A-F when the number base is hexadecimal.}.
7537:
7538: Let <decimal digit> represent any character in the range 0-9.
7539:
7540: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7541: in the braces (@i{a} or @i{b} or neither).
7542:
7543: Let * represent any number of instances of the previous character
7544: (including none).
7545:
7546: Let any other character represent itself.
7547:
7548: @noindent
7549: Now, the conversion rules are:
7550:
7551: @itemize @bullet
7552: @item
7553: A string of the form <digit><digit>* is treated as a single-precision
7554: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
7555: @item
7556: A string of the form -<digit><digit>* is treated as a single-precision
7557: (cell-sized) negative integer, and is represented using 2's-complement
7558: arithmetic. Examples are -45 -5681 -0
7559: @item
7560: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
7561: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7562: (all three of these represent the same number).
7563: @item
7564: A string of the form -<digit><digit>*.<digit>* is treated as a
7565: double-precision (double-cell-sized) negative integer, and is
7566: represented using 2's-complement arithmetic. Examples are -3465. -3.465
7567: -34.65 (all three of these represent the same number).
7568: @item
7569: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7570: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
7571: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
7572: number) +12.E-4
7573: @end itemize
7574:
7575: By default, the number base used for integer number conversion is given
7576: by the contents of the variable @code{base}. Note that a lot of
7577: confusion can result from unexpected values of @code{base}. If you
7578: change @code{base} anywhere, make sure to save the old value and restore
7579: it afterwards. In general I recommend keeping @code{base} decimal, and
7580: using the prefixes described below for the popular non-decimal bases.
7581:
7582: doc-dpl
7583: doc-base
7584: doc-hex
7585: doc-decimal
7586:
7587:
7588: @cindex '-prefix for character strings
7589: @cindex &-prefix for decimal numbers
7590: @cindex %-prefix for binary numbers
7591: @cindex $-prefix for hexadecimal numbers
7592: Gforth allows you to override the value of @code{base} by using a
7593: prefix@footnote{Some Forth implementations provide a similar scheme by
7594: implementing @code{$} etc. as parsing words that process the subsequent
7595: number in the input stream and push it onto the stack. For example, see
7596: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7597: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7598: is required between the prefix and the number.} before the first digit
7599: of an (integer) number. Four prefixes are supported:
7600:
7601: @itemize @bullet
7602: @item
7603: @code{&} -- decimal
7604: @item
7605: @code{%} -- binary
7606: @item
7607: @code{$} -- hexadecimal
7608: @item
7609: @code{'} -- base @code{max-char+1}
7610: @end itemize
7611:
7612: Here are some examples, with the equivalent decimal number shown after
7613: in braces:
7614:
7615: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
7616: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
7617: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
7618: &905 (905), $abc (2478), $ABC (2478).
7619:
7620: @cindex number conversion - traps for the unwary
7621: @noindent
7622: Number conversion has a number of traps for the unwary:
7623:
7624: @itemize @bullet
7625: @item
7626: You cannot determine the current number base using the code sequence
7627: @code{base @@ .} -- the number base is always 10 in the current number
7628: base. Instead, use something like @code{base @@ dec.}
7629: @item
7630: If the number base is set to a value greater than 14 (for example,
7631: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7632: it to be intepreted as either a single-precision integer or a
7633: floating-point number (Gforth treats it as an integer). The ambiguity
7634: can be resolved by explicitly stating the sign of the mantissa and/or
7635: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7636: ambiguity arises; either representation will be treated as a
7637: floating-point number.
7638: @item
7639: There is a word @code{bin} but it does @i{not} set the number base!
7640: It is used to specify file types.
7641: @item
7642: ANS Forth requires the @code{.} of a double-precision number to be the
7643: final character in the string. Gforth allows the @code{.} to be
7644: anywhere after the first digit.
7645: @item
7646: The number conversion process does not check for overflow.
7647: @item
7648: In an ANS Forth program @code{base} is required to be decimal when
7649: converting floating-point numbers. In Gforth, number conversion to
7650: floating-point numbers always uses base &10, irrespective of the value
7651: of @code{base}.
7652: @end itemize
7653:
7654: You can read numbers into your programs with the words described in
7655: @ref{Input}.
7656:
7657: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
7658: @subsection Interpret/Compile states
7659: @cindex Interpret/Compile states
7660:
7661: A standard program is not permitted to change @code{state}
7662: explicitly. However, it can change @code{state} implicitly, using the
7663: words @code{[} and @code{]}. When @code{[} is executed it switches
7664: @code{state} to interpret state, and therefore the text interpreter
7665: starts interpreting. When @code{]} is executed it switches @code{state}
7666: to compile state and therefore the text interpreter starts
7667: compiling. The most common usage for these words is for switching into
7668: interpret state and back from within a colon definition; this technique
7669: can be used to compile a literal (for an example, @pxref{Literals}) or
7670: for conditional compilation (for an example, @pxref{Interpreter
7671: Directives}).
7672:
7673:
7674: @c This is a bad example: It's non-standard, and it's not necessary.
7675: @c However, I can't think of a good example for switching into compile
7676: @c state when there is no current word (@code{state}-smart words are not a
7677: @c good reason). So maybe we should use an example for switching into
7678: @c interpret @code{state} in a colon def. - anton
7679: @c nac-> I agree. I started out by putting in the example, then realised
7680: @c that it was non-ANS, so wrote more words around it. I hope this
7681: @c re-written version is acceptable to you. I do want to keep the example
7682: @c as it is helpful for showing what is and what is not portable, particularly
7683: @c where it outlaws a style in common use.
7684:
7685: @c anton: it's more important to show what's portable. After we have done
7686: @c that, we can also show what's not. In any case, I have written a
7687: @c section Compiling Words which also deals with [ ].
7688:
7689: @c !! The following example does not work in Gforth 0.5.9 or later.
7690:
7691: @c @code{[} and @code{]} also give you the ability to switch into compile
7692: @c state and back, but we cannot think of any useful Standard application
7693: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7694:
7695: @c @example
7696: @c : AA ." this is A" ;
7697: @c : BB ." this is B" ;
7698: @c : CC ." this is C" ;
7699:
7700: @c create table ] aa bb cc [
7701:
7702: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7703: @c cells table + @@ execute ;
7704: @c @end example
7705:
7706: @c This example builds a jump table; @code{0 go} will display ``@code{this
7707: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7708: @c defining @code{table} like this:
7709:
7710: @c @example
7711: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7712: @c @end example
7713:
7714: @c The problem with this code is that the definition of @code{table} is not
7715: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7716: @c @i{may} work on systems where code space and data space co-incide, the
7717: @c Standard only allows data space to be assigned for a @code{CREATE}d
7718: @c word. In addition, the Standard only allows @code{@@} to access data
7719: @c space, whilst this example is using it to access code space. The only
7720: @c portable, Standard way to build this table is to build it in data space,
7721: @c like this:
7722:
7723: @c @example
7724: @c create table ' aa , ' bb , ' cc ,
7725: @c @end example
7726:
7727: @c doc-state
7728:
7729:
7730: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
7731: @subsection Interpreter Directives
7732: @cindex interpreter directives
7733: @cindex conditional compilation
7734:
7735: These words are usually used in interpret state; typically to control
7736: which parts of a source file are processed by the text
7737: interpreter. There are only a few ANS Forth Standard words, but Gforth
7738: supplements these with a rich set of immediate control structure words
7739: to compensate for the fact that the non-immediate versions can only be
7740: used in compile state (@pxref{Control Structures}). Typical usages:
7741:
7742: @example
7743: FALSE Constant HAVE-ASSEMBLER
7744: .
7745: .
7746: HAVE-ASSEMBLER [IF]
7747: : ASSEMBLER-FEATURE
7748: ...
7749: ;
7750: [ENDIF]
7751: .
7752: .
7753: : SEE
7754: ... \ general-purpose SEE code
7755: [ HAVE-ASSEMBLER [IF] ]
7756: ... \ assembler-specific SEE code
7757: [ [ENDIF] ]
7758: ;
7759: @end example
7760:
7761:
7762: doc-[IF]
7763: doc-[ELSE]
7764: doc-[THEN]
7765: doc-[ENDIF]
7766:
7767: doc-[IFDEF]
7768: doc-[IFUNDEF]
7769:
7770: doc-[?DO]
7771: doc-[DO]
7772: doc-[FOR]
7773: doc-[LOOP]
7774: doc-[+LOOP]
7775: doc-[NEXT]
7776:
7777: doc-[BEGIN]
7778: doc-[UNTIL]
7779: doc-[AGAIN]
7780: doc-[WHILE]
7781: doc-[REPEAT]
7782:
7783:
7784: @c -------------------------------------------------------------
7785: @node The Input Stream, Word Lists, The Text Interpreter, Words
7786: @section The Input Stream
7787: @cindex input stream
7788:
7789: @c !! integrate this better with the "Text Interpreter" section
7790: The text interpreter reads from the input stream, which can come from
7791: several sources (@pxref{Input Sources}). Some words, in particular
7792: defining words, but also words like @code{'}, read parameters from the
7793: input stream instead of from the stack.
7794:
7795: Such words are called parsing words, because they parse the input
7796: stream. Parsing words are hard to use in other words, because it is
7797: hard to pass program-generated parameters through the input stream.
7798: They also usually have an unintuitive combination of interpretation and
7799: compilation semantics when implemented naively, leading to various
7800: approaches that try to produce a more intuitive behaviour
7801: (@pxref{Combined words}).
7802:
7803: It should be obvious by now that parsing words are a bad idea. If you
7804: want to implement a parsing word for convenience, also provide a factor
7805: of the word that does not parse, but takes the parameters on the stack.
7806: To implement the parsing word on top if it, you can use the following
7807: words:
7808:
7809: @c anton: these belong in the input stream section
7810: doc-parse
7811: doc-parse-word
7812: doc-name
7813: doc-word
7814: doc-\"-parse
7815: doc-refill
7816:
7817: Conversely, if you have the bad luck (or lack of foresight) to have to
7818: deal with parsing words without having such factors, how do you pass a
7819: string that is not in the input stream to it?
7820:
7821: doc-execute-parsing
7822:
7823: If you want to run a parsing word on a file, the following word should
7824: help:
7825:
7826: doc-execute-parsing-file
7827:
7828: @c -------------------------------------------------------------
7829: @node Word Lists, Environmental Queries, The Input Stream, Words
7830: @section Word Lists
7831: @cindex word lists
7832: @cindex header space
7833:
7834: A wordlist is a list of named words; you can add new words and look up
7835: words by name (and you can remove words in a restricted way with
7836: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7837:
7838: @cindex search order stack
7839: The text interpreter searches the wordlists present in the search order
7840: (a stack of wordlists), from the top to the bottom. Within each
7841: wordlist, the search starts conceptually at the newest word; i.e., if
7842: two words in a wordlist have the same name, the newer word is found.
7843:
7844: @cindex compilation word list
7845: New words are added to the @dfn{compilation wordlist} (aka current
7846: wordlist).
7847:
7848: @cindex wid
7849: A word list is identified by a cell-sized word list identifier (@i{wid})
7850: in much the same way as a file is identified by a file handle. The
7851: numerical value of the wid has no (portable) meaning, and might change
7852: from session to session.
7853:
7854: The ANS Forth ``Search order'' word set is intended to provide a set of
7855: low-level tools that allow various different schemes to be
7856: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
7857: word. @file{compat/vocabulary.fs} provides an implementation in ANS
7858: Forth.
7859:
7860: @comment TODO: locals section refers to here, saying that every word list (aka
7861: @comment vocabulary) has its own methods for searching etc. Need to document that.
7862: @c anton: but better in a separate subsection on wordlist internals
7863:
7864: @comment TODO: document markers, reveal, tables, mappedwordlist
7865:
7866: @comment the gforthman- prefix is used to pick out the true definition of a
7867: @comment word from the source files, rather than some alias.
7868:
7869: doc-forth-wordlist
7870: doc-definitions
7871: doc-get-current
7872: doc-set-current
7873: doc-get-order
7874: doc---gforthman-set-order
7875: doc-wordlist
7876: doc-table
7877: doc->order
7878: doc-previous
7879: doc-also
7880: doc---gforthman-forth
7881: doc-only
7882: doc---gforthman-order
7883:
7884: doc-find
7885: doc-search-wordlist
7886:
7887: doc-words
7888: doc-vlist
7889: @c doc-words-deferred
7890:
7891: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
7892: doc-root
7893: doc-vocabulary
7894: doc-seal
7895: doc-vocs
7896: doc-current
7897: doc-context
7898:
7899:
7900: @menu
7901: * Vocabularies::
7902: * Why use word lists?::
7903: * Word list example::
7904: @end menu
7905:
7906: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
7907: @subsection Vocabularies
7908: @cindex Vocabularies, detailed explanation
7909:
7910: Here is an example of creating and using a new wordlist using ANS
7911: Forth words:
7912:
7913: @example
7914: wordlist constant my-new-words-wordlist
7915: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
7916:
7917: \ add it to the search order
7918: also my-new-words
7919:
7920: \ alternatively, add it to the search order and make it
7921: \ the compilation word list
7922: also my-new-words definitions
7923: \ type "order" to see the problem
7924: @end example
7925:
7926: The problem with this example is that @code{order} has no way to
7927: associate the name @code{my-new-words} with the wid of the word list (in
7928: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7929: that has no associated name). There is no Standard way of associating a
7930: name with a wid.
7931:
7932: In Gforth, this example can be re-coded using @code{vocabulary}, which
7933: associates a name with a wid:
7934:
7935: @example
7936: vocabulary my-new-words
7937:
7938: \ add it to the search order
7939: also my-new-words
7940:
7941: \ alternatively, add it to the search order and make it
7942: \ the compilation word list
7943: my-new-words definitions
7944: \ type "order" to see that the problem is solved
7945: @end example
7946:
7947:
7948: @node Why use word lists?, Word list example, Vocabularies, Word Lists
7949: @subsection Why use word lists?
7950: @cindex word lists - why use them?
7951:
7952: Here are some reasons why people use wordlists:
7953:
7954: @itemize @bullet
7955:
7956: @c anton: Gforth's hashing implementation makes the search speed
7957: @c independent from the number of words. But it is linear with the number
7958: @c of wordlists that have to be searched, so in effect using more wordlists
7959: @c actually slows down compilation.
7960:
7961: @c @item
7962: @c To improve compilation speed by reducing the number of header space
7963: @c entries that must be searched. This is achieved by creating a new
7964: @c word list that contains all of the definitions that are used in the
7965: @c definition of a Forth system but which would not usually be used by
7966: @c programs running on that system. That word list would be on the search
7967: @c list when the Forth system was compiled but would be removed from the
7968: @c search list for normal operation. This can be a useful technique for
7969: @c low-performance systems (for example, 8-bit processors in embedded
7970: @c systems) but is unlikely to be necessary in high-performance desktop
7971: @c systems.
7972:
7973: @item
7974: To prevent a set of words from being used outside the context in which
7975: they are valid. Two classic examples of this are an integrated editor
7976: (all of the edit commands are defined in a separate word list; the
7977: search order is set to the editor word list when the editor is invoked;
7978: the old search order is restored when the editor is terminated) and an
7979: integrated assembler (the op-codes for the machine are defined in a
7980: separate word list which is used when a @code{CODE} word is defined).
7981:
7982: @item
7983: To organize the words of an application or library into a user-visible
7984: set (in @code{forth-wordlist} or some other common wordlist) and a set
7985: of helper words used just for the implementation (hidden in a separate
7986: wordlist). This keeps @code{words}' output smaller, separates
7987: implementation and interface, and reduces the chance of name conflicts
7988: within the common wordlist.
7989:
7990: @item
7991: To prevent a name-space clash between multiple definitions with the same
7992: name. For example, when building a cross-compiler you might have a word
7993: @code{IF} that generates conditional code for your target system. By
7994: placing this definition in a different word list you can control whether
7995: the host system's @code{IF} or the target system's @code{IF} get used in
7996: any particular context by controlling the order of the word lists on the
7997: search order stack.
7998:
7999: @end itemize
8000:
8001: The downsides of using wordlists are:
8002:
8003: @itemize
8004:
8005: @item
8006: Debugging becomes more cumbersome.
8007:
8008: @item
8009: Name conflicts worked around with wordlists are still there, and you
8010: have to arrange the search order carefully to get the desired results;
8011: if you forget to do that, you get hard-to-find errors (as in any case
8012: where you read the code differently from the compiler; @code{see} can
8013: help seeing which of several possible words the name resolves to in such
8014: cases). @code{See} displays just the name of the words, not what
8015: wordlist they belong to, so it might be misleading. Using unique names
8016: is a better approach to avoid name conflicts.
8017:
8018: @item
8019: You have to explicitly undo any changes to the search order. In many
8020: cases it would be more convenient if this happened implicitly. Gforth
8021: currently does not provide such a feature, but it may do so in the
8022: future.
8023: @end itemize
8024:
8025:
8026: @node Word list example, , Why use word lists?, Word Lists
8027: @subsection Word list example
8028: @cindex word lists - example
8029:
8030: The following example is from the
8031: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8032: garbage collector} and uses wordlists to separate public words from
8033: helper words:
8034:
8035: @example
8036: get-current ( wid )
8037: vocabulary garbage-collector also garbage-collector definitions
8038: ... \ define helper words
8039: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8040: ... \ define the public (i.e., API) words
8041: \ they can refer to the helper words
8042: previous \ restore original search order (helper words become invisible)
8043: @end example
8044:
8045: @c -------------------------------------------------------------
8046: @node Environmental Queries, Files, Word Lists, Words
8047: @section Environmental Queries
8048: @cindex environmental queries
8049:
8050: ANS Forth introduced the idea of ``environmental queries'' as a way
8051: for a program running on a system to determine certain characteristics of the system.
8052: The Standard specifies a number of strings that might be recognised by a system.
8053:
8054: The Standard requires that the header space used for environmental queries
8055: be distinct from the header space used for definitions.
8056:
8057: Typically, environmental queries are supported by creating a set of
8058: definitions in a word list that is @i{only} used during environmental
8059: queries; that is what Gforth does. There is no Standard way of adding
8060: definitions to the set of recognised environmental queries, but any
8061: implementation that supports the loading of optional word sets must have
8062: some mechanism for doing this (after loading the word set, the
8063: associated environmental query string must return @code{true}). In
8064: Gforth, the word list used to honour environmental queries can be
8065: manipulated just like any other word list.
8066:
8067:
8068: doc-environment?
8069: doc-environment-wordlist
8070:
8071: doc-gforth
8072: doc-os-class
8073:
8074:
8075: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8076: returning two items on the stack, querying it using @code{environment?}
8077: will return an additional item; the @code{true} flag that shows that the
8078: string was recognised.
8079:
8080: @comment TODO Document the standard strings or note where they are documented herein
8081:
8082: Here are some examples of using environmental queries:
8083:
8084: @example
8085: s" address-unit-bits" environment? 0=
8086: [IF]
8087: cr .( environmental attribute address-units-bits unknown... ) cr
8088: [ELSE]
8089: drop \ ensure balanced stack effect
8090: [THEN]
8091:
8092: \ this might occur in the prelude of a standard program that uses THROW
8093: s" exception" environment? [IF]
8094: 0= [IF]
8095: : throw abort" exception thrown" ;
8096: [THEN]
8097: [ELSE] \ we don't know, so make sure
8098: : throw abort" exception thrown" ;
8099: [THEN]
8100:
8101: s" gforth" environment? [IF] .( Gforth version ) TYPE
8102: [ELSE] .( Not Gforth..) [THEN]
8103:
8104: \ a program using v*
8105: s" gforth" environment? [IF]
8106: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8107: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8108: >r swap 2swap swap 0e r> 0 ?DO
8109: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8110: LOOP
8111: 2drop 2drop ;
8112: [THEN]
8113: [ELSE] \
8114: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8115: ...
8116: [THEN]
8117: @end example
8118:
8119: Here is an example of adding a definition to the environment word list:
8120:
8121: @example
8122: get-current environment-wordlist set-current
8123: true constant block
8124: true constant block-ext
8125: set-current
8126: @end example
8127:
8128: You can see what definitions are in the environment word list like this:
8129:
8130: @example
8131: environment-wordlist >order words previous
8132: @end example
8133:
8134:
8135: @c -------------------------------------------------------------
8136: @node Files, Blocks, Environmental Queries, Words
8137: @section Files
8138: @cindex files
8139: @cindex I/O - file-handling
8140:
8141: Gforth provides facilities for accessing files that are stored in the
8142: host operating system's file-system. Files that are processed by Gforth
8143: can be divided into two categories:
8144:
8145: @itemize @bullet
8146: @item
8147: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
8148: @item
8149: Files that are processed by some other program (@dfn{general files}).
8150: @end itemize
8151:
8152: @menu
8153: * Forth source files::
8154: * General files::
8155: * Search Paths::
8156: @end menu
8157:
8158: @c -------------------------------------------------------------
8159: @node Forth source files, General files, Files, Files
8160: @subsection Forth source files
8161: @cindex including files
8162: @cindex Forth source files
8163:
8164: The simplest way to interpret the contents of a file is to use one of
8165: these two formats:
8166:
8167: @example
8168: include mysource.fs
8169: s" mysource.fs" included
8170: @end example
8171:
8172: You usually want to include a file only if it is not included already
8173: (by, say, another source file). In that case, you can use one of these
8174: three formats:
8175:
8176: @example
8177: require mysource.fs
8178: needs mysource.fs
8179: s" mysource.fs" required
8180: @end example
8181:
8182: @cindex stack effect of included files
8183: @cindex including files, stack effect
8184: It is good practice to write your source files such that interpreting them
8185: does not change the stack. Source files designed in this way can be used with
8186: @code{required} and friends without complications. For example:
8187:
8188: @example
8189: 1024 require foo.fs drop
8190: @end example
8191:
8192: Here you want to pass the argument 1024 (e.g., a buffer size) to
8193: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8194: ), which allows its use with @code{require}. Of course with such
8195: parameters to required files, you have to ensure that the first
8196: @code{require} fits for all uses (i.e., @code{require} it early in the
8197: master load file).
8198:
8199: doc-include-file
8200: doc-included
8201: doc-included?
8202: doc-include
8203: doc-required
8204: doc-require
8205: doc-needs
8206: @c doc-init-included-files @c internal
8207: doc-sourcefilename
8208: doc-sourceline#
8209:
8210: A definition in ANS Forth for @code{required} is provided in
8211: @file{compat/required.fs}.
8212:
8213: @c -------------------------------------------------------------
8214: @node General files, Search Paths, Forth source files, Files
8215: @subsection General files
8216: @cindex general files
8217: @cindex file-handling
8218:
8219: Files are opened/created by name and type. The following file access
8220: methods (FAMs) are recognised:
8221:
8222: @cindex fam (file access method)
8223: doc-r/o
8224: doc-r/w
8225: doc-w/o
8226: doc-bin
8227:
8228:
8229: When a file is opened/created, it returns a file identifier,
8230: @i{wfileid} that is used for all other file commands. All file
8231: commands also return a status value, @i{wior}, that is 0 for a
8232: successful operation and an implementation-defined non-zero value in the
8233: case of an error.
8234:
8235:
8236: doc-open-file
8237: doc-create-file
8238:
8239: doc-close-file
8240: doc-delete-file
8241: doc-rename-file
8242: doc-read-file
8243: doc-read-line
8244: doc-write-file
8245: doc-write-line
8246: doc-emit-file
8247: doc-flush-file
8248:
8249: doc-file-status
8250: doc-file-position
8251: doc-reposition-file
8252: doc-file-size
8253: doc-resize-file
8254:
8255: doc-slurp-file
8256: doc-slurp-fid
8257: doc-stdin
8258: doc-stdout
8259: doc-stderr
8260:
8261: @c ---------------------------------------------------------
8262: @node Search Paths, , General files, Files
8263: @subsection Search Paths
8264: @cindex path for @code{included}
8265: @cindex file search path
8266: @cindex @code{include} search path
8267: @cindex search path for files
8268:
8269: If you specify an absolute filename (i.e., a filename starting with
8270: @file{/} or @file{~}, or with @file{:} in the second position (as in
8271: @samp{C:...})) for @code{included} and friends, that file is included
8272: just as you would expect.
8273:
8274: If the filename starts with @file{./}, this refers to the directory that
8275: the present file was @code{included} from. This allows files to include
8276: other files relative to their own position (irrespective of the current
8277: working directory or the absolute position). This feature is essential
8278: for libraries consisting of several files, where a file may include
8279: other files from the library. It corresponds to @code{#include "..."}
8280: in C. If the current input source is not a file, @file{.} refers to the
8281: directory of the innermost file being included, or, if there is no file
8282: being included, to the current working directory.
8283:
8284: For relative filenames (not starting with @file{./}), Gforth uses a
8285: search path similar to Forth's search order (@pxref{Word Lists}). It
8286: tries to find the given filename in the directories present in the path,
8287: and includes the first one it finds. There are separate search paths for
8288: Forth source files and general files. If the search path contains the
8289: directory @file{.}, this refers to the directory of the current file, or
8290: the working directory, as if the file had been specified with @file{./}.
8291:
8292: Use @file{~+} to refer to the current working directory (as in the
8293: @code{bash}).
8294:
8295: @c anton: fold the following subsubsections into this subsection?
8296:
8297: @menu
8298: * Source Search Paths::
8299: * General Search Paths::
8300: @end menu
8301:
8302: @c ---------------------------------------------------------
8303: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8304: @subsubsection Source Search Paths
8305: @cindex search path control, source files
8306:
8307: The search path is initialized when you start Gforth (@pxref{Invoking
8308: Gforth}). You can display it and change it using @code{fpath} in
8309: combination with the general path handling words.
8310:
8311: doc-fpath
8312: @c the functionality of the following words is easily available through
8313: @c fpath and the general path words. The may go away.
8314: @c doc-.fpath
8315: @c doc-fpath+
8316: @c doc-fpath=
8317: @c doc-open-fpath-file
8318:
8319: @noindent
8320: Here is an example of using @code{fpath} and @code{require}:
8321:
8322: @example
8323: fpath path= /usr/lib/forth/|./
8324: require timer.fs
8325: @end example
8326:
8327:
8328: @c ---------------------------------------------------------
8329: @node General Search Paths, , Source Search Paths, Search Paths
8330: @subsubsection General Search Paths
8331: @cindex search path control, source files
8332:
8333: Your application may need to search files in several directories, like
8334: @code{included} does. To facilitate this, Gforth allows you to define
8335: and use your own search paths, by providing generic equivalents of the
8336: Forth search path words:
8337:
8338: doc-open-path-file
8339: doc-path-allot
8340: doc-clear-path
8341: doc-also-path
8342: doc-.path
8343: doc-path+
8344: doc-path=
8345:
8346: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
8347:
8348: Here's an example of creating an empty search path:
8349: @c
8350: @example
8351: create mypath 500 path-allot \ maximum length 500 chars (is checked)
8352: @end example
8353:
8354: @c -------------------------------------------------------------
8355: @node Blocks, Other I/O, Files, Words
8356: @section Blocks
8357: @cindex I/O - blocks
8358: @cindex blocks
8359:
8360: When you run Gforth on a modern desk-top computer, it runs under the
8361: control of an operating system which provides certain services. One of
8362: these services is @var{file services}, which allows Forth source code
8363: and data to be stored in files and read into Gforth (@pxref{Files}).
8364:
8365: Traditionally, Forth has been an important programming language on
8366: systems where it has interfaced directly to the underlying hardware with
8367: no intervening operating system. Forth provides a mechanism, called
8368: @dfn{blocks}, for accessing mass storage on such systems.
8369:
8370: A block is a 1024-byte data area, which can be used to hold data or
8371: Forth source code. No structure is imposed on the contents of the
8372: block. A block is identified by its number; blocks are numbered
8373: contiguously from 1 to an implementation-defined maximum.
8374:
8375: A typical system that used blocks but no operating system might use a
8376: single floppy-disk drive for mass storage, with the disks formatted to
8377: provide 256-byte sectors. Blocks would be implemented by assigning the
8378: first four sectors of the disk to block 1, the second four sectors to
8379: block 2 and so on, up to the limit of the capacity of the disk. The disk
8380: would not contain any file system information, just the set of blocks.
8381:
8382: @cindex blocks file
8383: On systems that do provide file services, blocks are typically
8384: implemented by storing a sequence of blocks within a single @dfn{blocks
8385: file}. The size of the blocks file will be an exact multiple of 1024
8386: bytes, corresponding to the number of blocks it contains. This is the
8387: mechanism that Gforth uses.
8388:
8389: @cindex @file{blocks.fb}
8390: Only one blocks file can be open at a time. If you use block words without
8391: having specified a blocks file, Gforth defaults to the blocks file
8392: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
8393: locate a blocks file (@pxref{Source Search Paths}).
8394:
8395: @cindex block buffers
8396: When you read and write blocks under program control, Gforth uses a
8397: number of @dfn{block buffers} as intermediate storage. These buffers are
8398: not used when you use @code{load} to interpret the contents of a block.
8399:
8400: The behaviour of the block buffers is analagous to that of a cache.
8401: Each block buffer has three states:
8402:
8403: @itemize @bullet
8404: @item
8405: Unassigned
8406: @item
8407: Assigned-clean
8408: @item
8409: Assigned-dirty
8410: @end itemize
8411:
8412: Initially, all block buffers are @i{unassigned}. In order to access a
8413: block, the block (specified by its block number) must be assigned to a
8414: block buffer.
8415:
8416: The assignment of a block to a block buffer is performed by @code{block}
8417: or @code{buffer}. Use @code{block} when you wish to modify the existing
8418: contents of a block. Use @code{buffer} when you don't care about the
8419: existing contents of the block@footnote{The ANS Forth definition of
8420: @code{buffer} is intended not to cause disk I/O; if the data associated
8421: with the particular block is already stored in a block buffer due to an
8422: earlier @code{block} command, @code{buffer} will return that block
8423: buffer and the existing contents of the block will be
8424: available. Otherwise, @code{buffer} will simply assign a new, empty
8425: block buffer for the block.}.
8426:
8427: Once a block has been assigned to a block buffer using @code{block} or
8428: @code{buffer}, that block buffer becomes the @i{current block
8429: buffer}. Data may only be manipulated (read or written) within the
8430: current block buffer.
8431:
8432: When the contents of the current block buffer has been modified it is
8433: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
8434: either abandon the changes (by doing nothing) or mark the block as
8435: changed (assigned-dirty), using @code{update}. Using @code{update} does
8436: not change the blocks file; it simply changes a block buffer's state to
8437: @i{assigned-dirty}. The block will be written implicitly when it's
8438: buffer is needed for another block, or explicitly by @code{flush} or
8439: @code{save-buffers}.
8440:
8441: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8442: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8443: @code{flush}.
8444:
8445: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
8446: algorithm to assign a block buffer to a block. That means that any
8447: particular block can only be assigned to one specific block buffer,
8448: called (for the particular operation) the @i{victim buffer}. If the
8449: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8450: the new block immediately. If it is @i{assigned-dirty} its current
8451: contents are written back to the blocks file on disk before it is
8452: allocated to the new block.
8453:
8454: Although no structure is imposed on the contents of a block, it is
8455: traditional to display the contents as 16 lines each of 64 characters. A
8456: block provides a single, continuous stream of input (for example, it
8457: acts as a single parse area) -- there are no end-of-line characters
8458: within a block, and no end-of-file character at the end of a
8459: block. There are two consequences of this:
8460:
8461: @itemize @bullet
8462: @item
8463: The last character of one line wraps straight into the first character
8464: of the following line
8465: @item
8466: The word @code{\} -- comment to end of line -- requires special
8467: treatment; in the context of a block it causes all characters until the
8468: end of the current 64-character ``line'' to be ignored.
8469: @end itemize
8470:
8471: In Gforth, when you use @code{block} with a non-existent block number,
8472: the current blocks file will be extended to the appropriate size and the
8473: block buffer will be initialised with spaces.
8474:
8475: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8476: for details) but doesn't encourage the use of blocks; the mechanism is
8477: only provided for backward compatibility -- ANS Forth requires blocks to
8478: be available when files are.
8479:
8480: Common techniques that are used when working with blocks include:
8481:
8482: @itemize @bullet
8483: @item
8484: A screen editor that allows you to edit blocks without leaving the Forth
8485: environment.
8486: @item
8487: Shadow screens; where every code block has an associated block
8488: containing comments (for example: code in odd block numbers, comments in
8489: even block numbers). Typically, the block editor provides a convenient
8490: mechanism to toggle between code and comments.
8491: @item
8492: Load blocks; a single block (typically block 1) contains a number of
8493: @code{thru} commands which @code{load} the whole of the application.
8494: @end itemize
8495:
8496: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8497: integrated into a Forth programming environment.
8498:
8499: @comment TODO what about errors on open-blocks?
8500:
8501: doc-open-blocks
8502: doc-use
8503: doc-block-offset
8504: doc-get-block-fid
8505: doc-block-position
8506:
8507: doc-list
8508: doc-scr
8509:
8510: doc---gforthman-block
8511: doc-buffer
8512:
8513: doc-empty-buffers
8514: doc-empty-buffer
8515: doc-update
8516: doc-updated?
8517: doc-save-buffers
8518: doc-save-buffer
8519: doc-flush
8520:
8521: doc-load
8522: doc-thru
8523: doc-+load
8524: doc-+thru
8525: doc---gforthman--->
8526: doc-block-included
8527:
8528:
8529: @c -------------------------------------------------------------
8530: @node Other I/O, Locals, Blocks, Words
8531: @section Other I/O
8532: @cindex I/O - keyboard and display
8533:
8534: @menu
8535: * Simple numeric output:: Predefined formats
8536: * Formatted numeric output:: Formatted (pictured) output
8537: * String Formats:: How Forth stores strings in memory
8538: * Displaying characters and strings:: Other stuff
8539: * Input:: Input
8540: * Pipes:: How to create your own pipes
8541: @end menu
8542:
8543: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8544: @subsection Simple numeric output
8545: @cindex numeric output - simple/free-format
8546:
8547: The simplest output functions are those that display numbers from the
8548: data or floating-point stacks. Floating-point output is always displayed
8549: using base 10. Numbers displayed from the data stack use the value stored
8550: in @code{base}.
8551:
8552:
8553: doc-.
8554: doc-dec.
8555: doc-hex.
8556: doc-u.
8557: doc-.r
8558: doc-u.r
8559: doc-d.
8560: doc-ud.
8561: doc-d.r
8562: doc-ud.r
8563: doc-f.
8564: doc-fe.
8565: doc-fs.
8566: doc-f.rdp
8567:
8568: Examples of printing the number 1234.5678E23 in the different floating-point output
8569: formats are shown below:
8570:
8571: @example
8572: f. 123456779999999000000000000.
8573: fe. 123.456779999999E24
8574: fs. 1.23456779999999E26
8575: @end example
8576:
8577:
8578: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8579: @subsection Formatted numeric output
8580: @cindex formatted numeric output
8581: @cindex pictured numeric output
8582: @cindex numeric output - formatted
8583:
8584: Forth traditionally uses a technique called @dfn{pictured numeric
8585: output} for formatted printing of integers. In this technique, digits
8586: are extracted from the number (using the current output radix defined by
8587: @code{base}), converted to ASCII codes and appended to a string that is
8588: built in a scratch-pad area of memory (@pxref{core-idef,
8589: Implementation-defined options, Implementation-defined
8590: options}). Arbitrary characters can be appended to the string during the
8591: extraction process. The completed string is specified by an address
8592: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8593: under program control.
8594:
8595: All of the integer output words described in the previous section
8596: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8597: numeric output.
8598:
8599: Three important things to remember about pictured numeric output:
8600:
8601: @itemize @bullet
8602: @item
8603: It always operates on double-precision numbers; to display a
8604: single-precision number, convert it first (for ways of doing this
8605: @pxref{Double precision}).
8606: @item
8607: It always treats the double-precision number as though it were
8608: unsigned. The examples below show ways of printing signed numbers.
8609: @item
8610: The string is built up from right to left; least significant digit first.
8611: @end itemize
8612:
8613:
8614: doc-<#
8615: doc-<<#
8616: doc-#
8617: doc-#s
8618: doc-hold
8619: doc-sign
8620: doc-#>
8621: doc-#>>
8622:
8623: doc-represent
8624: doc-f>str-rdp
8625: doc-f>buf-rdp
8626:
8627:
8628: @noindent
8629: Here are some examples of using pictured numeric output:
8630:
8631: @example
8632: : my-u. ( u -- )
8633: \ Simplest use of pns.. behaves like Standard u.
8634: 0 \ convert to unsigned double
8635: <<# \ start conversion
8636: #s \ convert all digits
8637: #> \ complete conversion
8638: TYPE SPACE \ display, with trailing space
8639: #>> ; \ release hold area
8640:
8641: : cents-only ( u -- )
8642: 0 \ convert to unsigned double
8643: <<# \ start conversion
8644: # # \ convert two least-significant digits
8645: #> \ complete conversion, discard other digits
8646: TYPE SPACE \ display, with trailing space
8647: #>> ; \ release hold area
8648:
8649: : dollars-and-cents ( u -- )
8650: 0 \ convert to unsigned double
8651: <<# \ start conversion
8652: # # \ convert two least-significant digits
8653: [char] . hold \ insert decimal point
8654: #s \ convert remaining digits
8655: [char] $ hold \ append currency symbol
8656: #> \ complete conversion
8657: TYPE SPACE \ display, with trailing space
8658: #>> ; \ release hold area
8659:
8660: : my-. ( n -- )
8661: \ handling negatives.. behaves like Standard .
8662: s>d \ convert to signed double
8663: swap over dabs \ leave sign byte followed by unsigned double
8664: <<# \ start conversion
8665: #s \ convert all digits
8666: rot sign \ get at sign byte, append "-" if needed
8667: #> \ complete conversion
8668: TYPE SPACE \ display, with trailing space
8669: #>> ; \ release hold area
8670:
8671: : account. ( n -- )
8672: \ accountants don't like minus signs, they use parentheses
8673: \ for negative numbers
8674: s>d \ convert to signed double
8675: swap over dabs \ leave sign byte followed by unsigned double
8676: <<# \ start conversion
8677: 2 pick \ get copy of sign byte
8678: 0< IF [char] ) hold THEN \ right-most character of output
8679: #s \ convert all digits
8680: rot \ get at sign byte
8681: 0< IF [char] ( hold THEN
8682: #> \ complete conversion
8683: TYPE SPACE \ display, with trailing space
8684: #>> ; \ release hold area
8685:
8686: @end example
8687:
8688: Here are some examples of using these words:
8689:
8690: @example
8691: 1 my-u. 1
8692: hex -1 my-u. decimal FFFFFFFF
8693: 1 cents-only 01
8694: 1234 cents-only 34
8695: 2 dollars-and-cents $0.02
8696: 1234 dollars-and-cents $12.34
8697: 123 my-. 123
8698: -123 my. -123
8699: 123 account. 123
8700: -456 account. (456)
8701: @end example
8702:
8703:
8704: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8705: @subsection String Formats
8706: @cindex strings - see character strings
8707: @cindex character strings - formats
8708: @cindex I/O - see character strings
8709: @cindex counted strings
8710:
8711: @c anton: this does not really belong here; maybe the memory section,
8712: @c or the principles chapter
8713:
8714: Forth commonly uses two different methods for representing character
8715: strings:
8716:
8717: @itemize @bullet
8718: @item
8719: @cindex address of counted string
8720: @cindex counted string
8721: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8722: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8723: string and the string occupies the subsequent @i{n} char addresses in
8724: memory.
8725: @item
8726: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8727: of the string in characters, and @i{c-addr} is the address of the
8728: first byte of the string.
8729: @end itemize
8730:
8731: ANS Forth encourages the use of the second format when representing
8732: strings.
8733:
8734:
8735: doc-count
8736:
8737:
8738: For words that move, copy and search for strings see @ref{Memory
8739: Blocks}. For words that display characters and strings see
8740: @ref{Displaying characters and strings}.
8741:
8742: @node Displaying characters and strings, Input, String Formats, Other I/O
8743: @subsection Displaying characters and strings
8744: @cindex characters - compiling and displaying
8745: @cindex character strings - compiling and displaying
8746:
8747: This section starts with a glossary of Forth words and ends with a set
8748: of examples.
8749:
8750:
8751: doc-bl
8752: doc-space
8753: doc-spaces
8754: doc-emit
8755: doc-toupper
8756: doc-."
8757: doc-.(
8758: doc-.\"
8759: doc-type
8760: doc-typewhite
8761: doc-cr
8762: @cindex cursor control
8763: doc-at-xy
8764: doc-page
8765: doc-s"
8766: doc-s\"
8767: doc-c"
8768: doc-char
8769: doc-[char]
8770:
8771:
8772: @noindent
8773: As an example, consider the following text, stored in a file @file{test.fs}:
8774:
8775: @example
8776: .( text-1)
8777: : my-word
8778: ." text-2" cr
8779: .( text-3)
8780: ;
8781:
8782: ." text-4"
8783:
8784: : my-char
8785: [char] ALPHABET emit
8786: char emit
8787: ;
8788: @end example
8789:
8790: When you load this code into Gforth, the following output is generated:
8791:
8792: @example
8793: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
8794: @end example
8795:
8796: @itemize @bullet
8797: @item
8798: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8799: is an immediate word; it behaves in the same way whether it is used inside
8800: or outside a colon definition.
8801: @item
8802: Message @code{text-4} is displayed because of Gforth's added interpretation
8803: semantics for @code{."}.
8804: @item
8805: Message @code{text-2} is @i{not} displayed, because the text interpreter
8806: performs the compilation semantics for @code{."} within the definition of
8807: @code{my-word}.
8808: @end itemize
8809:
8810: Here are some examples of executing @code{my-word} and @code{my-char}:
8811:
8812: @example
8813: @kbd{my-word @key{RET}} text-2
8814: ok
8815: @kbd{my-char fred @key{RET}} Af ok
8816: @kbd{my-char jim @key{RET}} Aj ok
8817: @end example
8818:
8819: @itemize @bullet
8820: @item
8821: Message @code{text-2} is displayed because of the run-time behaviour of
8822: @code{."}.
8823: @item
8824: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8825: on the stack at run-time. @code{emit} always displays the character
8826: when @code{my-char} is executed.
8827: @item
8828: @code{char} parses a string at run-time and the second @code{emit} displays
8829: the first character of the string.
8830: @item
8831: If you type @code{see my-char} you can see that @code{[char]} discarded
8832: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8833: definition of @code{my-char}.
8834: @end itemize
8835:
8836:
8837:
8838: @node Input, Pipes, Displaying characters and strings, Other I/O
8839: @subsection Input
8840: @cindex input
8841: @cindex I/O - see input
8842: @cindex parsing a string
8843:
8844: For ways of storing character strings in memory see @ref{String Formats}.
8845:
8846: @comment TODO examples for >number >float accept key key? pad parse word refill
8847: @comment then index them
8848:
8849:
8850: doc-key
8851: doc-key?
8852: doc-ekey
8853: doc-ekey?
8854: doc-ekey>char
8855: doc->number
8856: doc->float
8857: doc-accept
8858: doc-edit-line
8859: doc-pad
8860: @comment obsolescent words..
8861: doc-convert
8862: doc-expect
8863: doc-span
8864:
8865:
8866: @node Pipes, , Input, Other I/O
8867: @subsection Pipes
8868: @cindex pipes, creating your own
8869:
8870: In addition to using Gforth in pipes created by other processes
8871: (@pxref{Gforth in pipes}), you can create your own pipe with
8872: @code{open-pipe}, and read from or write to it.
8873:
8874: doc-open-pipe
8875: doc-close-pipe
8876:
8877: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
8878: you don't catch this exception, Gforth will catch it and exit, usually
8879: silently (@pxref{Gforth in pipes}). Since you probably do not want
8880: this, you should wrap a @code{catch} or @code{try} block around the code
8881: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
8882: problem yourself, and then return to regular processing.
8883:
8884: doc-broken-pipe-error
8885:
8886:
8887: @node OS command line arguments, Locals, Other I/O, Words
8888: @section OS command line arguments
8889: @cindex OS command line arguments
8890: @cindex command line arguments, OS
8891: @cindex arguments, OS command line
8892:
8893: The usual way to pass arguments to Gforth programs on the command line
8894: is via the @option{-e} option, e.g.
8895:
8896: @example
8897: gforth -e "123 456" foo.fs -e bye
8898: @end example
8899:
8900: However, you may want to interpret the command-line arguments directly.
8901: In that case, you can access the (image-specific) command-line arguments
8902: through @code{next-arg}:
8903:
8904: doc-next-arg
8905:
8906: Here's an example program @file{echo.fs} for @code{next-arg}:
8907:
8908: @example
8909: : echo ( -- )
8910: begin
8911: next-arg 2dup 0 0 d<> while
8912: type space
8913: repeat
8914: 2drop ;
8915:
8916: echo cr bye
8917: @end example
8918:
8919: This can be invoked with
8920:
8921: @example
8922: gforth echo.fs hello world
8923: @end example
8924:
8925: and it will print
8926:
8927: @example
8928: hello world
8929: @end example
8930:
8931: The next lower level of dealing with the OS command line are the
8932: following words:
8933:
8934: doc-arg
8935: doc-shift-args
8936:
8937: Finally, at the lowest level Gforth provides the following words:
8938:
8939: doc-argc
8940: doc-argv
8941:
8942: @c -------------------------------------------------------------
8943: @node Locals, Structures, Other I/O, Words
8944: @section Locals
8945: @cindex locals
8946:
8947: Local variables can make Forth programming more enjoyable and Forth
8948: programs easier to read. Unfortunately, the locals of ANS Forth are
8949: laden with restrictions. Therefore, we provide not only the ANS Forth
8950: locals wordset, but also our own, more powerful locals wordset (we
8951: implemented the ANS Forth locals wordset through our locals wordset).
8952:
8953: The ideas in this section have also been published in M. Anton Ertl,
8954: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
8955: Automatic Scoping of Local Variables}}, EuroForth '94.
8956:
8957: @menu
8958: * Gforth locals::
8959: * ANS Forth locals::
8960: @end menu
8961:
8962: @node Gforth locals, ANS Forth locals, Locals, Locals
8963: @subsection Gforth locals
8964: @cindex Gforth locals
8965: @cindex locals, Gforth style
8966:
8967: Locals can be defined with
8968:
8969: @example
8970: @{ local1 local2 ... -- comment @}
8971: @end example
8972: or
8973: @example
8974: @{ local1 local2 ... @}
8975: @end example
8976:
8977: E.g.,
8978: @example
8979: : max @{ n1 n2 -- n3 @}
8980: n1 n2 > if
8981: n1
8982: else
8983: n2
8984: endif ;
8985: @end example
8986:
8987: The similarity of locals definitions with stack comments is intended. A
8988: locals definition often replaces the stack comment of a word. The order
8989: of the locals corresponds to the order in a stack comment and everything
8990: after the @code{--} is really a comment.
8991:
8992: This similarity has one disadvantage: It is too easy to confuse locals
8993: declarations with stack comments, causing bugs and making them hard to
8994: find. However, this problem can be avoided by appropriate coding
8995: conventions: Do not use both notations in the same program. If you do,
8996: they should be distinguished using additional means, e.g. by position.
8997:
8998: @cindex types of locals
8999: @cindex locals types
9000: The name of the local may be preceded by a type specifier, e.g.,
9001: @code{F:} for a floating point value:
9002:
9003: @example
9004: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9005: \ complex multiplication
9006: Ar Br f* Ai Bi f* f-
9007: Ar Bi f* Ai Br f* f+ ;
9008: @end example
9009:
9010: @cindex flavours of locals
9011: @cindex locals flavours
9012: @cindex value-flavoured locals
9013: @cindex variable-flavoured locals
9014: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9015: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9016: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9017: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9018: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9019: produces its address (which becomes invalid when the variable's scope is
9020: left). E.g., the standard word @code{emit} can be defined in terms of
9021: @code{type} like this:
9022:
9023: @example
9024: : emit @{ C^ char* -- @}
9025: char* 1 type ;
9026: @end example
9027:
9028: @cindex default type of locals
9029: @cindex locals, default type
9030: A local without type specifier is a @code{W:} local. Both flavours of
9031: locals are initialized with values from the data or FP stack.
9032:
9033: Currently there is no way to define locals with user-defined data
9034: structures, but we are working on it.
9035:
9036: Gforth allows defining locals everywhere in a colon definition. This
9037: poses the following questions:
9038:
9039: @menu
9040: * Where are locals visible by name?::
9041: * How long do locals live?::
9042: * Locals programming style::
9043: * Locals implementation::
9044: @end menu
9045:
9046: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9047: @subsubsection Where are locals visible by name?
9048: @cindex locals visibility
9049: @cindex visibility of locals
9050: @cindex scope of locals
9051:
9052: Basically, the answer is that locals are visible where you would expect
9053: it in block-structured languages, and sometimes a little longer. If you
9054: want to restrict the scope of a local, enclose its definition in
9055: @code{SCOPE}...@code{ENDSCOPE}.
9056:
9057:
9058: doc-scope
9059: doc-endscope
9060:
9061:
9062: These words behave like control structure words, so you can use them
9063: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9064: arbitrary ways.
9065:
9066: If you want a more exact answer to the visibility question, here's the
9067: basic principle: A local is visible in all places that can only be
9068: reached through the definition of the local@footnote{In compiler
9069: construction terminology, all places dominated by the definition of the
9070: local.}. In other words, it is not visible in places that can be reached
9071: without going through the definition of the local. E.g., locals defined
9072: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9073: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9074: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
9075:
9076: The reasoning behind this solution is: We want to have the locals
9077: visible as long as it is meaningful. The user can always make the
9078: visibility shorter by using explicit scoping. In a place that can
9079: only be reached through the definition of a local, the meaning of a
9080: local name is clear. In other places it is not: How is the local
9081: initialized at the control flow path that does not contain the
9082: definition? Which local is meant, if the same name is defined twice in
9083: two independent control flow paths?
9084:
9085: This should be enough detail for nearly all users, so you can skip the
9086: rest of this section. If you really must know all the gory details and
9087: options, read on.
9088:
9089: In order to implement this rule, the compiler has to know which places
9090: are unreachable. It knows this automatically after @code{AHEAD},
9091: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9092: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9093: compiler that the control flow never reaches that place. If
9094: @code{UNREACHABLE} is not used where it could, the only consequence is
9095: that the visibility of some locals is more limited than the rule above
9096: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9097: lie to the compiler), buggy code will be produced.
9098:
9099:
9100: doc-unreachable
9101:
9102:
9103: Another problem with this rule is that at @code{BEGIN}, the compiler
9104: does not know which locals will be visible on the incoming
9105: back-edge. All problems discussed in the following are due to this
9106: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9107: loops as examples; the discussion also applies to @code{?DO} and other
9108: loops). Perhaps the most insidious example is:
9109: @example
9110: AHEAD
9111: BEGIN
9112: x
9113: [ 1 CS-ROLL ] THEN
9114: @{ x @}
9115: ...
9116: UNTIL
9117: @end example
9118:
9119: This should be legal according to the visibility rule. The use of
9120: @code{x} can only be reached through the definition; but that appears
9121: textually below the use.
9122:
9123: From this example it is clear that the visibility rules cannot be fully
9124: implemented without major headaches. Our implementation treats common
9125: cases as advertised and the exceptions are treated in a safe way: The
9126: compiler makes a reasonable guess about the locals visible after a
9127: @code{BEGIN}; if it is too pessimistic, the
9128: user will get a spurious error about the local not being defined; if the
9129: compiler is too optimistic, it will notice this later and issue a
9130: warning. In the case above the compiler would complain about @code{x}
9131: being undefined at its use. You can see from the obscure examples in
9132: this section that it takes quite unusual control structures to get the
9133: compiler into trouble, and even then it will often do fine.
9134:
9135: If the @code{BEGIN} is reachable from above, the most optimistic guess
9136: is that all locals visible before the @code{BEGIN} will also be
9137: visible after the @code{BEGIN}. This guess is valid for all loops that
9138: are entered only through the @code{BEGIN}, in particular, for normal
9139: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9140: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9141: compiler. When the branch to the @code{BEGIN} is finally generated by
9142: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9143: warns the user if it was too optimistic:
9144: @example
9145: IF
9146: @{ x @}
9147: BEGIN
9148: \ x ?
9149: [ 1 cs-roll ] THEN
9150: ...
9151: UNTIL
9152: @end example
9153:
9154: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9155: optimistically assumes that it lives until the @code{THEN}. It notices
9156: this difference when it compiles the @code{UNTIL} and issues a
9157: warning. The user can avoid the warning, and make sure that @code{x}
9158: is not used in the wrong area by using explicit scoping:
9159: @example
9160: IF
9161: SCOPE
9162: @{ x @}
9163: ENDSCOPE
9164: BEGIN
9165: [ 1 cs-roll ] THEN
9166: ...
9167: UNTIL
9168: @end example
9169:
9170: Since the guess is optimistic, there will be no spurious error messages
9171: about undefined locals.
9172:
9173: If the @code{BEGIN} is not reachable from above (e.g., after
9174: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9175: optimistic guess, as the locals visible after the @code{BEGIN} may be
9176: defined later. Therefore, the compiler assumes that no locals are
9177: visible after the @code{BEGIN}. However, the user can use
9178: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9179: visible at the BEGIN as at the point where the top control-flow stack
9180: item was created.
9181:
9182:
9183: doc-assume-live
9184:
9185:
9186: @noindent
9187: E.g.,
9188: @example
9189: @{ x @}
9190: AHEAD
9191: ASSUME-LIVE
9192: BEGIN
9193: x
9194: [ 1 CS-ROLL ] THEN
9195: ...
9196: UNTIL
9197: @end example
9198:
9199: Other cases where the locals are defined before the @code{BEGIN} can be
9200: handled by inserting an appropriate @code{CS-ROLL} before the
9201: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9202: behind the @code{ASSUME-LIVE}).
9203:
9204: Cases where locals are defined after the @code{BEGIN} (but should be
9205: visible immediately after the @code{BEGIN}) can only be handled by
9206: rearranging the loop. E.g., the ``most insidious'' example above can be
9207: arranged into:
9208: @example
9209: BEGIN
9210: @{ x @}
9211: ... 0=
9212: WHILE
9213: x
9214: REPEAT
9215: @end example
9216:
9217: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9218: @subsubsection How long do locals live?
9219: @cindex locals lifetime
9220: @cindex lifetime of locals
9221:
9222: The right answer for the lifetime question would be: A local lives at
9223: least as long as it can be accessed. For a value-flavoured local this
9224: means: until the end of its visibility. However, a variable-flavoured
9225: local could be accessed through its address far beyond its visibility
9226: scope. Ultimately, this would mean that such locals would have to be
9227: garbage collected. Since this entails un-Forth-like implementation
9228: complexities, I adopted the same cowardly solution as some other
9229: languages (e.g., C): The local lives only as long as it is visible;
9230: afterwards its address is invalid (and programs that access it
9231: afterwards are erroneous).
9232:
9233: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9234: @subsubsection Locals programming style
9235: @cindex locals programming style
9236: @cindex programming style, locals
9237:
9238: The freedom to define locals anywhere has the potential to change
9239: programming styles dramatically. In particular, the need to use the
9240: return stack for intermediate storage vanishes. Moreover, all stack
9241: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9242: determined arguments) can be eliminated: If the stack items are in the
9243: wrong order, just write a locals definition for all of them; then
9244: write the items in the order you want.
9245:
9246: This seems a little far-fetched and eliminating stack manipulations is
9247: unlikely to become a conscious programming objective. Still, the number
9248: of stack manipulations will be reduced dramatically if local variables
9249: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9250: a traditional implementation of @code{max}).
9251:
9252: This shows one potential benefit of locals: making Forth programs more
9253: readable. Of course, this benefit will only be realized if the
9254: programmers continue to honour the principle of factoring instead of
9255: using the added latitude to make the words longer.
9256:
9257: @cindex single-assignment style for locals
9258: Using @code{TO} can and should be avoided. Without @code{TO},
9259: every value-flavoured local has only a single assignment and many
9260: advantages of functional languages apply to Forth. I.e., programs are
9261: easier to analyse, to optimize and to read: It is clear from the
9262: definition what the local stands for, it does not turn into something
9263: different later.
9264:
9265: E.g., a definition using @code{TO} might look like this:
9266: @example
9267: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9268: u1 u2 min 0
9269: ?do
9270: addr1 c@@ addr2 c@@ -
9271: ?dup-if
9272: unloop exit
9273: then
9274: addr1 char+ TO addr1
9275: addr2 char+ TO addr2
9276: loop
9277: u1 u2 - ;
9278: @end example
9279: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9280: every loop iteration. @code{strcmp} is a typical example of the
9281: readability problems of using @code{TO}. When you start reading
9282: @code{strcmp}, you think that @code{addr1} refers to the start of the
9283: string. Only near the end of the loop you realize that it is something
9284: else.
9285:
9286: This can be avoided by defining two locals at the start of the loop that
9287: are initialized with the right value for the current iteration.
9288: @example
9289: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9290: addr1 addr2
9291: u1 u2 min 0
9292: ?do @{ s1 s2 @}
9293: s1 c@@ s2 c@@ -
9294: ?dup-if
9295: unloop exit
9296: then
9297: s1 char+ s2 char+
9298: loop
9299: 2drop
9300: u1 u2 - ;
9301: @end example
9302: Here it is clear from the start that @code{s1} has a different value
9303: in every loop iteration.
9304:
9305: @node Locals implementation, , Locals programming style, Gforth locals
9306: @subsubsection Locals implementation
9307: @cindex locals implementation
9308: @cindex implementation of locals
9309:
9310: @cindex locals stack
9311: Gforth uses an extra locals stack. The most compelling reason for
9312: this is that the return stack is not float-aligned; using an extra stack
9313: also eliminates the problems and restrictions of using the return stack
9314: as locals stack. Like the other stacks, the locals stack grows toward
9315: lower addresses. A few primitives allow an efficient implementation:
9316:
9317:
9318: doc-@local#
9319: doc-f@local#
9320: doc-laddr#
9321: doc-lp+!#
9322: doc-lp!
9323: doc->l
9324: doc-f>l
9325:
9326:
9327: In addition to these primitives, some specializations of these
9328: primitives for commonly occurring inline arguments are provided for
9329: efficiency reasons, e.g., @code{@@local0} as specialization of
9330: @code{@@local#} for the inline argument 0. The following compiling words
9331: compile the right specialized version, or the general version, as
9332: appropriate:
9333:
9334:
9335: @c doc-compile-@local
9336: @c doc-compile-f@local
9337: doc-compile-lp+!
9338:
9339:
9340: Combinations of conditional branches and @code{lp+!#} like
9341: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9342: is taken) are provided for efficiency and correctness in loops.
9343:
9344: A special area in the dictionary space is reserved for keeping the
9345: local variable names. @code{@{} switches the dictionary pointer to this
9346: area and @code{@}} switches it back and generates the locals
9347: initializing code. @code{W:} etc.@ are normal defining words. This
9348: special area is cleared at the start of every colon definition.
9349:
9350: @cindex word list for defining locals
9351: A special feature of Gforth's dictionary is used to implement the
9352: definition of locals without type specifiers: every word list (aka
9353: vocabulary) has its own methods for searching
9354: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9355: with a special search method: When it is searched for a word, it
9356: actually creates that word using @code{W:}. @code{@{} changes the search
9357: order to first search the word list containing @code{@}}, @code{W:} etc.,
9358: and then the word list for defining locals without type specifiers.
9359:
9360: The lifetime rules support a stack discipline within a colon
9361: definition: The lifetime of a local is either nested with other locals
9362: lifetimes or it does not overlap them.
9363:
9364: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9365: pointer manipulation is generated. Between control structure words
9366: locals definitions can push locals onto the locals stack. @code{AGAIN}
9367: is the simplest of the other three control flow words. It has to
9368: restore the locals stack depth of the corresponding @code{BEGIN}
9369: before branching. The code looks like this:
9370: @format
9371: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9372: @code{branch} <begin>
9373: @end format
9374:
9375: @code{UNTIL} is a little more complicated: If it branches back, it
9376: must adjust the stack just like @code{AGAIN}. But if it falls through,
9377: the locals stack must not be changed. The compiler generates the
9378: following code:
9379: @format
9380: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9381: @end format
9382: The locals stack pointer is only adjusted if the branch is taken.
9383:
9384: @code{THEN} can produce somewhat inefficient code:
9385: @format
9386: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9387: <orig target>:
9388: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9389: @end format
9390: The second @code{lp+!#} adjusts the locals stack pointer from the
9391: level at the @i{orig} point to the level after the @code{THEN}. The
9392: first @code{lp+!#} adjusts the locals stack pointer from the current
9393: level to the level at the orig point, so the complete effect is an
9394: adjustment from the current level to the right level after the
9395: @code{THEN}.
9396:
9397: @cindex locals information on the control-flow stack
9398: @cindex control-flow stack items, locals information
9399: In a conventional Forth implementation a dest control-flow stack entry
9400: is just the target address and an orig entry is just the address to be
9401: patched. Our locals implementation adds a word list to every orig or dest
9402: item. It is the list of locals visible (or assumed visible) at the point
9403: described by the entry. Our implementation also adds a tag to identify
9404: the kind of entry, in particular to differentiate between live and dead
9405: (reachable and unreachable) orig entries.
9406:
9407: A few unusual operations have to be performed on locals word lists:
9408:
9409:
9410: doc-common-list
9411: doc-sub-list?
9412: doc-list-size
9413:
9414:
9415: Several features of our locals word list implementation make these
9416: operations easy to implement: The locals word lists are organised as
9417: linked lists; the tails of these lists are shared, if the lists
9418: contain some of the same locals; and the address of a name is greater
9419: than the address of the names behind it in the list.
9420:
9421: Another important implementation detail is the variable
9422: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9423: determine if they can be reached directly or only through the branch
9424: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9425: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9426: definition, by @code{BEGIN} and usually by @code{THEN}.
9427:
9428: Counted loops are similar to other loops in most respects, but
9429: @code{LEAVE} requires special attention: It performs basically the same
9430: service as @code{AHEAD}, but it does not create a control-flow stack
9431: entry. Therefore the information has to be stored elsewhere;
9432: traditionally, the information was stored in the target fields of the
9433: branches created by the @code{LEAVE}s, by organizing these fields into a
9434: linked list. Unfortunately, this clever trick does not provide enough
9435: space for storing our extended control flow information. Therefore, we
9436: introduce another stack, the leave stack. It contains the control-flow
9437: stack entries for all unresolved @code{LEAVE}s.
9438:
9439: Local names are kept until the end of the colon definition, even if
9440: they are no longer visible in any control-flow path. In a few cases
9441: this may lead to increased space needs for the locals name area, but
9442: usually less than reclaiming this space would cost in code size.
9443:
9444:
9445: @node ANS Forth locals, , Gforth locals, Locals
9446: @subsection ANS Forth locals
9447: @cindex locals, ANS Forth style
9448:
9449: The ANS Forth locals wordset does not define a syntax for locals, but
9450: words that make it possible to define various syntaxes. One of the
9451: possible syntaxes is a subset of the syntax we used in the Gforth locals
9452: wordset, i.e.:
9453:
9454: @example
9455: @{ local1 local2 ... -- comment @}
9456: @end example
9457: @noindent
9458: or
9459: @example
9460: @{ local1 local2 ... @}
9461: @end example
9462:
9463: The order of the locals corresponds to the order in a stack comment. The
9464: restrictions are:
9465:
9466: @itemize @bullet
9467: @item
9468: Locals can only be cell-sized values (no type specifiers are allowed).
9469: @item
9470: Locals can be defined only outside control structures.
9471: @item
9472: Locals can interfere with explicit usage of the return stack. For the
9473: exact (and long) rules, see the standard. If you don't use return stack
9474: accessing words in a definition using locals, you will be all right. The
9475: purpose of this rule is to make locals implementation on the return
9476: stack easier.
9477: @item
9478: The whole definition must be in one line.
9479: @end itemize
9480:
9481: Locals defined in ANS Forth behave like @code{VALUE}s
9482: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9483: name produces their value. Their value can be changed using @code{TO}.
9484:
9485: Since the syntax above is supported by Gforth directly, you need not do
9486: anything to use it. If you want to port a program using this syntax to
9487: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9488: syntax on the other system.
9489:
9490: Note that a syntax shown in the standard, section A.13 looks
9491: similar, but is quite different in having the order of locals
9492: reversed. Beware!
9493:
9494: The ANS Forth locals wordset itself consists of one word:
9495:
9496: doc-(local)
9497:
9498: The ANS Forth locals extension wordset defines a syntax using
9499: @code{locals|}, but it is so awful that we strongly recommend not to use
9500: it. We have implemented this syntax to make porting to Gforth easy, but
9501: do not document it here. The problem with this syntax is that the locals
9502: are defined in an order reversed with respect to the standard stack
9503: comment notation, making programs harder to read, and easier to misread
9504: and miswrite. The only merit of this syntax is that it is easy to
9505: implement using the ANS Forth locals wordset.
9506:
9507:
9508: @c ----------------------------------------------------------
9509: @node Structures, Object-oriented Forth, Locals, Words
9510: @section Structures
9511: @cindex structures
9512: @cindex records
9513:
9514: This section presents the structure package that comes with Gforth. A
9515: version of the package implemented in ANS Forth is available in
9516: @file{compat/struct.fs}. This package was inspired by a posting on
9517: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9518: possibly John Hayes). A version of this section has been published in
9519: M. Anton Ertl,
9520: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9521: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9522: 13--16. Marcel Hendrix provided helpful comments.
9523:
9524: @menu
9525: * Why explicit structure support?::
9526: * Structure Usage::
9527: * Structure Naming Convention::
9528: * Structure Implementation::
9529: * Structure Glossary::
9530: @end menu
9531:
9532: @node Why explicit structure support?, Structure Usage, Structures, Structures
9533: @subsection Why explicit structure support?
9534:
9535: @cindex address arithmetic for structures
9536: @cindex structures using address arithmetic
9537: If we want to use a structure containing several fields, we could simply
9538: reserve memory for it, and access the fields using address arithmetic
9539: (@pxref{Address arithmetic}). As an example, consider a structure with
9540: the following fields
9541:
9542: @table @code
9543: @item a
9544: is a float
9545: @item b
9546: is a cell
9547: @item c
9548: is a float
9549: @end table
9550:
9551: Given the (float-aligned) base address of the structure we get the
9552: address of the field
9553:
9554: @table @code
9555: @item a
9556: without doing anything further.
9557: @item b
9558: with @code{float+}
9559: @item c
9560: with @code{float+ cell+ faligned}
9561: @end table
9562:
9563: It is easy to see that this can become quite tiring.
9564:
9565: Moreover, it is not very readable, because seeing a
9566: @code{cell+} tells us neither which kind of structure is
9567: accessed nor what field is accessed; we have to somehow infer the kind
9568: of structure, and then look up in the documentation, which field of
9569: that structure corresponds to that offset.
9570:
9571: Finally, this kind of address arithmetic also causes maintenance
9572: troubles: If you add or delete a field somewhere in the middle of the
9573: structure, you have to find and change all computations for the fields
9574: afterwards.
9575:
9576: So, instead of using @code{cell+} and friends directly, how
9577: about storing the offsets in constants:
9578:
9579: @example
9580: 0 constant a-offset
9581: 0 float+ constant b-offset
9582: 0 float+ cell+ faligned c-offset
9583: @end example
9584:
9585: Now we can get the address of field @code{x} with @code{x-offset
9586: +}. This is much better in all respects. Of course, you still
9587: have to change all later offset definitions if you add a field. You can
9588: fix this by declaring the offsets in the following way:
9589:
9590: @example
9591: 0 constant a-offset
9592: a-offset float+ constant b-offset
9593: b-offset cell+ faligned constant c-offset
9594: @end example
9595:
9596: Since we always use the offsets with @code{+}, we could use a defining
9597: word @code{cfield} that includes the @code{+} in the action of the
9598: defined word:
9599:
9600: @example
9601: : cfield ( n "name" -- )
9602: create ,
9603: does> ( name execution: addr1 -- addr2 )
9604: @@ + ;
9605:
9606: 0 cfield a
9607: 0 a float+ cfield b
9608: 0 b cell+ faligned cfield c
9609: @end example
9610:
9611: Instead of @code{x-offset +}, we now simply write @code{x}.
9612:
9613: The structure field words now can be used quite nicely. However,
9614: their definition is still a bit cumbersome: We have to repeat the
9615: name, the information about size and alignment is distributed before
9616: and after the field definitions etc. The structure package presented
9617: here addresses these problems.
9618:
9619: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9620: @subsection Structure Usage
9621: @cindex structure usage
9622:
9623: @cindex @code{field} usage
9624: @cindex @code{struct} usage
9625: @cindex @code{end-struct} usage
9626: You can define a structure for a (data-less) linked list with:
9627: @example
9628: struct
9629: cell% field list-next
9630: end-struct list%
9631: @end example
9632:
9633: With the address of the list node on the stack, you can compute the
9634: address of the field that contains the address of the next node with
9635: @code{list-next}. E.g., you can determine the length of a list
9636: with:
9637:
9638: @example
9639: : list-length ( list -- n )
9640: \ "list" is a pointer to the first element of a linked list
9641: \ "n" is the length of the list
9642: 0 BEGIN ( list1 n1 )
9643: over
9644: WHILE ( list1 n1 )
9645: 1+ swap list-next @@ swap
9646: REPEAT
9647: nip ;
9648: @end example
9649:
9650: You can reserve memory for a list node in the dictionary with
9651: @code{list% %allot}, which leaves the address of the list node on the
9652: stack. For the equivalent allocation on the heap you can use @code{list%
9653: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9654: use @code{list% %allocate}). You can get the the size of a list
9655: node with @code{list% %size} and its alignment with @code{list%
9656: %alignment}.
9657:
9658: Note that in ANS Forth the body of a @code{create}d word is
9659: @code{aligned} but not necessarily @code{faligned};
9660: therefore, if you do a:
9661:
9662: @example
9663: create @emph{name} foo% %allot drop
9664: @end example
9665:
9666: @noindent
9667: then the memory alloted for @code{foo%} is guaranteed to start at the
9668: body of @code{@emph{name}} only if @code{foo%} contains only character,
9669: cell and double fields. Therefore, if your structure contains floats,
9670: better use
9671:
9672: @example
9673: foo% %allot constant @emph{name}
9674: @end example
9675:
9676: @cindex structures containing structures
9677: You can include a structure @code{foo%} as a field of
9678: another structure, like this:
9679: @example
9680: struct
9681: ...
9682: foo% field ...
9683: ...
9684: end-struct ...
9685: @end example
9686:
9687: @cindex structure extension
9688: @cindex extended records
9689: Instead of starting with an empty structure, you can extend an
9690: existing structure. E.g., a plain linked list without data, as defined
9691: above, is hardly useful; You can extend it to a linked list of integers,
9692: like this:@footnote{This feature is also known as @emph{extended
9693: records}. It is the main innovation in the Oberon language; in other
9694: words, adding this feature to Modula-2 led Wirth to create a new
9695: language, write a new compiler etc. Adding this feature to Forth just
9696: required a few lines of code.}
9697:
9698: @example
9699: list%
9700: cell% field intlist-int
9701: end-struct intlist%
9702: @end example
9703:
9704: @code{intlist%} is a structure with two fields:
9705: @code{list-next} and @code{intlist-int}.
9706:
9707: @cindex structures containing arrays
9708: You can specify an array type containing @emph{n} elements of
9709: type @code{foo%} like this:
9710:
9711: @example
9712: foo% @emph{n} *
9713: @end example
9714:
9715: You can use this array type in any place where you can use a normal
9716: type, e.g., when defining a @code{field}, or with
9717: @code{%allot}.
9718:
9719: @cindex first field optimization
9720: The first field is at the base address of a structure and the word for
9721: this field (e.g., @code{list-next}) actually does not change the address
9722: on the stack. You may be tempted to leave it away in the interest of
9723: run-time and space efficiency. This is not necessary, because the
9724: structure package optimizes this case: If you compile a first-field
9725: words, no code is generated. So, in the interest of readability and
9726: maintainability you should include the word for the field when accessing
9727: the field.
9728:
9729:
9730: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9731: @subsection Structure Naming Convention
9732: @cindex structure naming convention
9733:
9734: The field names that come to (my) mind are often quite generic, and,
9735: if used, would cause frequent name clashes. E.g., many structures
9736: probably contain a @code{counter} field. The structure names
9737: that come to (my) mind are often also the logical choice for the names
9738: of words that create such a structure.
9739:
9740: Therefore, I have adopted the following naming conventions:
9741:
9742: @itemize @bullet
9743: @cindex field naming convention
9744: @item
9745: The names of fields are of the form
9746: @code{@emph{struct}-@emph{field}}, where
9747: @code{@emph{struct}} is the basic name of the structure, and
9748: @code{@emph{field}} is the basic name of the field. You can
9749: think of field words as converting the (address of the)
9750: structure into the (address of the) field.
9751:
9752: @cindex structure naming convention
9753: @item
9754: The names of structures are of the form
9755: @code{@emph{struct}%}, where
9756: @code{@emph{struct}} is the basic name of the structure.
9757: @end itemize
9758:
9759: This naming convention does not work that well for fields of extended
9760: structures; e.g., the integer list structure has a field
9761: @code{intlist-int}, but has @code{list-next}, not
9762: @code{intlist-next}.
9763:
9764: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9765: @subsection Structure Implementation
9766: @cindex structure implementation
9767: @cindex implementation of structures
9768:
9769: The central idea in the implementation is to pass the data about the
9770: structure being built on the stack, not in some global
9771: variable. Everything else falls into place naturally once this design
9772: decision is made.
9773:
9774: The type description on the stack is of the form @emph{align
9775: size}. Keeping the size on the top-of-stack makes dealing with arrays
9776: very simple.
9777:
9778: @code{field} is a defining word that uses @code{Create}
9779: and @code{DOES>}. The body of the field contains the offset
9780: of the field, and the normal @code{DOES>} action is simply:
9781:
9782: @example
9783: @@ +
9784: @end example
9785:
9786: @noindent
9787: i.e., add the offset to the address, giving the stack effect
9788: @i{addr1 -- addr2} for a field.
9789:
9790: @cindex first field optimization, implementation
9791: This simple structure is slightly complicated by the optimization
9792: for fields with offset 0, which requires a different
9793: @code{DOES>}-part (because we cannot rely on there being
9794: something on the stack if such a field is invoked during
9795: compilation). Therefore, we put the different @code{DOES>}-parts
9796: in separate words, and decide which one to invoke based on the
9797: offset. For a zero offset, the field is basically a noop; it is
9798: immediate, and therefore no code is generated when it is compiled.
9799:
9800: @node Structure Glossary, , Structure Implementation, Structures
9801: @subsection Structure Glossary
9802: @cindex structure glossary
9803:
9804:
9805: doc-%align
9806: doc-%alignment
9807: doc-%alloc
9808: doc-%allocate
9809: doc-%allot
9810: doc-cell%
9811: doc-char%
9812: doc-dfloat%
9813: doc-double%
9814: doc-end-struct
9815: doc-field
9816: doc-float%
9817: doc-naligned
9818: doc-sfloat%
9819: doc-%size
9820: doc-struct
9821:
9822:
9823: @c -------------------------------------------------------------
9824: @node Object-oriented Forth, Programming Tools, Structures, Words
9825: @section Object-oriented Forth
9826:
9827: Gforth comes with three packages for object-oriented programming:
9828: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9829: is preloaded, so you have to @code{include} them before use. The most
9830: important differences between these packages (and others) are discussed
9831: in @ref{Comparison with other object models}. All packages are written
9832: in ANS Forth and can be used with any other ANS Forth.
9833:
9834: @menu
9835: * Why object-oriented programming?::
9836: * Object-Oriented Terminology::
9837: * Objects::
9838: * OOF::
9839: * Mini-OOF::
9840: * Comparison with other object models::
9841: @end menu
9842:
9843: @c ----------------------------------------------------------------
9844: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9845: @subsection Why object-oriented programming?
9846: @cindex object-oriented programming motivation
9847: @cindex motivation for object-oriented programming
9848:
9849: Often we have to deal with several data structures (@emph{objects}),
9850: that have to be treated similarly in some respects, but differently in
9851: others. Graphical objects are the textbook example: circles, triangles,
9852: dinosaurs, icons, and others, and we may want to add more during program
9853: development. We want to apply some operations to any graphical object,
9854: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9855: has to do something different for every kind of object.
9856: @comment TODO add some other operations eg perimeter, area
9857: @comment and tie in to concrete examples later..
9858:
9859: We could implement @code{draw} as a big @code{CASE}
9860: control structure that executes the appropriate code depending on the
9861: kind of object to be drawn. This would be not be very elegant, and,
9862: moreover, we would have to change @code{draw} every time we add
9863: a new kind of graphical object (say, a spaceship).
9864:
9865: What we would rather do is: When defining spaceships, we would tell
9866: the system: ``Here's how you @code{draw} a spaceship; you figure
9867: out the rest''.
9868:
9869: This is the problem that all systems solve that (rightfully) call
9870: themselves object-oriented; the object-oriented packages presented here
9871: solve this problem (and not much else).
9872: @comment TODO ?list properties of oo systems.. oo vs o-based?
9873:
9874: @c ------------------------------------------------------------------------
9875: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
9876: @subsection Object-Oriented Terminology
9877: @cindex object-oriented terminology
9878: @cindex terminology for object-oriented programming
9879:
9880: This section is mainly for reference, so you don't have to understand
9881: all of it right away. The terminology is mainly Smalltalk-inspired. In
9882: short:
9883:
9884: @table @emph
9885: @cindex class
9886: @item class
9887: a data structure definition with some extras.
9888:
9889: @cindex object
9890: @item object
9891: an instance of the data structure described by the class definition.
9892:
9893: @cindex instance variables
9894: @item instance variables
9895: fields of the data structure.
9896:
9897: @cindex selector
9898: @cindex method selector
9899: @cindex virtual function
9900: @item selector
9901: (or @emph{method selector}) a word (e.g.,
9902: @code{draw}) that performs an operation on a variety of data
9903: structures (classes). A selector describes @emph{what} operation to
9904: perform. In C++ terminology: a (pure) virtual function.
9905:
9906: @cindex method
9907: @item method
9908: the concrete definition that performs the operation
9909: described by the selector for a specific class. A method specifies
9910: @emph{how} the operation is performed for a specific class.
9911:
9912: @cindex selector invocation
9913: @cindex message send
9914: @cindex invoking a selector
9915: @item selector invocation
9916: a call of a selector. One argument of the call (the TOS (top-of-stack))
9917: is used for determining which method is used. In Smalltalk terminology:
9918: a message (consisting of the selector and the other arguments) is sent
9919: to the object.
9920:
9921: @cindex receiving object
9922: @item receiving object
9923: the object used for determining the method executed by a selector
9924: invocation. In the @file{objects.fs} model, it is the object that is on
9925: the TOS when the selector is invoked. (@emph{Receiving} comes from
9926: the Smalltalk @emph{message} terminology.)
9927:
9928: @cindex child class
9929: @cindex parent class
9930: @cindex inheritance
9931: @item child class
9932: a class that has (@emph{inherits}) all properties (instance variables,
9933: selectors, methods) from a @emph{parent class}. In Smalltalk
9934: terminology: The subclass inherits from the superclass. In C++
9935: terminology: The derived class inherits from the base class.
9936:
9937: @end table
9938:
9939: @c If you wonder about the message sending terminology, it comes from
9940: @c a time when each object had it's own task and objects communicated via
9941: @c message passing; eventually the Smalltalk developers realized that
9942: @c they can do most things through simple (indirect) calls. They kept the
9943: @c terminology.
9944:
9945: @c --------------------------------------------------------------
9946: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
9947: @subsection The @file{objects.fs} model
9948: @cindex objects
9949: @cindex object-oriented programming
9950:
9951: @cindex @file{objects.fs}
9952: @cindex @file{oof.fs}
9953:
9954: This section describes the @file{objects.fs} package. This material also
9955: has been published in M. Anton Ertl,
9956: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
9957: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
9958: 37--43.
9959: @c McKewan's and Zsoter's packages
9960:
9961: This section assumes that you have read @ref{Structures}.
9962:
9963: The techniques on which this model is based have been used to implement
9964: the parser generator, Gray, and have also been used in Gforth for
9965: implementing the various flavours of word lists (hashed or not,
9966: case-sensitive or not, special-purpose word lists for locals etc.).
9967:
9968:
9969: @menu
9970: * Properties of the Objects model::
9971: * Basic Objects Usage::
9972: * The Objects base class::
9973: * Creating objects::
9974: * Object-Oriented Programming Style::
9975: * Class Binding::
9976: * Method conveniences::
9977: * Classes and Scoping::
9978: * Dividing classes::
9979: * Object Interfaces::
9980: * Objects Implementation::
9981: * Objects Glossary::
9982: @end menu
9983:
9984: Marcel Hendrix provided helpful comments on this section.
9985:
9986: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
9987: @subsubsection Properties of the @file{objects.fs} model
9988: @cindex @file{objects.fs} properties
9989:
9990: @itemize @bullet
9991: @item
9992: It is straightforward to pass objects on the stack. Passing
9993: selectors on the stack is a little less convenient, but possible.
9994:
9995: @item
9996: Objects are just data structures in memory, and are referenced by their
9997: address. You can create words for objects with normal defining words
9998: like @code{constant}. Likewise, there is no difference between instance
9999: variables that contain objects and those that contain other data.
10000:
10001: @item
10002: Late binding is efficient and easy to use.
10003:
10004: @item
10005: It avoids parsing, and thus avoids problems with state-smartness
10006: and reduced extensibility; for convenience there are a few parsing
10007: words, but they have non-parsing counterparts. There are also a few
10008: defining words that parse. This is hard to avoid, because all standard
10009: defining words parse (except @code{:noname}); however, such
10010: words are not as bad as many other parsing words, because they are not
10011: state-smart.
10012:
10013: @item
10014: It does not try to incorporate everything. It does a few things and does
10015: them well (IMO). In particular, this model was not designed to support
10016: information hiding (although it has features that may help); you can use
10017: a separate package for achieving this.
10018:
10019: @item
10020: It is layered; you don't have to learn and use all features to use this
10021: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10022: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10023: are optional and independent of each other.
10024:
10025: @item
10026: An implementation in ANS Forth is available.
10027:
10028: @end itemize
10029:
10030:
10031: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10032: @subsubsection Basic @file{objects.fs} Usage
10033: @cindex basic objects usage
10034: @cindex objects, basic usage
10035:
10036: You can define a class for graphical objects like this:
10037:
10038: @cindex @code{class} usage
10039: @cindex @code{end-class} usage
10040: @cindex @code{selector} usage
10041: @example
10042: object class \ "object" is the parent class
10043: selector draw ( x y graphical -- )
10044: end-class graphical
10045: @end example
10046:
10047: This code defines a class @code{graphical} with an
10048: operation @code{draw}. We can perform the operation
10049: @code{draw} on any @code{graphical} object, e.g.:
10050:
10051: @example
10052: 100 100 t-rex draw
10053: @end example
10054:
10055: @noindent
10056: where @code{t-rex} is a word (say, a constant) that produces a
10057: graphical object.
10058:
10059: @comment TODO add a 2nd operation eg perimeter.. and use for
10060: @comment a concrete example
10061:
10062: @cindex abstract class
10063: How do we create a graphical object? With the present definitions,
10064: we cannot create a useful graphical object. The class
10065: @code{graphical} describes graphical objects in general, but not
10066: any concrete graphical object type (C++ users would call it an
10067: @emph{abstract class}); e.g., there is no method for the selector
10068: @code{draw} in the class @code{graphical}.
10069:
10070: For concrete graphical objects, we define child classes of the
10071: class @code{graphical}, e.g.:
10072:
10073: @cindex @code{overrides} usage
10074: @cindex @code{field} usage in class definition
10075: @example
10076: graphical class \ "graphical" is the parent class
10077: cell% field circle-radius
10078:
10079: :noname ( x y circle -- )
10080: circle-radius @@ draw-circle ;
10081: overrides draw
10082:
10083: :noname ( n-radius circle -- )
10084: circle-radius ! ;
10085: overrides construct
10086:
10087: end-class circle
10088: @end example
10089:
10090: Here we define a class @code{circle} as a child of @code{graphical},
10091: with field @code{circle-radius} (which behaves just like a field
10092: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10093: for the selectors @code{draw} and @code{construct} (@code{construct} is
10094: defined in @code{object}, the parent class of @code{graphical}).
10095:
10096: Now we can create a circle on the heap (i.e.,
10097: @code{allocate}d memory) with:
10098:
10099: @cindex @code{heap-new} usage
10100: @example
10101: 50 circle heap-new constant my-circle
10102: @end example
10103:
10104: @noindent
10105: @code{heap-new} invokes @code{construct}, thus
10106: initializing the field @code{circle-radius} with 50. We can draw
10107: this new circle at (100,100) with:
10108:
10109: @example
10110: 100 100 my-circle draw
10111: @end example
10112:
10113: @cindex selector invocation, restrictions
10114: @cindex class definition, restrictions
10115: Note: You can only invoke a selector if the object on the TOS
10116: (the receiving object) belongs to the class where the selector was
10117: defined or one of its descendents; e.g., you can invoke
10118: @code{draw} only for objects belonging to @code{graphical}
10119: or its descendents (e.g., @code{circle}). Immediately before
10120: @code{end-class}, the search order has to be the same as
10121: immediately after @code{class}.
10122:
10123: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10124: @subsubsection The @file{object.fs} base class
10125: @cindex @code{object} class
10126:
10127: When you define a class, you have to specify a parent class. So how do
10128: you start defining classes? There is one class available from the start:
10129: @code{object}. It is ancestor for all classes and so is the
10130: only class that has no parent. It has two selectors: @code{construct}
10131: and @code{print}.
10132:
10133: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10134: @subsubsection Creating objects
10135: @cindex creating objects
10136: @cindex object creation
10137: @cindex object allocation options
10138:
10139: @cindex @code{heap-new} discussion
10140: @cindex @code{dict-new} discussion
10141: @cindex @code{construct} discussion
10142: You can create and initialize an object of a class on the heap with
10143: @code{heap-new} ( ... class -- object ) and in the dictionary
10144: (allocation with @code{allot}) with @code{dict-new} (
10145: ... class -- object ). Both words invoke @code{construct}, which
10146: consumes the stack items indicated by "..." above.
10147:
10148: @cindex @code{init-object} discussion
10149: @cindex @code{class-inst-size} discussion
10150: If you want to allocate memory for an object yourself, you can get its
10151: alignment and size with @code{class-inst-size 2@@} ( class --
10152: align size ). Once you have memory for an object, you can initialize
10153: it with @code{init-object} ( ... class object -- );
10154: @code{construct} does only a part of the necessary work.
10155:
10156: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10157: @subsubsection Object-Oriented Programming Style
10158: @cindex object-oriented programming style
10159: @cindex programming style, object-oriented
10160:
10161: This section is not exhaustive.
10162:
10163: @cindex stack effects of selectors
10164: @cindex selectors and stack effects
10165: In general, it is a good idea to ensure that all methods for the
10166: same selector have the same stack effect: when you invoke a selector,
10167: you often have no idea which method will be invoked, so, unless all
10168: methods have the same stack effect, you will not know the stack effect
10169: of the selector invocation.
10170:
10171: One exception to this rule is methods for the selector
10172: @code{construct}. We know which method is invoked, because we
10173: specify the class to be constructed at the same place. Actually, I
10174: defined @code{construct} as a selector only to give the users a
10175: convenient way to specify initialization. The way it is used, a
10176: mechanism different from selector invocation would be more natural
10177: (but probably would take more code and more space to explain).
10178:
10179: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10180: @subsubsection Class Binding
10181: @cindex class binding
10182: @cindex early binding
10183:
10184: @cindex late binding
10185: Normal selector invocations determine the method at run-time depending
10186: on the class of the receiving object. This run-time selection is called
10187: @i{late binding}.
10188:
10189: Sometimes it's preferable to invoke a different method. For example,
10190: you might want to use the simple method for @code{print}ing
10191: @code{object}s instead of the possibly long-winded @code{print} method
10192: of the receiver class. You can achieve this by replacing the invocation
10193: of @code{print} with:
10194:
10195: @cindex @code{[bind]} usage
10196: @example
10197: [bind] object print
10198: @end example
10199:
10200: @noindent
10201: in compiled code or:
10202:
10203: @cindex @code{bind} usage
10204: @example
10205: bind object print
10206: @end example
10207:
10208: @cindex class binding, alternative to
10209: @noindent
10210: in interpreted code. Alternatively, you can define the method with a
10211: name (e.g., @code{print-object}), and then invoke it through the
10212: name. Class binding is just a (often more convenient) way to achieve
10213: the same effect; it avoids name clutter and allows you to invoke
10214: methods directly without naming them first.
10215:
10216: @cindex superclass binding
10217: @cindex parent class binding
10218: A frequent use of class binding is this: When we define a method
10219: for a selector, we often want the method to do what the selector does
10220: in the parent class, and a little more. There is a special word for
10221: this purpose: @code{[parent]}; @code{[parent]
10222: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10223: selector}}, where @code{@emph{parent}} is the parent
10224: class of the current class. E.g., a method definition might look like:
10225:
10226: @cindex @code{[parent]} usage
10227: @example
10228: :noname
10229: dup [parent] foo \ do parent's foo on the receiving object
10230: ... \ do some more
10231: ; overrides foo
10232: @end example
10233:
10234: @cindex class binding as optimization
10235: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10236: March 1997), Andrew McKewan presents class binding as an optimization
10237: technique. I recommend not using it for this purpose unless you are in
10238: an emergency. Late binding is pretty fast with this model anyway, so the
10239: benefit of using class binding is small; the cost of using class binding
10240: where it is not appropriate is reduced maintainability.
10241:
10242: While we are at programming style questions: You should bind
10243: selectors only to ancestor classes of the receiving object. E.g., say,
10244: you know that the receiving object is of class @code{foo} or its
10245: descendents; then you should bind only to @code{foo} and its
10246: ancestors.
10247:
10248: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10249: @subsubsection Method conveniences
10250: @cindex method conveniences
10251:
10252: In a method you usually access the receiving object pretty often. If
10253: you define the method as a plain colon definition (e.g., with
10254: @code{:noname}), you may have to do a lot of stack
10255: gymnastics. To avoid this, you can define the method with @code{m:
10256: ... ;m}. E.g., you could define the method for
10257: @code{draw}ing a @code{circle} with
10258:
10259: @cindex @code{this} usage
10260: @cindex @code{m:} usage
10261: @cindex @code{;m} usage
10262: @example
10263: m: ( x y circle -- )
10264: ( x y ) this circle-radius @@ draw-circle ;m
10265: @end example
10266:
10267: @cindex @code{exit} in @code{m: ... ;m}
10268: @cindex @code{exitm} discussion
10269: @cindex @code{catch} in @code{m: ... ;m}
10270: When this method is executed, the receiver object is removed from the
10271: stack; you can access it with @code{this} (admittedly, in this
10272: example the use of @code{m: ... ;m} offers no advantage). Note
10273: that I specify the stack effect for the whole method (i.e. including
10274: the receiver object), not just for the code between @code{m:}
10275: and @code{;m}. You cannot use @code{exit} in
10276: @code{m:...;m}; instead, use
10277: @code{exitm}.@footnote{Moreover, for any word that calls
10278: @code{catch} and was defined before loading
10279: @code{objects.fs}, you have to redefine it like I redefined
10280: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10281:
10282: @cindex @code{inst-var} usage
10283: You will frequently use sequences of the form @code{this
10284: @emph{field}} (in the example above: @code{this
10285: circle-radius}). If you use the field only in this way, you can
10286: define it with @code{inst-var} and eliminate the
10287: @code{this} before the field name. E.g., the @code{circle}
10288: class above could also be defined with:
10289:
10290: @example
10291: graphical class
10292: cell% inst-var radius
10293:
10294: m: ( x y circle -- )
10295: radius @@ draw-circle ;m
10296: overrides draw
10297:
10298: m: ( n-radius circle -- )
10299: radius ! ;m
10300: overrides construct
10301:
10302: end-class circle
10303: @end example
10304:
10305: @code{radius} can only be used in @code{circle} and its
10306: descendent classes and inside @code{m:...;m}.
10307:
10308: @cindex @code{inst-value} usage
10309: You can also define fields with @code{inst-value}, which is
10310: to @code{inst-var} what @code{value} is to
10311: @code{variable}. You can change the value of such a field with
10312: @code{[to-inst]}. E.g., we could also define the class
10313: @code{circle} like this:
10314:
10315: @example
10316: graphical class
10317: inst-value radius
10318:
10319: m: ( x y circle -- )
10320: radius draw-circle ;m
10321: overrides draw
10322:
10323: m: ( n-radius circle -- )
10324: [to-inst] radius ;m
10325: overrides construct
10326:
10327: end-class circle
10328: @end example
10329:
10330: @c !! :m is easy to confuse with m:. Another name would be better.
10331:
10332: @c Finally, you can define named methods with @code{:m}. One use of this
10333: @c feature is the definition of words that occur only in one class and are
10334: @c not intended to be overridden, but which still need method context
10335: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10336: @c would be bound frequently, if defined anonymously.
10337:
10338:
10339: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10340: @subsubsection Classes and Scoping
10341: @cindex classes and scoping
10342: @cindex scoping and classes
10343:
10344: Inheritance is frequent, unlike structure extension. This exacerbates
10345: the problem with the field name convention (@pxref{Structure Naming
10346: Convention}): One always has to remember in which class the field was
10347: originally defined; changing a part of the class structure would require
10348: changes for renaming in otherwise unaffected code.
10349:
10350: @cindex @code{inst-var} visibility
10351: @cindex @code{inst-value} visibility
10352: To solve this problem, I added a scoping mechanism (which was not in my
10353: original charter): A field defined with @code{inst-var} (or
10354: @code{inst-value}) is visible only in the class where it is defined and in
10355: the descendent classes of this class. Using such fields only makes
10356: sense in @code{m:}-defined methods in these classes anyway.
10357:
10358: This scoping mechanism allows us to use the unadorned field name,
10359: because name clashes with unrelated words become much less likely.
10360:
10361: @cindex @code{protected} discussion
10362: @cindex @code{private} discussion
10363: Once we have this mechanism, we can also use it for controlling the
10364: visibility of other words: All words defined after
10365: @code{protected} are visible only in the current class and its
10366: descendents. @code{public} restores the compilation
10367: (i.e. @code{current}) word list that was in effect before. If you
10368: have several @code{protected}s without an intervening
10369: @code{public} or @code{set-current}, @code{public}
10370: will restore the compilation word list in effect before the first of
10371: these @code{protected}s.
10372:
10373: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10374: @subsubsection Dividing classes
10375: @cindex Dividing classes
10376: @cindex @code{methods}...@code{end-methods}
10377:
10378: You may want to do the definition of methods separate from the
10379: definition of the class, its selectors, fields, and instance variables,
10380: i.e., separate the implementation from the definition. You can do this
10381: in the following way:
10382:
10383: @example
10384: graphical class
10385: inst-value radius
10386: end-class circle
10387:
10388: ... \ do some other stuff
10389:
10390: circle methods \ now we are ready
10391:
10392: m: ( x y circle -- )
10393: radius draw-circle ;m
10394: overrides draw
10395:
10396: m: ( n-radius circle -- )
10397: [to-inst] radius ;m
10398: overrides construct
10399:
10400: end-methods
10401: @end example
10402:
10403: You can use several @code{methods}...@code{end-methods} sections. The
10404: only things you can do to the class in these sections are: defining
10405: methods, and overriding the class's selectors. You must not define new
10406: selectors or fields.
10407:
10408: Note that you often have to override a selector before using it. In
10409: particular, you usually have to override @code{construct} with a new
10410: method before you can invoke @code{heap-new} and friends. E.g., you
10411: must not create a circle before the @code{overrides construct} sequence
10412: in the example above.
10413:
10414: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10415: @subsubsection Object Interfaces
10416: @cindex object interfaces
10417: @cindex interfaces for objects
10418:
10419: In this model you can only call selectors defined in the class of the
10420: receiving objects or in one of its ancestors. If you call a selector
10421: with a receiving object that is not in one of these classes, the
10422: result is undefined; if you are lucky, the program crashes
10423: immediately.
10424:
10425: @cindex selectors common to hardly-related classes
10426: Now consider the case when you want to have a selector (or several)
10427: available in two classes: You would have to add the selector to a
10428: common ancestor class, in the worst case to @code{object}. You
10429: may not want to do this, e.g., because someone else is responsible for
10430: this ancestor class.
10431:
10432: The solution for this problem is interfaces. An interface is a
10433: collection of selectors. If a class implements an interface, the
10434: selectors become available to the class and its descendents. A class
10435: can implement an unlimited number of interfaces. For the problem
10436: discussed above, we would define an interface for the selector(s), and
10437: both classes would implement the interface.
10438:
10439: As an example, consider an interface @code{storage} for
10440: writing objects to disk and getting them back, and a class
10441: @code{foo} that implements it. The code would look like this:
10442:
10443: @cindex @code{interface} usage
10444: @cindex @code{end-interface} usage
10445: @cindex @code{implementation} usage
10446: @example
10447: interface
10448: selector write ( file object -- )
10449: selector read1 ( file object -- )
10450: end-interface storage
10451:
10452: bar class
10453: storage implementation
10454:
10455: ... overrides write
10456: ... overrides read1
10457: ...
10458: end-class foo
10459: @end example
10460:
10461: @noindent
10462: (I would add a word @code{read} @i{( file -- object )} that uses
10463: @code{read1} internally, but that's beyond the point illustrated
10464: here.)
10465:
10466: Note that you cannot use @code{protected} in an interface; and
10467: of course you cannot define fields.
10468:
10469: In the Neon model, all selectors are available for all classes;
10470: therefore it does not need interfaces. The price you pay in this model
10471: is slower late binding, and therefore, added complexity to avoid late
10472: binding.
10473:
10474: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10475: @subsubsection @file{objects.fs} Implementation
10476: @cindex @file{objects.fs} implementation
10477:
10478: @cindex @code{object-map} discussion
10479: An object is a piece of memory, like one of the data structures
10480: described with @code{struct...end-struct}. It has a field
10481: @code{object-map} that points to the method map for the object's
10482: class.
10483:
10484: @cindex method map
10485: @cindex virtual function table
10486: The @emph{method map}@footnote{This is Self terminology; in C++
10487: terminology: virtual function table.} is an array that contains the
10488: execution tokens (@i{xt}s) of the methods for the object's class. Each
10489: selector contains an offset into a method map.
10490:
10491: @cindex @code{selector} implementation, class
10492: @code{selector} is a defining word that uses
10493: @code{CREATE} and @code{DOES>}. The body of the
10494: selector contains the offset; the @code{DOES>} action for a
10495: class selector is, basically:
10496:
10497: @example
10498: ( object addr ) @@ over object-map @@ + @@ execute
10499: @end example
10500:
10501: Since @code{object-map} is the first field of the object, it
10502: does not generate any code. As you can see, calling a selector has a
10503: small, constant cost.
10504:
10505: @cindex @code{current-interface} discussion
10506: @cindex class implementation and representation
10507: A class is basically a @code{struct} combined with a method
10508: map. During the class definition the alignment and size of the class
10509: are passed on the stack, just as with @code{struct}s, so
10510: @code{field} can also be used for defining class
10511: fields. However, passing more items on the stack would be
10512: inconvenient, so @code{class} builds a data structure in memory,
10513: which is accessed through the variable
10514: @code{current-interface}. After its definition is complete, the
10515: class is represented on the stack by a pointer (e.g., as parameter for
10516: a child class definition).
10517:
10518: A new class starts off with the alignment and size of its parent,
10519: and a copy of the parent's method map. Defining new fields extends the
10520: size and alignment; likewise, defining new selectors extends the
10521: method map. @code{overrides} just stores a new @i{xt} in the method
10522: map at the offset given by the selector.
10523:
10524: @cindex class binding, implementation
10525: Class binding just gets the @i{xt} at the offset given by the selector
10526: from the class's method map and @code{compile,}s (in the case of
10527: @code{[bind]}) it.
10528:
10529: @cindex @code{this} implementation
10530: @cindex @code{catch} and @code{this}
10531: @cindex @code{this} and @code{catch}
10532: I implemented @code{this} as a @code{value}. At the
10533: start of an @code{m:...;m} method the old @code{this} is
10534: stored to the return stack and restored at the end; and the object on
10535: the TOS is stored @code{TO this}. This technique has one
10536: disadvantage: If the user does not leave the method via
10537: @code{;m}, but via @code{throw} or @code{exit},
10538: @code{this} is not restored (and @code{exit} may
10539: crash). To deal with the @code{throw} problem, I have redefined
10540: @code{catch} to save and restore @code{this}; the same
10541: should be done with any word that can catch an exception. As for
10542: @code{exit}, I simply forbid it (as a replacement, there is
10543: @code{exitm}).
10544:
10545: @cindex @code{inst-var} implementation
10546: @code{inst-var} is just the same as @code{field}, with
10547: a different @code{DOES>} action:
10548: @example
10549: @@ this +
10550: @end example
10551: Similar for @code{inst-value}.
10552:
10553: @cindex class scoping implementation
10554: Each class also has a word list that contains the words defined with
10555: @code{inst-var} and @code{inst-value}, and its protected
10556: words. It also has a pointer to its parent. @code{class} pushes
10557: the word lists of the class and all its ancestors onto the search order stack,
10558: and @code{end-class} drops them.
10559:
10560: @cindex interface implementation
10561: An interface is like a class without fields, parent and protected
10562: words; i.e., it just has a method map. If a class implements an
10563: interface, its method map contains a pointer to the method map of the
10564: interface. The positive offsets in the map are reserved for class
10565: methods, therefore interface map pointers have negative
10566: offsets. Interfaces have offsets that are unique throughout the
10567: system, unlike class selectors, whose offsets are only unique for the
10568: classes where the selector is available (invokable).
10569:
10570: This structure means that interface selectors have to perform one
10571: indirection more than class selectors to find their method. Their body
10572: contains the interface map pointer offset in the class method map, and
10573: the method offset in the interface method map. The
10574: @code{does>} action for an interface selector is, basically:
10575:
10576: @example
10577: ( object selector-body )
10578: 2dup selector-interface @@ ( object selector-body object interface-offset )
10579: swap object-map @@ + @@ ( object selector-body map )
10580: swap selector-offset @@ + @@ execute
10581: @end example
10582:
10583: where @code{object-map} and @code{selector-offset} are
10584: first fields and generate no code.
10585:
10586: As a concrete example, consider the following code:
10587:
10588: @example
10589: interface
10590: selector if1sel1
10591: selector if1sel2
10592: end-interface if1
10593:
10594: object class
10595: if1 implementation
10596: selector cl1sel1
10597: cell% inst-var cl1iv1
10598:
10599: ' m1 overrides construct
10600: ' m2 overrides if1sel1
10601: ' m3 overrides if1sel2
10602: ' m4 overrides cl1sel2
10603: end-class cl1
10604:
10605: create obj1 object dict-new drop
10606: create obj2 cl1 dict-new drop
10607: @end example
10608:
10609: The data structure created by this code (including the data structure
10610: for @code{object}) is shown in the
10611: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10612: @comment TODO add this diagram..
10613:
10614: @node Objects Glossary, , Objects Implementation, Objects
10615: @subsubsection @file{objects.fs} Glossary
10616: @cindex @file{objects.fs} Glossary
10617:
10618:
10619: doc---objects-bind
10620: doc---objects-<bind>
10621: doc---objects-bind'
10622: doc---objects-[bind]
10623: doc---objects-class
10624: doc---objects-class->map
10625: doc---objects-class-inst-size
10626: doc---objects-class-override!
10627: doc---objects-class-previous
10628: doc---objects-class>order
10629: doc---objects-construct
10630: doc---objects-current'
10631: doc---objects-[current]
10632: doc---objects-current-interface
10633: doc---objects-dict-new
10634: doc---objects-end-class
10635: doc---objects-end-class-noname
10636: doc---objects-end-interface
10637: doc---objects-end-interface-noname
10638: doc---objects-end-methods
10639: doc---objects-exitm
10640: doc---objects-heap-new
10641: doc---objects-implementation
10642: doc---objects-init-object
10643: doc---objects-inst-value
10644: doc---objects-inst-var
10645: doc---objects-interface
10646: doc---objects-m:
10647: doc---objects-:m
10648: doc---objects-;m
10649: doc---objects-method
10650: doc---objects-methods
10651: doc---objects-object
10652: doc---objects-overrides
10653: doc---objects-[parent]
10654: doc---objects-print
10655: doc---objects-protected
10656: doc---objects-public
10657: doc---objects-selector
10658: doc---objects-this
10659: doc---objects-<to-inst>
10660: doc---objects-[to-inst]
10661: doc---objects-to-this
10662: doc---objects-xt-new
10663:
10664:
10665: @c -------------------------------------------------------------
10666: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10667: @subsection The @file{oof.fs} model
10668: @cindex oof
10669: @cindex object-oriented programming
10670:
10671: @cindex @file{objects.fs}
10672: @cindex @file{oof.fs}
10673:
10674: This section describes the @file{oof.fs} package.
10675:
10676: The package described in this section has been used in bigFORTH since 1991, and
10677: used for two large applications: a chromatographic system used to
10678: create new medicaments, and a graphic user interface library (MINOS).
10679:
10680: You can find a description (in German) of @file{oof.fs} in @cite{Object
10681: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10682: 10(2), 1994.
10683:
10684: @menu
10685: * Properties of the OOF model::
10686: * Basic OOF Usage::
10687: * The OOF base class::
10688: * Class Declaration::
10689: * Class Implementation::
10690: @end menu
10691:
10692: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10693: @subsubsection Properties of the @file{oof.fs} model
10694: @cindex @file{oof.fs} properties
10695:
10696: @itemize @bullet
10697: @item
10698: This model combines object oriented programming with information
10699: hiding. It helps you writing large application, where scoping is
10700: necessary, because it provides class-oriented scoping.
10701:
10702: @item
10703: Named objects, object pointers, and object arrays can be created,
10704: selector invocation uses the ``object selector'' syntax. Selector invocation
10705: to objects and/or selectors on the stack is a bit less convenient, but
10706: possible.
10707:
10708: @item
10709: Selector invocation and instance variable usage of the active object is
10710: straightforward, since both make use of the active object.
10711:
10712: @item
10713: Late binding is efficient and easy to use.
10714:
10715: @item
10716: State-smart objects parse selectors. However, extensibility is provided
10717: using a (parsing) selector @code{postpone} and a selector @code{'}.
10718:
10719: @item
10720: An implementation in ANS Forth is available.
10721:
10722: @end itemize
10723:
10724:
10725: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10726: @subsubsection Basic @file{oof.fs} Usage
10727: @cindex @file{oof.fs} usage
10728:
10729: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
10730:
10731: You can define a class for graphical objects like this:
10732:
10733: @cindex @code{class} usage
10734: @cindex @code{class;} usage
10735: @cindex @code{method} usage
10736: @example
10737: object class graphical \ "object" is the parent class
10738: method draw ( x y graphical -- )
10739: class;
10740: @end example
10741:
10742: This code defines a class @code{graphical} with an
10743: operation @code{draw}. We can perform the operation
10744: @code{draw} on any @code{graphical} object, e.g.:
10745:
10746: @example
10747: 100 100 t-rex draw
10748: @end example
10749:
10750: @noindent
10751: where @code{t-rex} is an object or object pointer, created with e.g.
10752: @code{graphical : t-rex}.
10753:
10754: @cindex abstract class
10755: How do we create a graphical object? With the present definitions,
10756: we cannot create a useful graphical object. The class
10757: @code{graphical} describes graphical objects in general, but not
10758: any concrete graphical object type (C++ users would call it an
10759: @emph{abstract class}); e.g., there is no method for the selector
10760: @code{draw} in the class @code{graphical}.
10761:
10762: For concrete graphical objects, we define child classes of the
10763: class @code{graphical}, e.g.:
10764:
10765: @example
10766: graphical class circle \ "graphical" is the parent class
10767: cell var circle-radius
10768: how:
10769: : draw ( x y -- )
10770: circle-radius @@ draw-circle ;
10771:
10772: : init ( n-radius -- (
10773: circle-radius ! ;
10774: class;
10775: @end example
10776:
10777: Here we define a class @code{circle} as a child of @code{graphical},
10778: with a field @code{circle-radius}; it defines new methods for the
10779: selectors @code{draw} and @code{init} (@code{init} is defined in
10780: @code{object}, the parent class of @code{graphical}).
10781:
10782: Now we can create a circle in the dictionary with:
10783:
10784: @example
10785: 50 circle : my-circle
10786: @end example
10787:
10788: @noindent
10789: @code{:} invokes @code{init}, thus initializing the field
10790: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10791: with:
10792:
10793: @example
10794: 100 100 my-circle draw
10795: @end example
10796:
10797: @cindex selector invocation, restrictions
10798: @cindex class definition, restrictions
10799: Note: You can only invoke a selector if the receiving object belongs to
10800: the class where the selector was defined or one of its descendents;
10801: e.g., you can invoke @code{draw} only for objects belonging to
10802: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10803: mechanism will check if you try to invoke a selector that is not
10804: defined in this class hierarchy, so you'll get an error at compilation
10805: time.
10806:
10807:
10808: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10809: @subsubsection The @file{oof.fs} base class
10810: @cindex @file{oof.fs} base class
10811:
10812: When you define a class, you have to specify a parent class. So how do
10813: you start defining classes? There is one class available from the start:
10814: @code{object}. You have to use it as ancestor for all classes. It is the
10815: only class that has no parent. Classes are also objects, except that
10816: they don't have instance variables; class manipulation such as
10817: inheritance or changing definitions of a class is handled through
10818: selectors of the class @code{object}.
10819:
10820: @code{object} provides a number of selectors:
10821:
10822: @itemize @bullet
10823: @item
10824: @code{class} for subclassing, @code{definitions} to add definitions
10825: later on, and @code{class?} to get type informations (is the class a
10826: subclass of the class passed on the stack?).
10827:
10828: doc---object-class
10829: doc---object-definitions
10830: doc---object-class?
10831:
10832:
10833: @item
10834: @code{init} and @code{dispose} as constructor and destructor of the
10835: object. @code{init} is invocated after the object's memory is allocated,
10836: while @code{dispose} also handles deallocation. Thus if you redefine
10837: @code{dispose}, you have to call the parent's dispose with @code{super
10838: dispose}, too.
10839:
10840: doc---object-init
10841: doc---object-dispose
10842:
10843:
10844: @item
10845: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10846: @code{[]} to create named and unnamed objects and object arrays or
10847: object pointers.
10848:
10849: doc---object-new
10850: doc---object-new[]
10851: doc---object-:
10852: doc---object-ptr
10853: doc---object-asptr
10854: doc---object-[]
10855:
10856:
10857: @item
10858: @code{::} and @code{super} for explicit scoping. You should use explicit
10859: scoping only for super classes or classes with the same set of instance
10860: variables. Explicitly-scoped selectors use early binding.
10861:
10862: doc---object-::
10863: doc---object-super
10864:
10865:
10866: @item
10867: @code{self} to get the address of the object
10868:
10869: doc---object-self
10870:
10871:
10872: @item
10873: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10874: pointers and instance defers.
10875:
10876: doc---object-bind
10877: doc---object-bound
10878: doc---object-link
10879: doc---object-is
10880:
10881:
10882: @item
10883: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10884: form the stack, and @code{postpone} to generate selector invocation code.
10885:
10886: doc---object-'
10887: doc---object-postpone
10888:
10889:
10890: @item
10891: @code{with} and @code{endwith} to select the active object from the
10892: stack, and enable its scope. Using @code{with} and @code{endwith}
10893: also allows you to create code using selector @code{postpone} without being
10894: trapped by the state-smart objects.
10895:
10896: doc---object-with
10897: doc---object-endwith
10898:
10899:
10900: @end itemize
10901:
10902: @node Class Declaration, Class Implementation, The OOF base class, OOF
10903: @subsubsection Class Declaration
10904: @cindex class declaration
10905:
10906: @itemize @bullet
10907: @item
10908: Instance variables
10909:
10910: doc---oof-var
10911:
10912:
10913: @item
10914: Object pointers
10915:
10916: doc---oof-ptr
10917: doc---oof-asptr
10918:
10919:
10920: @item
10921: Instance defers
10922:
10923: doc---oof-defer
10924:
10925:
10926: @item
10927: Method selectors
10928:
10929: doc---oof-early
10930: doc---oof-method
10931:
10932:
10933: @item
10934: Class-wide variables
10935:
10936: doc---oof-static
10937:
10938:
10939: @item
10940: End declaration
10941:
10942: doc---oof-how:
10943: doc---oof-class;
10944:
10945:
10946: @end itemize
10947:
10948: @c -------------------------------------------------------------
10949: @node Class Implementation, , Class Declaration, OOF
10950: @subsubsection Class Implementation
10951: @cindex class implementation
10952:
10953: @c -------------------------------------------------------------
10954: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
10955: @subsection The @file{mini-oof.fs} model
10956: @cindex mini-oof
10957:
10958: Gforth's third object oriented Forth package is a 12-liner. It uses a
10959: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
10960: and reduces to the bare minimum of features. This is based on a posting
10961: of Bernd Paysan in comp.lang.forth.
10962:
10963: @menu
10964: * Basic Mini-OOF Usage::
10965: * Mini-OOF Example::
10966: * Mini-OOF Implementation::
10967: @end menu
10968:
10969: @c -------------------------------------------------------------
10970: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
10971: @subsubsection Basic @file{mini-oof.fs} Usage
10972: @cindex mini-oof usage
10973:
10974: There is a base class (@code{class}, which allocates one cell for the
10975: object pointer) plus seven other words: to define a method, a variable,
10976: a class; to end a class, to resolve binding, to allocate an object and
10977: to compile a class method.
10978: @comment TODO better description of the last one
10979:
10980:
10981: doc-object
10982: doc-method
10983: doc-var
10984: doc-class
10985: doc-end-class
10986: doc-defines
10987: doc-new
10988: doc-::
10989:
10990:
10991:
10992: @c -------------------------------------------------------------
10993: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
10994: @subsubsection Mini-OOF Example
10995: @cindex mini-oof example
10996:
10997: A short example shows how to use this package. This example, in slightly
10998: extended form, is supplied as @file{moof-exm.fs}
10999: @comment TODO could flesh this out with some comments from the Forthwrite article
11000:
11001: @example
11002: object class
11003: method init
11004: method draw
11005: end-class graphical
11006: @end example
11007:
11008: This code defines a class @code{graphical} with an
11009: operation @code{draw}. We can perform the operation
11010: @code{draw} on any @code{graphical} object, e.g.:
11011:
11012: @example
11013: 100 100 t-rex draw
11014: @end example
11015:
11016: where @code{t-rex} is an object or object pointer, created with e.g.
11017: @code{graphical new Constant t-rex}.
11018:
11019: For concrete graphical objects, we define child classes of the
11020: class @code{graphical}, e.g.:
11021:
11022: @example
11023: graphical class
11024: cell var circle-radius
11025: end-class circle \ "graphical" is the parent class
11026:
11027: :noname ( x y -- )
11028: circle-radius @@ draw-circle ; circle defines draw
11029: :noname ( r -- )
11030: circle-radius ! ; circle defines init
11031: @end example
11032:
11033: There is no implicit init method, so we have to define one. The creation
11034: code of the object now has to call init explicitely.
11035:
11036: @example
11037: circle new Constant my-circle
11038: 50 my-circle init
11039: @end example
11040:
11041: It is also possible to add a function to create named objects with
11042: automatic call of @code{init}, given that all objects have @code{init}
11043: on the same place:
11044:
11045: @example
11046: : new: ( .. o "name" -- )
11047: new dup Constant init ;
11048: 80 circle new: large-circle
11049: @end example
11050:
11051: We can draw this new circle at (100,100) with:
11052:
11053: @example
11054: 100 100 my-circle draw
11055: @end example
11056:
11057: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11058: @subsubsection @file{mini-oof.fs} Implementation
11059:
11060: Object-oriented systems with late binding typically use a
11061: ``vtable''-approach: the first variable in each object is a pointer to a
11062: table, which contains the methods as function pointers. The vtable
11063: may also contain other information.
11064:
11065: So first, let's declare selectors:
11066:
11067: @example
11068: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
11069: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11070: @end example
11071:
11072: During selector declaration, the number of selectors and instance
11073: variables is on the stack (in address units). @code{method} creates one
11074: selector and increments the selector number. To execute a selector, it
11075: takes the object, fetches the vtable pointer, adds the offset, and
11076: executes the method @i{xt} stored there. Each selector takes the object
11077: it is invoked with as top of stack parameter; it passes the parameters
11078: (including the object) unchanged to the appropriate method which should
11079: consume that object.
11080:
11081: Now, we also have to declare instance variables
11082:
11083: @example
11084: : var ( m v size "name" -- m v' ) Create over , +
11085: DOES> ( o -- addr ) @@ + ;
11086: @end example
11087:
11088: As before, a word is created with the current offset. Instance
11089: variables can have different sizes (cells, floats, doubles, chars), so
11090: all we do is take the size and add it to the offset. If your machine
11091: has alignment restrictions, put the proper @code{aligned} or
11092: @code{faligned} before the variable, to adjust the variable
11093: offset. That's why it is on the top of stack.
11094:
11095: We need a starting point (the base object) and some syntactic sugar:
11096:
11097: @example
11098: Create object 1 cells , 2 cells ,
11099: : class ( class -- class selectors vars ) dup 2@@ ;
11100: @end example
11101:
11102: For inheritance, the vtable of the parent object has to be
11103: copied when a new, derived class is declared. This gives all the
11104: methods of the parent class, which can be overridden, though.
11105:
11106: @example
11107: : end-class ( class selectors vars "name" -- )
11108: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11109: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11110: @end example
11111:
11112: The first line creates the vtable, initialized with
11113: @code{noop}s. The second line is the inheritance mechanism, it
11114: copies the xts from the parent vtable.
11115:
11116: We still have no way to define new methods, let's do that now:
11117:
11118: @example
11119: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11120: @end example
11121:
11122: To allocate a new object, we need a word, too:
11123:
11124: @example
11125: : new ( class -- o ) here over @@ allot swap over ! ;
11126: @end example
11127:
11128: Sometimes derived classes want to access the method of the
11129: parent object. There are two ways to achieve this with Mini-OOF:
11130: first, you could use named words, and second, you could look up the
11131: vtable of the parent object.
11132:
11133: @example
11134: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11135: @end example
11136:
11137:
11138: Nothing can be more confusing than a good example, so here is
11139: one. First let's declare a text object (called
11140: @code{button}), that stores text and position:
11141:
11142: @example
11143: object class
11144: cell var text
11145: cell var len
11146: cell var x
11147: cell var y
11148: method init
11149: method draw
11150: end-class button
11151: @end example
11152:
11153: @noindent
11154: Now, implement the two methods, @code{draw} and @code{init}:
11155:
11156: @example
11157: :noname ( o -- )
11158: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11159: button defines draw
11160: :noname ( addr u o -- )
11161: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11162: button defines init
11163: @end example
11164:
11165: @noindent
11166: To demonstrate inheritance, we define a class @code{bold-button}, with no
11167: new data and no new selectors:
11168:
11169: @example
11170: button class
11171: end-class bold-button
11172:
11173: : bold 27 emit ." [1m" ;
11174: : normal 27 emit ." [0m" ;
11175: @end example
11176:
11177: @noindent
11178: The class @code{bold-button} has a different draw method to
11179: @code{button}, but the new method is defined in terms of the draw method
11180: for @code{button}:
11181:
11182: @example
11183: :noname bold [ button :: draw ] normal ; bold-button defines draw
11184: @end example
11185:
11186: @noindent
11187: Finally, create two objects and apply selectors:
11188:
11189: @example
11190: button new Constant foo
11191: s" thin foo" foo init
11192: page
11193: foo draw
11194: bold-button new Constant bar
11195: s" fat bar" bar init
11196: 1 bar y !
11197: bar draw
11198: @end example
11199:
11200:
11201: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11202: @subsection Comparison with other object models
11203: @cindex comparison of object models
11204: @cindex object models, comparison
11205:
11206: Many object-oriented Forth extensions have been proposed (@cite{A survey
11207: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11208: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11209: relation of the object models described here to two well-known and two
11210: closely-related (by the use of method maps) models. Andras Zsoter
11211: helped us with this section.
11212:
11213: @cindex Neon model
11214: The most popular model currently seems to be the Neon model (see
11215: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11216: 1997) by Andrew McKewan) but this model has a number of limitations
11217: @footnote{A longer version of this critique can be
11218: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11219: Dimensions, May 1997) by Anton Ertl.}:
11220:
11221: @itemize @bullet
11222: @item
11223: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11224: to pass objects on the stack.
11225:
11226: @item
11227: It requires that the selector parses the input stream (at
11228: compile time); this leads to reduced extensibility and to bugs that are
11229: hard to find.
11230:
11231: @item
11232: It allows using every selector on every object; this eliminates the
11233: need for interfaces, but makes it harder to create efficient
11234: implementations.
11235: @end itemize
11236:
11237: @cindex Pountain's object-oriented model
11238: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11239: Press, London, 1987) by Dick Pountain. However, it is not really about
11240: object-oriented programming, because it hardly deals with late
11241: binding. Instead, it focuses on features like information hiding and
11242: overloading that are characteristic of modular languages like Ada (83).
11243:
11244: @cindex Zsoter's object-oriented model
11245: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11246: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11247: describes a model that makes heavy use of an active object (like
11248: @code{this} in @file{objects.fs}): The active object is not only used
11249: for accessing all fields, but also specifies the receiving object of
11250: every selector invocation; you have to change the active object
11251: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11252: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11253: the method entry point is unnecessary with Zsoter's model, because the
11254: receiving object is the active object already. On the other hand, the
11255: explicit change is absolutely necessary in that model, because otherwise
11256: no one could ever change the active object. An ANS Forth implementation
11257: of this model is available through
11258: @uref{http://www.forth.org/oopf.html}.
11259:
11260: @cindex @file{oof.fs}, differences to other models
11261: The @file{oof.fs} model combines information hiding and overloading
11262: resolution (by keeping names in various word lists) with object-oriented
11263: programming. It sets the active object implicitly on method entry, but
11264: also allows explicit changing (with @code{>o...o>} or with
11265: @code{with...endwith}). It uses parsing and state-smart objects and
11266: classes for resolving overloading and for early binding: the object or
11267: class parses the selector and determines the method from this. If the
11268: selector is not parsed by an object or class, it performs a call to the
11269: selector for the active object (late binding), like Zsoter's model.
11270: Fields are always accessed through the active object. The big
11271: disadvantage of this model is the parsing and the state-smartness, which
11272: reduces extensibility and increases the opportunities for subtle bugs;
11273: essentially, you are only safe if you never tick or @code{postpone} an
11274: object or class (Bernd disagrees, but I (Anton) am not convinced).
11275:
11276: @cindex @file{mini-oof.fs}, differences to other models
11277: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11278: version of the @file{objects.fs} model, but syntactically it is a
11279: mixture of the @file{objects.fs} and @file{oof.fs} models.
11280:
11281:
11282: @c -------------------------------------------------------------
11283: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11284: @section Programming Tools
11285: @cindex programming tools
11286:
11287: @c !! move this and assembler down below OO stuff.
11288:
11289: @menu
11290: * Examining::
11291: * Forgetting words::
11292: * Debugging:: Simple and quick.
11293: * Assertions:: Making your programs self-checking.
11294: * Singlestep Debugger:: Executing your program word by word.
11295: @end menu
11296:
11297: @node Examining, Forgetting words, Programming Tools, Programming Tools
11298: @subsection Examining data and code
11299: @cindex examining data and code
11300: @cindex data examination
11301: @cindex code examination
11302:
11303: The following words inspect the stack non-destructively:
11304:
11305: doc-.s
11306: doc-f.s
11307:
11308: There is a word @code{.r} but it does @i{not} display the return stack!
11309: It is used for formatted numeric output (@pxref{Simple numeric output}).
11310:
11311: doc-depth
11312: doc-fdepth
11313: doc-clearstack
11314: doc-clearstacks
11315:
11316: The following words inspect memory.
11317:
11318: doc-?
11319: doc-dump
11320:
11321: And finally, @code{see} allows to inspect code:
11322:
11323: doc-see
11324: doc-xt-see
11325: doc-simple-see
11326: doc-simple-see-range
11327:
11328: @node Forgetting words, Debugging, Examining, Programming Tools
11329: @subsection Forgetting words
11330: @cindex words, forgetting
11331: @cindex forgeting words
11332:
11333: @c anton: other, maybe better places for this subsection: Defining Words;
11334: @c Dictionary allocation. At least a reference should be there.
11335:
11336: Forth allows you to forget words (and everything that was alloted in the
11337: dictonary after them) in a LIFO manner.
11338:
11339: doc-marker
11340:
11341: The most common use of this feature is during progam development: when
11342: you change a source file, forget all the words it defined and load it
11343: again (since you also forget everything defined after the source file
11344: was loaded, you have to reload that, too). Note that effects like
11345: storing to variables and destroyed system words are not undone when you
11346: forget words. With a system like Gforth, that is fast enough at
11347: starting up and compiling, I find it more convenient to exit and restart
11348: Gforth, as this gives me a clean slate.
11349:
11350: Here's an example of using @code{marker} at the start of a source file
11351: that you are debugging; it ensures that you only ever have one copy of
11352: the file's definitions compiled at any time:
11353:
11354: @example
11355: [IFDEF] my-code
11356: my-code
11357: [ENDIF]
11358:
11359: marker my-code
11360: init-included-files
11361:
11362: \ .. definitions start here
11363: \ .
11364: \ .
11365: \ end
11366: @end example
11367:
11368:
11369: @node Debugging, Assertions, Forgetting words, Programming Tools
11370: @subsection Debugging
11371: @cindex debugging
11372:
11373: Languages with a slow edit/compile/link/test development loop tend to
11374: require sophisticated tracing/stepping debuggers to facilate debugging.
11375:
11376: A much better (faster) way in fast-compiling languages is to add
11377: printing code at well-selected places, let the program run, look at
11378: the output, see where things went wrong, add more printing code, etc.,
11379: until the bug is found.
11380:
11381: The simple debugging aids provided in @file{debugs.fs}
11382: are meant to support this style of debugging.
11383:
11384: The word @code{~~} prints debugging information (by default the source
11385: location and the stack contents). It is easy to insert. If you use Emacs
11386: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11387: query-replace them with nothing). The deferred words
11388: @code{printdebugdata} and @code{.debugline} control the output of
11389: @code{~~}. The default source location output format works well with
11390: Emacs' compilation mode, so you can step through the program at the
11391: source level using @kbd{C-x `} (the advantage over a stepping debugger
11392: is that you can step in any direction and you know where the crash has
11393: happened or where the strange data has occurred).
11394:
11395: doc-~~
11396: doc-printdebugdata
11397: doc-.debugline
11398:
11399: @cindex filenames in @code{~~} output
11400: @code{~~} (and assertions) will usually print the wrong file name if a
11401: marker is executed in the same file after their occurance. They will
11402: print @samp{*somewhere*} as file name if a marker is executed in the
11403: same file before their occurance.
11404:
11405:
11406: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11407: @subsection Assertions
11408: @cindex assertions
11409:
11410: It is a good idea to make your programs self-checking, especially if you
11411: make an assumption that may become invalid during maintenance (for
11412: example, that a certain field of a data structure is never zero). Gforth
11413: supports @dfn{assertions} for this purpose. They are used like this:
11414:
11415: @example
11416: assert( @i{flag} )
11417: @end example
11418:
11419: The code between @code{assert(} and @code{)} should compute a flag, that
11420: should be true if everything is alright and false otherwise. It should
11421: not change anything else on the stack. The overall stack effect of the
11422: assertion is @code{( -- )}. E.g.
11423:
11424: @example
11425: assert( 1 1 + 2 = ) \ what we learn in school
11426: assert( dup 0<> ) \ assert that the top of stack is not zero
11427: assert( false ) \ this code should not be reached
11428: @end example
11429:
11430: The need for assertions is different at different times. During
11431: debugging, we want more checking, in production we sometimes care more
11432: for speed. Therefore, assertions can be turned off, i.e., the assertion
11433: becomes a comment. Depending on the importance of an assertion and the
11434: time it takes to check it, you may want to turn off some assertions and
11435: keep others turned on. Gforth provides several levels of assertions for
11436: this purpose:
11437:
11438:
11439: doc-assert0(
11440: doc-assert1(
11441: doc-assert2(
11442: doc-assert3(
11443: doc-assert(
11444: doc-)
11445:
11446:
11447: The variable @code{assert-level} specifies the highest assertions that
11448: are turned on. I.e., at the default @code{assert-level} of one,
11449: @code{assert0(} and @code{assert1(} assertions perform checking, while
11450: @code{assert2(} and @code{assert3(} assertions are treated as comments.
11451:
11452: The value of @code{assert-level} is evaluated at compile-time, not at
11453: run-time. Therefore you cannot turn assertions on or off at run-time;
11454: you have to set the @code{assert-level} appropriately before compiling a
11455: piece of code. You can compile different pieces of code at different
11456: @code{assert-level}s (e.g., a trusted library at level 1 and
11457: newly-written code at level 3).
11458:
11459:
11460: doc-assert-level
11461:
11462:
11463: If an assertion fails, a message compatible with Emacs' compilation mode
11464: is produced and the execution is aborted (currently with @code{ABORT"}.
11465: If there is interest, we will introduce a special throw code. But if you
11466: intend to @code{catch} a specific condition, using @code{throw} is
11467: probably more appropriate than an assertion).
11468:
11469: @cindex filenames in assertion output
11470: Assertions (and @code{~~}) will usually print the wrong file name if a
11471: marker is executed in the same file after their occurance. They will
11472: print @samp{*somewhere*} as file name if a marker is executed in the
11473: same file before their occurance.
11474:
11475: Definitions in ANS Forth for these assertion words are provided
11476: in @file{compat/assert.fs}.
11477:
11478:
11479: @node Singlestep Debugger, , Assertions, Programming Tools
11480: @subsection Singlestep Debugger
11481: @cindex singlestep Debugger
11482: @cindex debugging Singlestep
11483:
11484: The singlestep debugger does not work in this release.
11485:
11486: When you create a new word there's often the need to check whether it
11487: behaves correctly or not. You can do this by typing @code{dbg
11488: badword}. A debug session might look like this:
11489:
11490: @example
11491: : badword 0 DO i . LOOP ; ok
11492: 2 dbg badword
11493: : badword
11494: Scanning code...
11495:
11496: Nesting debugger ready!
11497:
11498: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11499: 400D4740 8049F68 DO -> [ 0 ]
11500: 400D4744 804A0C8 i -> [ 1 ] 00000
11501: 400D4748 400C5E60 . -> 0 [ 0 ]
11502: 400D474C 8049D0C LOOP -> [ 0 ]
11503: 400D4744 804A0C8 i -> [ 1 ] 00001
11504: 400D4748 400C5E60 . -> 1 [ 0 ]
11505: 400D474C 8049D0C LOOP -> [ 0 ]
11506: 400D4758 804B384 ; -> ok
11507: @end example
11508:
11509: Each line displayed is one step. You always have to hit return to
11510: execute the next word that is displayed. If you don't want to execute
11511: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11512: an overview what keys are available:
11513:
11514: @table @i
11515:
11516: @item @key{RET}
11517: Next; Execute the next word.
11518:
11519: @item n
11520: Nest; Single step through next word.
11521:
11522: @item u
11523: Unnest; Stop debugging and execute rest of word. If we got to this word
11524: with nest, continue debugging with the calling word.
11525:
11526: @item d
11527: Done; Stop debugging and execute rest.
11528:
11529: @item s
11530: Stop; Abort immediately.
11531:
11532: @end table
11533:
11534: Debugging large application with this mechanism is very difficult, because
11535: you have to nest very deeply into the program before the interesting part
11536: begins. This takes a lot of time.
11537:
11538: To do it more directly put a @code{BREAK:} command into your source code.
11539: When program execution reaches @code{BREAK:} the single step debugger is
11540: invoked and you have all the features described above.
11541:
11542: If you have more than one part to debug it is useful to know where the
11543: program has stopped at the moment. You can do this by the
11544: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11545: string is typed out when the ``breakpoint'' is reached.
11546:
11547:
11548: doc-dbg
11549: doc-break:
11550: doc-break"
11551:
11552:
11553:
11554: @c -------------------------------------------------------------
11555: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11556: @section Assembler and Code Words
11557: @cindex assembler
11558: @cindex code words
11559:
11560: @menu
11561: * Code and ;code::
11562: * Common Assembler:: Assembler Syntax
11563: * Common Disassembler::
11564: * 386 Assembler:: Deviations and special cases
11565: * Alpha Assembler:: Deviations and special cases
11566: * MIPS assembler:: Deviations and special cases
11567: * Other assemblers:: How to write them
11568: @end menu
11569:
11570: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11571: @subsection @code{Code} and @code{;code}
11572:
11573: Gforth provides some words for defining primitives (words written in
11574: machine code), and for defining the machine-code equivalent of
11575: @code{DOES>}-based defining words. However, the machine-independent
11576: nature of Gforth poses a few problems: First of all, Gforth runs on
11577: several architectures, so it can provide no standard assembler. What's
11578: worse is that the register allocation not only depends on the processor,
11579: but also on the @code{gcc} version and options used.
11580:
11581: The words that Gforth offers encapsulate some system dependences (e.g.,
11582: the header structure), so a system-independent assembler may be used in
11583: Gforth. If you do not have an assembler, you can compile machine code
11584: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11585: because these words emit stuff in @i{data} space; it works because
11586: Gforth has unified code/data spaces. Assembler isn't likely to be
11587: portable anyway.}.
11588:
11589:
11590: doc-assembler
11591: doc-init-asm
11592: doc-code
11593: doc-end-code
11594: doc-;code
11595: doc-flush-icache
11596:
11597:
11598: If @code{flush-icache} does not work correctly, @code{code} words
11599: etc. will not work (reliably), either.
11600:
11601: The typical usage of these @code{code} words can be shown most easily by
11602: analogy to the equivalent high-level defining words:
11603:
11604: @example
11605: : foo code foo
11606: <high-level Forth words> <assembler>
11607: ; end-code
11608:
11609: : bar : bar
11610: <high-level Forth words> <high-level Forth words>
11611: CREATE CREATE
11612: <high-level Forth words> <high-level Forth words>
11613: DOES> ;code
11614: <high-level Forth words> <assembler>
11615: ; end-code
11616: @end example
11617:
11618: @c anton: the following stuff is also in "Common Assembler", in less detail.
11619:
11620: @cindex registers of the inner interpreter
11621: In the assembly code you will want to refer to the inner interpreter's
11622: registers (e.g., the data stack pointer) and you may want to use other
11623: registers for temporary storage. Unfortunately, the register allocation
11624: is installation-dependent.
11625:
11626: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
11627: (return stack pointer) may be in different places in @code{gforth} and
11628: @code{gforth-fast}, or different installations. This means that you
11629: cannot write a @code{NEXT} routine that works reliably on both versions
11630: or different installations; so for doing @code{NEXT}, I recommend
11631: jumping to @code{' noop >code-address}, which contains nothing but a
11632: @code{NEXT}.
11633:
11634: For general accesses to the inner interpreter's registers, the easiest
11635: solution is to use explicit register declarations (@pxref{Explicit Reg
11636: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11637: all of the inner interpreter's registers: You have to compile Gforth
11638: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11639: the appropriate declarations must be present in the @code{machine.h}
11640: file (see @code{mips.h} for an example; you can find a full list of all
11641: declarable register symbols with @code{grep register engine.c}). If you
11642: give explicit registers to all variables that are declared at the
11643: beginning of @code{engine()}, you should be able to use the other
11644: caller-saved registers for temporary storage. Alternatively, you can use
11645: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11646: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11647: reserve a register (however, this restriction on register allocation may
11648: slow Gforth significantly).
11649:
11650: If this solution is not viable (e.g., because @code{gcc} does not allow
11651: you to explicitly declare all the registers you need), you have to find
11652: out by looking at the code where the inner interpreter's registers
11653: reside and which registers can be used for temporary storage. You can
11654: get an assembly listing of the engine's code with @code{make engine.s}.
11655:
11656: In any case, it is good practice to abstract your assembly code from the
11657: actual register allocation. E.g., if the data stack pointer resides in
11658: register @code{$17}, create an alias for this register called @code{sp},
11659: and use that in your assembly code.
11660:
11661: @cindex code words, portable
11662: Another option for implementing normal and defining words efficiently
11663: is to add the desired functionality to the source of Gforth. For normal
11664: words you just have to edit @file{primitives} (@pxref{Automatic
11665: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11666: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11667: @file{prims2x.fs}, and possibly @file{cross.fs}.
11668:
11669: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11670: @subsection Common Assembler
11671:
11672: The assemblers in Gforth generally use a postfix syntax, i.e., the
11673: instruction name follows the operands.
11674:
11675: The operands are passed in the usual order (the same that is used in the
11676: manual of the architecture). Since they all are Forth words, they have
11677: to be separated by spaces; you can also use Forth words to compute the
11678: operands.
11679:
11680: The instruction names usually end with a @code{,}. This makes it easier
11681: to visually separate instructions if you put several of them on one
11682: line; it also avoids shadowing other Forth words (e.g., @code{and}).
11683:
11684: Registers are usually specified by number; e.g., (decimal) @code{11}
11685: specifies registers R11 and F11 on the Alpha architecture (which one,
11686: depends on the instruction). The usual names are also available, e.g.,
11687: @code{s2} for R11 on Alpha.
11688:
11689: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11690: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11691: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11692: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
11693: conditions are specified in a way specific to each assembler.
11694:
11695: Note that the register assignments of the Gforth engine can change
11696: between Gforth versions, or even between different compilations of the
11697: same Gforth version (e.g., if you use a different GCC version). So if
11698: you want to refer to Gforth's registers (e.g., the stack pointer or
11699: TOS), I recommend defining your own words for refering to these
11700: registers, and using them later on; then you can easily adapt to a
11701: changed register assignment. The stability of the register assignment
11702: is usually better if you build Gforth with @code{--enable-force-reg}.
11703:
11704: The most common use of these registers is to dispatch to the next word
11705: (the @code{next} routine). A portable way to do this is to jump to
11706: @code{' noop >code-address} (of course, this is less efficient than
11707: integrating the @code{next} code and scheduling it well).
11708:
11709: Another difference between Gforth version is that the top of stack is
11710: kept in memory in @code{gforth} and, on most platforms, in a register in
11711: @code{gforth-fast}.
11712:
11713: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11714: @subsection Common Disassembler
11715:
11716: You can disassemble a @code{code} word with @code{see}
11717: (@pxref{Debugging}). You can disassemble a section of memory with
11718:
11719: doc-disasm
11720:
11721: The disassembler generally produces output that can be fed into the
11722: assembler (i.e., same syntax, etc.). It also includes additional
11723: information in comments. In particular, the address of the instruction
11724: is given in a comment before the instruction.
11725:
11726: @code{See} may display more or less than the actual code of the word,
11727: because the recognition of the end of the code is unreliable. You can
11728: use @code{disasm} if it did not display enough. It may display more, if
11729: the code word is not immediately followed by a named word. If you have
11730: something else there, you can follow the word with @code{align latest ,}
11731: to ensure that the end is recognized.
11732:
11733: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11734: @subsection 386 Assembler
11735:
11736: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11737: available under GPL, and originally part of bigFORTH.
11738:
11739: The 386 disassembler included in Gforth was written by Andrew McKewan
11740: and is in the public domain.
11741:
11742: The disassembler displays code in an Intel-like prefix syntax.
11743:
11744: The assembler uses a postfix syntax with reversed parameters.
11745:
11746: The assembler includes all instruction of the Athlon, i.e. 486 core
11747: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11748: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11749: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
11750:
11751: There are several prefixes to switch between different operation sizes,
11752: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11753: double-word accesses. Addressing modes can be switched with @code{.wa}
11754: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11755: need a prefix for byte register names (@code{AL} et al).
11756:
11757: For floating point operations, the prefixes are @code{.fs} (IEEE
11758: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11759: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
11760:
11761: The MMX opcodes don't have size prefixes, they are spelled out like in
11762: the Intel assembler. Instead of move from and to memory, there are
11763: PLDQ/PLDD and PSTQ/PSTD.
11764:
11765: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11766: ax. Immediate values are indicated by postfixing them with @code{#},
11767: e.g., @code{3 #}. Here are some examples of addressing modes in various
11768: syntaxes:
11769:
11770: @example
11771: Gforth Intel (NASM) AT&T (gas) Name
11772: .w ax ax %ax register (16 bit)
11773: ax eax %eax register (32 bit)
11774: 3 # offset 3 $3 immediate
11775: 1000 #) byte ptr 1000 1000 displacement
11776: bx ) [ebx] (%ebx) base
11777: 100 di d) 100[edi] 100(%edi) base+displacement
11778: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
11779: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
11780: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
11781: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
11782: @end example
11783:
11784: You can use @code{L)} and @code{LI)} instead of @code{D)} and
11785: @code{DI)} to enforce 32-bit displacement fields (useful for
11786: later patching).
11787:
11788: Some example of instructions are:
11789:
11790: @example
11791: ax bx mov \ move ebx,eax
11792: 3 # ax mov \ mov eax,3
11793: 100 di ) ax mov \ mov eax,100[edi]
11794: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
11795: .w ax bx mov \ mov bx,ax
11796: @end example
11797:
11798: The following forms are supported for binary instructions:
11799:
11800: @example
11801: <reg> <reg> <inst>
11802: <n> # <reg> <inst>
11803: <mem> <reg> <inst>
11804: <reg> <mem> <inst>
11805: @end example
11806:
11807: Immediate to memory is not supported. The shift/rotate syntax is:
11808:
11809: @example
11810: <reg/mem> 1 # shl \ shortens to shift without immediate
11811: <reg/mem> 4 # shl
11812: <reg/mem> cl shl
11813: @end example
11814:
11815: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11816: the byte version.
11817:
11818: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11819: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11820: pc < >= <= >}. (Note that most of these words shadow some Forth words
11821: when @code{assembler} is in front of @code{forth} in the search path,
11822: e.g., in @code{code} words). Currently the control structure words use
11823: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11824: to shuffle them (you can also use @code{swap} etc.).
11825:
11826: Here is an example of a @code{code} word (assumes that the stack pointer
11827: is in esi and the TOS is in ebx):
11828:
11829: @example
11830: code my+ ( n1 n2 -- n )
11831: 4 si D) bx add
11832: 4 # si add
11833: Next
11834: end-code
11835: @end example
11836:
11837: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11838: @subsection Alpha Assembler
11839:
11840: The Alpha assembler and disassembler were originally written by Bernd
11841: Thallner.
11842:
11843: The register names @code{a0}--@code{a5} are not available to avoid
11844: shadowing hex numbers.
11845:
11846: Immediate forms of arithmetic instructions are distinguished by a
11847: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11848: does not count as arithmetic instruction).
11849:
11850: You have to specify all operands to an instruction, even those that
11851: other assemblers consider optional, e.g., the destination register for
11852: @code{br,}, or the destination register and hint for @code{jmp,}.
11853:
11854: You can specify conditions for @code{if,} by removing the first @code{b}
11855: and the trailing @code{,} from a branch with a corresponding name; e.g.,
11856:
11857: @example
11858: 11 fgt if, \ if F11>0e
11859: ...
11860: endif,
11861: @end example
11862:
11863: @code{fbgt,} gives @code{fgt}.
11864:
11865: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11866: @subsection MIPS assembler
11867:
11868: The MIPS assembler was originally written by Christian Pirker.
11869:
11870: Currently the assembler and disassembler only cover the MIPS-I
11871: architecture (R3000), and don't support FP instructions.
11872:
11873: The register names @code{$a0}--@code{$a3} are not available to avoid
11874: shadowing hex numbers.
11875:
11876: Because there is no way to distinguish registers from immediate values,
11877: you have to explicitly use the immediate forms of instructions, i.e.,
11878: @code{addiu,}, not just @code{addu,} (@command{as} does this
11879: implicitly).
11880:
11881: If the architecture manual specifies several formats for the instruction
11882: (e.g., for @code{jalr,}), you usually have to use the one with more
11883: arguments (i.e., two for @code{jalr,}). When in doubt, see
11884: @code{arch/mips/testasm.fs} for an example of correct use.
11885:
11886: Branches and jumps in the MIPS architecture have a delay slot. You have
11887: to fill it yourself (the simplest way is to use @code{nop,}), the
11888: assembler does not do it for you (unlike @command{as}). Even
11889: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
11890: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
11891: and @code{then,} just specify branch targets, they are not affected.
11892:
11893: Note that you must not put branches, jumps, or @code{li,} into the delay
11894: slot: @code{li,} may expand to several instructions, and control flow
11895: instructions may not be put into the branch delay slot in any case.
11896:
11897: For branches the argument specifying the target is a relative address;
11898: You have to add the address of the delay slot to get the absolute
11899: address.
11900:
11901: The MIPS architecture also has load delay slots and restrictions on
11902: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
11903: yourself to satisfy these restrictions, the assembler does not do it for
11904: you.
11905:
11906: You can specify the conditions for @code{if,} etc. by taking a
11907: conditional branch and leaving away the @code{b} at the start and the
11908: @code{,} at the end. E.g.,
11909:
11910: @example
11911: 4 5 eq if,
11912: ... \ do something if $4 equals $5
11913: then,
11914: @end example
11915:
11916: @node Other assemblers, , MIPS assembler, Assembler and Code Words
11917: @subsection Other assemblers
11918:
11919: If you want to contribute another assembler/disassembler, please contact
11920: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
11921: an assembler already. If you are writing them from scratch, please use
11922: a similar syntax style as the one we use (i.e., postfix, commas at the
11923: end of the instruction names, @pxref{Common Assembler}); make the output
11924: of the disassembler be valid input for the assembler, and keep the style
11925: similar to the style we used.
11926:
11927: Hints on implementation: The most important part is to have a good test
11928: suite that contains all instructions. Once you have that, the rest is
11929: easy. For actual coding you can take a look at
11930: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
11931: the assembler and disassembler, avoiding redundancy and some potential
11932: bugs. You can also look at that file (and @pxref{Advanced does> usage
11933: example}) to get ideas how to factor a disassembler.
11934:
11935: Start with the disassembler, because it's easier to reuse data from the
11936: disassembler for the assembler than the other way round.
11937:
11938: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
11939: how simple it can be.
11940:
11941: @c -------------------------------------------------------------
11942: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
11943: @section Threading Words
11944: @cindex threading words
11945:
11946: @cindex code address
11947: These words provide access to code addresses and other threading stuff
11948: in Gforth (and, possibly, other interpretive Forths). It more or less
11949: abstracts away the differences between direct and indirect threading
11950: (and, for direct threading, the machine dependences). However, at
11951: present this wordset is still incomplete. It is also pretty low-level;
11952: some day it will hopefully be made unnecessary by an internals wordset
11953: that abstracts implementation details away completely.
11954:
11955: The terminology used here stems from indirect threaded Forth systems; in
11956: such a system, the XT of a word is represented by the CFA (code field
11957: address) of a word; the CFA points to a cell that contains the code
11958: address. The code address is the address of some machine code that
11959: performs the run-time action of invoking the word (e.g., the
11960: @code{dovar:} routine pushes the address of the body of the word (a
11961: variable) on the stack
11962: ).
11963:
11964: @cindex code address
11965: @cindex code field address
11966: In an indirect threaded Forth, you can get the code address of @i{name}
11967: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
11968: >code-address}, independent of the threading method.
11969:
11970: doc-threading-method
11971: doc->code-address
11972: doc-code-address!
11973:
11974: @cindex @code{does>}-handler
11975: @cindex @code{does>}-code
11976: For a word defined with @code{DOES>}, the code address usually points to
11977: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
11978: routine (in Gforth on some platforms, it can also point to the dodoes
11979: routine itself). What you are typically interested in, though, is
11980: whether a word is a @code{DOES>}-defined word, and what Forth code it
11981: executes; @code{>does-code} tells you that.
11982:
11983: doc->does-code
11984:
11985: To create a @code{DOES>}-defined word with the following basic words,
11986: you have to set up a @code{DOES>}-handler with @code{does-handler!};
11987: @code{/does-handler} aus behind you have to place your executable Forth
11988: code. Finally you have to create a word and modify its behaviour with
11989: @code{does-handler!}.
11990:
11991: doc-does-code!
11992: doc-does-handler!
11993: doc-/does-handler
11994:
11995: The code addresses produced by various defining words are produced by
11996: the following words:
11997:
11998: doc-docol:
11999: doc-docon:
12000: doc-dovar:
12001: doc-douser:
12002: doc-dodefer:
12003: doc-dofield:
12004:
12005: @cindex definer
12006: The following two words generalize @code{>code-address},
12007: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12008:
12009: doc->definer
12010: doc-definer!
12011:
12012: @c -------------------------------------------------------------
12013: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
12014: @section Passing Commands to the Operating System
12015: @cindex operating system - passing commands
12016: @cindex shell commands
12017:
12018: Gforth allows you to pass an arbitrary string to the host operating
12019: system shell (if such a thing exists) for execution.
12020:
12021:
12022: doc-sh
12023: doc-system
12024: doc-$?
12025: doc-getenv
12026:
12027:
12028: @c -------------------------------------------------------------
12029: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12030: @section Keeping track of Time
12031: @cindex time-related words
12032:
12033: doc-ms
12034: doc-time&date
12035: doc-utime
12036: doc-cputime
12037:
12038:
12039: @c -------------------------------------------------------------
12040: @node Miscellaneous Words, , Keeping track of Time, Words
12041: @section Miscellaneous Words
12042: @cindex miscellaneous words
12043:
12044: @comment TODO find homes for these
12045:
12046: These section lists the ANS Forth words that are not documented
12047: elsewhere in this manual. Ultimately, they all need proper homes.
12048:
12049: doc-quit
12050:
12051: The following ANS Forth words are not currently supported by Gforth
12052: (@pxref{ANS conformance}):
12053:
12054: @code{EDITOR}
12055: @code{EMIT?}
12056: @code{FORGET}
12057:
12058: @c ******************************************************************
12059: @node Error messages, Tools, Words, Top
12060: @chapter Error messages
12061: @cindex error messages
12062: @cindex backtrace
12063:
12064: A typical Gforth error message looks like this:
12065:
12066: @example
12067: in file included from \evaluated string/:-1
12068: in file included from ./yyy.fs:1
12069: ./xxx.fs:4: Invalid memory address
12070: bar
12071: ^^^
12072: Backtrace:
12073: $400E664C @@
12074: $400E6664 foo
12075: @end example
12076:
12077: The message identifying the error is @code{Invalid memory address}. The
12078: error happened when text-interpreting line 4 of the file
12079: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12080: word on the line where the error happened, is pointed out (with
12081: @code{^^^}).
12082:
12083: The file containing the error was included in line 1 of @file{./yyy.fs},
12084: and @file{yyy.fs} was included from a non-file (in this case, by giving
12085: @file{yyy.fs} as command-line parameter to Gforth).
12086:
12087: At the end of the error message you find a return stack dump that can be
12088: interpreted as a backtrace (possibly empty). On top you find the top of
12089: the return stack when the @code{throw} happened, and at the bottom you
12090: find the return stack entry just above the return stack of the topmost
12091: text interpreter.
12092:
12093: To the right of most return stack entries you see a guess for the word
12094: that pushed that return stack entry as its return address. This gives a
12095: backtrace. In our case we see that @code{bar} called @code{foo}, and
12096: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12097: address} exception).
12098:
12099: Note that the backtrace is not perfect: We don't know which return stack
12100: entries are return addresses (so we may get false positives); and in
12101: some cases (e.g., for @code{abort"}) we cannot determine from the return
12102: address the word that pushed the return address, so for some return
12103: addresses you see no names in the return stack dump.
12104:
12105: @cindex @code{catch} and backtraces
12106: The return stack dump represents the return stack at the time when a
12107: specific @code{throw} was executed. In programs that make use of
12108: @code{catch}, it is not necessarily clear which @code{throw} should be
12109: used for the return stack dump (e.g., consider one @code{throw} that
12110: indicates an error, which is caught, and during recovery another error
12111: happens; which @code{throw} should be used for the stack dump?). Gforth
12112: presents the return stack dump for the first @code{throw} after the last
12113: executed (not returned-to) @code{catch}; this works well in the usual
12114: case.
12115:
12116: @cindex @code{gforth-fast} and backtraces
12117: @cindex @code{gforth-fast}, difference from @code{gforth}
12118: @cindex backtraces with @code{gforth-fast}
12119: @cindex return stack dump with @code{gforth-fast}
12120: @code{Gforth} is able to do a return stack dump for throws generated
12121: from primitives (e.g., invalid memory address, stack empty etc.);
12122: @code{gforth-fast} is only able to do a return stack dump from a
12123: directly called @code{throw} (including @code{abort} etc.). Given an
12124: exception caused by a primitive in @code{gforth-fast}, you will
12125: typically see no return stack dump at all; however, if the exception is
12126: caught by @code{catch} (e.g., for restoring some state), and then
12127: @code{throw}n again, the return stack dump will be for the first such
12128: @code{throw}.
12129:
12130: @c ******************************************************************
12131: @node Tools, ANS conformance, Error messages, Top
12132: @chapter Tools
12133:
12134: @menu
12135: * ANS Report:: Report the words used, sorted by wordset.
12136: @end menu
12137:
12138: See also @ref{Emacs and Gforth}.
12139:
12140: @node ANS Report, , Tools, Tools
12141: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12142: @cindex @file{ans-report.fs}
12143: @cindex report the words used in your program
12144: @cindex words used in your program
12145:
12146: If you want to label a Forth program as ANS Forth Program, you must
12147: document which wordsets the program uses; for extension wordsets, it is
12148: helpful to list the words the program requires from these wordsets
12149: (because Forth systems are allowed to provide only some words of them).
12150:
12151: The @file{ans-report.fs} tool makes it easy for you to determine which
12152: words from which wordset and which non-ANS words your application
12153: uses. You simply have to include @file{ans-report.fs} before loading the
12154: program you want to check. After loading your program, you can get the
12155: report with @code{print-ans-report}. A typical use is to run this as
12156: batch job like this:
12157: @example
12158: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12159: @end example
12160:
12161: The output looks like this (for @file{compat/control.fs}):
12162: @example
12163: The program uses the following words
12164: from CORE :
12165: : POSTPONE THEN ; immediate ?dup IF 0=
12166: from BLOCK-EXT :
12167: \
12168: from FILE :
12169: (
12170: @end example
12171:
12172: @subsection Caveats
12173:
12174: Note that @file{ans-report.fs} just checks which words are used, not whether
12175: they are used in an ANS Forth conforming way!
12176:
12177: Some words are defined in several wordsets in the
12178: standard. @file{ans-report.fs} reports them for only one of the
12179: wordsets, and not necessarily the one you expect. It depends on usage
12180: which wordset is the right one to specify. E.g., if you only use the
12181: compilation semantics of @code{S"}, it is a Core word; if you also use
12182: its interpretation semantics, it is a File word.
12183:
12184:
12185: @node Stack depth changes
12186: @section Stack depth changes during interpretation
12187: @cindex @file{depth-changes.fs}
12188: @cindex depth changes during interpretation
12189: @cindex stack depth changes during interpretation
12190: @cindex items on the stack after interpretation
12191:
12192: Sometimes you notice that, after loading a file, there are items left
12193: on the stack. The tool @file{depth-changes.fs} helps you find out
12194: quickly where in the file these stack items are coming from.
12195:
12196: The simplest way of using @file{depth-changes.fs} is to include it
12197: before the file(s) you want to check, e.g.:
12198:
12199: @example
12200: gforth depth-changes.fs my-file.fs
12201: @end example
12202:
12203: This will compare the stack depths of the data and FP stack at every
12204: empty line (in interpretation state) against these depths at the last
12205: empty line (in interpretation state). If the depths are not equal,
12206: the position in the file and the stack contents are printed with
12207: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
12208: change has occured in the paragraph of non-empty lines before the
12209: indicated line. It is a good idea to leave an empty line at the end
12210: of the file, so the last paragraph is checked, too.
12211:
12212: Checking only at empty lines usually works well, but sometimes you
12213: have big blocks of non-empty lines (e.g., when building a big table),
12214: and you want to know where in this block the stack depth changed. You
12215: can check all interpreted lines with
12216:
12217: @example
12218: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12219: @end example
12220:
12221: This checks the stack depth at every end-of-line. So the depth change
12222: occured in the line reported by the @code{~~} (not in the line
12223: before).
12224:
12225: Note that, while this offers better accuracy in indicating where the
12226: stack depth changes, it will often report many intentional stack depth
12227: changes (e.g., when an interpreted computation stretches across
12228: several lines). You can suppress the checking of some lines by
12229: putting backslashes at the end of these lines (not followed by white
12230: space), and using
12231:
12232: @example
12233: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12234: @end example
12235:
12236: @c ******************************************************************
12237: @node ANS conformance, Standard vs Extensions, Tools, Top
12238: @chapter ANS conformance
12239: @cindex ANS conformance of Gforth
12240:
12241: To the best of our knowledge, Gforth is an
12242:
12243: ANS Forth System
12244: @itemize @bullet
12245: @item providing the Core Extensions word set
12246: @item providing the Block word set
12247: @item providing the Block Extensions word set
12248: @item providing the Double-Number word set
12249: @item providing the Double-Number Extensions word set
12250: @item providing the Exception word set
12251: @item providing the Exception Extensions word set
12252: @item providing the Facility word set
12253: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
12254: @item providing the File Access word set
12255: @item providing the File Access Extensions word set
12256: @item providing the Floating-Point word set
12257: @item providing the Floating-Point Extensions word set
12258: @item providing the Locals word set
12259: @item providing the Locals Extensions word set
12260: @item providing the Memory-Allocation word set
12261: @item providing the Memory-Allocation Extensions word set (that one's easy)
12262: @item providing the Programming-Tools word set
12263: @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
12264: @item providing the Search-Order word set
12265: @item providing the Search-Order Extensions word set
12266: @item providing the String word set
12267: @item providing the String Extensions word set (another easy one)
12268: @end itemize
12269:
12270: Gforth has the following environmental restrictions:
12271:
12272: @cindex environmental restrictions
12273: @itemize @bullet
12274: @item
12275: While processing the OS command line, if an exception is not caught,
12276: Gforth exits with a non-zero exit code instyead of performing QUIT.
12277:
12278: @item
12279: When an @code{throw} is performed after a @code{query}, Gforth does not
12280: allways restore the input source specification in effect at the
12281: corresponding catch.
12282:
12283: @end itemize
12284:
12285:
12286: @cindex system documentation
12287: In addition, ANS Forth systems are required to document certain
12288: implementation choices. This chapter tries to meet these
12289: requirements. In many cases it gives a way to ask the system for the
12290: information instead of providing the information directly, in
12291: particular, if the information depends on the processor, the operating
12292: system or the installation options chosen, or if they are likely to
12293: change during the maintenance of Gforth.
12294:
12295: @comment The framework for the rest has been taken from pfe.
12296:
12297: @menu
12298: * The Core Words::
12299: * The optional Block word set::
12300: * The optional Double Number word set::
12301: * The optional Exception word set::
12302: * The optional Facility word set::
12303: * The optional File-Access word set::
12304: * The optional Floating-Point word set::
12305: * The optional Locals word set::
12306: * The optional Memory-Allocation word set::
12307: * The optional Programming-Tools word set::
12308: * The optional Search-Order word set::
12309: @end menu
12310:
12311:
12312: @c =====================================================================
12313: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12314: @comment node-name, next, previous, up
12315: @section The Core Words
12316: @c =====================================================================
12317: @cindex core words, system documentation
12318: @cindex system documentation, core words
12319:
12320: @menu
12321: * core-idef:: Implementation Defined Options
12322: * core-ambcond:: Ambiguous Conditions
12323: * core-other:: Other System Documentation
12324: @end menu
12325:
12326: @c ---------------------------------------------------------------------
12327: @node core-idef, core-ambcond, The Core Words, The Core Words
12328: @subsection Implementation Defined Options
12329: @c ---------------------------------------------------------------------
12330: @cindex core words, implementation-defined options
12331: @cindex implementation-defined options, core words
12332:
12333:
12334: @table @i
12335: @item (Cell) aligned addresses:
12336: @cindex cell-aligned addresses
12337: @cindex aligned addresses
12338: processor-dependent. Gforth's alignment words perform natural alignment
12339: (e.g., an address aligned for a datum of size 8 is divisible by
12340: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12341:
12342: @item @code{EMIT} and non-graphic characters:
12343: @cindex @code{EMIT} and non-graphic characters
12344: @cindex non-graphic characters and @code{EMIT}
12345: The character is output using the C library function (actually, macro)
12346: @code{putc}.
12347:
12348: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12349: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12350: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12351: @cindex @code{ACCEPT}, editing
12352: @cindex @code{EXPECT}, editing
12353: This is modeled on the GNU readline library (@pxref{Readline
12354: Interaction, , Command Line Editing, readline, The GNU Readline
12355: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12356: producing a full word completion every time you type it (instead of
12357: producing the common prefix of all completions). @xref{Command-line editing}.
12358:
12359: @item character set:
12360: @cindex character set
12361: The character set of your computer and display device. Gforth is
12362: 8-bit-clean (but some other component in your system may make trouble).
12363:
12364: @item Character-aligned address requirements:
12365: @cindex character-aligned address requirements
12366: installation-dependent. Currently a character is represented by a C
12367: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12368: (Comments on that requested).
12369:
12370: @item character-set extensions and matching of names:
12371: @cindex character-set extensions and matching of names
12372: @cindex case-sensitivity for name lookup
12373: @cindex name lookup, case-sensitivity
12374: @cindex locale and case-sensitivity
12375: Any character except the ASCII NUL character can be used in a
12376: name. Matching is case-insensitive (except in @code{TABLE}s). The
12377: matching is performed using the C library function @code{strncasecmp}, whose
12378: function is probably influenced by the locale. E.g., the @code{C} locale
12379: does not know about accents and umlauts, so they are matched
12380: case-sensitively in that locale. For portability reasons it is best to
12381: write programs such that they work in the @code{C} locale. Then one can
12382: use libraries written by a Polish programmer (who might use words
12383: containing ISO Latin-2 encoded characters) and by a French programmer
12384: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12385: funny results for some of the words (which ones, depends on the font you
12386: are using)). Also, the locale you prefer may not be available in other
12387: operating systems. Hopefully, Unicode will solve these problems one day.
12388:
12389: @item conditions under which control characters match a space delimiter:
12390: @cindex space delimiters
12391: @cindex control characters as delimiters
12392: If @code{word} is called with the space character as a delimiter, all
12393: white-space characters (as identified by the C macro @code{isspace()})
12394: are delimiters. @code{Parse}, on the other hand, treats space like other
12395: delimiters. @code{Parse-word}, which is used by the outer
12396: interpreter (aka text interpreter) by default, treats all white-space
12397: characters as delimiters.
12398:
12399: @item format of the control-flow stack:
12400: @cindex control-flow stack, format
12401: The data stack is used as control-flow stack. The size of a control-flow
12402: stack item in cells is given by the constant @code{cs-item-size}. At the
12403: time of this writing, an item consists of a (pointer to a) locals list
12404: (third), an address in the code (second), and a tag for identifying the
12405: item (TOS). The following tags are used: @code{defstart},
12406: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12407: @code{scopestart}.
12408:
12409: @item conversion of digits > 35
12410: @cindex digits > 35
12411: The characters @code{[\]^_'} are the digits with the decimal value
12412: 36@minus{}41. There is no way to input many of the larger digits.
12413:
12414: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12415: @cindex @code{EXPECT}, display after end of input
12416: @cindex @code{ACCEPT}, display after end of input
12417: The cursor is moved to the end of the entered string. If the input is
12418: terminated using the @kbd{Return} key, a space is typed.
12419:
12420: @item exception abort sequence of @code{ABORT"}:
12421: @cindex exception abort sequence of @code{ABORT"}
12422: @cindex @code{ABORT"}, exception abort sequence
12423: The error string is stored into the variable @code{"error} and a
12424: @code{-2 throw} is performed.
12425:
12426: @item input line terminator:
12427: @cindex input line terminator
12428: @cindex line terminator on input
12429: @cindex newline character on input
12430: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12431: lines. One of these characters is typically produced when you type the
12432: @kbd{Enter} or @kbd{Return} key.
12433:
12434: @item maximum size of a counted string:
12435: @cindex maximum size of a counted string
12436: @cindex counted string, maximum size
12437: @code{s" /counted-string" environment? drop .}. Currently 255 characters
12438: on all platforms, but this may change.
12439:
12440: @item maximum size of a parsed string:
12441: @cindex maximum size of a parsed string
12442: @cindex parsed string, maximum size
12443: Given by the constant @code{/line}. Currently 255 characters.
12444:
12445: @item maximum size of a definition name, in characters:
12446: @cindex maximum size of a definition name, in characters
12447: @cindex name, maximum length
12448: MAXU/8
12449:
12450: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12451: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12452: @cindex @code{ENVIRONMENT?} string length, maximum
12453: MAXU/8
12454:
12455: @item method of selecting the user input device:
12456: @cindex user input device, method of selecting
12457: The user input device is the standard input. There is currently no way to
12458: change it from within Gforth. However, the input can typically be
12459: redirected in the command line that starts Gforth.
12460:
12461: @item method of selecting the user output device:
12462: @cindex user output device, method of selecting
12463: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
12464: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12465: output when the user output device is a terminal, otherwise the output
12466: is buffered.
12467:
12468: @item methods of dictionary compilation:
12469: What are we expected to document here?
12470:
12471: @item number of bits in one address unit:
12472: @cindex number of bits in one address unit
12473: @cindex address unit, size in bits
12474: @code{s" address-units-bits" environment? drop .}. 8 in all current
12475: platforms.
12476:
12477: @item number representation and arithmetic:
12478: @cindex number representation and arithmetic
12479: Processor-dependent. Binary two's complement on all current platforms.
12480:
12481: @item ranges for integer types:
12482: @cindex ranges for integer types
12483: @cindex integer types, ranges
12484: Installation-dependent. Make environmental queries for @code{MAX-N},
12485: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12486: unsigned (and positive) types is 0. The lower bound for signed types on
12487: two's complement and one's complement machines machines can be computed
12488: by adding 1 to the upper bound.
12489:
12490: @item read-only data space regions:
12491: @cindex read-only data space regions
12492: @cindex data-space, read-only regions
12493: The whole Forth data space is writable.
12494:
12495: @item size of buffer at @code{WORD}:
12496: @cindex size of buffer at @code{WORD}
12497: @cindex @code{WORD} buffer size
12498: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12499: shared with the pictured numeric output string. If overwriting
12500: @code{PAD} is acceptable, it is as large as the remaining dictionary
12501: space, although only as much can be sensibly used as fits in a counted
12502: string.
12503:
12504: @item size of one cell in address units:
12505: @cindex cell size
12506: @code{1 cells .}.
12507:
12508: @item size of one character in address units:
12509: @cindex char size
12510: @code{1 chars .}. 1 on all current platforms.
12511:
12512: @item size of the keyboard terminal buffer:
12513: @cindex size of the keyboard terminal buffer
12514: @cindex terminal buffer, size
12515: Varies. You can determine the size at a specific time using @code{lp@@
12516: tib - .}. It is shared with the locals stack and TIBs of files that
12517: include the current file. You can change the amount of space for TIBs
12518: and locals stack at Gforth startup with the command line option
12519: @code{-l}.
12520:
12521: @item size of the pictured numeric output buffer:
12522: @cindex size of the pictured numeric output buffer
12523: @cindex pictured numeric output buffer, size
12524: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12525: shared with @code{WORD}.
12526:
12527: @item size of the scratch area returned by @code{PAD}:
12528: @cindex size of the scratch area returned by @code{PAD}
12529: @cindex @code{PAD} size
12530: The remainder of dictionary space. @code{unused pad here - - .}.
12531:
12532: @item system case-sensitivity characteristics:
12533: @cindex case-sensitivity characteristics
12534: Dictionary searches are case-insensitive (except in
12535: @code{TABLE}s). However, as explained above under @i{character-set
12536: extensions}, the matching for non-ASCII characters is determined by the
12537: locale you are using. In the default @code{C} locale all non-ASCII
12538: characters are matched case-sensitively.
12539:
12540: @item system prompt:
12541: @cindex system prompt
12542: @cindex prompt
12543: @code{ ok} in interpret state, @code{ compiled} in compile state.
12544:
12545: @item division rounding:
12546: @cindex division rounding
12547: installation dependent. @code{s" floored" environment? drop .}. We leave
12548: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12549: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12550:
12551: @item values of @code{STATE} when true:
12552: @cindex @code{STATE} values
12553: -1.
12554:
12555: @item values returned after arithmetic overflow:
12556: On two's complement machines, arithmetic is performed modulo
12557: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12558: arithmetic (with appropriate mapping for signed types). Division by zero
12559: typically results in a @code{-55 throw} (Floating-point unidentified
12560: fault) or @code{-10 throw} (divide by zero).
12561:
12562: @item whether the current definition can be found after @t{DOES>}:
12563: @cindex @t{DOES>}, visibility of current definition
12564: No.
12565:
12566: @end table
12567:
12568: @c ---------------------------------------------------------------------
12569: @node core-ambcond, core-other, core-idef, The Core Words
12570: @subsection Ambiguous conditions
12571: @c ---------------------------------------------------------------------
12572: @cindex core words, ambiguous conditions
12573: @cindex ambiguous conditions, core words
12574:
12575: @table @i
12576:
12577: @item a name is neither a word nor a number:
12578: @cindex name not found
12579: @cindex undefined word
12580: @code{-13 throw} (Undefined word).
12581:
12582: @item a definition name exceeds the maximum length allowed:
12583: @cindex word name too long
12584: @code{-19 throw} (Word name too long)
12585:
12586: @item addressing a region not inside the various data spaces of the forth system:
12587: @cindex Invalid memory address
12588: The stacks, code space and header space are accessible. Machine code space is
12589: typically readable. Accessing other addresses gives results dependent on
12590: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12591: address).
12592:
12593: @item argument type incompatible with parameter:
12594: @cindex argument type mismatch
12595: This is usually not caught. Some words perform checks, e.g., the control
12596: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12597: mismatch).
12598:
12599: @item attempting to obtain the execution token of a word with undefined execution semantics:
12600: @cindex Interpreting a compile-only word, for @code{'} etc.
12601: @cindex execution token of words with undefined execution semantics
12602: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12603: get an execution token for @code{compile-only-error} (which performs a
12604: @code{-14 throw} when executed).
12605:
12606: @item dividing by zero:
12607: @cindex dividing by zero
12608: @cindex floating point unidentified fault, integer division
12609: On some platforms, this produces a @code{-10 throw} (Division by
12610: zero); on other systems, this typically results in a @code{-55 throw}
12611: (Floating-point unidentified fault).
12612:
12613: @item insufficient data stack or return stack space:
12614: @cindex insufficient data stack or return stack space
12615: @cindex stack overflow
12616: @cindex address alignment exception, stack overflow
12617: @cindex Invalid memory address, stack overflow
12618: Depending on the operating system, the installation, and the invocation
12619: of Gforth, this is either checked by the memory management hardware, or
12620: it is not checked. If it is checked, you typically get a @code{-3 throw}
12621: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12622: throw} (Invalid memory address) (depending on the platform and how you
12623: achieved the overflow) as soon as the overflow happens. If it is not
12624: checked, overflows typically result in mysterious illegal memory
12625: accesses, producing @code{-9 throw} (Invalid memory address) or
12626: @code{-23 throw} (Address alignment exception); they might also destroy
12627: the internal data structure of @code{ALLOCATE} and friends, resulting in
12628: various errors in these words.
12629:
12630: @item insufficient space for loop control parameters:
12631: @cindex insufficient space for loop control parameters
12632: Like other return stack overflows.
12633:
12634: @item insufficient space in the dictionary:
12635: @cindex insufficient space in the dictionary
12636: @cindex dictionary overflow
12637: If you try to allot (either directly with @code{allot}, or indirectly
12638: with @code{,}, @code{create} etc.) more memory than available in the
12639: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12640: to access memory beyond the end of the dictionary, the results are
12641: similar to stack overflows.
12642:
12643: @item interpreting a word with undefined interpretation semantics:
12644: @cindex interpreting a word with undefined interpretation semantics
12645: @cindex Interpreting a compile-only word
12646: For some words, we have defined interpretation semantics. For the
12647: others: @code{-14 throw} (Interpreting a compile-only word).
12648:
12649: @item modifying the contents of the input buffer or a string literal:
12650: @cindex modifying the contents of the input buffer or a string literal
12651: These are located in writable memory and can be modified.
12652:
12653: @item overflow of the pictured numeric output string:
12654: @cindex overflow of the pictured numeric output string
12655: @cindex pictured numeric output string, overflow
12656: @code{-17 throw} (Pictured numeric ouput string overflow).
12657:
12658: @item parsed string overflow:
12659: @cindex parsed string overflow
12660: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12661:
12662: @item producing a result out of range:
12663: @cindex result out of range
12664: On two's complement machines, arithmetic is performed modulo
12665: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12666: arithmetic (with appropriate mapping for signed types). Division by zero
12667: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12668: throw} (floating point unidentified fault). @code{convert} and
12669: @code{>number} currently overflow silently.
12670:
12671: @item reading from an empty data or return stack:
12672: @cindex stack empty
12673: @cindex stack underflow
12674: @cindex return stack underflow
12675: The data stack is checked by the outer (aka text) interpreter after
12676: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12677: underflow) is performed. Apart from that, stacks may be checked or not,
12678: depending on operating system, installation, and invocation. If they are
12679: caught by a check, they typically result in @code{-4 throw} (Stack
12680: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12681: (Invalid memory address), depending on the platform and which stack
12682: underflows and by how much. Note that even if the system uses checking
12683: (through the MMU), your program may have to underflow by a significant
12684: number of stack items to trigger the reaction (the reason for this is
12685: that the MMU, and therefore the checking, works with a page-size
12686: granularity). If there is no checking, the symptoms resulting from an
12687: underflow are similar to those from an overflow. Unbalanced return
12688: stack errors can result in a variety of symptoms, including @code{-9 throw}
12689: (Invalid memory address) and Illegal Instruction (typically @code{-260
12690: throw}).
12691:
12692: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12693: @cindex unexpected end of the input buffer
12694: @cindex zero-length string as a name
12695: @cindex Attempt to use zero-length string as a name
12696: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12697: use zero-length string as a name). Words like @code{'} probably will not
12698: find what they search. Note that it is possible to create zero-length
12699: names with @code{nextname} (should it not?).
12700:
12701: @item @code{>IN} greater than input buffer:
12702: @cindex @code{>IN} greater than input buffer
12703: The next invocation of a parsing word returns a string with length 0.
12704:
12705: @item @code{RECURSE} appears after @code{DOES>}:
12706: @cindex @code{RECURSE} appears after @code{DOES>}
12707: Compiles a recursive call to the defining word, not to the defined word.
12708:
12709: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12710: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
12711: @cindex argument type mismatch, @code{RESTORE-INPUT}
12712: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12713: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12714: the end of the file was reached), its source-id may be
12715: reused. Therefore, restoring an input source specification referencing a
12716: closed file may lead to unpredictable results instead of a @code{-12
12717: THROW}.
12718:
12719: In the future, Gforth may be able to restore input source specifications
12720: from other than the current input source.
12721:
12722: @item data space containing definitions gets de-allocated:
12723: @cindex data space containing definitions gets de-allocated
12724: Deallocation with @code{allot} is not checked. This typically results in
12725: memory access faults or execution of illegal instructions.
12726:
12727: @item data space read/write with incorrect alignment:
12728: @cindex data space read/write with incorrect alignment
12729: @cindex alignment faults
12730: @cindex address alignment exception
12731: Processor-dependent. Typically results in a @code{-23 throw} (Address
12732: alignment exception). Under Linux-Intel on a 486 or later processor with
12733: alignment turned on, incorrect alignment results in a @code{-9 throw}
12734: (Invalid memory address). There are reportedly some processors with
12735: alignment restrictions that do not report violations.
12736:
12737: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12738: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12739: Like other alignment errors.
12740:
12741: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12742: Like other stack underflows.
12743:
12744: @item loop control parameters not available:
12745: @cindex loop control parameters not available
12746: Not checked. The counted loop words simply assume that the top of return
12747: stack items are loop control parameters and behave accordingly.
12748:
12749: @item most recent definition does not have a name (@code{IMMEDIATE}):
12750: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12751: @cindex last word was headerless
12752: @code{abort" last word was headerless"}.
12753:
12754: @item name not defined by @code{VALUE} used by @code{TO}:
12755: @cindex name not defined by @code{VALUE} used by @code{TO}
12756: @cindex @code{TO} on non-@code{VALUE}s
12757: @cindex Invalid name argument, @code{TO}
12758: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12759: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12760:
12761: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12762: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
12763: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
12764: @code{-13 throw} (Undefined word)
12765:
12766: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12767: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12768: Gforth behaves as if they were of the same type. I.e., you can predict
12769: the behaviour by interpreting all parameters as, e.g., signed.
12770:
12771: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12772: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12773: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12774: compilation semantics of @code{TO}.
12775:
12776: @item String longer than a counted string returned by @code{WORD}:
12777: @cindex string longer than a counted string returned by @code{WORD}
12778: @cindex @code{WORD}, string overflow
12779: Not checked. The string will be ok, but the count will, of course,
12780: contain only the least significant bits of the length.
12781:
12782: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12783: @cindex @code{LSHIFT}, large shift counts
12784: @cindex @code{RSHIFT}, large shift counts
12785: Processor-dependent. Typical behaviours are returning 0 and using only
12786: the low bits of the shift count.
12787:
12788: @item word not defined via @code{CREATE}:
12789: @cindex @code{>BODY} of non-@code{CREATE}d words
12790: @code{>BODY} produces the PFA of the word no matter how it was defined.
12791:
12792: @cindex @code{DOES>} of non-@code{CREATE}d words
12793: @code{DOES>} changes the execution semantics of the last defined word no
12794: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12795: @code{CREATE , DOES>}.
12796:
12797: @item words improperly used outside @code{<#} and @code{#>}:
12798: Not checked. As usual, you can expect memory faults.
12799:
12800: @end table
12801:
12802:
12803: @c ---------------------------------------------------------------------
12804: @node core-other, , core-ambcond, The Core Words
12805: @subsection Other system documentation
12806: @c ---------------------------------------------------------------------
12807: @cindex other system documentation, core words
12808: @cindex core words, other system documentation
12809:
12810: @table @i
12811: @item nonstandard words using @code{PAD}:
12812: @cindex @code{PAD} use by nonstandard words
12813: None.
12814:
12815: @item operator's terminal facilities available:
12816: @cindex operator's terminal facilities available
12817: After processing the OS's command line, Gforth goes into interactive mode,
12818: and you can give commands to Gforth interactively. The actual facilities
12819: available depend on how you invoke Gforth.
12820:
12821: @item program data space available:
12822: @cindex program data space available
12823: @cindex data space available
12824: @code{UNUSED .} gives the remaining dictionary space. The total
12825: dictionary space can be specified with the @code{-m} switch
12826: (@pxref{Invoking Gforth}) when Gforth starts up.
12827:
12828: @item return stack space available:
12829: @cindex return stack space available
12830: You can compute the total return stack space in cells with
12831: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12832: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12833:
12834: @item stack space available:
12835: @cindex stack space available
12836: You can compute the total data stack space in cells with
12837: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12838: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12839:
12840: @item system dictionary space required, in address units:
12841: @cindex system dictionary space required, in address units
12842: Type @code{here forthstart - .} after startup. At the time of this
12843: writing, this gives 80080 (bytes) on a 32-bit system.
12844: @end table
12845:
12846:
12847: @c =====================================================================
12848: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12849: @section The optional Block word set
12850: @c =====================================================================
12851: @cindex system documentation, block words
12852: @cindex block words, system documentation
12853:
12854: @menu
12855: * block-idef:: Implementation Defined Options
12856: * block-ambcond:: Ambiguous Conditions
12857: * block-other:: Other System Documentation
12858: @end menu
12859:
12860:
12861: @c ---------------------------------------------------------------------
12862: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12863: @subsection Implementation Defined Options
12864: @c ---------------------------------------------------------------------
12865: @cindex implementation-defined options, block words
12866: @cindex block words, implementation-defined options
12867:
12868: @table @i
12869: @item the format for display by @code{LIST}:
12870: @cindex @code{LIST} display format
12871: First the screen number is displayed, then 16 lines of 64 characters,
12872: each line preceded by the line number.
12873:
12874: @item the length of a line affected by @code{\}:
12875: @cindex length of a line affected by @code{\}
12876: @cindex @code{\}, line length in blocks
12877: 64 characters.
12878: @end table
12879:
12880:
12881: @c ---------------------------------------------------------------------
12882: @node block-ambcond, block-other, block-idef, The optional Block word set
12883: @subsection Ambiguous conditions
12884: @c ---------------------------------------------------------------------
12885: @cindex block words, ambiguous conditions
12886: @cindex ambiguous conditions, block words
12887:
12888: @table @i
12889: @item correct block read was not possible:
12890: @cindex block read not possible
12891: Typically results in a @code{throw} of some OS-derived value (between
12892: -512 and -2048). If the blocks file was just not long enough, blanks are
12893: supplied for the missing portion.
12894:
12895: @item I/O exception in block transfer:
12896: @cindex I/O exception in block transfer
12897: @cindex block transfer, I/O exception
12898: Typically results in a @code{throw} of some OS-derived value (between
12899: -512 and -2048).
12900:
12901: @item invalid block number:
12902: @cindex invalid block number
12903: @cindex block number invalid
12904: @code{-35 throw} (Invalid block number)
12905:
12906: @item a program directly alters the contents of @code{BLK}:
12907: @cindex @code{BLK}, altering @code{BLK}
12908: The input stream is switched to that other block, at the same
12909: position. If the storing to @code{BLK} happens when interpreting
12910: non-block input, the system will get quite confused when the block ends.
12911:
12912: @item no current block buffer for @code{UPDATE}:
12913: @cindex @code{UPDATE}, no current block buffer
12914: @code{UPDATE} has no effect.
12915:
12916: @end table
12917:
12918: @c ---------------------------------------------------------------------
12919: @node block-other, , block-ambcond, The optional Block word set
12920: @subsection Other system documentation
12921: @c ---------------------------------------------------------------------
12922: @cindex other system documentation, block words
12923: @cindex block words, other system documentation
12924:
12925: @table @i
12926: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12927: No restrictions (yet).
12928:
12929: @item the number of blocks available for source and data:
12930: depends on your disk space.
12931:
12932: @end table
12933:
12934:
12935: @c =====================================================================
12936: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12937: @section The optional Double Number word set
12938: @c =====================================================================
12939: @cindex system documentation, double words
12940: @cindex double words, system documentation
12941:
12942: @menu
12943: * double-ambcond:: Ambiguous Conditions
12944: @end menu
12945:
12946:
12947: @c ---------------------------------------------------------------------
12948: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
12949: @subsection Ambiguous conditions
12950: @c ---------------------------------------------------------------------
12951: @cindex double words, ambiguous conditions
12952: @cindex ambiguous conditions, double words
12953:
12954: @table @i
12955: @item @i{d} outside of range of @i{n} in @code{D>S}:
12956: @cindex @code{D>S}, @i{d} out of range of @i{n}
12957: The least significant cell of @i{d} is produced.
12958:
12959: @end table
12960:
12961:
12962: @c =====================================================================
12963: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
12964: @section The optional Exception word set
12965: @c =====================================================================
12966: @cindex system documentation, exception words
12967: @cindex exception words, system documentation
12968:
12969: @menu
12970: * exception-idef:: Implementation Defined Options
12971: @end menu
12972:
12973:
12974: @c ---------------------------------------------------------------------
12975: @node exception-idef, , The optional Exception word set, The optional Exception word set
12976: @subsection Implementation Defined Options
12977: @c ---------------------------------------------------------------------
12978: @cindex implementation-defined options, exception words
12979: @cindex exception words, implementation-defined options
12980:
12981: @table @i
12982: @item @code{THROW}-codes used in the system:
12983: @cindex @code{THROW}-codes used in the system
12984: The codes -256@minus{}-511 are used for reporting signals. The mapping
12985: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
12986: codes -512@minus{}-2047 are used for OS errors (for file and memory
12987: allocation operations). The mapping from OS error numbers to throw codes
12988: is -512@minus{}@code{errno}. One side effect of this mapping is that
12989: undefined OS errors produce a message with a strange number; e.g.,
12990: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
12991: @end table
12992:
12993: @c =====================================================================
12994: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
12995: @section The optional Facility word set
12996: @c =====================================================================
12997: @cindex system documentation, facility words
12998: @cindex facility words, system documentation
12999:
13000: @menu
13001: * facility-idef:: Implementation Defined Options
13002: * facility-ambcond:: Ambiguous Conditions
13003: @end menu
13004:
13005:
13006: @c ---------------------------------------------------------------------
13007: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13008: @subsection Implementation Defined Options
13009: @c ---------------------------------------------------------------------
13010: @cindex implementation-defined options, facility words
13011: @cindex facility words, implementation-defined options
13012:
13013: @table @i
13014: @item encoding of keyboard events (@code{EKEY}):
13015: @cindex keyboard events, encoding in @code{EKEY}
13016: @cindex @code{EKEY}, encoding of keyboard events
13017: Keys corresponding to ASCII characters are encoded as ASCII characters.
13018: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13019: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13020: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13021: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
13022:
13023:
13024: @item duration of a system clock tick:
13025: @cindex duration of a system clock tick
13026: @cindex clock tick duration
13027: System dependent. With respect to @code{MS}, the time is specified in
13028: microseconds. How well the OS and the hardware implement this, is
13029: another question.
13030:
13031: @item repeatability to be expected from the execution of @code{MS}:
13032: @cindex repeatability to be expected from the execution of @code{MS}
13033: @cindex @code{MS}, repeatability to be expected
13034: System dependent. On Unix, a lot depends on load. If the system is
13035: lightly loaded, and the delay is short enough that Gforth does not get
13036: swapped out, the performance should be acceptable. Under MS-DOS and
13037: other single-tasking systems, it should be good.
13038:
13039: @end table
13040:
13041:
13042: @c ---------------------------------------------------------------------
13043: @node facility-ambcond, , facility-idef, The optional Facility word set
13044: @subsection Ambiguous conditions
13045: @c ---------------------------------------------------------------------
13046: @cindex facility words, ambiguous conditions
13047: @cindex ambiguous conditions, facility words
13048:
13049: @table @i
13050: @item @code{AT-XY} can't be performed on user output device:
13051: @cindex @code{AT-XY} can't be performed on user output device
13052: Largely terminal dependent. No range checks are done on the arguments.
13053: No errors are reported. You may see some garbage appearing, you may see
13054: simply nothing happen.
13055:
13056: @end table
13057:
13058:
13059: @c =====================================================================
13060: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13061: @section The optional File-Access word set
13062: @c =====================================================================
13063: @cindex system documentation, file words
13064: @cindex file words, system documentation
13065:
13066: @menu
13067: * file-idef:: Implementation Defined Options
13068: * file-ambcond:: Ambiguous Conditions
13069: @end menu
13070:
13071: @c ---------------------------------------------------------------------
13072: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13073: @subsection Implementation Defined Options
13074: @c ---------------------------------------------------------------------
13075: @cindex implementation-defined options, file words
13076: @cindex file words, implementation-defined options
13077:
13078: @table @i
13079: @item file access methods used:
13080: @cindex file access methods used
13081: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13082: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13083: @code{wb}): The file is cleared, if it exists, and created, if it does
13084: not (with both @code{open-file} and @code{create-file}). Under Unix
13085: @code{create-file} creates a file with 666 permissions modified by your
13086: umask.
13087:
13088: @item file exceptions:
13089: @cindex file exceptions
13090: The file words do not raise exceptions (except, perhaps, memory access
13091: faults when you pass illegal addresses or file-ids).
13092:
13093: @item file line terminator:
13094: @cindex file line terminator
13095: System-dependent. Gforth uses C's newline character as line
13096: terminator. What the actual character code(s) of this are is
13097: system-dependent.
13098:
13099: @item file name format:
13100: @cindex file name format
13101: System dependent. Gforth just uses the file name format of your OS.
13102:
13103: @item information returned by @code{FILE-STATUS}:
13104: @cindex @code{FILE-STATUS}, returned information
13105: @code{FILE-STATUS} returns the most powerful file access mode allowed
13106: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13107: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13108: along with the returned mode.
13109:
13110: @item input file state after an exception when including source:
13111: @cindex exception when including source
13112: All files that are left via the exception are closed.
13113:
13114: @item @i{ior} values and meaning:
13115: @cindex @i{ior} values and meaning
13116: @cindex @i{wior} values and meaning
13117: The @i{ior}s returned by the file and memory allocation words are
13118: intended as throw codes. They typically are in the range
13119: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
13120: @i{ior}s is -512@minus{}@i{errno}.
13121:
13122: @item maximum depth of file input nesting:
13123: @cindex maximum depth of file input nesting
13124: @cindex file input nesting, maximum depth
13125: limited by the amount of return stack, locals/TIB stack, and the number
13126: of open files available. This should not give you troubles.
13127:
13128: @item maximum size of input line:
13129: @cindex maximum size of input line
13130: @cindex input line size, maximum
13131: @code{/line}. Currently 255.
13132:
13133: @item methods of mapping block ranges to files:
13134: @cindex mapping block ranges to files
13135: @cindex files containing blocks
13136: @cindex blocks in files
13137: By default, blocks are accessed in the file @file{blocks.fb} in the
13138: current working directory. The file can be switched with @code{USE}.
13139:
13140: @item number of string buffers provided by @code{S"}:
13141: @cindex @code{S"}, number of string buffers
13142: 1
13143:
13144: @item size of string buffer used by @code{S"}:
13145: @cindex @code{S"}, size of string buffer
13146: @code{/line}. currently 255.
13147:
13148: @end table
13149:
13150: @c ---------------------------------------------------------------------
13151: @node file-ambcond, , file-idef, The optional File-Access word set
13152: @subsection Ambiguous conditions
13153: @c ---------------------------------------------------------------------
13154: @cindex file words, ambiguous conditions
13155: @cindex ambiguous conditions, file words
13156:
13157: @table @i
13158: @item attempting to position a file outside its boundaries:
13159: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13160: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13161: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13162:
13163: @item attempting to read from file positions not yet written:
13164: @cindex reading from file positions not yet written
13165: End-of-file, i.e., zero characters are read and no error is reported.
13166:
13167: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13168: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
13169: An appropriate exception may be thrown, but a memory fault or other
13170: problem is more probable.
13171:
13172: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13173: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13174: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13175: The @i{ior} produced by the operation, that discovered the problem, is
13176: thrown.
13177:
13178: @item named file cannot be opened (@code{INCLUDED}):
13179: @cindex @code{INCLUDED}, named file cannot be opened
13180: The @i{ior} produced by @code{open-file} is thrown.
13181:
13182: @item requesting an unmapped block number:
13183: @cindex unmapped block numbers
13184: There are no unmapped legal block numbers. On some operating systems,
13185: writing a block with a large number may overflow the file system and
13186: have an error message as consequence.
13187:
13188: @item using @code{source-id} when @code{blk} is non-zero:
13189: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13190: @code{source-id} performs its function. Typically it will give the id of
13191: the source which loaded the block. (Better ideas?)
13192:
13193: @end table
13194:
13195:
13196: @c =====================================================================
13197: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13198: @section The optional Floating-Point word set
13199: @c =====================================================================
13200: @cindex system documentation, floating-point words
13201: @cindex floating-point words, system documentation
13202:
13203: @menu
13204: * floating-idef:: Implementation Defined Options
13205: * floating-ambcond:: Ambiguous Conditions
13206: @end menu
13207:
13208:
13209: @c ---------------------------------------------------------------------
13210: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13211: @subsection Implementation Defined Options
13212: @c ---------------------------------------------------------------------
13213: @cindex implementation-defined options, floating-point words
13214: @cindex floating-point words, implementation-defined options
13215:
13216: @table @i
13217: @item format and range of floating point numbers:
13218: @cindex format and range of floating point numbers
13219: @cindex floating point numbers, format and range
13220: System-dependent; the @code{double} type of C.
13221:
13222: @item results of @code{REPRESENT} when @i{float} is out of range:
13223: @cindex @code{REPRESENT}, results when @i{float} is out of range
13224: System dependent; @code{REPRESENT} is implemented using the C library
13225: function @code{ecvt()} and inherits its behaviour in this respect.
13226:
13227: @item rounding or truncation of floating-point numbers:
13228: @cindex rounding of floating-point numbers
13229: @cindex truncation of floating-point numbers
13230: @cindex floating-point numbers, rounding or truncation
13231: System dependent; the rounding behaviour is inherited from the hosting C
13232: compiler. IEEE-FP-based (i.e., most) systems by default round to
13233: nearest, and break ties by rounding to even (i.e., such that the last
13234: bit of the mantissa is 0).
13235:
13236: @item size of floating-point stack:
13237: @cindex floating-point stack size
13238: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13239: the floating-point stack (in floats). You can specify this on startup
13240: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13241:
13242: @item width of floating-point stack:
13243: @cindex floating-point stack width
13244: @code{1 floats}.
13245:
13246: @end table
13247:
13248:
13249: @c ---------------------------------------------------------------------
13250: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13251: @subsection Ambiguous conditions
13252: @c ---------------------------------------------------------------------
13253: @cindex floating-point words, ambiguous conditions
13254: @cindex ambiguous conditions, floating-point words
13255:
13256: @table @i
13257: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13258: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13259: System-dependent. Typically results in a @code{-23 THROW} like other
13260: alignment violations.
13261:
13262: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13263: @cindex @code{f@@} used with an address that is not float aligned
13264: @cindex @code{f!} used with an address that is not float aligned
13265: System-dependent. Typically results in a @code{-23 THROW} like other
13266: alignment violations.
13267:
13268: @item floating-point result out of range:
13269: @cindex floating-point result out of range
13270: System-dependent. Can result in a @code{-43 throw} (floating point
13271: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13272: (floating point inexact result), @code{-55 THROW} (Floating-point
13273: unidentified fault), or can produce a special value representing, e.g.,
13274: Infinity.
13275:
13276: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13277: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13278: System-dependent. Typically results in an alignment fault like other
13279: alignment violations.
13280:
13281: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13282: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
13283: The floating-point number is converted into decimal nonetheless.
13284:
13285: @item Both arguments are equal to zero (@code{FATAN2}):
13286: @cindex @code{FATAN2}, both arguments are equal to zero
13287: System-dependent. @code{FATAN2} is implemented using the C library
13288: function @code{atan2()}.
13289:
13290: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13291: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13292: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
13293: because of small errors and the tan will be a very large (or very small)
13294: but finite number.
13295:
13296: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13297: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
13298: The result is rounded to the nearest float.
13299:
13300: @item dividing by zero:
13301: @cindex dividing by zero, floating-point
13302: @cindex floating-point dividing by zero
13303: @cindex floating-point unidentified fault, FP divide-by-zero
13304: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13305: (floating point divide by zero) or @code{-55 throw} (Floating-point
13306: unidentified fault).
13307:
13308: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13309: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13310: System dependent. On IEEE-FP based systems the number is converted into
13311: an infinity.
13312:
13313: @item @i{float}<1 (@code{FACOSH}):
13314: @cindex @code{FACOSH}, @i{float}<1
13315: @cindex floating-point unidentified fault, @code{FACOSH}
13316: Platform-dependent; on IEEE-FP systems typically produces a NaN.
13317:
13318: @item @i{float}=<-1 (@code{FLNP1}):
13319: @cindex @code{FLNP1}, @i{float}=<-1
13320: @cindex floating-point unidentified fault, @code{FLNP1}
13321: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13322: negative infinity for @i{float}=-1).
13323:
13324: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13325: @cindex @code{FLN}, @i{float}=<0
13326: @cindex @code{FLOG}, @i{float}=<0
13327: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
13328: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13329: negative infinity for @i{float}=0).
13330:
13331: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13332: @cindex @code{FASINH}, @i{float}<0
13333: @cindex @code{FSQRT}, @i{float}<0
13334: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
13335: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13336: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13337: C library?).
13338:
13339: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13340: @cindex @code{FACOS}, |@i{float}|>1
13341: @cindex @code{FASIN}, |@i{float}|>1
13342: @cindex @code{FATANH}, |@i{float}|>1
13343: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
13344: Platform-dependent; IEEE-FP systems typically produce a NaN.
13345:
13346: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13347: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
13348: @cindex floating-point unidentified fault, @code{F>D}
13349: Platform-dependent; typically, some double number is produced and no
13350: error is reported.
13351:
13352: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13353: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
13354: @code{Precision} characters of the numeric output area are used. If
13355: @code{precision} is too high, these words will smash the data or code
13356: close to @code{here}.
13357: @end table
13358:
13359: @c =====================================================================
13360: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13361: @section The optional Locals word set
13362: @c =====================================================================
13363: @cindex system documentation, locals words
13364: @cindex locals words, system documentation
13365:
13366: @menu
13367: * locals-idef:: Implementation Defined Options
13368: * locals-ambcond:: Ambiguous Conditions
13369: @end menu
13370:
13371:
13372: @c ---------------------------------------------------------------------
13373: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13374: @subsection Implementation Defined Options
13375: @c ---------------------------------------------------------------------
13376: @cindex implementation-defined options, locals words
13377: @cindex locals words, implementation-defined options
13378:
13379: @table @i
13380: @item maximum number of locals in a definition:
13381: @cindex maximum number of locals in a definition
13382: @cindex locals, maximum number in a definition
13383: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13384: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13385: characters. The number of locals in a definition is bounded by the size
13386: of locals-buffer, which contains the names of the locals.
13387:
13388: @end table
13389:
13390:
13391: @c ---------------------------------------------------------------------
13392: @node locals-ambcond, , locals-idef, The optional Locals word set
13393: @subsection Ambiguous conditions
13394: @c ---------------------------------------------------------------------
13395: @cindex locals words, ambiguous conditions
13396: @cindex ambiguous conditions, locals words
13397:
13398: @table @i
13399: @item executing a named local in interpretation state:
13400: @cindex local in interpretation state
13401: @cindex Interpreting a compile-only word, for a local
13402: Locals have no interpretation semantics. If you try to perform the
13403: interpretation semantics, you will get a @code{-14 throw} somewhere
13404: (Interpreting a compile-only word). If you perform the compilation
13405: semantics, the locals access will be compiled (irrespective of state).
13406:
13407: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
13408: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13409: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13410: @cindex Invalid name argument, @code{TO}
13411: @code{-32 throw} (Invalid name argument)
13412:
13413: @end table
13414:
13415:
13416: @c =====================================================================
13417: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13418: @section The optional Memory-Allocation word set
13419: @c =====================================================================
13420: @cindex system documentation, memory-allocation words
13421: @cindex memory-allocation words, system documentation
13422:
13423: @menu
13424: * memory-idef:: Implementation Defined Options
13425: @end menu
13426:
13427:
13428: @c ---------------------------------------------------------------------
13429: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13430: @subsection Implementation Defined Options
13431: @c ---------------------------------------------------------------------
13432: @cindex implementation-defined options, memory-allocation words
13433: @cindex memory-allocation words, implementation-defined options
13434:
13435: @table @i
13436: @item values and meaning of @i{ior}:
13437: @cindex @i{ior} values and meaning
13438: The @i{ior}s returned by the file and memory allocation words are
13439: intended as throw codes. They typically are in the range
13440: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
13441: @i{ior}s is -512@minus{}@i{errno}.
13442:
13443: @end table
13444:
13445: @c =====================================================================
13446: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13447: @section The optional Programming-Tools word set
13448: @c =====================================================================
13449: @cindex system documentation, programming-tools words
13450: @cindex programming-tools words, system documentation
13451:
13452: @menu
13453: * programming-idef:: Implementation Defined Options
13454: * programming-ambcond:: Ambiguous Conditions
13455: @end menu
13456:
13457:
13458: @c ---------------------------------------------------------------------
13459: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13460: @subsection Implementation Defined Options
13461: @c ---------------------------------------------------------------------
13462: @cindex implementation-defined options, programming-tools words
13463: @cindex programming-tools words, implementation-defined options
13464:
13465: @table @i
13466: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13467: @cindex @code{;CODE} ending sequence
13468: @cindex @code{CODE} ending sequence
13469: @code{END-CODE}
13470:
13471: @item manner of processing input following @code{;CODE} and @code{CODE}:
13472: @cindex @code{;CODE}, processing input
13473: @cindex @code{CODE}, processing input
13474: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13475: the input is processed by the text interpreter, (starting) in interpret
13476: state.
13477:
13478: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13479: @cindex @code{ASSEMBLER}, search order capability
13480: The ANS Forth search order word set.
13481:
13482: @item source and format of display by @code{SEE}:
13483: @cindex @code{SEE}, source and format of output
13484: The source for @code{see} is the executable code used by the inner
13485: interpreter. The current @code{see} tries to output Forth source code
13486: (and on some platforms, assembly code for primitives) as well as
13487: possible.
13488:
13489: @end table
13490:
13491: @c ---------------------------------------------------------------------
13492: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13493: @subsection Ambiguous conditions
13494: @c ---------------------------------------------------------------------
13495: @cindex programming-tools words, ambiguous conditions
13496: @cindex ambiguous conditions, programming-tools words
13497:
13498: @table @i
13499:
13500: @item deleting the compilation word list (@code{FORGET}):
13501: @cindex @code{FORGET}, deleting the compilation word list
13502: Not implemented (yet).
13503:
13504: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13505: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13506: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
13507: @cindex control-flow stack underflow
13508: This typically results in an @code{abort"} with a descriptive error
13509: message (may change into a @code{-22 throw} (Control structure mismatch)
13510: in the future). You may also get a memory access error. If you are
13511: unlucky, this ambiguous condition is not caught.
13512:
13513: @item @i{name} can't be found (@code{FORGET}):
13514: @cindex @code{FORGET}, @i{name} can't be found
13515: Not implemented (yet).
13516:
13517: @item @i{name} not defined via @code{CREATE}:
13518: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
13519: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13520: the execution semantics of the last defined word no matter how it was
13521: defined.
13522:
13523: @item @code{POSTPONE} applied to @code{[IF]}:
13524: @cindex @code{POSTPONE} applied to @code{[IF]}
13525: @cindex @code{[IF]} and @code{POSTPONE}
13526: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13527: equivalent to @code{[IF]}.
13528:
13529: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13530: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13531: Continue in the same state of conditional compilation in the next outer
13532: input source. Currently there is no warning to the user about this.
13533:
13534: @item removing a needed definition (@code{FORGET}):
13535: @cindex @code{FORGET}, removing a needed definition
13536: Not implemented (yet).
13537:
13538: @end table
13539:
13540:
13541: @c =====================================================================
13542: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13543: @section The optional Search-Order word set
13544: @c =====================================================================
13545: @cindex system documentation, search-order words
13546: @cindex search-order words, system documentation
13547:
13548: @menu
13549: * search-idef:: Implementation Defined Options
13550: * search-ambcond:: Ambiguous Conditions
13551: @end menu
13552:
13553:
13554: @c ---------------------------------------------------------------------
13555: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13556: @subsection Implementation Defined Options
13557: @c ---------------------------------------------------------------------
13558: @cindex implementation-defined options, search-order words
13559: @cindex search-order words, implementation-defined options
13560:
13561: @table @i
13562: @item maximum number of word lists in search order:
13563: @cindex maximum number of word lists in search order
13564: @cindex search order, maximum depth
13565: @code{s" wordlists" environment? drop .}. Currently 16.
13566:
13567: @item minimum search order:
13568: @cindex minimum search order
13569: @cindex search order, minimum
13570: @code{root root}.
13571:
13572: @end table
13573:
13574: @c ---------------------------------------------------------------------
13575: @node search-ambcond, , search-idef, The optional Search-Order word set
13576: @subsection Ambiguous conditions
13577: @c ---------------------------------------------------------------------
13578: @cindex search-order words, ambiguous conditions
13579: @cindex ambiguous conditions, search-order words
13580:
13581: @table @i
13582: @item changing the compilation word list (during compilation):
13583: @cindex changing the compilation word list (during compilation)
13584: @cindex compilation word list, change before definition ends
13585: The word is entered into the word list that was the compilation word list
13586: at the start of the definition. Any changes to the name field (e.g.,
13587: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13588: are applied to the latest defined word (as reported by @code{latest} or
13589: @code{latestxt}), if possible, irrespective of the compilation word list.
13590:
13591: @item search order empty (@code{previous}):
13592: @cindex @code{previous}, search order empty
13593: @cindex vocstack empty, @code{previous}
13594: @code{abort" Vocstack empty"}.
13595:
13596: @item too many word lists in search order (@code{also}):
13597: @cindex @code{also}, too many word lists in search order
13598: @cindex vocstack full, @code{also}
13599: @code{abort" Vocstack full"}.
13600:
13601: @end table
13602:
13603: @c ***************************************************************
13604: @node Standard vs Extensions, Model, ANS conformance, Top
13605: @chapter Should I use Gforth extensions?
13606: @cindex Gforth extensions
13607:
13608: As you read through the rest of this manual, you will see documentation
13609: for @i{Standard} words, and documentation for some appealing Gforth
13610: @i{extensions}. You might ask yourself the question: @i{``Should I
13611: restrict myself to the standard, or should I use the extensions?''}
13612:
13613: The answer depends on the goals you have for the program you are working
13614: on:
13615:
13616: @itemize @bullet
13617:
13618: @item Is it just for yourself or do you want to share it with others?
13619:
13620: @item
13621: If you want to share it, do the others all use Gforth?
13622:
13623: @item
13624: If it is just for yourself, do you want to restrict yourself to Gforth?
13625:
13626: @end itemize
13627:
13628: If restricting the program to Gforth is ok, then there is no reason not
13629: to use extensions. It is still a good idea to keep to the standard
13630: where it is easy, in case you want to reuse these parts in another
13631: program that you want to be portable.
13632:
13633: If you want to be able to port the program to other Forth systems, there
13634: are the following points to consider:
13635:
13636: @itemize @bullet
13637:
13638: @item
13639: Most Forth systems that are being maintained support the ANS Forth
13640: standard. So if your program complies with the standard, it will be
13641: portable among many systems.
13642:
13643: @item
13644: A number of the Gforth extensions can be implemented in ANS Forth using
13645: public-domain files provided in the @file{compat/} directory. These are
13646: mentioned in the text in passing. There is no reason not to use these
13647: extensions, your program will still be ANS Forth compliant; just include
13648: the appropriate compat files with your program.
13649:
13650: @item
13651: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13652: analyse your program and determine what non-Standard words it relies
13653: upon. However, it does not check whether you use standard words in a
13654: non-standard way.
13655:
13656: @item
13657: Some techniques are not standardized by ANS Forth, and are hard or
13658: impossible to implement in a standard way, but can be implemented in
13659: most Forth systems easily, and usually in similar ways (e.g., accessing
13660: word headers). Forth has a rich historical precedent for programmers
13661: taking advantage of implementation-dependent features of their tools
13662: (for example, relying on a knowledge of the dictionary
13663: structure). Sometimes these techniques are necessary to extract every
13664: last bit of performance from the hardware, sometimes they are just a
13665: programming shorthand.
13666:
13667: @item
13668: Does using a Gforth extension save more work than the porting this part
13669: to other Forth systems (if any) will cost?
13670:
13671: @item
13672: Is the additional functionality worth the reduction in portability and
13673: the additional porting problems?
13674:
13675: @end itemize
13676:
13677: In order to perform these consideratios, you need to know what's
13678: standard and what's not. This manual generally states if something is
13679: non-standard, but the authoritative source is the
13680: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
13681: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13682: into the thought processes of the technical committee.
13683:
13684: Note also that portability between Forth systems is not the only
13685: portability issue; there is also the issue of portability between
13686: different platforms (processor/OS combinations).
13687:
13688: @c ***************************************************************
13689: @node Model, Integrating Gforth, Standard vs Extensions, Top
13690: @chapter Model
13691:
13692: This chapter has yet to be written. It will contain information, on
13693: which internal structures you can rely.
13694:
13695: @c ***************************************************************
13696: @node Integrating Gforth, Emacs and Gforth, Model, Top
13697: @chapter Integrating Gforth into C programs
13698:
13699: This is not yet implemented.
13700:
13701: Several people like to use Forth as scripting language for applications
13702: that are otherwise written in C, C++, or some other language.
13703:
13704: The Forth system ATLAST provides facilities for embedding it into
13705: applications; unfortunately it has several disadvantages: most
13706: importantly, it is not based on ANS Forth, and it is apparently dead
13707: (i.e., not developed further and not supported). The facilities
13708: provided by Gforth in this area are inspired by ATLAST's facilities, so
13709: making the switch should not be hard.
13710:
13711: We also tried to design the interface such that it can easily be
13712: implemented by other Forth systems, so that we may one day arrive at a
13713: standardized interface. Such a standard interface would allow you to
13714: replace the Forth system without having to rewrite C code.
13715:
13716: You embed the Gforth interpreter by linking with the library
13717: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13718: global symbols in this library that belong to the interface, have the
13719: prefix @code{forth_}. (Global symbols that are used internally have the
13720: prefix @code{gforth_}).
13721:
13722: You can include the declarations of Forth types and the functions and
13723: variables of the interface with @code{#include <forth.h>}.
13724:
13725: Types.
13726:
13727: Variables.
13728:
13729: Data and FP Stack pointer. Area sizes.
13730:
13731: functions.
13732:
13733: forth_init(imagefile)
13734: forth_evaluate(string) exceptions?
13735: forth_goto(address) (or forth_execute(xt)?)
13736: forth_continue() (a corountining mechanism)
13737:
13738: Adding primitives.
13739:
13740: No checking.
13741:
13742: Signals?
13743:
13744: Accessing the Stacks
13745:
13746: @c ******************************************************************
13747: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13748: @chapter Emacs and Gforth
13749: @cindex Emacs and Gforth
13750:
13751: @cindex @file{gforth.el}
13752: @cindex @file{forth.el}
13753: @cindex Rydqvist, Goran
13754: @cindex Kuehling, David
13755: @cindex comment editing commands
13756: @cindex @code{\}, editing with Emacs
13757: @cindex debug tracer editing commands
13758: @cindex @code{~~}, removal with Emacs
13759: @cindex Forth mode in Emacs
13760:
13761: Gforth comes with @file{gforth.el}, an improved version of
13762: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
13763: improvements are:
13764:
13765: @itemize @bullet
13766: @item
13767: A better handling of indentation.
13768: @item
13769: A custom hilighting engine for Forth-code.
13770: @item
13771: Comment paragraph filling (@kbd{M-q})
13772: @item
13773: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13774: @item
13775: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
13776: @item
13777: Support of the @code{info-lookup} feature for looking up the
13778: documentation of a word.
13779: @item
13780: Support for reading and writing blocks files.
13781: @end itemize
13782:
13783: To get a basic description of these features, enter Forth mode and
13784: type @kbd{C-h m}.
13785:
13786: @cindex source location of error or debugging output in Emacs
13787: @cindex error output, finding the source location in Emacs
13788: @cindex debugging output, finding the source location in Emacs
13789: In addition, Gforth supports Emacs quite well: The source code locations
13790: given in error messages, debugging output (from @code{~~}) and failed
13791: assertion messages are in the right format for Emacs' compilation mode
13792: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13793: Manual}) so the source location corresponding to an error or other
13794: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13795: @kbd{C-c C-c} for the error under the cursor).
13796:
13797: @cindex viewing the documentation of a word in Emacs
13798: @cindex context-sensitive help
13799: Moreover, for words documented in this manual, you can look up the
13800: glossary entry quickly by using @kbd{C-h TAB}
13801: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13802: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
13803: later and does not work for words containing @code{:}.
13804:
13805: @menu
13806: * Installing gforth.el:: Making Emacs aware of Forth.
13807: * Emacs Tags:: Viewing the source of a word in Emacs.
13808: * Hilighting:: Making Forth code look prettier.
13809: * Auto-Indentation:: Customizing auto-indentation.
13810: * Blocks Files:: Reading and writing blocks files.
13811: @end menu
13812:
13813: @c ----------------------------------
13814: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
13815: @section Installing gforth.el
13816: @cindex @file{.emacs}
13817: @cindex @file{gforth.el}, installation
13818: To make the features from @file{gforth.el} available in Emacs, add
13819: the following lines to your @file{.emacs} file:
13820:
13821: @example
13822: (autoload 'forth-mode "gforth.el")
13823: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
13824: auto-mode-alist))
13825: (autoload 'forth-block-mode "gforth.el")
13826: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
13827: auto-mode-alist))
13828: (add-hook 'forth-mode-hook (function (lambda ()
13829: ;; customize variables here:
13830: (setq forth-indent-level 4)
13831: (setq forth-minor-indent-level 2)
13832: (setq forth-hilight-level 3)
13833: ;;; ...
13834: )))
13835: @end example
13836:
13837: @c ----------------------------------
13838: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
13839: @section Emacs Tags
13840: @cindex @file{TAGS} file
13841: @cindex @file{etags.fs}
13842: @cindex viewing the source of a word in Emacs
13843: @cindex @code{require}, placement in files
13844: @cindex @code{include}, placement in files
13845: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
13846: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
13847: contains the definitions of all words defined afterwards. You can then
13848: find the source for a word using @kbd{M-.}. Note that Emacs can use
13849: several tags files at the same time (e.g., one for the Gforth sources
13850: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13851: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13852: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
13853: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
13854: with @file{etags.fs}, you should avoid putting definitions both before
13855: and after @code{require} etc., otherwise you will see the same file
13856: visited several times by commands like @code{tags-search}.
13857:
13858: @c ----------------------------------
13859: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
13860: @section Hilighting
13861: @cindex hilighting Forth code in Emacs
13862: @cindex highlighting Forth code in Emacs
13863: @file{gforth.el} comes with a custom source hilighting engine. When
13864: you open a file in @code{forth-mode}, it will be completely parsed,
13865: assigning faces to keywords, comments, strings etc. While you edit
13866: the file, modified regions get parsed and updated on-the-fly.
13867:
13868: Use the variable `forth-hilight-level' to change the level of
13869: decoration from 0 (no hilighting at all) to 3 (the default). Even if
13870: you set the hilighting level to 0, the parser will still work in the
13871: background, collecting information about whether regions of text are
13872: ``compiled'' or ``interpreted''. Those information are required for
13873: auto-indentation to work properly. Set `forth-disable-parser' to
13874: non-nil if your computer is too slow to handle parsing. This will
13875: have an impact on the smartness of the auto-indentation engine,
13876: though.
13877:
13878: Sometimes Forth sources define new features that should be hilighted,
13879: new control structures, defining-words etc. You can use the variable
13880: `forth-custom-words' to make @code{forth-mode} hilight additional
13881: words and constructs. See the docstring of `forth-words' for details
13882: (in Emacs, type @kbd{C-h v forth-words}).
13883:
13884: `forth-custom-words' is meant to be customized in your
13885: @file{.emacs} file. To customize hilighing in a file-specific manner,
13886: set `forth-local-words' in a local-variables section at the end of
13887: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
13888:
13889: Example:
13890: @example
13891: 0 [IF]
13892: Local Variables:
13893: forth-local-words:
13894: ((("t:") definition-starter (font-lock-keyword-face . 1)
13895: "[ \t\n]" t name (font-lock-function-name-face . 3))
13896: ((";t") definition-ender (font-lock-keyword-face . 1)))
13897: End:
13898: [THEN]
13899: @end example
13900:
13901: @c ----------------------------------
13902: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
13903: @section Auto-Indentation
13904: @cindex auto-indentation of Forth code in Emacs
13905: @cindex indentation of Forth code in Emacs
13906: @code{forth-mode} automatically tries to indent lines in a smart way,
13907: whenever you type @key{TAB} or break a line with @kbd{C-m}.
13908:
13909: Simple customization can be achieved by setting
13910: `forth-indent-level' and `forth-minor-indent-level' in your
13911: @file{.emacs} file. For historical reasons @file{gforth.el} indents
13912: per default by multiples of 4 columns. To use the more traditional
13913: 3-column indentation, add the following lines to your @file{.emacs}:
13914:
13915: @example
13916: (add-hook 'forth-mode-hook (function (lambda ()
13917: ;; customize variables here:
13918: (setq forth-indent-level 3)
13919: (setq forth-minor-indent-level 1)
13920: )))
13921: @end example
13922:
13923: If you want indentation to recognize non-default words, customize it
13924: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
13925: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
13926: v forth-indent-words}).
13927:
13928: To customize indentation in a file-specific manner, set
13929: `forth-local-indent-words' in a local-variables section at the end of
13930: your source file (@pxref{Local Variables in Files, Variables,,emacs,
13931: Emacs Manual}).
13932:
13933: Example:
13934: @example
13935: 0 [IF]
13936: Local Variables:
13937: forth-local-indent-words:
13938: ((("t:") (0 . 2) (0 . 2))
13939: ((";t") (-2 . 0) (0 . -2)))
13940: End:
13941: [THEN]
13942: @end example
13943:
13944: @c ----------------------------------
13945: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
13946: @section Blocks Files
13947: @cindex blocks files, use with Emacs
13948: @code{forth-mode} Autodetects blocks files by checking whether the
13949: length of the first line exceeds 1023 characters. It then tries to
13950: convert the file into normal text format. When you save the file, it
13951: will be written to disk as normal stream-source file.
13952:
13953: If you want to write blocks files, use @code{forth-blocks-mode}. It
13954: inherits all the features from @code{forth-mode}, plus some additions:
13955:
13956: @itemize @bullet
13957: @item
13958: Files are written to disk in blocks file format.
13959: @item
13960: Screen numbers are displayed in the mode line (enumerated beginning
13961: with the value of `forth-block-base')
13962: @item
13963: Warnings are displayed when lines exceed 64 characters.
13964: @item
13965: The beginning of the currently edited block is marked with an
13966: overlay-arrow.
13967: @end itemize
13968:
13969: There are some restrictions you should be aware of. When you open a
13970: blocks file that contains tabulator or newline characters, these
13971: characters will be translated into spaces when the file is written
13972: back to disk. If tabs or newlines are encountered during blocks file
13973: reading, an error is output to the echo area. So have a look at the
13974: `*Messages*' buffer, when Emacs' bell rings during reading.
13975:
13976: Please consult the docstring of @code{forth-blocks-mode} for more
13977: information by typing @kbd{C-h v forth-blocks-mode}).
13978:
13979: @c ******************************************************************
13980: @node Image Files, Engine, Emacs and Gforth, Top
13981: @chapter Image Files
13982: @cindex image file
13983: @cindex @file{.fi} files
13984: @cindex precompiled Forth code
13985: @cindex dictionary in persistent form
13986: @cindex persistent form of dictionary
13987:
13988: An image file is a file containing an image of the Forth dictionary,
13989: i.e., compiled Forth code and data residing in the dictionary. By
13990: convention, we use the extension @code{.fi} for image files.
13991:
13992: @menu
13993: * Image Licensing Issues:: Distribution terms for images.
13994: * Image File Background:: Why have image files?
13995: * Non-Relocatable Image Files:: don't always work.
13996: * Data-Relocatable Image Files:: are better.
13997: * Fully Relocatable Image Files:: better yet.
13998: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
13999: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
14000: * Modifying the Startup Sequence:: and turnkey applications.
14001: @end menu
14002:
14003: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14004: @section Image Licensing Issues
14005: @cindex license for images
14006: @cindex image license
14007:
14008: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14009: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14010: original image; i.e., according to copyright law it is a derived work of
14011: the original image.
14012:
14013: Since Gforth is distributed under the GNU GPL, the newly created image
14014: falls under the GNU GPL, too. In particular, this means that if you
14015: distribute the image, you have to make all of the sources for the image
14016: available, including those you wrote. For details see @ref{Copying, ,
14017: GNU General Public License (Section 3)}.
14018:
14019: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14020: contains only code compiled from the sources you gave it; if none of
14021: these sources is under the GPL, the terms discussed above do not apply
14022: to the image. However, if your image needs an engine (a gforth binary)
14023: that is under the GPL, you should make sure that you distribute both in
14024: a way that is at most a @emph{mere aggregation}, if you don't want the
14025: terms of the GPL to apply to the image.
14026:
14027: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
14028: @section Image File Background
14029: @cindex image file background
14030:
14031: Gforth consists not only of primitives (in the engine), but also of
14032: definitions written in Forth. Since the Forth compiler itself belongs to
14033: those definitions, it is not possible to start the system with the
14034: engine and the Forth source alone. Therefore we provide the Forth
14035: code as an image file in nearly executable form. When Gforth starts up,
14036: a C routine loads the image file into memory, optionally relocates the
14037: addresses, then sets up the memory (stacks etc.) according to
14038: information in the image file, and (finally) starts executing Forth
14039: code.
14040:
14041: The image file variants represent different compromises between the
14042: goals of making it easy to generate image files and making them
14043: portable.
14044:
14045: @cindex relocation at run-time
14046: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
14047: run-time. This avoids many of the complications discussed below (image
14048: files are data relocatable without further ado), but costs performance
14049: (one addition per memory access).
14050:
14051: @cindex relocation at load-time
14052: By contrast, the Gforth loader performs relocation at image load time. The
14053: loader also has to replace tokens that represent primitive calls with the
14054: appropriate code-field addresses (or code addresses in the case of
14055: direct threading).
14056:
14057: There are three kinds of image files, with different degrees of
14058: relocatability: non-relocatable, data-relocatable, and fully relocatable
14059: image files.
14060:
14061: @cindex image file loader
14062: @cindex relocating loader
14063: @cindex loader for image files
14064: These image file variants have several restrictions in common; they are
14065: caused by the design of the image file loader:
14066:
14067: @itemize @bullet
14068: @item
14069: There is only one segment; in particular, this means, that an image file
14070: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
14071: them). The contents of the stacks are not represented, either.
14072:
14073: @item
14074: The only kinds of relocation supported are: adding the same offset to
14075: all cells that represent data addresses; and replacing special tokens
14076: with code addresses or with pieces of machine code.
14077:
14078: If any complex computations involving addresses are performed, the
14079: results cannot be represented in the image file. Several applications that
14080: use such computations come to mind:
14081: @itemize @minus
14082: @item
14083: Hashing addresses (or data structures which contain addresses) for table
14084: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14085: purpose, you will have no problem, because the hash tables are
14086: recomputed automatically when the system is started. If you use your own
14087: hash tables, you will have to do something similar.
14088:
14089: @item
14090: There's a cute implementation of doubly-linked lists that uses
14091: @code{XOR}ed addresses. You could represent such lists as singly-linked
14092: in the image file, and restore the doubly-linked representation on
14093: startup.@footnote{In my opinion, though, you should think thrice before
14094: using a doubly-linked list (whatever implementation).}
14095:
14096: @item
14097: The code addresses of run-time routines like @code{docol:} cannot be
14098: represented in the image file (because their tokens would be replaced by
14099: machine code in direct threaded implementations). As a workaround,
14100: compute these addresses at run-time with @code{>code-address} from the
14101: executions tokens of appropriate words (see the definitions of
14102: @code{docol:} and friends in @file{kernel/getdoers.fs}).
14103:
14104: @item
14105: On many architectures addresses are represented in machine code in some
14106: shifted or mangled form. You cannot put @code{CODE} words that contain
14107: absolute addresses in this form in a relocatable image file. Workarounds
14108: are representing the address in some relative form (e.g., relative to
14109: the CFA, which is present in some register), or loading the address from
14110: a place where it is stored in a non-mangled form.
14111: @end itemize
14112: @end itemize
14113:
14114: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14115: @section Non-Relocatable Image Files
14116: @cindex non-relocatable image files
14117: @cindex image file, non-relocatable
14118:
14119: These files are simple memory dumps of the dictionary. They are specific
14120: to the executable (i.e., @file{gforth} file) they were created
14121: with. What's worse, they are specific to the place on which the
14122: dictionary resided when the image was created. Now, there is no
14123: guarantee that the dictionary will reside at the same place the next
14124: time you start Gforth, so there's no guarantee that a non-relocatable
14125: image will work the next time (Gforth will complain instead of crashing,
14126: though).
14127:
14128: You can create a non-relocatable image file with
14129:
14130:
14131: doc-savesystem
14132:
14133:
14134: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14135: @section Data-Relocatable Image Files
14136: @cindex data-relocatable image files
14137: @cindex image file, data-relocatable
14138:
14139: These files contain relocatable data addresses, but fixed code addresses
14140: (instead of tokens). They are specific to the executable (i.e.,
14141: @file{gforth} file) they were created with. For direct threading on some
14142: architectures (e.g., the i386), data-relocatable images do not work. You
14143: get a data-relocatable image, if you use @file{gforthmi} with a
14144: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14145: Relocatable Image Files}).
14146:
14147: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14148: @section Fully Relocatable Image Files
14149: @cindex fully relocatable image files
14150: @cindex image file, fully relocatable
14151:
14152: @cindex @file{kern*.fi}, relocatability
14153: @cindex @file{gforth.fi}, relocatability
14154: These image files have relocatable data addresses, and tokens for code
14155: addresses. They can be used with different binaries (e.g., with and
14156: without debugging) on the same machine, and even across machines with
14157: the same data formats (byte order, cell size, floating point
14158: format). However, they are usually specific to the version of Gforth
14159: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14160: are fully relocatable.
14161:
14162: There are two ways to create a fully relocatable image file:
14163:
14164: @menu
14165: * gforthmi:: The normal way
14166: * cross.fs:: The hard way
14167: @end menu
14168:
14169: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14170: @subsection @file{gforthmi}
14171: @cindex @file{comp-i.fs}
14172: @cindex @file{gforthmi}
14173:
14174: You will usually use @file{gforthmi}. If you want to create an
14175: image @i{file} that contains everything you would load by invoking
14176: Gforth with @code{gforth @i{options}}, you simply say:
14177: @example
14178: gforthmi @i{file} @i{options}
14179: @end example
14180:
14181: E.g., if you want to create an image @file{asm.fi} that has the file
14182: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14183: like this:
14184:
14185: @example
14186: gforthmi asm.fi asm.fs
14187: @end example
14188:
14189: @file{gforthmi} is implemented as a sh script and works like this: It
14190: produces two non-relocatable images for different addresses and then
14191: compares them. Its output reflects this: first you see the output (if
14192: any) of the two Gforth invocations that produce the non-relocatable image
14193: files, then you see the output of the comparing program: It displays the
14194: offset used for data addresses and the offset used for code addresses;
14195: moreover, for each cell that cannot be represented correctly in the
14196: image files, it displays a line like this:
14197:
14198: @example
14199: 78DC BFFFFA50 BFFFFA40
14200: @end example
14201:
14202: This means that at offset $78dc from @code{forthstart}, one input image
14203: contains $bffffa50, and the other contains $bffffa40. Since these cells
14204: cannot be represented correctly in the output image, you should examine
14205: these places in the dictionary and verify that these cells are dead
14206: (i.e., not read before they are written).
14207:
14208: @cindex --application, @code{gforthmi} option
14209: If you insert the option @code{--application} in front of the image file
14210: name, you will get an image that uses the @code{--appl-image} option
14211: instead of the @code{--image-file} option (@pxref{Invoking
14212: Gforth}). When you execute such an image on Unix (by typing the image
14213: name as command), the Gforth engine will pass all options to the image
14214: instead of trying to interpret them as engine options.
14215:
14216: If you type @file{gforthmi} with no arguments, it prints some usage
14217: instructions.
14218:
14219: @cindex @code{savesystem} during @file{gforthmi}
14220: @cindex @code{bye} during @file{gforthmi}
14221: @cindex doubly indirect threaded code
14222: @cindex environment variables
14223: @cindex @code{GFORTHD} -- environment variable
14224: @cindex @code{GFORTH} -- environment variable
14225: @cindex @code{gforth-ditc}
14226: There are a few wrinkles: After processing the passed @i{options}, the
14227: words @code{savesystem} and @code{bye} must be visible. A special doubly
14228: indirect threaded version of the @file{gforth} executable is used for
14229: creating the non-relocatable images; you can pass the exact filename of
14230: this executable through the environment variable @code{GFORTHD}
14231: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14232: indirect threaded, you will not get a fully relocatable image, but a
14233: data-relocatable image (because there is no code address offset). The
14234: normal @file{gforth} executable is used for creating the relocatable
14235: image; you can pass the exact filename of this executable through the
14236: environment variable @code{GFORTH}.
14237:
14238: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14239: @subsection @file{cross.fs}
14240: @cindex @file{cross.fs}
14241: @cindex cross-compiler
14242: @cindex metacompiler
14243: @cindex target compiler
14244:
14245: You can also use @code{cross}, a batch compiler that accepts a Forth-like
14246: programming language (@pxref{Cross Compiler}).
14247:
14248: @code{cross} allows you to create image files for machines with
14249: different data sizes and data formats than the one used for generating
14250: the image file. You can also use it to create an application image that
14251: does not contain a Forth compiler. These features are bought with
14252: restrictions and inconveniences in programming. E.g., addresses have to
14253: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14254: order to make the code relocatable.
14255:
14256:
14257: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14258: @section Stack and Dictionary Sizes
14259: @cindex image file, stack and dictionary sizes
14260: @cindex dictionary size default
14261: @cindex stack size default
14262:
14263: If you invoke Gforth with a command line flag for the size
14264: (@pxref{Invoking Gforth}), the size you specify is stored in the
14265: dictionary. If you save the dictionary with @code{savesystem} or create
14266: an image with @file{gforthmi}, this size will become the default
14267: for the resulting image file. E.g., the following will create a
14268: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
14269:
14270: @example
14271: gforthmi gforth.fi -m 1M
14272: @end example
14273:
14274: In other words, if you want to set the default size for the dictionary
14275: and the stacks of an image, just invoke @file{gforthmi} with the
14276: appropriate options when creating the image.
14277:
14278: @cindex stack size, cache-friendly
14279: Note: For cache-friendly behaviour (i.e., good performance), you should
14280: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14281: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14282: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14283:
14284: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14285: @section Running Image Files
14286: @cindex running image files
14287: @cindex invoking image files
14288: @cindex image file invocation
14289:
14290: @cindex -i, invoke image file
14291: @cindex --image file, invoke image file
14292: You can invoke Gforth with an image file @i{image} instead of the
14293: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14294: @example
14295: gforth -i @i{image}
14296: @end example
14297:
14298: @cindex executable image file
14299: @cindex image file, executable
14300: If your operating system supports starting scripts with a line of the
14301: form @code{#! ...}, you just have to type the image file name to start
14302: Gforth with this image file (note that the file extension @code{.fi} is
14303: just a convention). I.e., to run Gforth with the image file @i{image},
14304: you can just type @i{image} instead of @code{gforth -i @i{image}}.
14305: This works because every @code{.fi} file starts with a line of this
14306: format:
14307:
14308: @example
14309: #! /usr/local/bin/gforth-0.4.0 -i
14310: @end example
14311:
14312: The file and pathname for the Gforth engine specified on this line is
14313: the specific Gforth executable that it was built against; i.e. the value
14314: of the environment variable @code{GFORTH} at the time that
14315: @file{gforthmi} was executed.
14316:
14317: You can make use of the same shell capability to make a Forth source
14318: file into an executable. For example, if you place this text in a file:
14319:
14320: @example
14321: #! /usr/local/bin/gforth
14322:
14323: ." Hello, world" CR
14324: bye
14325: @end example
14326:
14327: @noindent
14328: and then make the file executable (chmod +x in Unix), you can run it
14329: directly from the command line. The sequence @code{#!} is used in two
14330: ways; firstly, it is recognised as a ``magic sequence'' by the operating
14331: system@footnote{The Unix kernel actually recognises two types of files:
14332: executable files and files of data, where the data is processed by an
14333: interpreter that is specified on the ``interpreter line'' -- the first
14334: line of the file, starting with the sequence #!. There may be a small
14335: limit (e.g., 32) on the number of characters that may be specified on
14336: the interpreter line.} secondly it is treated as a comment character by
14337: Gforth. Because of the second usage, a space is required between
14338: @code{#!} and the path to the executable (moreover, some Unixes
14339: require the sequence @code{#! /}).
14340:
14341: The disadvantage of this latter technique, compared with using
14342: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14343: compiled on-the-fly, each time the program is invoked.
14344:
14345: doc-#!
14346:
14347:
14348: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14349: @section Modifying the Startup Sequence
14350: @cindex startup sequence for image file
14351: @cindex image file initialization sequence
14352: @cindex initialization sequence of image file
14353:
14354: You can add your own initialization to the startup sequence of an image
14355: through the deferred word @code{'cold}. @code{'cold} is invoked just
14356: before the image-specific command line processing (i.e., loading files
14357: and evaluating (@code{-e}) strings) starts.
14358:
14359: A sequence for adding your initialization usually looks like this:
14360:
14361: @example
14362: :noname
14363: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14364: ... \ your stuff
14365: ; IS 'cold
14366: @end example
14367:
14368: @cindex turnkey image files
14369: @cindex image file, turnkey applications
14370: You can make a turnkey image by letting @code{'cold} execute a word
14371: (your turnkey application) that never returns; instead, it exits Gforth
14372: via @code{bye} or @code{throw}.
14373:
14374: You can access the (image-specific) command-line arguments through
14375: @code{argc}, @code{argv} and @code{arg} (@pxref{OS command line
14376: arguments}).
14377:
14378: If @code{'cold} exits normally, Gforth processes the command-line
14379: arguments as files to be loaded and strings to be evaluated. Therefore,
14380: @code{'cold} should remove the arguments it has used in this case.
14381:
14382: doc-'cold
14383:
14384: @c ******************************************************************
14385: @node Engine, Cross Compiler, Image Files, Top
14386: @chapter Engine
14387: @cindex engine
14388: @cindex virtual machine
14389:
14390: Reading this chapter is not necessary for programming with Gforth. It
14391: may be helpful for finding your way in the Gforth sources.
14392:
14393: The ideas in this section have also been published in the following
14394: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14395: Forth-Tagung '93; M. Anton Ertl,
14396: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14397: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14398: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14399: Threaded code variations and optimizations (extended version)}},
14400: Forth-Tagung '02.
14401:
14402: @menu
14403: * Portability::
14404: * Threading::
14405: * Primitives::
14406: * Performance::
14407: @end menu
14408:
14409: @node Portability, Threading, Engine, Engine
14410: @section Portability
14411: @cindex engine portability
14412:
14413: An important goal of the Gforth Project is availability across a wide
14414: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14415: achieved this goal by manually coding the engine in assembly language
14416: for several then-popular processors. This approach is very
14417: labor-intensive and the results are short-lived due to progress in
14418: computer architecture.
14419:
14420: @cindex C, using C for the engine
14421: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14422: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14423: particularly popular for UNIX-based Forths due to the large variety of
14424: architectures of UNIX machines. Unfortunately an implementation in C
14425: does not mix well with the goals of efficiency and with using
14426: traditional techniques: Indirect or direct threading cannot be expressed
14427: in C, and switch threading, the fastest technique available in C, is
14428: significantly slower. Another problem with C is that it is very
14429: cumbersome to express double integer arithmetic.
14430:
14431: @cindex GNU C for the engine
14432: @cindex long long
14433: Fortunately, there is a portable language that does not have these
14434: limitations: GNU C, the version of C processed by the GNU C compiler
14435: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14436: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14437: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14438: threading possible, its @code{long long} type (@pxref{Long Long, ,
14439: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
14440: double numbers on many systems. GNU C is freely available on all
14441: important (and many unimportant) UNIX machines, VMS, 80386s running
14442: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14443: on all these machines.
14444:
14445: Writing in a portable language has the reputation of producing code that
14446: is slower than assembly. For our Forth engine we repeatedly looked at
14447: the code produced by the compiler and eliminated most compiler-induced
14448: inefficiencies by appropriate changes in the source code.
14449:
14450: @cindex explicit register declarations
14451: @cindex --enable-force-reg, configuration flag
14452: @cindex -DFORCE_REG
14453: However, register allocation cannot be portably influenced by the
14454: programmer, leading to some inefficiencies on register-starved
14455: machines. We use explicit register declarations (@pxref{Explicit Reg
14456: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14457: improve the speed on some machines. They are turned on by using the
14458: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14459: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14460: machine, but also on the compiler version: On some machines some
14461: compiler versions produce incorrect code when certain explicit register
14462: declarations are used. So by default @code{-DFORCE_REG} is not used.
14463:
14464: @node Threading, Primitives, Portability, Engine
14465: @section Threading
14466: @cindex inner interpreter implementation
14467: @cindex threaded code implementation
14468:
14469: @cindex labels as values
14470: GNU C's labels as values extension (available since @code{gcc-2.0},
14471: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
14472: makes it possible to take the address of @i{label} by writing
14473: @code{&&@i{label}}. This address can then be used in a statement like
14474: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
14475: @code{goto x}.
14476:
14477: @cindex @code{NEXT}, indirect threaded
14478: @cindex indirect threaded inner interpreter
14479: @cindex inner interpreter, indirect threaded
14480: With this feature an indirect threaded @code{NEXT} looks like:
14481: @example
14482: cfa = *ip++;
14483: ca = *cfa;
14484: goto *ca;
14485: @end example
14486: @cindex instruction pointer
14487: For those unfamiliar with the names: @code{ip} is the Forth instruction
14488: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14489: execution token and points to the code field of the next word to be
14490: executed; The @code{ca} (code address) fetched from there points to some
14491: executable code, e.g., a primitive or the colon definition handler
14492: @code{docol}.
14493:
14494: @cindex @code{NEXT}, direct threaded
14495: @cindex direct threaded inner interpreter
14496: @cindex inner interpreter, direct threaded
14497: Direct threading is even simpler:
14498: @example
14499: ca = *ip++;
14500: goto *ca;
14501: @end example
14502:
14503: Of course we have packaged the whole thing neatly in macros called
14504: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
14505:
14506: @menu
14507: * Scheduling::
14508: * Direct or Indirect Threaded?::
14509: * Dynamic Superinstructions::
14510: * DOES>::
14511: @end menu
14512:
14513: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14514: @subsection Scheduling
14515: @cindex inner interpreter optimization
14516:
14517: There is a little complication: Pipelined and superscalar processors,
14518: i.e., RISC and some modern CISC machines can process independent
14519: instructions while waiting for the results of an instruction. The
14520: compiler usually reorders (schedules) the instructions in a way that
14521: achieves good usage of these delay slots. However, on our first tries
14522: the compiler did not do well on scheduling primitives. E.g., for
14523: @code{+} implemented as
14524: @example
14525: n=sp[0]+sp[1];
14526: sp++;
14527: sp[0]=n;
14528: NEXT;
14529: @end example
14530: the @code{NEXT} comes strictly after the other code, i.e., there is
14531: nearly no scheduling. After a little thought the problem becomes clear:
14532: The compiler cannot know that @code{sp} and @code{ip} point to different
14533: addresses (and the version of @code{gcc} we used would not know it even
14534: if it was possible), so it could not move the load of the cfa above the
14535: store to the TOS. Indeed the pointers could be the same, if code on or
14536: very near the top of stack were executed. In the interest of speed we
14537: chose to forbid this probably unused ``feature'' and helped the compiler
14538: in scheduling: @code{NEXT} is divided into several parts:
14539: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14540: like:
14541: @example
14542: NEXT_P0;
14543: n=sp[0]+sp[1];
14544: sp++;
14545: NEXT_P1;
14546: sp[0]=n;
14547: NEXT_P2;
14548: @end example
14549:
14550: There are various schemes that distribute the different operations of
14551: NEXT between these parts in several ways; in general, different schemes
14552: perform best on different processors. We use a scheme for most
14553: architectures that performs well for most processors of this
14554: architecture; in the future we may switch to benchmarking and chosing
14555: the scheme on installation time.
14556:
14557:
14558: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
14559: @subsection Direct or Indirect Threaded?
14560: @cindex threading, direct or indirect?
14561:
14562: Threaded forth code consists of references to primitives (simple machine
14563: code routines like @code{+}) and to non-primitives (e.g., colon
14564: definitions, variables, constants); for a specific class of
14565: non-primitives (e.g., variables) there is one code routine (e.g.,
14566: @code{dovar}), but each variable needs a separate reference to its data.
14567:
14568: Traditionally Forth has been implemented as indirect threaded code,
14569: because this allows to use only one cell to reference a non-primitive
14570: (basically you point to the data, and find the code address there).
14571:
14572: @cindex primitive-centric threaded code
14573: However, threaded code in Gforth (since 0.6.0) uses two cells for
14574: non-primitives, one for the code address, and one for the data address;
14575: the data pointer is an immediate argument for the virtual machine
14576: instruction represented by the code address. We call this
14577: @emph{primitive-centric} threaded code, because all code addresses point
14578: to simple primitives. E.g., for a variable, the code address is for
14579: @code{lit} (also used for integer literals like @code{99}).
14580:
14581: Primitive-centric threaded code allows us to use (faster) direct
14582: threading as dispatch method, completely portably (direct threaded code
14583: in Gforth before 0.6.0 required architecture-specific code). It also
14584: eliminates the performance problems related to I-cache consistency that
14585: 386 implementations have with direct threaded code, and allows
14586: additional optimizations.
14587:
14588: @cindex hybrid direct/indirect threaded code
14589: There is a catch, however: the @var{xt} parameter of @code{execute} can
14590: occupy only one cell, so how do we pass non-primitives with their code
14591: @emph{and} data addresses to them? Our answer is to use indirect
14592: threaded dispatch for @code{execute} and other words that use a
14593: single-cell xt. So, normal threaded code in colon definitions uses
14594: direct threading, and @code{execute} and similar words, which dispatch
14595: to xts on the data stack, use indirect threaded code. We call this
14596: @emph{hybrid direct/indirect} threaded code.
14597:
14598: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14599: @cindex gforth engine
14600: @cindex gforth-fast engine
14601: The engines @command{gforth} and @command{gforth-fast} use hybrid
14602: direct/indirect threaded code. This means that with these engines you
14603: cannot use @code{,} to compile an xt. Instead, you have to use
14604: @code{compile,}.
14605:
14606: @cindex gforth-itc engine
14607: If you want to compile xts with @code{,}, use @command{gforth-itc}.
14608: This engine uses plain old indirect threaded code. It still compiles in
14609: a primitive-centric style, so you cannot use @code{compile,} instead of
14610: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
14611: ... [}). If you want to do that, you have to use @command{gforth-itc}
14612: and execute @code{' , is compile,}. Your program can check if it is
14613: running on a hybrid direct/indirect threaded engine or a pure indirect
14614: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14615:
14616:
14617: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14618: @subsection Dynamic Superinstructions
14619: @cindex Dynamic superinstructions with replication
14620: @cindex Superinstructions
14621: @cindex Replication
14622:
14623: The engines @command{gforth} and @command{gforth-fast} use another
14624: optimization: Dynamic superinstructions with replication. As an
14625: example, consider the following colon definition:
14626:
14627: @example
14628: : squared ( n1 -- n2 )
14629: dup * ;
14630: @end example
14631:
14632: Gforth compiles this into the threaded code sequence
14633:
14634: @example
14635: dup
14636: *
14637: ;s
14638: @end example
14639:
14640: In normal direct threaded code there is a code address occupying one
14641: cell for each of these primitives. Each code address points to a
14642: machine code routine, and the interpreter jumps to this machine code in
14643: order to execute the primitive. The routines for these three
14644: primitives are (in @command{gforth-fast} on the 386):
14645:
14646: @example
14647: Code dup
14648: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
14649: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
14650: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14651: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14652: end-code
14653: Code *
14654: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14655: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
14656: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
14657: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
14658: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14659: end-code
14660: Code ;s
14661: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
14662: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
14663: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14664: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14665: end-code
14666: @end example
14667:
14668: With dynamic superinstructions and replication the compiler does not
14669: just lay down the threaded code, but also copies the machine code
14670: fragments, usually without the jump at the end.
14671:
14672: @example
14673: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
14674: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
14675: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14676: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14677: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
14678: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
14679: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
14680: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
14681: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
14682: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14683: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14684: @end example
14685:
14686: Only when a threaded-code control-flow change happens (e.g., in
14687: @code{;s}), the jump is appended. This optimization eliminates many of
14688: these jumps and makes the rest much more predictable. The speedup
14689: depends on the processor and the application; on the Athlon and Pentium
14690: III this optimization typically produces a speedup by a factor of 2.
14691:
14692: The code addresses in the direct-threaded code are set to point to the
14693: appropriate points in the copied machine code, in this example like
14694: this:
14695:
14696: @example
14697: primitive code address
14698: dup $4057D27D
14699: * $4057D286
14700: ;s $4057D292
14701: @end example
14702:
14703: Thus there can be threaded-code jumps to any place in this piece of
14704: code. This also simplifies decompilation quite a bit.
14705:
14706: @cindex --no-dynamic command-line option
14707: @cindex --no-super command-line option
14708: You can disable this optimization with @option{--no-dynamic}. You can
14709: use the copying without eliminating the jumps (i.e., dynamic
14710: replication, but without superinstructions) with @option{--no-super};
14711: this gives the branch prediction benefit alone; the effect on
14712: performance depends on the CPU; on the Athlon and Pentium III the
14713: speedup is a little less than for dynamic superinstructions with
14714: replication.
14715:
14716: @cindex patching threaded code
14717: One use of these options is if you want to patch the threaded code.
14718: With superinstructions, many of the dispatch jumps are eliminated, so
14719: patching often has no effect. These options preserve all the dispatch
14720: jumps.
14721:
14722: @cindex --dynamic command-line option
14723: On some machines dynamic superinstructions are disabled by default,
14724: because it is unsafe on these machines. However, if you feel
14725: adventurous, you can enable it with @option{--dynamic}.
14726:
14727: @node DOES>, , Dynamic Superinstructions, Threading
14728: @subsection DOES>
14729: @cindex @code{DOES>} implementation
14730:
14731: @cindex @code{dodoes} routine
14732: @cindex @code{DOES>}-code
14733: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14734: the chunk of code executed by every word defined by a
14735: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
14736: this is only needed if the xt of the word is @code{execute}d. The main
14737: problem here is: How to find the Forth code to be executed, i.e. the
14738: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
14739: solutions:
14740:
14741: In fig-Forth the code field points directly to the @code{dodoes} and the
14742: @code{DOES>}-code address is stored in the cell after the code address
14743: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
14744: illegal in the Forth-79 and all later standards, because in fig-Forth
14745: this address lies in the body (which is illegal in these
14746: standards). However, by making the code field larger for all words this
14747: solution becomes legal again. We use this approach. Leaving a cell
14748: unused in most words is a bit wasteful, but on the machines we are
14749: targeting this is hardly a problem.
14750:
14751:
14752: @node Primitives, Performance, Threading, Engine
14753: @section Primitives
14754: @cindex primitives, implementation
14755: @cindex virtual machine instructions, implementation
14756:
14757: @menu
14758: * Automatic Generation::
14759: * TOS Optimization::
14760: * Produced code::
14761: @end menu
14762:
14763: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14764: @subsection Automatic Generation
14765: @cindex primitives, automatic generation
14766:
14767: @cindex @file{prims2x.fs}
14768:
14769: Since the primitives are implemented in a portable language, there is no
14770: longer any need to minimize the number of primitives. On the contrary,
14771: having many primitives has an advantage: speed. In order to reduce the
14772: number of errors in primitives and to make programming them easier, we
14773: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
14774: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
14775: generates most (and sometimes all) of the C code for a primitive from
14776: the stack effect notation. The source for a primitive has the following
14777: form:
14778:
14779: @cindex primitive source format
14780: @format
14781: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
14782: [@code{""}@i{glossary entry}@code{""}]
14783: @i{C code}
14784: [@code{:}
14785: @i{Forth code}]
14786: @end format
14787:
14788: The items in brackets are optional. The category and glossary fields
14789: are there for generating the documentation, the Forth code is there
14790: for manual implementations on machines without GNU C. E.g., the source
14791: for the primitive @code{+} is:
14792: @example
14793: + ( n1 n2 -- n ) core plus
14794: n = n1+n2;
14795: @end example
14796:
14797: This looks like a specification, but in fact @code{n = n1+n2} is C
14798: code. Our primitive generation tool extracts a lot of information from
14799: the stack effect notations@footnote{We use a one-stack notation, even
14800: though we have separate data and floating-point stacks; The separate
14801: notation can be generated easily from the unified notation.}: The number
14802: of items popped from and pushed on the stack, their type, and by what
14803: name they are referred to in the C code. It then generates a C code
14804: prelude and postlude for each primitive. The final C code for @code{+}
14805: looks like this:
14806:
14807: @example
14808: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
14809: /* */ /* documentation */
14810: NAME("+") /* debugging output (with -DDEBUG) */
14811: @{
14812: DEF_CA /* definition of variable ca (indirect threading) */
14813: Cell n1; /* definitions of variables */
14814: Cell n2;
14815: Cell n;
14816: NEXT_P0; /* NEXT part 0 */
14817: n1 = (Cell) sp[1]; /* input */
14818: n2 = (Cell) TOS;
14819: sp += 1; /* stack adjustment */
14820: @{
14821: n = n1+n2; /* C code taken from the source */
14822: @}
14823: NEXT_P1; /* NEXT part 1 */
14824: TOS = (Cell)n; /* output */
14825: NEXT_P2; /* NEXT part 2 */
14826: @}
14827: @end example
14828:
14829: This looks long and inefficient, but the GNU C compiler optimizes quite
14830: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14831: HP RISC machines: Defining the @code{n}s does not produce any code, and
14832: using them as intermediate storage also adds no cost.
14833:
14834: There are also other optimizations that are not illustrated by this
14835: example: assignments between simple variables are usually for free (copy
14836: propagation). If one of the stack items is not used by the primitive
14837: (e.g. in @code{drop}), the compiler eliminates the load from the stack
14838: (dead code elimination). On the other hand, there are some things that
14839: the compiler does not do, therefore they are performed by
14840: @file{prims2x.fs}: The compiler does not optimize code away that stores
14841: a stack item to the place where it just came from (e.g., @code{over}).
14842:
14843: While programming a primitive is usually easy, there are a few cases
14844: where the programmer has to take the actions of the generator into
14845: account, most notably @code{?dup}, but also words that do not (always)
14846: fall through to @code{NEXT}.
14847:
14848: For more information
14849:
14850: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14851: @subsection TOS Optimization
14852: @cindex TOS optimization for primitives
14853: @cindex primitives, keeping the TOS in a register
14854:
14855: An important optimization for stack machine emulators, e.g., Forth
14856: engines, is keeping one or more of the top stack items in
14857: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
14858: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
14859: @itemize @bullet
14860: @item
14861: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
14862: due to fewer loads from and stores to the stack.
14863: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14864: @i{y<n}, due to additional moves between registers.
14865: @end itemize
14866:
14867: @cindex -DUSE_TOS
14868: @cindex -DUSE_NO_TOS
14869: In particular, keeping one item in a register is never a disadvantage,
14870: if there are enough registers. Keeping two items in registers is a
14871: disadvantage for frequent words like @code{?branch}, constants,
14872: variables, literals and @code{i}. Therefore our generator only produces
14873: code that keeps zero or one items in registers. The generated C code
14874: covers both cases; the selection between these alternatives is made at
14875: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14876: code for @code{+} is just a simple variable name in the one-item case,
14877: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14878: GNU C compiler tries to keep simple variables like @code{TOS} in
14879: registers, and it usually succeeds, if there are enough registers.
14880:
14881: @cindex -DUSE_FTOS
14882: @cindex -DUSE_NO_FTOS
14883: The primitive generator performs the TOS optimization for the
14884: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14885: operations the benefit of this optimization is even larger:
14886: floating-point operations take quite long on most processors, but can be
14887: performed in parallel with other operations as long as their results are
14888: not used. If the FP-TOS is kept in a register, this works. If
14889: it is kept on the stack, i.e., in memory, the store into memory has to
14890: wait for the result of the floating-point operation, lengthening the
14891: execution time of the primitive considerably.
14892:
14893: The TOS optimization makes the automatic generation of primitives a
14894: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14895: @code{TOS} is not sufficient. There are some special cases to
14896: consider:
14897: @itemize @bullet
14898: @item In the case of @code{dup ( w -- w w )} the generator must not
14899: eliminate the store to the original location of the item on the stack,
14900: if the TOS optimization is turned on.
14901: @item Primitives with stack effects of the form @code{--}
14902: @i{out1}...@i{outy} must store the TOS to the stack at the start.
14903: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
14904: must load the TOS from the stack at the end. But for the null stack
14905: effect @code{--} no stores or loads should be generated.
14906: @end itemize
14907:
14908: @node Produced code, , TOS Optimization, Primitives
14909: @subsection Produced code
14910: @cindex primitives, assembly code listing
14911:
14912: @cindex @file{engine.s}
14913: To see what assembly code is produced for the primitives on your machine
14914: with your compiler and your flag settings, type @code{make engine.s} and
14915: look at the resulting file @file{engine.s}. Alternatively, you can also
14916: disassemble the code of primitives with @code{see} on some architectures.
14917:
14918: @node Performance, , Primitives, Engine
14919: @section Performance
14920: @cindex performance of some Forth interpreters
14921: @cindex engine performance
14922: @cindex benchmarking Forth systems
14923: @cindex Gforth performance
14924:
14925: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
14926: impossible to write a significantly faster threaded-code engine.
14927:
14928: On register-starved machines like the 386 architecture processors
14929: improvements are possible, because @code{gcc} does not utilize the
14930: registers as well as a human, even with explicit register declarations;
14931: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
14932: and hand-tuned it for the 486; this system is 1.19 times faster on the
14933: Sieve benchmark on a 486DX2/66 than Gforth compiled with
14934: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
14935: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
14936: registers fit in real registers (and we can even afford to use the TOS
14937: optimization), resulting in a speedup of 1.14 on the sieve over the
14938: earlier results. And dynamic superinstructions provide another speedup
14939: (but only around a factor 1.2 on the 486).
14940:
14941: @cindex Win32Forth performance
14942: @cindex NT Forth performance
14943: @cindex eforth performance
14944: @cindex ThisForth performance
14945: @cindex PFE performance
14946: @cindex TILE performance
14947: The potential advantage of assembly language implementations is not
14948: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
14949: (direct threaded, compiled with @code{gcc-2.95.1} and
14950: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
14951: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
14952: (with and without peephole (aka pinhole) optimization of the threaded
14953: code); all these systems were written in assembly language. We also
14954: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
14955: with @code{gcc-2.6.3} with the default configuration for Linux:
14956: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
14957: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
14958: employs peephole optimization of the threaded code) and TILE (compiled
14959: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
14960: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
14961: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
14962: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
14963: then extended it to run the benchmarks, added the peephole optimizer,
14964: ran the benchmarks and reported the results.
14965:
14966: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
14967: matrix multiplication come from the Stanford integer benchmarks and have
14968: been translated into Forth by Martin Fraeman; we used the versions
14969: included in the TILE Forth package, but with bigger data set sizes; and
14970: a recursive Fibonacci number computation for benchmarking calling
14971: performance. The following table shows the time taken for the benchmarks
14972: scaled by the time taken by Gforth (in other words, it shows the speedup
14973: factor that Gforth achieved over the other systems).
14974:
14975: @example
14976: relative Win32- NT eforth This-
14977: time Gforth Forth Forth eforth +opt PFE Forth TILE
14978: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
14979: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
14980: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
14981: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
14982: @end example
14983:
14984: You may be quite surprised by the good performance of Gforth when
14985: compared with systems written in assembly language. One important reason
14986: for the disappointing performance of these other systems is probably
14987: that they are not written optimally for the 486 (e.g., they use the
14988: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
14989: but costly method for relocating the Forth image: like @code{cforth}, it
14990: computes the actual addresses at run time, resulting in two address
14991: computations per @code{NEXT} (@pxref{Image File Background}).
14992:
14993: The speedup of Gforth over PFE, ThisForth and TILE can be easily
14994: explained with the self-imposed restriction of the latter systems to
14995: standard C, which makes efficient threading impossible (however, the
14996: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
14997: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
14998: Moreover, current C compilers have a hard time optimizing other aspects
14999: of the ThisForth and the TILE source.
15000:
15001: The performance of Gforth on 386 architecture processors varies widely
15002: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15003: allocate any of the virtual machine registers into real machine
15004: registers by itself and would not work correctly with explicit register
15005: declarations, giving a significantly slower engine (on a 486DX2/66
15006: running the Sieve) than the one measured above.
15007:
15008: Note that there have been several releases of Win32Forth since the
15009: release presented here, so the results presented above may have little
15010: predictive value for the performance of Win32Forth today (results for
15011: the current release on an i486DX2/66 are welcome).
15012:
15013: @cindex @file{Benchres}
15014: In
15015: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15016: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
15017: Maierhofer (presented at EuroForth '95), an indirect threaded version of
15018: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15019: several native code systems; that version of Gforth is slower on a 486
15020: than the version used here. You can find a newer version of these
15021: measurements at
15022: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
15023: find numbers for Gforth on various machines in @file{Benchres}.
15024:
15025: @c ******************************************************************
15026: @c @node Binding to System Library, Cross Compiler, Engine, Top
15027: @c @chapter Binding to System Library
15028:
15029: @c ****************************************************************
15030: @node Cross Compiler, Bugs, Engine, Top
15031: @chapter Cross Compiler
15032: @cindex @file{cross.fs}
15033: @cindex cross-compiler
15034: @cindex metacompiler
15035: @cindex target compiler
15036:
15037: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15038: mostly written in Forth, including crucial parts like the outer
15039: interpreter and compiler, it needs compiled Forth code to get
15040: started. The cross compiler allows to create new images for other
15041: architectures, even running under another Forth system.
15042:
15043: @menu
15044: * Using the Cross Compiler::
15045: * How the Cross Compiler Works::
15046: @end menu
15047:
15048: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
15049: @section Using the Cross Compiler
15050:
15051: The cross compiler uses a language that resembles Forth, but isn't. The
15052: main difference is that you can execute Forth code after definition,
15053: while you usually can't execute the code compiled by cross, because the
15054: code you are compiling is typically for a different computer than the
15055: one you are compiling on.
15056:
15057: @c anton: This chapter is somewhat different from waht I would expect: I
15058: @c would expect an explanation of the cross language and how to create an
15059: @c application image with it. The section explains some aspects of
15060: @c creating a Gforth kernel.
15061:
15062: The Makefile is already set up to allow you to create kernels for new
15063: architectures with a simple make command. The generic kernels using the
15064: GCC compiled virtual machine are created in the normal build process
15065: with @code{make}. To create a embedded Gforth executable for e.g. the
15066: 8086 processor (running on a DOS machine), type
15067:
15068: @example
15069: make kernl-8086.fi
15070: @end example
15071:
15072: This will use the machine description from the @file{arch/8086}
15073: directory to create a new kernel. A machine file may look like that:
15074:
15075: @example
15076: \ Parameter for target systems 06oct92py
15077:
15078: 4 Constant cell \ cell size in bytes
15079: 2 Constant cell<< \ cell shift to bytes
15080: 5 Constant cell>bit \ cell shift to bits
15081: 8 Constant bits/char \ bits per character
15082: 8 Constant bits/byte \ bits per byte [default: 8]
15083: 8 Constant float \ bytes per float
15084: 8 Constant /maxalign \ maximum alignment in bytes
15085: false Constant bigendian \ byte order
15086: ( true=big, false=little )
15087:
15088: include machpc.fs \ feature list
15089: @end example
15090:
15091: This part is obligatory for the cross compiler itself, the feature list
15092: is used by the kernel to conditionally compile some features in and out,
15093: depending on whether the target supports these features.
15094:
15095: There are some optional features, if you define your own primitives,
15096: have an assembler, or need special, nonstandard preparation to make the
15097: boot process work. @code{asm-include} includes an assembler,
15098: @code{prims-include} includes primitives, and @code{>boot} prepares for
15099: booting.
15100:
15101: @example
15102: : asm-include ." Include assembler" cr
15103: s" arch/8086/asm.fs" included ;
15104:
15105: : prims-include ." Include primitives" cr
15106: s" arch/8086/prim.fs" included ;
15107:
15108: : >boot ." Prepare booting" cr
15109: s" ' boot >body into-forth 1+ !" evaluate ;
15110: @end example
15111:
15112: These words are used as sort of macro during the cross compilation in
15113: the file @file{kernel/main.fs}. Instead of using these macros, it would
15114: be possible --- but more complicated --- to write a new kernel project
15115: file, too.
15116:
15117: @file{kernel/main.fs} expects the machine description file name on the
15118: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15119: @code{mach-file} leaves a counted string on the stack, or
15120: @code{machine-file} leaves an address, count pair of the filename on the
15121: stack.
15122:
15123: The feature list is typically controlled using @code{SetValue}, generic
15124: files that are used by several projects can use @code{DefaultValue}
15125: instead. Both functions work like @code{Value}, when the value isn't
15126: defined, but @code{SetValue} works like @code{to} if the value is
15127: defined, and @code{DefaultValue} doesn't set anything, if the value is
15128: defined.
15129:
15130: @example
15131: \ generic mach file for pc gforth 03sep97jaw
15132:
15133: true DefaultValue NIL \ relocating
15134:
15135: >ENVIRON
15136:
15137: true DefaultValue file \ controls the presence of the
15138: \ file access wordset
15139: true DefaultValue OS \ flag to indicate a operating system
15140:
15141: true DefaultValue prims \ true: primitives are c-code
15142:
15143: true DefaultValue floating \ floating point wordset is present
15144:
15145: true DefaultValue glocals \ gforth locals are present
15146: \ will be loaded
15147: true DefaultValue dcomps \ double number comparisons
15148:
15149: true DefaultValue hash \ hashing primitives are loaded/present
15150:
15151: true DefaultValue xconds \ used together with glocals,
15152: \ special conditionals supporting gforths'
15153: \ local variables
15154: true DefaultValue header \ save a header information
15155:
15156: true DefaultValue backtrace \ enables backtrace code
15157:
15158: false DefaultValue ec
15159: false DefaultValue crlf
15160:
15161: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15162:
15163: &16 KB DefaultValue stack-size
15164: &15 KB &512 + DefaultValue fstack-size
15165: &15 KB DefaultValue rstack-size
15166: &14 KB &512 + DefaultValue lstack-size
15167: @end example
15168:
15169: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
15170: @section How the Cross Compiler Works
15171:
15172: @node Bugs, Origin, Cross Compiler, Top
15173: @appendix Bugs
15174: @cindex bug reporting
15175:
15176: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
15177:
15178: If you find a bug, please submit a bug report through
15179: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
15180:
15181: @itemize @bullet
15182: @item
15183: A program (or a sequence of keyboard commands) that reproduces the bug.
15184: @item
15185: A description of what you think constitutes the buggy behaviour.
15186: @item
15187: The Gforth version used (it is announced at the start of an
15188: interactive Gforth session).
15189: @item
15190: The machine and operating system (on Unix
15191: systems @code{uname -a} will report this information).
15192: @item
15193: The installation options (you can find the configure options at the
15194: start of @file{config.status}) and configuration (@code{configure}
15195: output or @file{config.cache}).
15196: @item
15197: A complete list of changes (if any) you (or your installer) have made to the
15198: Gforth sources.
15199: @end itemize
15200:
15201: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15202: to Report Bugs, gcc.info, GNU C Manual}.
15203:
15204:
15205: @node Origin, Forth-related information, Bugs, Top
15206: @appendix Authors and Ancestors of Gforth
15207:
15208: @section Authors and Contributors
15209: @cindex authors of Gforth
15210: @cindex contributors to Gforth
15211:
15212: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
15213: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15214: lot to the manual. Assemblers and disassemblers were contributed by
15215: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
15216: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15217: inspired us with their continuous feedback. Lennart Benshop contributed
15218: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15219: support for calling C libraries. Helpful comments also came from Paul
15220: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
15221: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert
15222: Epprecht, Dennis Ruffer and David N. Williams. Since the release of
15223: Gforth-0.2.1 there were also helpful comments from many others; thank
15224: you all, sorry for not listing you here (but digging through my mailbox
15225: to extract your names is on my to-do list).
15226:
15227: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15228: and autoconf, among others), and to the creators of the Internet: Gforth
15229: was developed across the Internet, and its authors did not meet
15230: physically for the first 4 years of development.
15231:
15232: @section Pedigree
15233: @cindex pedigree of Gforth
15234:
15235: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15236: significant part of the design of Gforth was prescribed by ANS Forth.
15237:
15238: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
15239: 32 bit native code version of VolksForth for the Atari ST, written
15240: mostly by Dietrich Weineck.
15241:
15242: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15243: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
15244: the mid-80s and ported to the Atari ST in 1986. It descends from F83.
15245:
15246: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15247: Forth-83 standard. !! Pedigree? When?
15248:
15249: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15250: 1979. Robert Selzer and Bill Ragsdale developed the original
15251: implementation of fig-Forth for the 6502 based on microForth.
15252:
15253: The principal architect of microForth was Dean Sanderson. microForth was
15254: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15255: the 1802, and subsequently implemented on the 8080, the 6800 and the
15256: Z80.
15257:
15258: All earlier Forth systems were custom-made, usually by Charles Moore,
15259: who discovered (as he puts it) Forth during the late 60s. The first full
15260: Forth existed in 1971.
15261:
15262: A part of the information in this section comes from
15263: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15264: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
15265: Charles H. Moore, presented at the HOPL-II conference and preprinted in
15266: SIGPLAN Notices 28(3), 1993. You can find more historical and
15267: genealogical information about Forth there.
15268:
15269: @c ------------------------------------------------------------------
15270: @node Forth-related information, Licenses, Origin, Top
15271: @appendix Other Forth-related information
15272: @cindex Forth-related information
15273:
15274: @c anton: I threw most of this stuff out, because it can be found through
15275: @c the FAQ and the FAQ is more likely to be up-to-date.
15276:
15277: @cindex comp.lang.forth
15278: @cindex frequently asked questions
15279: There is an active news group (comp.lang.forth) discussing Forth
15280: (including Gforth) and Forth-related issues. Its
15281: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15282: (frequently asked questions and their answers) contains a lot of
15283: information on Forth. You should read it before posting to
15284: comp.lang.forth.
15285:
15286: The ANS Forth standard is most usable in its
15287: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
15288:
15289: @c ---------------------------------------------------
15290: @node Licenses, Word Index, Forth-related information, Top
15291: @appendix Licenses
15292:
15293: @menu
15294: * GNU Free Documentation License:: License for copying this manual.
15295: * Copying:: GPL (for copying this software).
15296: @end menu
15297:
15298: @include fdl.texi
15299:
15300: @include gpl.texi
15301:
15302:
15303:
15304: @c ------------------------------------------------------------------
15305: @node Word Index, Concept Index, Licenses, Top
15306: @unnumbered Word Index
15307:
15308: This index is a list of Forth words that have ``glossary'' entries
15309: within this manual. Each word is listed with its stack effect and
15310: wordset.
15311:
15312: @printindex fn
15313:
15314: @c anton: the name index seems superfluous given the word and concept indices.
15315:
15316: @c @node Name Index, Concept Index, Word Index, Top
15317: @c @unnumbered Name Index
15318:
15319: @c This index is a list of Forth words that have ``glossary'' entries
15320: @c within this manual.
15321:
15322: @c @printindex ky
15323:
15324: @c -------------------------------------------------------
15325: @node Concept Index, , Word Index, Top
15326: @unnumbered Concept and Word Index
15327:
15328: Not all entries listed in this index are present verbatim in the
15329: text. This index also duplicates, in abbreviated form, all of the words
15330: listed in the Word Index (only the names are listed for the words here).
15331:
15332: @printindex cp
15333:
15334: @bye
15335:
15336:
15337:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>