1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
3:
4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
5: @comment 1. x-ref all ambiguous or implementation-defined features?
6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
7: @comment 3. words in miscellaneous section need a home.
8: @comment 4. search for TODO for other minor and major works required.
9: @comment 5. [rats] change all @var to @i in Forth source so that info
10: @comment file looks decent.
11: @c Not an improvement IMO - anton
12: @c and anyway, this should be taken up
13: @c with Karl Berry (the texinfo guy) - anton
14: @c
15: @c Karl Berry writes:
16: @c If they don't like the all-caps for @var Info output, all I can say is
17: @c that it's always been that way, and the usage of all-caps for
18: @c metavariables has a long tradition. I think it's best to just let it be
19: @c what it is, for the sake of consistency among manuals.
20: @c
21: @comment .. would be useful to have a word that identified all deferred words
22: @comment should semantics stuff in intro be moved to another section
23:
24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
25:
26: @comment %**start of header (This is for running Texinfo on a region.)
27: @setfilename gforth.info
28: @include version.texi
29: @settitle Gforth Manual
30: @c @syncodeindex pg cp
31:
32: @macro progstyle {}
33: Programming style note:
34: @end macro
35:
36: @macro assignment {}
37: @table @i
38: @item Assignment:
39: @end macro
40: @macro endassignment {}
41: @end table
42: @end macro
43:
44: @comment macros for beautifying glossary entries
45: @macro GLOSS-START {}
46: @iftex
47: @ninerm
48: @end iftex
49: @end macro
50:
51: @macro GLOSS-END {}
52: @iftex
53: @rm
54: @end iftex
55: @end macro
56:
57: @comment %**end of header (This is for running Texinfo on a region.)
58: @copying
59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
60: a fast and portable implementation of the ANS Forth language. It
61: serves as reference manual, but it also contains an introduction to
62: Forth and a Forth tutorial.
63:
64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007,2008,2009 Free Software Foundation, Inc.
65:
66: @quotation
67: Permission is granted to copy, distribute and/or modify this document
68: under the terms of the GNU Free Documentation License, Version 1.1 or
69: any later version published by the Free Software Foundation; with no
70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
71: and with the Back-Cover Texts as in (a) below. A copy of the
72: license is included in the section entitled ``GNU Free Documentation
73: License.''
74:
75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
76: this GNU Manual, like GNU software. Copies published by the Free
77: Software Foundation raise funds for GNU development.''
78: @end quotation
79: @end copying
80:
81: @dircategory Software development
82: @direntry
83: * Gforth: (gforth). A fast interpreter for the Forth language.
84: @end direntry
85: @c The Texinfo manual also recommends doing this, but for Gforth it may
86: @c not make much sense
87: @c @dircategory Individual utilities
88: @c @direntry
89: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
90: @c @end direntry
91:
92: @titlepage
93: @title Gforth
94: @subtitle for version @value{VERSION}, @value{UPDATED}
95: @author Neal Crook
96: @author Anton Ertl
97: @author David Kuehling
98: @author Bernd Paysan
99: @author Jens Wilke
100: @page
101: @vskip 0pt plus 1filll
102: @insertcopying
103: @end titlepage
104:
105: @contents
106:
107: @ifnottex
108: @node Top, Goals, (dir), (dir)
109: @top Gforth
110:
111: @insertcopying
112: @end ifnottex
113:
114: @menu
115: * Goals:: About the Gforth Project
116: * Gforth Environment:: Starting (and exiting) Gforth
117: * Tutorial:: Hands-on Forth Tutorial
118: * Introduction:: An introduction to ANS Forth
119: * Words:: Forth words available in Gforth
120: * Error messages:: How to interpret them
121: * Tools:: Programming tools
122: * ANS conformance:: Implementation-defined options etc.
123: * Standard vs Extensions:: Should I use extensions?
124: * Model:: The abstract machine of Gforth
125: * Integrating Gforth:: Forth as scripting language for applications
126: * Emacs and Gforth:: The Gforth Mode
127: * Image Files:: @code{.fi} files contain compiled code
128: * Engine:: The inner interpreter and the primitives
129: * Cross Compiler:: The Cross Compiler
130: * Bugs:: How to report them
131: * Origin:: Authors and ancestors of Gforth
132: * Forth-related information:: Books and places to look on the WWW
133: * Licenses::
134: * Word Index:: An item for each Forth word
135: * Concept Index:: A menu covering many topics
136:
137: @detailmenu
138: --- The Detailed Node Listing ---
139:
140: Gforth Environment
141:
142: * Invoking Gforth:: Getting in
143: * Leaving Gforth:: Getting out
144: * Command-line editing::
145: * Environment variables:: that affect how Gforth starts up
146: * Gforth Files:: What gets installed and where
147: * Gforth in pipes::
148: * Startup speed:: When 14ms is not fast enough ...
149:
150: Forth Tutorial
151:
152: * Starting Gforth Tutorial::
153: * Syntax Tutorial::
154: * Crash Course Tutorial::
155: * Stack Tutorial::
156: * Arithmetics Tutorial::
157: * Stack Manipulation Tutorial::
158: * Using files for Forth code Tutorial::
159: * Comments Tutorial::
160: * Colon Definitions Tutorial::
161: * Decompilation Tutorial::
162: * Stack-Effect Comments Tutorial::
163: * Types Tutorial::
164: * Factoring Tutorial::
165: * Designing the stack effect Tutorial::
166: * Local Variables Tutorial::
167: * Conditional execution Tutorial::
168: * Flags and Comparisons Tutorial::
169: * General Loops Tutorial::
170: * Counted loops Tutorial::
171: * Recursion Tutorial::
172: * Leaving definitions or loops Tutorial::
173: * Return Stack Tutorial::
174: * Memory Tutorial::
175: * Characters and Strings Tutorial::
176: * Alignment Tutorial::
177: * Floating Point Tutorial::
178: * Files Tutorial::
179: * Interpretation and Compilation Semantics and Immediacy Tutorial::
180: * Execution Tokens Tutorial::
181: * Exceptions Tutorial::
182: * Defining Words Tutorial::
183: * Arrays and Records Tutorial::
184: * POSTPONE Tutorial::
185: * Literal Tutorial::
186: * Advanced macros Tutorial::
187: * Compilation Tokens Tutorial::
188: * Wordlists and Search Order Tutorial::
189:
190: An Introduction to ANS Forth
191:
192: * Introducing the Text Interpreter::
193: * Stacks and Postfix notation::
194: * Your first definition::
195: * How does that work?::
196: * Forth is written in Forth::
197: * Review - elements of a Forth system::
198: * Where to go next::
199: * Exercises::
200:
201: Forth Words
202:
203: * Notation::
204: * Case insensitivity::
205: * Comments::
206: * Boolean Flags::
207: * Arithmetic::
208: * Stack Manipulation::
209: * Memory::
210: * Control Structures::
211: * Defining Words::
212: * Interpretation and Compilation Semantics::
213: * Tokens for Words::
214: * Compiling words::
215: * The Text Interpreter::
216: * The Input Stream::
217: * Word Lists::
218: * Environmental Queries::
219: * Files::
220: * Blocks::
221: * Other I/O::
222: * OS command line arguments::
223: * Locals::
224: * Structures::
225: * Object-oriented Forth::
226: * Programming Tools::
227: * C Interface::
228: * Assembler and Code Words::
229: * Threading Words::
230: * Passing Commands to the OS::
231: * Keeping track of Time::
232: * Miscellaneous Words::
233:
234: Arithmetic
235:
236: * Single precision::
237: * Double precision:: Double-cell integer arithmetic
238: * Bitwise operations::
239: * Numeric comparison::
240: * Mixed precision:: Operations with single and double-cell integers
241: * Floating Point::
242:
243: Stack Manipulation
244:
245: * Data stack::
246: * Floating point stack::
247: * Return stack::
248: * Locals stack::
249: * Stack pointer manipulation::
250:
251: Memory
252:
253: * Memory model::
254: * Dictionary allocation::
255: * Heap Allocation::
256: * Memory Access::
257: * Address arithmetic::
258: * Memory Blocks::
259:
260: Control Structures
261:
262: * Selection:: IF ... ELSE ... ENDIF
263: * Simple Loops:: BEGIN ...
264: * Counted Loops:: DO
265: * Arbitrary control structures::
266: * Calls and returns::
267: * Exception Handling::
268:
269: Defining Words
270:
271: * CREATE::
272: * Variables:: Variables and user variables
273: * Constants::
274: * Values:: Initialised variables
275: * Colon Definitions::
276: * Anonymous Definitions:: Definitions without names
277: * Supplying names:: Passing definition names as strings
278: * User-defined Defining Words::
279: * Deferred Words:: Allow forward references
280: * Aliases::
281:
282: User-defined Defining Words
283:
284: * CREATE..DOES> applications::
285: * CREATE..DOES> details::
286: * Advanced does> usage example::
287: * Const-does>::
288:
289: Interpretation and Compilation Semantics
290:
291: * Combined words::
292:
293: Tokens for Words
294:
295: * Execution token:: represents execution/interpretation semantics
296: * Compilation token:: represents compilation semantics
297: * Name token:: represents named words
298:
299: Compiling words
300:
301: * Literals:: Compiling data values
302: * Macros:: Compiling words
303:
304: The Text Interpreter
305:
306: * Input Sources::
307: * Number Conversion::
308: * Interpret/Compile states::
309: * Interpreter Directives::
310:
311: Word Lists
312:
313: * Vocabularies::
314: * Why use word lists?::
315: * Word list example::
316:
317: Files
318:
319: * Forth source files::
320: * General files::
321: * Redirection::
322: * Search Paths::
323:
324: Search Paths
325:
326: * Source Search Paths::
327: * General Search Paths::
328:
329: Other I/O
330:
331: * Simple numeric output:: Predefined formats
332: * Formatted numeric output:: Formatted (pictured) output
333: * String Formats:: How Forth stores strings in memory
334: * Displaying characters and strings:: Other stuff
335: * Terminal output:: Cursor positioning etc.
336: * Single-key input::
337: * Line input and conversion::
338: * Pipes:: How to create your own pipes
339: * Xchars and Unicode:: Non-ASCII characters
340:
341: Locals
342:
343: * Gforth locals::
344: * ANS Forth locals::
345:
346: Gforth locals
347:
348: * Where are locals visible by name?::
349: * How long do locals live?::
350: * Locals programming style::
351: * Locals implementation::
352:
353: Structures
354:
355: * Why explicit structure support?::
356: * Structure Usage::
357: * Structure Naming Convention::
358: * Structure Implementation::
359: * Structure Glossary::
360: * Forth200x Structures::
361:
362: Object-oriented Forth
363:
364: * Why object-oriented programming?::
365: * Object-Oriented Terminology::
366: * Objects::
367: * OOF::
368: * Mini-OOF::
369: * Comparison with other object models::
370:
371: The @file{objects.fs} model
372:
373: * Properties of the Objects model::
374: * Basic Objects Usage::
375: * The Objects base class::
376: * Creating objects::
377: * Object-Oriented Programming Style::
378: * Class Binding::
379: * Method conveniences::
380: * Classes and Scoping::
381: * Dividing classes::
382: * Object Interfaces::
383: * Objects Implementation::
384: * Objects Glossary::
385:
386: The @file{oof.fs} model
387:
388: * Properties of the OOF model::
389: * Basic OOF Usage::
390: * The OOF base class::
391: * Class Declaration::
392: * Class Implementation::
393:
394: The @file{mini-oof.fs} model
395:
396: * Basic Mini-OOF Usage::
397: * Mini-OOF Example::
398: * Mini-OOF Implementation::
399:
400: Programming Tools
401:
402: * Examining:: Data and Code.
403: * Forgetting words:: Usually before reloading.
404: * Debugging:: Simple and quick.
405: * Assertions:: Making your programs self-checking.
406: * Singlestep Debugger:: Executing your program word by word.
407:
408: C Interface
409:
410: * Calling C Functions::
411: * Declaring C Functions::
412: * Calling C function pointers::
413: * Defining library interfaces::
414: * Declaring OS-level libraries::
415: * Callbacks::
416: * C interface internals::
417: * Low-Level C Interface Words::
418:
419: Assembler and Code Words
420:
421: * Code and ;code::
422: * Common Assembler:: Assembler Syntax
423: * Common Disassembler::
424: * 386 Assembler:: Deviations and special cases
425: * Alpha Assembler:: Deviations and special cases
426: * MIPS assembler:: Deviations and special cases
427: * PowerPC assembler:: Deviations and special cases
428: * ARM Assembler:: Deviations and special cases
429: * Other assemblers:: How to write them
430:
431: Tools
432:
433: * ANS Report:: Report the words used, sorted by wordset.
434: * Stack depth changes:: Where does this stack item come from?
435:
436: ANS conformance
437:
438: * The Core Words::
439: * The optional Block word set::
440: * The optional Double Number word set::
441: * The optional Exception word set::
442: * The optional Facility word set::
443: * The optional File-Access word set::
444: * The optional Floating-Point word set::
445: * The optional Locals word set::
446: * The optional Memory-Allocation word set::
447: * The optional Programming-Tools word set::
448: * The optional Search-Order word set::
449:
450: The Core Words
451:
452: * core-idef:: Implementation Defined Options
453: * core-ambcond:: Ambiguous Conditions
454: * core-other:: Other System Documentation
455:
456: The optional Block word set
457:
458: * block-idef:: Implementation Defined Options
459: * block-ambcond:: Ambiguous Conditions
460: * block-other:: Other System Documentation
461:
462: The optional Double Number word set
463:
464: * double-ambcond:: Ambiguous Conditions
465:
466: The optional Exception word set
467:
468: * exception-idef:: Implementation Defined Options
469:
470: The optional Facility word set
471:
472: * facility-idef:: Implementation Defined Options
473: * facility-ambcond:: Ambiguous Conditions
474:
475: The optional File-Access word set
476:
477: * file-idef:: Implementation Defined Options
478: * file-ambcond:: Ambiguous Conditions
479:
480: The optional Floating-Point word set
481:
482: * floating-idef:: Implementation Defined Options
483: * floating-ambcond:: Ambiguous Conditions
484:
485: The optional Locals word set
486:
487: * locals-idef:: Implementation Defined Options
488: * locals-ambcond:: Ambiguous Conditions
489:
490: The optional Memory-Allocation word set
491:
492: * memory-idef:: Implementation Defined Options
493:
494: The optional Programming-Tools word set
495:
496: * programming-idef:: Implementation Defined Options
497: * programming-ambcond:: Ambiguous Conditions
498:
499: The optional Search-Order word set
500:
501: * search-idef:: Implementation Defined Options
502: * search-ambcond:: Ambiguous Conditions
503:
504: Emacs and Gforth
505:
506: * Installing gforth.el:: Making Emacs aware of Forth.
507: * Emacs Tags:: Viewing the source of a word in Emacs.
508: * Hilighting:: Making Forth code look prettier.
509: * Auto-Indentation:: Customizing auto-indentation.
510: * Blocks Files:: Reading and writing blocks files.
511:
512: Image Files
513:
514: * Image Licensing Issues:: Distribution terms for images.
515: * Image File Background:: Why have image files?
516: * Non-Relocatable Image Files:: don't always work.
517: * Data-Relocatable Image Files:: are better.
518: * Fully Relocatable Image Files:: better yet.
519: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
520: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
521: * Modifying the Startup Sequence:: and turnkey applications.
522:
523: Fully Relocatable Image Files
524:
525: * gforthmi:: The normal way
526: * cross.fs:: The hard way
527:
528: Engine
529:
530: * Portability::
531: * Threading::
532: * Primitives::
533: * Performance::
534:
535: Threading
536:
537: * Scheduling::
538: * Direct or Indirect Threaded?::
539: * Dynamic Superinstructions::
540: * DOES>::
541:
542: Primitives
543:
544: * Automatic Generation::
545: * TOS Optimization::
546: * Produced code::
547:
548: Cross Compiler
549:
550: * Using the Cross Compiler::
551: * How the Cross Compiler Works::
552:
553: Licenses
554:
555: * GNU Free Documentation License:: License for copying this manual.
556: * Copying:: GPL (for copying this software).
557:
558: @end detailmenu
559: @end menu
560:
561: @c ----------------------------------------------------------
562: @iftex
563: @unnumbered Preface
564: @cindex Preface
565: This manual documents Gforth. Some introductory material is provided for
566: readers who are unfamiliar with Forth or who are migrating to Gforth
567: from other Forth compilers. However, this manual is primarily a
568: reference manual.
569: @end iftex
570:
571: @comment TODO much more blurb here.
572:
573: @c ******************************************************************
574: @node Goals, Gforth Environment, Top, Top
575: @comment node-name, next, previous, up
576: @chapter Goals of Gforth
577: @cindex goals of the Gforth project
578: The goal of the Gforth Project is to develop a standard model for
579: ANS Forth. This can be split into several subgoals:
580:
581: @itemize @bullet
582: @item
583: Gforth should conform to the ANS Forth Standard.
584: @item
585: It should be a model, i.e. it should define all the
586: implementation-dependent things.
587: @item
588: It should become standard, i.e. widely accepted and used. This goal
589: is the most difficult one.
590: @end itemize
591:
592: To achieve these goals Gforth should be
593: @itemize @bullet
594: @item
595: Similar to previous models (fig-Forth, F83)
596: @item
597: Powerful. It should provide for all the things that are considered
598: necessary today and even some that are not yet considered necessary.
599: @item
600: Efficient. It should not get the reputation of being exceptionally
601: slow.
602: @item
603: Free.
604: @item
605: Available on many machines/easy to port.
606: @end itemize
607:
608: Have we achieved these goals? Gforth conforms to the ANS Forth
609: standard. It may be considered a model, but we have not yet documented
610: which parts of the model are stable and which parts we are likely to
611: change. It certainly has not yet become a de facto standard, but it
612: appears to be quite popular. It has some similarities to and some
613: differences from previous models. It has some powerful features, but not
614: yet everything that we envisioned. We certainly have achieved our
615: execution speed goals (@pxref{Performance})@footnote{However, in 1998
616: the bar was raised when the major commercial Forth vendors switched to
617: native code compilers.}. It is free and available on many machines.
618:
619: @c ******************************************************************
620: @node Gforth Environment, Tutorial, Goals, Top
621: @chapter Gforth Environment
622: @cindex Gforth environment
623:
624: Note: ultimately, the Gforth man page will be auto-generated from the
625: material in this chapter.
626:
627: @menu
628: * Invoking Gforth:: Getting in
629: * Leaving Gforth:: Getting out
630: * Command-line editing::
631: * Environment variables:: that affect how Gforth starts up
632: * Gforth Files:: What gets installed and where
633: * Gforth in pipes::
634: * Startup speed:: When 14ms is not fast enough ...
635: @end menu
636:
637: For related information about the creation of images see @ref{Image Files}.
638:
639: @comment ----------------------------------------------
640: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
641: @section Invoking Gforth
642: @cindex invoking Gforth
643: @cindex running Gforth
644: @cindex command-line options
645: @cindex options on the command line
646: @cindex flags on the command line
647:
648: Gforth is made up of two parts; an executable ``engine'' (named
649: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
650: will usually just say @code{gforth} -- this automatically loads the
651: default image file @file{gforth.fi}. In many other cases the default
652: Gforth image will be invoked like this:
653: @example
654: gforth [file | -e forth-code] ...
655: @end example
656: @noindent
657: This interprets the contents of the files and the Forth code in the order they
658: are given.
659:
660: In addition to the @command{gforth} engine, there is also an engine
661: called @command{gforth-fast}, which is faster, but gives less
662: informative error messages (@pxref{Error messages}) and may catch some
663: errors (in particular, stack underflows and integer division errors)
664: later or not at all. You should use it for debugged,
665: performance-critical programs.
666:
667: Moreover, there is an engine called @command{gforth-itc}, which is
668: useful in some backwards-compatibility situations (@pxref{Direct or
669: Indirect Threaded?}).
670:
671: In general, the command line looks like this:
672:
673: @example
674: gforth[-fast] [engine options] [image options]
675: @end example
676:
677: The engine options must come before the rest of the command
678: line. They are:
679:
680: @table @code
681: @cindex -i, command-line option
682: @cindex --image-file, command-line option
683: @item --image-file @i{file}
684: @itemx -i @i{file}
685: Loads the Forth image @i{file} instead of the default
686: @file{gforth.fi} (@pxref{Image Files}).
687:
688: @cindex --appl-image, command-line option
689: @item --appl-image @i{file}
690: Loads the image @i{file} and leaves all further command-line arguments
691: to the image (instead of processing them as engine options). This is
692: useful for building executable application images on Unix, built with
693: @code{gforthmi --application ...}.
694:
695: @cindex --path, command-line option
696: @cindex -p, command-line option
697: @item --path @i{path}
698: @itemx -p @i{path}
699: Uses @i{path} for searching the image file and Forth source code files
700: instead of the default in the environment variable @code{GFORTHPATH} or
701: the path specified at installation time (e.g.,
702: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
703: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
704:
705: @cindex --dictionary-size, command-line option
706: @cindex -m, command-line option
707: @cindex @i{size} parameters for command-line options
708: @cindex size of the dictionary and the stacks
709: @item --dictionary-size @i{size}
710: @itemx -m @i{size}
711: Allocate @i{size} space for the Forth dictionary space instead of
712: using the default specified in the image (typically 256K). The
713: @i{size} specification for this and subsequent options consists of
714: an integer and a unit (e.g.,
715: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
716: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
717: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
718: @code{e} is used.
719:
720: @cindex --data-stack-size, command-line option
721: @cindex -d, command-line option
722: @item --data-stack-size @i{size}
723: @itemx -d @i{size}
724: Allocate @i{size} space for the data stack instead of using the
725: default specified in the image (typically 16K).
726:
727: @cindex --return-stack-size, command-line option
728: @cindex -r, command-line option
729: @item --return-stack-size @i{size}
730: @itemx -r @i{size}
731: Allocate @i{size} space for the return stack instead of using the
732: default specified in the image (typically 15K).
733:
734: @cindex --fp-stack-size, command-line option
735: @cindex -f, command-line option
736: @item --fp-stack-size @i{size}
737: @itemx -f @i{size}
738: Allocate @i{size} space for the floating point stack instead of
739: using the default specified in the image (typically 15.5K). In this case
740: the unit specifier @code{e} refers to floating point numbers.
741:
742: @cindex --locals-stack-size, command-line option
743: @cindex -l, command-line option
744: @item --locals-stack-size @i{size}
745: @itemx -l @i{size}
746: Allocate @i{size} space for the locals stack instead of using the
747: default specified in the image (typically 14.5K).
748:
749: @cindex --vm-commit, command-line option
750: @cindex overcommit memory for dictionary and stacks
751: @cindex memory overcommit for dictionary and stacks
752: @item --vm-commit
753: Normally, Gforth tries to start up even if there is not enough virtual
754: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
755: on OSs that support it); so you can ask for a really big dictionary
756: and/or stacks, and as long as you don't use more virtual memory than
757: is available, everything will be fine (but if you use more, processes
758: get killed). With this option you just use the default allocation
759: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
760: means that you cannot and should not ask for as big dictionary and
761: stacks, but once Gforth successfully starts up, out-of-memory won't
762: kill it.
763:
764: @cindex -h, command-line option
765: @cindex --help, command-line option
766: @item --help
767: @itemx -h
768: Print a message about the command-line options
769:
770: @cindex -v, command-line option
771: @cindex --version, command-line option
772: @item --version
773: @itemx -v
774: Print version and exit
775:
776: @cindex --debug, command-line option
777: @item --debug
778: Print some information useful for debugging on startup.
779:
780: @cindex --offset-image, command-line option
781: @item --offset-image
782: Start the dictionary at a slightly different position than would be used
783: otherwise (useful for creating data-relocatable images,
784: @pxref{Data-Relocatable Image Files}).
785:
786: @cindex --no-offset-im, command-line option
787: @item --no-offset-im
788: Start the dictionary at the normal position.
789:
790: @cindex --clear-dictionary, command-line option
791: @item --clear-dictionary
792: Initialize all bytes in the dictionary to 0 before loading the image
793: (@pxref{Data-Relocatable Image Files}).
794:
795: @cindex --die-on-signal, command-line-option
796: @item --die-on-signal
797: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
798: or the segmentation violation SIGSEGV) by translating it into a Forth
799: @code{THROW}. With this option, Gforth exits if it receives such a
800: signal. This option is useful when the engine and/or the image might be
801: severely broken (such that it causes another signal before recovering
802: from the first); this option avoids endless loops in such cases.
803:
804: @cindex --no-dynamic, command-line option
805: @cindex --dynamic, command-line option
806: @item --no-dynamic
807: @item --dynamic
808: Disable or enable dynamic superinstructions with replication
809: (@pxref{Dynamic Superinstructions}).
810:
811: @cindex --no-super, command-line option
812: @item --no-super
813: Disable dynamic superinstructions, use just dynamic replication; this is
814: useful if you want to patch threaded code (@pxref{Dynamic
815: Superinstructions}).
816:
817: @cindex --ss-number, command-line option
818: @item --ss-number=@var{N}
819: Use only the first @var{N} static superinstructions compiled into the
820: engine (default: use them all; note that only @code{gforth-fast} has
821: any). This option is useful for measuring the performance impact of
822: static superinstructions.
823:
824: @cindex --ss-min-..., command-line options
825: @item --ss-min-codesize
826: @item --ss-min-ls
827: @item --ss-min-lsu
828: @item --ss-min-nexts
829: Use specified metric for determining the cost of a primitive or static
830: superinstruction for static superinstruction selection. @code{Codesize}
831: is the native code size of the primive or static superinstruction,
832: @code{ls} is the number of loads and stores, @code{lsu} is the number of
833: loads, stores, and updates, and @code{nexts} is the number of dispatches
834: (not taking dynamic superinstructions into account), i.e. every
835: primitive or static superinstruction has cost 1. Default:
836: @code{codesize} if you use dynamic code generation, otherwise
837: @code{nexts}.
838:
839: @cindex --ss-greedy, command-line option
840: @item --ss-greedy
841: This option is useful for measuring the performance impact of static
842: superinstructions. By default, an optimal shortest-path algorithm is
843: used for selecting static superinstructions. With @option{--ss-greedy}
844: this algorithm is modified to assume that anything after the static
845: superinstruction currently under consideration is not combined into
846: static superinstructions. With @option{--ss-min-nexts} this produces
847: the same result as a greedy algorithm that always selects the longest
848: superinstruction available at the moment. E.g., if there are
849: superinstructions AB and BCD, then for the sequence A B C D the optimal
850: algorithm will select A BCD and the greedy algorithm will select AB C D.
851:
852: @cindex --print-metrics, command-line option
853: @item --print-metrics
854: Prints some metrics used during static superinstruction selection:
855: @code{code size} is the actual size of the dynamically generated code.
856: @code{Metric codesize} is the sum of the codesize metrics as seen by
857: static superinstruction selection; there is a difference from @code{code
858: size}, because not all primitives and static superinstructions are
859: compiled into dynamically generated code, and because of markers. The
860: other metrics correspond to the @option{ss-min-...} options. This
861: option is useful for evaluating the effects of the @option{--ss-...}
862: options.
863:
864: @end table
865:
866: @cindex loading files at startup
867: @cindex executing code on startup
868: @cindex batch processing with Gforth
869: As explained above, the image-specific command-line arguments for the
870: default image @file{gforth.fi} consist of a sequence of filenames and
871: @code{-e @var{forth-code}} options that are interpreted in the sequence
872: in which they are given. The @code{-e @var{forth-code}} or
873: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
874: option takes only one argument; if you want to evaluate more Forth
875: words, you have to quote them or use @code{-e} several times. To exit
876: after processing the command line (instead of entering interactive mode)
877: append @code{-e bye} to the command line. You can also process the
878: command-line arguments with a Forth program (@pxref{OS command line
879: arguments}).
880:
881: @cindex versions, invoking other versions of Gforth
882: If you have several versions of Gforth installed, @code{gforth} will
883: invoke the version that was installed last. @code{gforth-@i{version}}
884: invokes a specific version. If your environment contains the variable
885: @code{GFORTHPATH}, you may want to override it by using the
886: @code{--path} option.
887:
888: Not yet implemented:
889: On startup the system first executes the system initialization file
890: (unless the option @code{--no-init-file} is given; note that the system
891: resulting from using this option may not be ANS Forth conformant). Then
892: the user initialization file @file{.gforth.fs} is executed, unless the
893: option @code{--no-rc} is given; this file is searched for in @file{.},
894: then in @file{~}, then in the normal path (see above).
895:
896:
897:
898: @comment ----------------------------------------------
899: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
900: @section Leaving Gforth
901: @cindex Gforth - leaving
902: @cindex leaving Gforth
903:
904: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
905: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
906: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
907: data are discarded. For ways of saving the state of the system before
908: leaving Gforth see @ref{Image Files}.
909:
910: doc-bye
911:
912:
913: @comment ----------------------------------------------
914: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
915: @section Command-line editing
916: @cindex command-line editing
917:
918: Gforth maintains a history file that records every line that you type to
919: the text interpreter. This file is preserved between sessions, and is
920: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
921: repeatedly you can recall successively older commands from this (or
922: previous) session(s). The full list of command-line editing facilities is:
923:
924: @itemize @bullet
925: @item
926: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
927: commands from the history buffer.
928: @item
929: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
930: from the history buffer.
931: @item
932: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
933: @item
934: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
935: @item
936: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
937: closing up the line.
938: @item
939: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
940: @item
941: @kbd{Ctrl-a} to move the cursor to the start of the line.
942: @item
943: @kbd{Ctrl-e} to move the cursor to the end of the line.
944: @item
945: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
946: line.
947: @item
948: @key{TAB} to step through all possible full-word completions of the word
949: currently being typed.
950: @item
951: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
952: using @code{bye}).
953: @item
954: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
955: character under the cursor.
956: @end itemize
957:
958: When editing, displayable characters are inserted to the left of the
959: cursor position; the line is always in ``insert'' (as opposed to
960: ``overstrike'') mode.
961:
962: @cindex history file
963: @cindex @file{.gforth-history}
964: On Unix systems, the history file is @file{~/.gforth-history} by
965: default@footnote{i.e. it is stored in the user's home directory.}. You
966: can find out the name and location of your history file using:
967:
968: @example
969: history-file type \ Unix-class systems
970:
971: history-file type \ Other systems
972: history-dir type
973: @end example
974:
975: If you enter long definitions by hand, you can use a text editor to
976: paste them out of the history file into a Forth source file for reuse at
977: a later time.
978:
979: Gforth never trims the size of the history file, so you should do this
980: periodically, if necessary.
981:
982: @comment this is all defined in history.fs
983: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
984: @comment chosen?
985:
986:
987: @comment ----------------------------------------------
988: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
989: @section Environment variables
990: @cindex environment variables
991:
992: Gforth uses these environment variables:
993:
994: @itemize @bullet
995: @item
996: @cindex @code{GFORTHHIST} -- environment variable
997: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
998: open/create the history file, @file{.gforth-history}. Default:
999: @code{$HOME}.
1000:
1001: @item
1002: @cindex @code{GFORTHPATH} -- environment variable
1003: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
1004: for Forth source-code files.
1005:
1006: @item
1007: @cindex @code{LANG} -- environment variable
1008: @code{LANG} -- see @code{LC_CTYPE}
1009:
1010: @item
1011: @cindex @code{LC_ALL} -- environment variable
1012: @code{LC_ALL} -- see @code{LC_CTYPE}
1013:
1014: @item
1015: @cindex @code{LC_CTYPE} -- environment variable
1016: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
1017: startup, Gforth uses the UTF-8 encoding for strings internally and
1018: expects its input and produces its output in UTF-8 encoding, otherwise
1019: the encoding is 8bit (see @pxref{Xchars and Unicode}). If this
1020: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
1021: that is unset, in @code{LANG}.
1022:
1023: @item
1024: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
1025:
1026: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
1027: of @code{system} before passing it to C's @code{system()}. Default:
1028: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1029: and the command are directly concatenated, so if a space between them is
1030: necessary, append it to the prefix.
1031:
1032: @item
1033: @cindex @code{GFORTH} -- environment variable
1034: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1035:
1036: @item
1037: @cindex @code{GFORTHD} -- environment variable
1038: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1039:
1040: @item
1041: @cindex @code{TMP}, @code{TEMP} - environment variable
1042: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1043: location for the history file.
1044: @end itemize
1045:
1046: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1047: @comment mentioning these.
1048:
1049: All the Gforth environment variables default to sensible values if they
1050: are not set.
1051:
1052:
1053: @comment ----------------------------------------------
1054: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1055: @section Gforth files
1056: @cindex Gforth files
1057:
1058: When you install Gforth on a Unix system, it installs files in these
1059: locations by default:
1060:
1061: @itemize @bullet
1062: @item
1063: @file{/usr/local/bin/gforth}
1064: @item
1065: @file{/usr/local/bin/gforthmi}
1066: @item
1067: @file{/usr/local/man/man1/gforth.1} - man page.
1068: @item
1069: @file{/usr/local/info} - the Info version of this manual.
1070: @item
1071: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1072: @item
1073: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1074: @item
1075: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1076: @item
1077: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1078: @end itemize
1079:
1080: You can select different places for installation by using
1081: @code{configure} options (listed with @code{configure --help}).
1082:
1083: @comment ----------------------------------------------
1084: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1085: @section Gforth in pipes
1086: @cindex pipes, Gforth as part of
1087:
1088: Gforth can be used in pipes created elsewhere (described here). It can
1089: also create pipes on its own (@pxref{Pipes}).
1090:
1091: @cindex input from pipes
1092: If you pipe into Gforth, your program should read with @code{read-file}
1093: or @code{read-line} from @code{stdin} (@pxref{General files}).
1094: @code{Key} does not recognize the end of input. Words like
1095: @code{accept} echo the input and are therefore usually not useful for
1096: reading from a pipe. You have to invoke the Forth program with an OS
1097: command-line option, as you have no chance to use the Forth command line
1098: (the text interpreter would try to interpret the pipe input).
1099:
1100: @cindex output in pipes
1101: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1102:
1103: @cindex silent exiting from Gforth
1104: When you write to a pipe that has been closed at the other end, Gforth
1105: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1106: into the exception @code{broken-pipe-error}. If your application does
1107: not catch that exception, the system catches it and exits, usually
1108: silently (unless you were working on the Forth command line; then it
1109: prints an error message and exits). This is usually the desired
1110: behaviour.
1111:
1112: If you do not like this behaviour, you have to catch the exception
1113: yourself, and react to it.
1114:
1115: Here's an example of an invocation of Gforth that is usable in a pipe:
1116:
1117: @example
1118: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1119: type repeat ; foo bye"
1120: @end example
1121:
1122: This example just copies the input verbatim to the output. A very
1123: simple pipe containing this example looks like this:
1124:
1125: @example
1126: cat startup.fs |
1127: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1128: type repeat ; foo bye"|
1129: head
1130: @end example
1131:
1132: @cindex stderr and pipes
1133: Pipes involving Gforth's @code{stderr} output do not work.
1134:
1135: @comment ----------------------------------------------
1136: @node Startup speed, , Gforth in pipes, Gforth Environment
1137: @section Startup speed
1138: @cindex Startup speed
1139: @cindex speed, startup
1140:
1141: If Gforth is used for CGI scripts or in shell scripts, its startup
1142: speed may become a problem. On a 3GHz Core 2 Duo E8400 under 64-bit
1143: Linux 2.6.27.8 with libc-2.7, @code{gforth-fast -e bye} takes 13.1ms
1144: user and 1.2ms system time (@code{gforth -e bye} is faster on startup
1145: with about 3.4ms user time and 1.2ms system time, because it subsumes
1146: some of the options discussed below).
1147:
1148: If startup speed is a problem, you may consider the following ways to
1149: improve it; or you may consider ways to reduce the number of startups
1150: (for example, by using Fast-CGI). Note that the first steps below
1151: improve the startup time at the cost of run-time (including
1152: compile-time), so whether they are profitable depends on the balance
1153: of these times in your application.
1154:
1155: An easy step that influences Gforth startup speed is the use of a
1156: number of options that increase run-time, but decrease image-loading
1157: time.
1158:
1159: The first of these that you should try is @code{--ss-number=0
1160: --ss-states=1} because this option buys relatively little run-time
1161: speedup and costs quite a bit of time at startup. @code{gforth-fast
1162: --ss-number=0 --ss-states=1 -e bye} takes about 2.8ms user and 1.5ms
1163: system time.
1164:
1165: The next option is @code{--no-dynamic} which has a substantial impact
1166: on run-time (about a factor of 2 on several platforms), but still
1167: makes startup speed a little faster: @code{gforth-fast --ss-number=0
1168: --ss-states=1 --no-dynamic -e bye} consumes about 2.6ms user and 1.2ms
1169: system time.
1170:
1171: The next step to improve startup speed is to use a data-relocatable
1172: image (@pxref{Data-Relocatable Image Files}). This avoids the
1173: relocation cost for the code in the image (but not for the data).
1174: Note that the image is then specific to the particular binary you are
1175: using (i.e., whether it is @code{gforth}, @code{gforth-fast}, and even
1176: the particular build). You create the data-relocatable image that
1177: works with @code{./gforth-fast} with @code{GFORTHD="./gforth-fast
1178: --no-dynamic" gforthmi gforthdr.fi} (the @code{--no-dynamic} is
1179: required here or the image will not work). And you run it with
1180: @code{gforth-fast -i gforthdr.fi ... -e bye} (the flags discussed
1181: above don't matter here, because they only come into play on
1182: relocatable code). @code{gforth-fast -i gforthdr.fi -e bye} takes
1183: about 1.1ms user and 1.2ms system time.
1184:
1185: One step further is to avoid all relocation cost and part of the
1186: copy-on-write cost through using a non-relocatable image
1187: (@pxref{Non-Relocatable Image Files}). However, this has the
1188: disadvantage that it does not work on operating systems with address
1189: space randomization (the default in, e.g., Linux nowadays), or if the
1190: dictionary moves for any other reason (e.g., because of a change of
1191: the OS kernel or an updated library), so we cannot really recommend
1192: it. You create a non-relocatable image with @code{gforth-fast
1193: --no-dynamic -e "savesystem gforthnr.fi bye"} (the @code{--no-dynamic}
1194: is required here, too). And you run it with @code{gforth-fast -i
1195: gforthnr.fi ... -e bye} (again the flags discussed above don't
1196: matter). @code{gforth-fast -i gforthdr.fi -e bye} takes
1197: about 0.9ms user and 0.9ms system time.
1198:
1199: If the script you want to execute contains a significant amount of
1200: code, it may be profitable to compile it into the image to avoid the
1201: cost of compiling it at startup time.
1202:
1203: @c ******************************************************************
1204: @node Tutorial, Introduction, Gforth Environment, Top
1205: @chapter Forth Tutorial
1206: @cindex Tutorial
1207: @cindex Forth Tutorial
1208:
1209: @c Topics from nac's Introduction that could be mentioned:
1210: @c press <ret> after each line
1211: @c Prompt
1212: @c numbers vs. words in dictionary on text interpretation
1213: @c what happens on redefinition
1214: @c parsing words (in particular, defining words)
1215:
1216: The difference of this chapter from the Introduction
1217: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1218: be used while sitting in front of a computer, and covers much more
1219: material, but does not explain how the Forth system works.
1220:
1221: This tutorial can be used with any ANS-compliant Forth; any
1222: Gforth-specific features are marked as such and you can skip them if
1223: you work with another Forth. This tutorial does not explain all
1224: features of Forth, just enough to get you started and give you some
1225: ideas about the facilities available in Forth. Read the rest of the
1226: manual when you are through this.
1227:
1228: The intended way to use this tutorial is that you work through it while
1229: sitting in front of the console, take a look at the examples and predict
1230: what they will do, then try them out; if the outcome is not as expected,
1231: find out why (e.g., by trying out variations of the example), so you
1232: understand what's going on. There are also some assignments that you
1233: should solve.
1234:
1235: This tutorial assumes that you have programmed before and know what,
1236: e.g., a loop is.
1237:
1238: @c !! explain compat library
1239:
1240: @menu
1241: * Starting Gforth Tutorial::
1242: * Syntax Tutorial::
1243: * Crash Course Tutorial::
1244: * Stack Tutorial::
1245: * Arithmetics Tutorial::
1246: * Stack Manipulation Tutorial::
1247: * Using files for Forth code Tutorial::
1248: * Comments Tutorial::
1249: * Colon Definitions Tutorial::
1250: * Decompilation Tutorial::
1251: * Stack-Effect Comments Tutorial::
1252: * Types Tutorial::
1253: * Factoring Tutorial::
1254: * Designing the stack effect Tutorial::
1255: * Local Variables Tutorial::
1256: * Conditional execution Tutorial::
1257: * Flags and Comparisons Tutorial::
1258: * General Loops Tutorial::
1259: * Counted loops Tutorial::
1260: * Recursion Tutorial::
1261: * Leaving definitions or loops Tutorial::
1262: * Return Stack Tutorial::
1263: * Memory Tutorial::
1264: * Characters and Strings Tutorial::
1265: * Alignment Tutorial::
1266: * Floating Point Tutorial::
1267: * Files Tutorial::
1268: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1269: * Execution Tokens Tutorial::
1270: * Exceptions Tutorial::
1271: * Defining Words Tutorial::
1272: * Arrays and Records Tutorial::
1273: * POSTPONE Tutorial::
1274: * Literal Tutorial::
1275: * Advanced macros Tutorial::
1276: * Compilation Tokens Tutorial::
1277: * Wordlists and Search Order Tutorial::
1278: @end menu
1279:
1280: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1281: @section Starting Gforth
1282: @cindex starting Gforth tutorial
1283: You can start Gforth by typing its name:
1284:
1285: @example
1286: gforth
1287: @end example
1288:
1289: That puts you into interactive mode; you can leave Gforth by typing
1290: @code{bye}. While in Gforth, you can edit the command line and access
1291: the command line history with cursor keys, similar to bash.
1292:
1293:
1294: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1295: @section Syntax
1296: @cindex syntax tutorial
1297:
1298: A @dfn{word} is a sequence of arbitrary characters (except white
1299: space). Words are separated by white space. E.g., each of the
1300: following lines contains exactly one word:
1301:
1302: @example
1303: word
1304: !@@#$%^&*()
1305: 1234567890
1306: 5!a
1307: @end example
1308:
1309: A frequent beginner's error is to leave out necessary white space,
1310: resulting in an error like @samp{Undefined word}; so if you see such an
1311: error, check if you have put spaces wherever necessary.
1312:
1313: @example
1314: ." hello, world" \ correct
1315: ."hello, world" \ gives an "Undefined word" error
1316: @end example
1317:
1318: Gforth and most other Forth systems ignore differences in case (they are
1319: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1320: your system is case-sensitive, you may have to type all the examples
1321: given here in upper case.
1322:
1323:
1324: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1325: @section Crash Course
1326:
1327: Forth does not prevent you from shooting yourself in the foot. Let's
1328: try a few ways to crash Gforth:
1329:
1330: @example
1331: 0 0 !
1332: here execute
1333: ' catch >body 20 erase abort
1334: ' (quit) >body 20 erase
1335: @end example
1336:
1337: The last two examples are guaranteed to destroy important parts of
1338: Gforth (and most other systems), so you better leave Gforth afterwards
1339: (if it has not finished by itself). On some systems you may have to
1340: kill gforth from outside (e.g., in Unix with @code{kill}).
1341:
1342: You will find out later what these lines do and then you will get an
1343: idea why they produce crashes.
1344:
1345: Now that you know how to produce crashes (and that there's not much to
1346: them), let's learn how to produce meaningful programs.
1347:
1348:
1349: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1350: @section Stack
1351: @cindex stack tutorial
1352:
1353: The most obvious feature of Forth is the stack. When you type in a
1354: number, it is pushed on the stack. You can display the contents of the
1355: stack with @code{.s}.
1356:
1357: @example
1358: 1 2 .s
1359: 3 .s
1360: @end example
1361:
1362: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1363: appear in @code{.s} output as they appeared in the input.
1364:
1365: You can print the top element of the stack with @code{.}.
1366:
1367: @example
1368: 1 2 3 . . .
1369: @end example
1370:
1371: In general, words consume their stack arguments (@code{.s} is an
1372: exception).
1373:
1374: @quotation Assignment
1375: What does the stack contain after @code{5 6 7 .}?
1376: @end quotation
1377:
1378:
1379: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1380: @section Arithmetics
1381: @cindex arithmetics tutorial
1382:
1383: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1384: operate on the top two stack items:
1385:
1386: @example
1387: 2 2 .s
1388: + .s
1389: .
1390: 2 1 - .
1391: 7 3 mod .
1392: @end example
1393:
1394: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1395: as in the corresponding infix expression (this is generally the case in
1396: Forth).
1397:
1398: Parentheses are superfluous (and not available), because the order of
1399: the words unambiguously determines the order of evaluation and the
1400: operands:
1401:
1402: @example
1403: 3 4 + 5 * .
1404: 3 4 5 * + .
1405: @end example
1406:
1407: @quotation Assignment
1408: What are the infix expressions corresponding to the Forth code above?
1409: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1410: known as Postfix or RPN (Reverse Polish Notation).}.
1411: @end quotation
1412:
1413: To change the sign, use @code{negate}:
1414:
1415: @example
1416: 2 negate .
1417: @end example
1418:
1419: @quotation Assignment
1420: Convert -(-3)*4-5 to Forth.
1421: @end quotation
1422:
1423: @code{/mod} performs both @code{/} and @code{mod}.
1424:
1425: @example
1426: 7 3 /mod . .
1427: @end example
1428:
1429: Reference: @ref{Arithmetic}.
1430:
1431:
1432: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1433: @section Stack Manipulation
1434: @cindex stack manipulation tutorial
1435:
1436: Stack manipulation words rearrange the data on the stack.
1437:
1438: @example
1439: 1 .s drop .s
1440: 1 .s dup .s drop drop .s
1441: 1 2 .s over .s drop drop drop
1442: 1 2 .s swap .s drop drop
1443: 1 2 3 .s rot .s drop drop drop
1444: @end example
1445:
1446: These are the most important stack manipulation words. There are also
1447: variants that manipulate twice as many stack items:
1448:
1449: @example
1450: 1 2 3 4 .s 2swap .s 2drop 2drop
1451: @end example
1452:
1453: Two more stack manipulation words are:
1454:
1455: @example
1456: 1 2 .s nip .s drop
1457: 1 2 .s tuck .s 2drop drop
1458: @end example
1459:
1460: @quotation Assignment
1461: Replace @code{nip} and @code{tuck} with combinations of other stack
1462: manipulation words.
1463:
1464: @example
1465: Given: How do you get:
1466: 1 2 3 3 2 1
1467: 1 2 3 1 2 3 2
1468: 1 2 3 1 2 3 3
1469: 1 2 3 1 3 3
1470: 1 2 3 2 1 3
1471: 1 2 3 4 4 3 2 1
1472: 1 2 3 1 2 3 1 2 3
1473: 1 2 3 4 1 2 3 4 1 2
1474: 1 2 3
1475: 1 2 3 1 2 3 4
1476: 1 2 3 1 3
1477: @end example
1478: @end quotation
1479:
1480: @example
1481: 5 dup * .
1482: @end example
1483:
1484: @quotation Assignment
1485: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1486: Write a piece of Forth code that expects two numbers on the stack
1487: (@var{a} and @var{b}, with @var{b} on top) and computes
1488: @code{(a-b)(a+1)}.
1489: @end quotation
1490:
1491: Reference: @ref{Stack Manipulation}.
1492:
1493:
1494: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1495: @section Using files for Forth code
1496: @cindex loading Forth code, tutorial
1497: @cindex files containing Forth code, tutorial
1498:
1499: While working at the Forth command line is convenient for one-line
1500: examples and short one-off code, you probably want to store your source
1501: code in files for convenient editing and persistence. You can use your
1502: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1503: Gforth}) to create @var{file.fs} and use
1504:
1505: @example
1506: s" @var{file.fs}" included
1507: @end example
1508:
1509: to load it into your Forth system. The file name extension I use for
1510: Forth files is @samp{.fs}.
1511:
1512: You can easily start Gforth with some files loaded like this:
1513:
1514: @example
1515: gforth @var{file1.fs} @var{file2.fs}
1516: @end example
1517:
1518: If an error occurs during loading these files, Gforth terminates,
1519: whereas an error during @code{INCLUDED} within Gforth usually gives you
1520: a Gforth command line. Starting the Forth system every time gives you a
1521: clean start every time, without interference from the results of earlier
1522: tries.
1523:
1524: I often put all the tests in a file, then load the code and run the
1525: tests with
1526:
1527: @example
1528: gforth @var{code.fs} @var{tests.fs} -e bye
1529: @end example
1530:
1531: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1532: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1533: restart this command without ado.
1534:
1535: The advantage of this approach is that the tests can be repeated easily
1536: every time the program ist changed, making it easy to catch bugs
1537: introduced by the change.
1538:
1539: Reference: @ref{Forth source files}.
1540:
1541:
1542: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1543: @section Comments
1544: @cindex comments tutorial
1545:
1546: @example
1547: \ That's a comment; it ends at the end of the line
1548: ( Another comment; it ends here: ) .s
1549: @end example
1550:
1551: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1552: separated with white space from the following text.
1553:
1554: @example
1555: \This gives an "Undefined word" error
1556: @end example
1557:
1558: The first @code{)} ends a comment started with @code{(}, so you cannot
1559: nest @code{(}-comments; and you cannot comment out text containing a
1560: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1561: avoid @code{)} in word names.}.
1562:
1563: I use @code{\}-comments for descriptive text and for commenting out code
1564: of one or more line; I use @code{(}-comments for describing the stack
1565: effect, the stack contents, or for commenting out sub-line pieces of
1566: code.
1567:
1568: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1569: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1570: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1571: with @kbd{M-q}.
1572:
1573: Reference: @ref{Comments}.
1574:
1575:
1576: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1577: @section Colon Definitions
1578: @cindex colon definitions, tutorial
1579: @cindex definitions, tutorial
1580: @cindex procedures, tutorial
1581: @cindex functions, tutorial
1582:
1583: are similar to procedures and functions in other programming languages.
1584:
1585: @example
1586: : squared ( n -- n^2 )
1587: dup * ;
1588: 5 squared .
1589: 7 squared .
1590: @end example
1591:
1592: @code{:} starts the colon definition; its name is @code{squared}. The
1593: following comment describes its stack effect. The words @code{dup *}
1594: are not executed, but compiled into the definition. @code{;} ends the
1595: colon definition.
1596:
1597: The newly-defined word can be used like any other word, including using
1598: it in other definitions:
1599:
1600: @example
1601: : cubed ( n -- n^3 )
1602: dup squared * ;
1603: -5 cubed .
1604: : fourth-power ( n -- n^4 )
1605: squared squared ;
1606: 3 fourth-power .
1607: @end example
1608:
1609: @quotation Assignment
1610: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1611: @code{/mod} in terms of other Forth words, and check if they work (hint:
1612: test your tests on the originals first). Don't let the
1613: @samp{redefined}-Messages spook you, they are just warnings.
1614: @end quotation
1615:
1616: Reference: @ref{Colon Definitions}.
1617:
1618:
1619: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1620: @section Decompilation
1621: @cindex decompilation tutorial
1622: @cindex see tutorial
1623:
1624: You can decompile colon definitions with @code{see}:
1625:
1626: @example
1627: see squared
1628: see cubed
1629: @end example
1630:
1631: In Gforth @code{see} shows you a reconstruction of the source code from
1632: the executable code. Informations that were present in the source, but
1633: not in the executable code, are lost (e.g., comments).
1634:
1635: You can also decompile the predefined words:
1636:
1637: @example
1638: see .
1639: see +
1640: @end example
1641:
1642:
1643: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1644: @section Stack-Effect Comments
1645: @cindex stack-effect comments, tutorial
1646: @cindex --, tutorial
1647: By convention the comment after the name of a definition describes the
1648: stack effect: The part in front of the @samp{--} describes the state of
1649: the stack before the execution of the definition, i.e., the parameters
1650: that are passed into the colon definition; the part behind the @samp{--}
1651: is the state of the stack after the execution of the definition, i.e.,
1652: the results of the definition. The stack comment only shows the top
1653: stack items that the definition accesses and/or changes.
1654:
1655: You should put a correct stack effect on every definition, even if it is
1656: just @code{( -- )}. You should also add some descriptive comment to
1657: more complicated words (I usually do this in the lines following
1658: @code{:}). If you don't do this, your code becomes unreadable (because
1659: you have to work through every definition before you can understand
1660: any).
1661:
1662: @quotation Assignment
1663: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1664: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1665: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1666: are done, you can compare your stack effects to those in this manual
1667: (@pxref{Word Index}).
1668: @end quotation
1669:
1670: Sometimes programmers put comments at various places in colon
1671: definitions that describe the contents of the stack at that place (stack
1672: comments); i.e., they are like the first part of a stack-effect
1673: comment. E.g.,
1674:
1675: @example
1676: : cubed ( n -- n^3 )
1677: dup squared ( n n^2 ) * ;
1678: @end example
1679:
1680: In this case the stack comment is pretty superfluous, because the word
1681: is simple enough. If you think it would be a good idea to add such a
1682: comment to increase readability, you should also consider factoring the
1683: word into several simpler words (@pxref{Factoring Tutorial,,
1684: Factoring}), which typically eliminates the need for the stack comment;
1685: however, if you decide not to refactor it, then having such a comment is
1686: better than not having it.
1687:
1688: The names of the stack items in stack-effect and stack comments in the
1689: standard, in this manual, and in many programs specify the type through
1690: a type prefix, similar to Fortran and Hungarian notation. The most
1691: frequent prefixes are:
1692:
1693: @table @code
1694: @item n
1695: signed integer
1696: @item u
1697: unsigned integer
1698: @item c
1699: character
1700: @item f
1701: Boolean flags, i.e. @code{false} or @code{true}.
1702: @item a-addr,a-
1703: Cell-aligned address
1704: @item c-addr,c-
1705: Char-aligned address (note that a Char may have two bytes in Windows NT)
1706: @item xt
1707: Execution token, same size as Cell
1708: @item w,x
1709: Cell, can contain an integer or an address. It usually takes 32, 64 or
1710: 16 bits (depending on your platform and Forth system). A cell is more
1711: commonly known as machine word, but the term @emph{word} already means
1712: something different in Forth.
1713: @item d
1714: signed double-cell integer
1715: @item ud
1716: unsigned double-cell integer
1717: @item r
1718: Float (on the FP stack)
1719: @end table
1720:
1721: You can find a more complete list in @ref{Notation}.
1722:
1723: @quotation Assignment
1724: Write stack-effect comments for all definitions you have written up to
1725: now.
1726: @end quotation
1727:
1728:
1729: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1730: @section Types
1731: @cindex types tutorial
1732:
1733: In Forth the names of the operations are not overloaded; so similar
1734: operations on different types need different names; e.g., @code{+} adds
1735: integers, and you have to use @code{f+} to add floating-point numbers.
1736: The following prefixes are often used for related operations on
1737: different types:
1738:
1739: @table @code
1740: @item (none)
1741: signed integer
1742: @item u
1743: unsigned integer
1744: @item c
1745: character
1746: @item d
1747: signed double-cell integer
1748: @item ud, du
1749: unsigned double-cell integer
1750: @item 2
1751: two cells (not-necessarily double-cell numbers)
1752: @item m, um
1753: mixed single-cell and double-cell operations
1754: @item f
1755: floating-point (note that in stack comments @samp{f} represents flags,
1756: and @samp{r} represents FP numbers; also, you need to include the
1757: exponent part in literal FP numbers, @pxref{Floating Point Tutorial}).
1758: @end table
1759:
1760: If there are no differences between the signed and the unsigned variant
1761: (e.g., for @code{+}), there is only the prefix-less variant.
1762:
1763: Forth does not perform type checking, neither at compile time, nor at
1764: run time. If you use the wrong operation, the data are interpreted
1765: incorrectly:
1766:
1767: @example
1768: -1 u.
1769: @end example
1770:
1771: If you have only experience with type-checked languages until now, and
1772: have heard how important type-checking is, don't panic! In my
1773: experience (and that of other Forthers), type errors in Forth code are
1774: usually easy to find (once you get used to it), the increased vigilance
1775: of the programmer tends to catch some harder errors in addition to most
1776: type errors, and you never have to work around the type system, so in
1777: most situations the lack of type-checking seems to be a win (projects to
1778: add type checking to Forth have not caught on).
1779:
1780:
1781: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1782: @section Factoring
1783: @cindex factoring tutorial
1784:
1785: If you try to write longer definitions, you will soon find it hard to
1786: keep track of the stack contents. Therefore, good Forth programmers
1787: tend to write only short definitions (e.g., three lines). The art of
1788: finding meaningful short definitions is known as factoring (as in
1789: factoring polynomials).
1790:
1791: Well-factored programs offer additional advantages: smaller, more
1792: general words, are easier to test and debug and can be reused more and
1793: better than larger, specialized words.
1794:
1795: So, if you run into difficulties with stack management, when writing
1796: code, try to define meaningful factors for the word, and define the word
1797: in terms of those. Even if a factor contains only two words, it is
1798: often helpful.
1799:
1800: Good factoring is not easy, and it takes some practice to get the knack
1801: for it; but even experienced Forth programmers often don't find the
1802: right solution right away, but only when rewriting the program. So, if
1803: you don't come up with a good solution immediately, keep trying, don't
1804: despair.
1805:
1806: @c example !!
1807:
1808:
1809: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1810: @section Designing the stack effect
1811: @cindex Stack effect design, tutorial
1812: @cindex design of stack effects, tutorial
1813:
1814: In other languages you can use an arbitrary order of parameters for a
1815: function; and since there is only one result, you don't have to deal with
1816: the order of results, either.
1817:
1818: In Forth (and other stack-based languages, e.g., PostScript) the
1819: parameter and result order of a definition is important and should be
1820: designed well. The general guideline is to design the stack effect such
1821: that the word is simple to use in most cases, even if that complicates
1822: the implementation of the word. Some concrete rules are:
1823:
1824: @itemize @bullet
1825:
1826: @item
1827: Words consume all of their parameters (e.g., @code{.}).
1828:
1829: @item
1830: If there is a convention on the order of parameters (e.g., from
1831: mathematics or another programming language), stick with it (e.g.,
1832: @code{-}).
1833:
1834: @item
1835: If one parameter usually requires only a short computation (e.g., it is
1836: a constant), pass it on the top of the stack. Conversely, parameters
1837: that usually require a long sequence of code to compute should be passed
1838: as the bottom (i.e., first) parameter. This makes the code easier to
1839: read, because the reader does not need to keep track of the bottom item
1840: through a long sequence of code (or, alternatively, through stack
1841: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1842: address on top of the stack because it is usually simpler to compute
1843: than the stored value (often the address is just a variable).
1844:
1845: @item
1846: Similarly, results that are usually consumed quickly should be returned
1847: on the top of stack, whereas a result that is often used in long
1848: computations should be passed as bottom result. E.g., the file words
1849: like @code{open-file} return the error code on the top of stack, because
1850: it is usually consumed quickly by @code{throw}; moreover, the error code
1851: has to be checked before doing anything with the other results.
1852:
1853: @end itemize
1854:
1855: These rules are just general guidelines, don't lose sight of the overall
1856: goal to make the words easy to use. E.g., if the convention rule
1857: conflicts with the computation-length rule, you might decide in favour
1858: of the convention if the word will be used rarely, and in favour of the
1859: computation-length rule if the word will be used frequently (because
1860: with frequent use the cost of breaking the computation-length rule would
1861: be quite high, and frequent use makes it easier to remember an
1862: unconventional order).
1863:
1864: @c example !! structure package
1865:
1866:
1867: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1868: @section Local Variables
1869: @cindex local variables, tutorial
1870:
1871: You can define local variables (@emph{locals}) in a colon definition:
1872:
1873: @example
1874: : swap @{ a b -- b a @}
1875: b a ;
1876: 1 2 swap .s 2drop
1877: @end example
1878:
1879: (If your Forth system does not support this syntax, include
1880: @file{compat/anslocal.fs} first).
1881:
1882: In this example @code{@{ a b -- b a @}} is the locals definition; it
1883: takes two cells from the stack, puts the top of stack in @code{b} and
1884: the next stack element in @code{a}. @code{--} starts a comment ending
1885: with @code{@}}. After the locals definition, using the name of the
1886: local will push its value on the stack. You can leave the comment
1887: part (@code{-- b a}) away:
1888:
1889: @example
1890: : swap ( x1 x2 -- x2 x1 )
1891: @{ a b @} b a ;
1892: @end example
1893:
1894: In Gforth you can have several locals definitions, anywhere in a colon
1895: definition; in contrast, in a standard program you can have only one
1896: locals definition per colon definition, and that locals definition must
1897: be outside any control structure.
1898:
1899: With locals you can write slightly longer definitions without running
1900: into stack trouble. However, I recommend trying to write colon
1901: definitions without locals for exercise purposes to help you gain the
1902: essential factoring skills.
1903:
1904: @quotation Assignment
1905: Rewrite your definitions until now with locals
1906: @end quotation
1907:
1908: Reference: @ref{Locals}.
1909:
1910:
1911: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1912: @section Conditional execution
1913: @cindex conditionals, tutorial
1914: @cindex if, tutorial
1915:
1916: In Forth you can use control structures only inside colon definitions.
1917: An @code{if}-structure looks like this:
1918:
1919: @example
1920: : abs ( n1 -- +n2 )
1921: dup 0 < if
1922: negate
1923: endif ;
1924: 5 abs .
1925: -5 abs .
1926: @end example
1927:
1928: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1929: the following code is performed, otherwise execution continues after the
1930: @code{endif} (or @code{else}). @code{<} compares the top two stack
1931: elements and produces a flag:
1932:
1933: @example
1934: 1 2 < .
1935: 2 1 < .
1936: 1 1 < .
1937: @end example
1938:
1939: Actually the standard name for @code{endif} is @code{then}. This
1940: tutorial presents the examples using @code{endif}, because this is often
1941: less confusing for people familiar with other programming languages
1942: where @code{then} has a different meaning. If your system does not have
1943: @code{endif}, define it with
1944:
1945: @example
1946: : endif postpone then ; immediate
1947: @end example
1948:
1949: You can optionally use an @code{else}-part:
1950:
1951: @example
1952: : min ( n1 n2 -- n )
1953: 2dup < if
1954: drop
1955: else
1956: nip
1957: endif ;
1958: 2 3 min .
1959: 3 2 min .
1960: @end example
1961:
1962: @quotation Assignment
1963: Write @code{min} without @code{else}-part (hint: what's the definition
1964: of @code{nip}?).
1965: @end quotation
1966:
1967: Reference: @ref{Selection}.
1968:
1969:
1970: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1971: @section Flags and Comparisons
1972: @cindex flags tutorial
1973: @cindex comparison tutorial
1974:
1975: In a false-flag all bits are clear (0 when interpreted as integer). In
1976: a canonical true-flag all bits are set (-1 as a twos-complement signed
1977: integer); in many contexts (e.g., @code{if}) any non-zero value is
1978: treated as true flag.
1979:
1980: @example
1981: false .
1982: true .
1983: true hex u. decimal
1984: @end example
1985:
1986: Comparison words produce canonical flags:
1987:
1988: @example
1989: 1 1 = .
1990: 1 0= .
1991: 0 1 < .
1992: 0 0 < .
1993: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1994: -1 1 < .
1995: @end example
1996:
1997: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1998: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1999: these combinations are standard (for details see the standard,
2000: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
2001:
2002: You can use @code{and or xor invert} as operations on canonical flags.
2003: Actually they are bitwise operations:
2004:
2005: @example
2006: 1 2 and .
2007: 1 2 or .
2008: 1 3 xor .
2009: 1 invert .
2010: @end example
2011:
2012: You can convert a zero/non-zero flag into a canonical flag with
2013: @code{0<>} (and complement it on the way with @code{0=}).
2014:
2015: @example
2016: 1 0= .
2017: 1 0<> .
2018: @end example
2019:
2020: You can use the all-bits-set feature of canonical flags and the bitwise
2021: operation of the Boolean operations to avoid @code{if}s:
2022:
2023: @example
2024: : foo ( n1 -- n2 )
2025: 0= if
2026: 14
2027: else
2028: 0
2029: endif ;
2030: 0 foo .
2031: 1 foo .
2032:
2033: : foo ( n1 -- n2 )
2034: 0= 14 and ;
2035: 0 foo .
2036: 1 foo .
2037: @end example
2038:
2039: @quotation Assignment
2040: Write @code{min} without @code{if}.
2041: @end quotation
2042:
2043: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2044: @ref{Bitwise operations}.
2045:
2046:
2047: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2048: @section General Loops
2049: @cindex loops, indefinite, tutorial
2050:
2051: The endless loop is the most simple one:
2052:
2053: @example
2054: : endless ( -- )
2055: 0 begin
2056: dup . 1+
2057: again ;
2058: endless
2059: @end example
2060:
2061: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2062: does nothing at run-time, @code{again} jumps back to @code{begin}.
2063:
2064: A loop with one exit at any place looks like this:
2065:
2066: @example
2067: : log2 ( +n1 -- n2 )
2068: \ logarithmus dualis of n1>0, rounded down to the next integer
2069: assert( dup 0> )
2070: 2/ 0 begin
2071: over 0> while
2072: 1+ swap 2/ swap
2073: repeat
2074: nip ;
2075: 7 log2 .
2076: 8 log2 .
2077: @end example
2078:
2079: At run-time @code{while} consumes a flag; if it is 0, execution
2080: continues behind the @code{repeat}; if the flag is non-zero, execution
2081: continues behind the @code{while}. @code{Repeat} jumps back to
2082: @code{begin}, just like @code{again}.
2083:
2084: In Forth there are a number of combinations/abbreviations, like
2085: @code{1+}. However, @code{2/} is not one of them; it shifts its
2086: argument right by one bit (arithmetic shift right), and viewed as
2087: division that always rounds towards negative infinity (floored
2088: division). In contrast, @code{/} rounds towards zero on some systems
2089: (not on default installations of gforth (>=0.7.0), however).
2090:
2091: @example
2092: -5 2 / . \ -2 or -3
2093: -5 2/ . \ -3
2094: @end example
2095:
2096: @code{assert(} is no standard word, but you can get it on systems other
2097: than Gforth by including @file{compat/assert.fs}. You can see what it
2098: does by trying
2099:
2100: @example
2101: 0 log2 .
2102: @end example
2103:
2104: Here's a loop with an exit at the end:
2105:
2106: @example
2107: : log2 ( +n1 -- n2 )
2108: \ logarithmus dualis of n1>0, rounded down to the next integer
2109: assert( dup 0 > )
2110: -1 begin
2111: 1+ swap 2/ swap
2112: over 0 <=
2113: until
2114: nip ;
2115: @end example
2116:
2117: @code{Until} consumes a flag; if it is non-zero, execution continues at
2118: the @code{begin}, otherwise after the @code{until}.
2119:
2120: @quotation Assignment
2121: Write a definition for computing the greatest common divisor.
2122: @end quotation
2123:
2124: Reference: @ref{Simple Loops}.
2125:
2126:
2127: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2128: @section Counted loops
2129: @cindex loops, counted, tutorial
2130:
2131: @example
2132: : ^ ( n1 u -- n )
2133: \ n = the uth power of n1
2134: 1 swap 0 u+do
2135: over *
2136: loop
2137: nip ;
2138: 3 2 ^ .
2139: 4 3 ^ .
2140: @end example
2141:
2142: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2143: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2144: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2145: times (or not at all, if @code{u3-u4<0}).
2146:
2147: You can see the stack effect design rules at work in the stack effect of
2148: the loop start words: Since the start value of the loop is more
2149: frequently constant than the end value, the start value is passed on
2150: the top-of-stack.
2151:
2152: You can access the counter of a counted loop with @code{i}:
2153:
2154: @example
2155: : fac ( u -- u! )
2156: 1 swap 1+ 1 u+do
2157: i *
2158: loop ;
2159: 5 fac .
2160: 7 fac .
2161: @end example
2162:
2163: There is also @code{+do}, which expects signed numbers (important for
2164: deciding whether to enter the loop).
2165:
2166: @quotation Assignment
2167: Write a definition for computing the nth Fibonacci number.
2168: @end quotation
2169:
2170: You can also use increments other than 1:
2171:
2172: @example
2173: : up2 ( n1 n2 -- )
2174: +do
2175: i .
2176: 2 +loop ;
2177: 10 0 up2
2178:
2179: : down2 ( n1 n2 -- )
2180: -do
2181: i .
2182: 2 -loop ;
2183: 0 10 down2
2184: @end example
2185:
2186: Reference: @ref{Counted Loops}.
2187:
2188:
2189: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2190: @section Recursion
2191: @cindex recursion tutorial
2192:
2193: Usually the name of a definition is not visible in the definition; but
2194: earlier definitions are usually visible:
2195:
2196: @example
2197: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
2198: : / ( n1 n2 -- n )
2199: dup 0= if
2200: -10 throw \ report division by zero
2201: endif
2202: / \ old version
2203: ;
2204: 1 0 /
2205: @end example
2206:
2207: For recursive definitions you can use @code{recursive} (non-standard) or
2208: @code{recurse}:
2209:
2210: @example
2211: : fac1 ( n -- n! ) recursive
2212: dup 0> if
2213: dup 1- fac1 *
2214: else
2215: drop 1
2216: endif ;
2217: 7 fac1 .
2218:
2219: : fac2 ( n -- n! )
2220: dup 0> if
2221: dup 1- recurse *
2222: else
2223: drop 1
2224: endif ;
2225: 8 fac2 .
2226: @end example
2227:
2228: @quotation Assignment
2229: Write a recursive definition for computing the nth Fibonacci number.
2230: @end quotation
2231:
2232: Reference (including indirect recursion): @xref{Calls and returns}.
2233:
2234:
2235: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2236: @section Leaving definitions or loops
2237: @cindex leaving definitions, tutorial
2238: @cindex leaving loops, tutorial
2239:
2240: @code{EXIT} exits the current definition right away. For every counted
2241: loop that is left in this way, an @code{UNLOOP} has to be performed
2242: before the @code{EXIT}:
2243:
2244: @c !! real examples
2245: @example
2246: : ...
2247: ... u+do
2248: ... if
2249: ... unloop exit
2250: endif
2251: ...
2252: loop
2253: ... ;
2254: @end example
2255:
2256: @code{LEAVE} leaves the innermost counted loop right away:
2257:
2258: @example
2259: : ...
2260: ... u+do
2261: ... if
2262: ... leave
2263: endif
2264: ...
2265: loop
2266: ... ;
2267: @end example
2268:
2269: @c !! example
2270:
2271: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2272:
2273:
2274: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2275: @section Return Stack
2276: @cindex return stack tutorial
2277:
2278: In addition to the data stack Forth also has a second stack, the return
2279: stack; most Forth systems store the return addresses of procedure calls
2280: there (thus its name). Programmers can also use this stack:
2281:
2282: @example
2283: : foo ( n1 n2 -- )
2284: .s
2285: >r .s
2286: r@@ .
2287: >r .s
2288: r@@ .
2289: r> .
2290: r@@ .
2291: r> . ;
2292: 1 2 foo
2293: @end example
2294:
2295: @code{>r} takes an element from the data stack and pushes it onto the
2296: return stack; conversely, @code{r>} moves an elementm from the return to
2297: the data stack; @code{r@@} pushes a copy of the top of the return stack
2298: on the data stack.
2299:
2300: Forth programmers usually use the return stack for storing data
2301: temporarily, if using the data stack alone would be too complex, and
2302: factoring and locals are not an option:
2303:
2304: @example
2305: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2306: rot >r rot r> ;
2307: @end example
2308:
2309: The return address of the definition and the loop control parameters of
2310: counted loops usually reside on the return stack, so you have to take
2311: all items, that you have pushed on the return stack in a colon
2312: definition or counted loop, from the return stack before the definition
2313: or loop ends. You cannot access items that you pushed on the return
2314: stack outside some definition or loop within the definition of loop.
2315:
2316: If you miscount the return stack items, this usually ends in a crash:
2317:
2318: @example
2319: : crash ( n -- )
2320: >r ;
2321: 5 crash
2322: @end example
2323:
2324: You cannot mix using locals and using the return stack (according to the
2325: standard; Gforth has no problem). However, they solve the same
2326: problems, so this shouldn't be an issue.
2327:
2328: @quotation Assignment
2329: Can you rewrite any of the definitions you wrote until now in a better
2330: way using the return stack?
2331: @end quotation
2332:
2333: Reference: @ref{Return stack}.
2334:
2335:
2336: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2337: @section Memory
2338: @cindex memory access/allocation tutorial
2339:
2340: You can create a global variable @code{v} with
2341:
2342: @example
2343: variable v ( -- addr )
2344: @end example
2345:
2346: @code{v} pushes the address of a cell in memory on the stack. This cell
2347: was reserved by @code{variable}. You can use @code{!} (store) to store
2348: values into this cell and @code{@@} (fetch) to load the value from the
2349: stack into memory:
2350:
2351: @example
2352: v .
2353: 5 v ! .s
2354: v @@ .
2355: @end example
2356:
2357: You can see a raw dump of memory with @code{dump}:
2358:
2359: @example
2360: v 1 cells .s dump
2361: @end example
2362:
2363: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2364: generally, address units (aus)) that @code{n1 cells} occupy. You can
2365: also reserve more memory:
2366:
2367: @example
2368: create v2 20 cells allot
2369: v2 20 cells dump
2370: @end example
2371:
2372: creates a variable-like word @code{v2} and reserves 20 uninitialized
2373: cells; the address pushed by @code{v2} points to the start of these 20
2374: cells (@pxref{CREATE}). You can use address arithmetic to access
2375: these cells:
2376:
2377: @example
2378: 3 v2 5 cells + !
2379: v2 20 cells dump
2380: @end example
2381:
2382: You can reserve and initialize memory with @code{,}:
2383:
2384: @example
2385: create v3
2386: 5 , 4 , 3 , 2 , 1 ,
2387: v3 @@ .
2388: v3 cell+ @@ .
2389: v3 2 cells + @@ .
2390: v3 5 cells dump
2391: @end example
2392:
2393: @quotation Assignment
2394: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2395: @code{u} cells, with the first of these cells at @code{addr}, the next
2396: one at @code{addr cell+} etc.
2397: @end quotation
2398:
2399: The difference between @code{variable} and @code{create} is that
2400: @code{variable} allots a cell, and that you cannot allot additional
2401: memory to a variable in standard Forth.
2402:
2403: You can also reserve memory without creating a new word:
2404:
2405: @example
2406: here 10 cells allot .
2407: here .
2408: @end example
2409:
2410: The first @code{here} pushes the start address of the memory area, the
2411: second @code{here} the address after the dictionary area. You should
2412: store the start address somewhere, or you will have a hard time
2413: finding the memory area again.
2414:
2415: @code{Allot} manages dictionary memory. The dictionary memory contains
2416: the system's data structures for words etc. on Gforth and most other
2417: Forth systems. It is managed like a stack: You can free the memory that
2418: you have just @code{allot}ed with
2419:
2420: @example
2421: -10 cells allot
2422: here .
2423: @end example
2424:
2425: Note that you cannot do this if you have created a new word in the
2426: meantime (because then your @code{allot}ed memory is no longer on the
2427: top of the dictionary ``stack'').
2428:
2429: Alternatively, you can use @code{allocate} and @code{free} which allow
2430: freeing memory in any order:
2431:
2432: @example
2433: 10 cells allocate throw .s
2434: 20 cells allocate throw .s
2435: swap
2436: free throw
2437: free throw
2438: @end example
2439:
2440: The @code{throw}s deal with errors (e.g., out of memory).
2441:
2442: And there is also a
2443: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2444: garbage collector}, which eliminates the need to @code{free} memory
2445: explicitly.
2446:
2447: Reference: @ref{Memory}.
2448:
2449:
2450: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2451: @section Characters and Strings
2452: @cindex strings tutorial
2453: @cindex characters tutorial
2454:
2455: On the stack characters take up a cell, like numbers. In memory they
2456: have their own size (one 8-bit byte on most systems), and therefore
2457: require their own words for memory access:
2458:
2459: @example
2460: create v4
2461: 104 c, 97 c, 108 c, 108 c, 111 c,
2462: v4 4 chars + c@@ .
2463: v4 5 chars dump
2464: @end example
2465:
2466: The preferred representation of strings on the stack is @code{addr
2467: u-count}, where @code{addr} is the address of the first character and
2468: @code{u-count} is the number of characters in the string.
2469:
2470: @example
2471: v4 5 type
2472: @end example
2473:
2474: You get a string constant with
2475:
2476: @example
2477: s" hello, world" .s
2478: type
2479: @end example
2480:
2481: Make sure you have a space between @code{s"} and the string; @code{s"}
2482: is a normal Forth word and must be delimited with white space (try what
2483: happens when you remove the space).
2484:
2485: However, this interpretive use of @code{s"} is quite restricted: the
2486: string exists only until the next call of @code{s"} (some Forth systems
2487: keep more than one of these strings, but usually they still have a
2488: limited lifetime).
2489:
2490: @example
2491: s" hello," s" world" .s
2492: type
2493: type
2494: @end example
2495:
2496: You can also use @code{s"} in a definition, and the resulting
2497: strings then live forever (well, for as long as the definition):
2498:
2499: @example
2500: : foo s" hello," s" world" ;
2501: foo .s
2502: type
2503: type
2504: @end example
2505:
2506: @quotation Assignment
2507: @code{Emit ( c -- )} types @code{c} as character (not a number).
2508: Implement @code{type ( addr u -- )}.
2509: @end quotation
2510:
2511: Reference: @ref{Memory Blocks}.
2512:
2513:
2514: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
2515: @section Alignment
2516: @cindex alignment tutorial
2517: @cindex memory alignment tutorial
2518:
2519: On many processors cells have to be aligned in memory, if you want to
2520: access them with @code{@@} and @code{!} (and even if the processor does
2521: not require alignment, access to aligned cells is faster).
2522:
2523: @code{Create} aligns @code{here} (i.e., the place where the next
2524: allocation will occur, and that the @code{create}d word points to).
2525: Likewise, the memory produced by @code{allocate} starts at an aligned
2526: address. Adding a number of @code{cells} to an aligned address produces
2527: another aligned address.
2528:
2529: However, address arithmetic involving @code{char+} and @code{chars} can
2530: create an address that is not cell-aligned. @code{Aligned ( addr --
2531: a-addr )} produces the next aligned address:
2532:
2533: @example
2534: v3 char+ aligned .s @@ .
2535: v3 char+ .s @@ .
2536: @end example
2537:
2538: Similarly, @code{align} advances @code{here} to the next aligned
2539: address:
2540:
2541: @example
2542: create v5 97 c,
2543: here .
2544: align here .
2545: 1000 ,
2546: @end example
2547:
2548: Note that you should use aligned addresses even if your processor does
2549: not require them, if you want your program to be portable.
2550:
2551: Reference: @ref{Address arithmetic}.
2552:
2553: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
2554: @section Floating Point
2555: @cindex floating point tutorial
2556: @cindex FP tutorial
2557:
2558: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
2559: might expect, but there are a few things worth noting:
2560:
2561: The first point is not specific to Forth, but so important and yet not
2562: universally known that I mention it here: FP numbers are not reals.
2563: Many properties (e.g., arithmetic laws) that reals have and that one
2564: expects of all kinds of numbers do not hold for FP numbers. If you
2565: want to use FP computations, you should learn about their problems and
2566: how to avoid them; a good starting point is @cite{David Goldberg,
2567: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
2568: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
2569: Computing Surveys 23(1):5@minus{}48, March 1991}.
2570:
2571: In Forth source code literal FP numbers need an exponent, e.g.,
2572: @code{1e0}; this can also be written shorter as @code{1e}, longer as
2573: @code{+1.0e+0}, and many variations in between. The reason for this is
2574: that, for historical reasons, Forth interprets a decimal point alone
2575: (e.g., @code{1.}) as indicating a double-cell integer. Examples:
2576:
2577: @example
2578: 2e 2e f+ f.
2579: @end example
2580:
2581: Another requirement for literal FP numbers is that the current base is
2582: decimal; with a hex base @code{1e} is interpreted as an integer.
2583:
2584: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
2585: ANS Forth system may implement the FP stack on the data stack, but
2586: virtually all systems implement a separate FP stack; and programming
2587: in a way that accommodates all models is so cumbersome that nobody
2588: does it.} One advantage of this model is that cells are not in the
2589: way when accessing FP values, and vice versa. Forth has a set of
2590: words for manipulating the FP stack: @code{fdup fswap fdrop fover
2591: frot} and (non-standard) @code{fnip ftuck fpick}.
2592:
2593: FP arithmetic words are prefixed with @code{F}. There is the usual
2594: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
2595: other functions, e.g., @code{fsqrt fsin fln fmin}. One word that you
2596: might expect is @code{f=}; but @code{f=} is non-standard, because FP
2597: computation results are usually inaccurate, so exact comparison is
2598: usually a mistake, and one should use approximate comparison.
2599: Unfortunately, @code{f~}, the standard word for that purpose, is not
2600: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
2601: well.
2602:
2603: And of course there are words for accessing FP numbers in memory
2604: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
2605: faligned}). There are also variants of these words with an @code{sf}
2606: and @code{df} prefix for accessing IEEE format single-precision and
2607: double-precision numbers in memory; their main purpose is for
2608: accessing external FP data (e.g., that has been read from or will be
2609: written to a file).
2610:
2611: Here is an example of a dot-product word and its use:
2612:
2613: @example
2614: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
2615: >r swap 2swap swap 0e r> 0 ?DO
2616: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
2617: LOOP
2618: 2drop 2drop ;
2619:
2620: create v 1.23e f, 4.56e f, 7.89e f,
2621:
2622: v 1 floats v 1 floats 3 v* f.
2623: @end example
2624:
2625: @quotation Assignment
2626: Write a program to solve a quadratic equation. Then read @cite{Henry
2627: G. Baker,
2628: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
2629: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
2630: 33(1):30@minus{}39, January 1998}, and see if you can improve your
2631: program. Finally, find a test case where the original and the
2632: improved version produce different results.
2633: @end quotation
2634:
2635: Reference: @ref{Floating Point}; @ref{Floating point stack};
2636: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
2637: arithmetic}.
2638:
2639: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
2640: @section Files
2641: @cindex files tutorial
2642:
2643: This section gives a short introduction into how to use files inside
2644: Forth. It's broken up into five easy steps:
2645:
2646: @enumerate 1
2647: @item Opened an ASCII text file for input
2648: @item Opened a file for output
2649: @item Read input file until string matched (or some other condition matched)
2650: @item Wrote some lines from input ( modified or not) to output
2651: @item Closed the files.
2652: @end enumerate
2653:
2654: Reference: @ref{General files}.
2655:
2656: @subsection Open file for input
2657:
2658: @example
2659: s" foo.in" r/o open-file throw Value fd-in
2660: @end example
2661:
2662: @subsection Create file for output
2663:
2664: @example
2665: s" foo.out" w/o create-file throw Value fd-out
2666: @end example
2667:
2668: The available file modes are r/o for read-only access, r/w for
2669: read-write access, and w/o for write-only access. You could open both
2670: files with r/w, too, if you like. All file words return error codes; for
2671: most applications, it's best to pass there error codes with @code{throw}
2672: to the outer error handler.
2673:
2674: If you want words for opening and assigning, define them as follows:
2675:
2676: @example
2677: 0 Value fd-in
2678: 0 Value fd-out
2679: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2680: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2681: @end example
2682:
2683: Usage example:
2684:
2685: @example
2686: s" foo.in" open-input
2687: s" foo.out" open-output
2688: @end example
2689:
2690: @subsection Scan file for a particular line
2691:
2692: @example
2693: 256 Constant max-line
2694: Create line-buffer max-line 2 + allot
2695:
2696: : scan-file ( addr u -- )
2697: begin
2698: line-buffer max-line fd-in read-line throw
2699: while
2700: >r 2dup line-buffer r> compare 0=
2701: until
2702: else
2703: drop
2704: then
2705: 2drop ;
2706: @end example
2707:
2708: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
2709: the buffer at addr, and returns the number of bytes read, a flag that is
2710: false when the end of file is reached, and an error code.
2711:
2712: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2713: returns zero if both strings are equal. It returns a positive number if
2714: the first string is lexically greater, a negative if the second string
2715: is lexically greater.
2716:
2717: We haven't seen this loop here; it has two exits. Since the @code{while}
2718: exits with the number of bytes read on the stack, we have to clean up
2719: that separately; that's after the @code{else}.
2720:
2721: Usage example:
2722:
2723: @example
2724: s" The text I search is here" scan-file
2725: @end example
2726:
2727: @subsection Copy input to output
2728:
2729: @example
2730: : copy-file ( -- )
2731: begin
2732: line-buffer max-line fd-in read-line throw
2733: while
2734: line-buffer swap fd-out write-line throw
2735: repeat ;
2736: @end example
2737: @c !! does not handle long lines, no newline at end of file
2738:
2739: @subsection Close files
2740:
2741: @example
2742: fd-in close-file throw
2743: fd-out close-file throw
2744: @end example
2745:
2746: Likewise, you can put that into definitions, too:
2747:
2748: @example
2749: : close-input ( -- ) fd-in close-file throw ;
2750: : close-output ( -- ) fd-out close-file throw ;
2751: @end example
2752:
2753: @quotation Assignment
2754: How could you modify @code{copy-file} so that it copies until a second line is
2755: matched? Can you write a program that extracts a section of a text file,
2756: given the line that starts and the line that terminates that section?
2757: @end quotation
2758:
2759: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
2760: @section Interpretation and Compilation Semantics and Immediacy
2761: @cindex semantics tutorial
2762: @cindex interpretation semantics tutorial
2763: @cindex compilation semantics tutorial
2764: @cindex immediate, tutorial
2765:
2766: When a word is compiled, it behaves differently from being interpreted.
2767: E.g., consider @code{+}:
2768:
2769: @example
2770: 1 2 + .
2771: : foo + ;
2772: @end example
2773:
2774: These two behaviours are known as compilation and interpretation
2775: semantics. For normal words (e.g., @code{+}), the compilation semantics
2776: is to append the interpretation semantics to the currently defined word
2777: (@code{foo} in the example above). I.e., when @code{foo} is executed
2778: later, the interpretation semantics of @code{+} (i.e., adding two
2779: numbers) will be performed.
2780:
2781: However, there are words with non-default compilation semantics, e.g.,
2782: the control-flow words like @code{if}. You can use @code{immediate} to
2783: change the compilation semantics of the last defined word to be equal to
2784: the interpretation semantics:
2785:
2786: @example
2787: : [FOO] ( -- )
2788: 5 . ; immediate
2789:
2790: [FOO]
2791: : bar ( -- )
2792: [FOO] ;
2793: bar
2794: see bar
2795: @end example
2796:
2797: Two conventions to mark words with non-default compilation semantics are
2798: names with brackets (more frequently used) and to write them all in
2799: upper case (less frequently used).
2800:
2801: In Gforth (and many other systems) you can also remove the
2802: interpretation semantics with @code{compile-only} (the compilation
2803: semantics is derived from the original interpretation semantics):
2804:
2805: @example
2806: : flip ( -- )
2807: 6 . ; compile-only \ but not immediate
2808: flip
2809:
2810: : flop ( -- )
2811: flip ;
2812: flop
2813: @end example
2814:
2815: In this example the interpretation semantics of @code{flop} is equal to
2816: the original interpretation semantics of @code{flip}.
2817:
2818: The text interpreter has two states: in interpret state, it performs the
2819: interpretation semantics of words it encounters; in compile state, it
2820: performs the compilation semantics of these words.
2821:
2822: Among other things, @code{:} switches into compile state, and @code{;}
2823: switches back to interpret state. They contain the factors @code{]}
2824: (switch to compile state) and @code{[} (switch to interpret state), that
2825: do nothing but switch the state.
2826:
2827: @example
2828: : xxx ( -- )
2829: [ 5 . ]
2830: ;
2831:
2832: xxx
2833: see xxx
2834: @end example
2835:
2836: These brackets are also the source of the naming convention mentioned
2837: above.
2838:
2839: Reference: @ref{Interpretation and Compilation Semantics}.
2840:
2841:
2842: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2843: @section Execution Tokens
2844: @cindex execution tokens tutorial
2845: @cindex XT tutorial
2846:
2847: @code{' word} gives you the execution token (XT) of a word. The XT is a
2848: cell representing the interpretation semantics of a word. You can
2849: execute this semantics with @code{execute}:
2850:
2851: @example
2852: ' + .s
2853: 1 2 rot execute .
2854: @end example
2855:
2856: The XT is similar to a function pointer in C. However, parameter
2857: passing through the stack makes it a little more flexible:
2858:
2859: @example
2860: : map-array ( ... addr u xt -- ... )
2861: \ executes xt ( ... x -- ... ) for every element of the array starting
2862: \ at addr and containing u elements
2863: @{ xt @}
2864: cells over + swap ?do
2865: i @@ xt execute
2866: 1 cells +loop ;
2867:
2868: create a 3 , 4 , 2 , -1 , 4 ,
2869: a 5 ' . map-array .s
2870: 0 a 5 ' + map-array .
2871: s" max-n" environment? drop .s
2872: a 5 ' min map-array .
2873: @end example
2874:
2875: You can use map-array with the XTs of words that consume one element
2876: more than they produce. In theory you can also use it with other XTs,
2877: but the stack effect then depends on the size of the array, which is
2878: hard to understand.
2879:
2880: Since XTs are cell-sized, you can store them in memory and manipulate
2881: them on the stack like other cells. You can also compile the XT into a
2882: word with @code{compile,}:
2883:
2884: @example
2885: : foo1 ( n1 n2 -- n )
2886: [ ' + compile, ] ;
2887: see foo
2888: @end example
2889:
2890: This is non-standard, because @code{compile,} has no compilation
2891: semantics in the standard, but it works in good Forth systems. For the
2892: broken ones, use
2893:
2894: @example
2895: : [compile,] compile, ; immediate
2896:
2897: : foo1 ( n1 n2 -- n )
2898: [ ' + ] [compile,] ;
2899: see foo
2900: @end example
2901:
2902: @code{'} is a word with default compilation semantics; it parses the
2903: next word when its interpretation semantics are executed, not during
2904: compilation:
2905:
2906: @example
2907: : foo ( -- xt )
2908: ' ;
2909: see foo
2910: : bar ( ... "word" -- ... )
2911: ' execute ;
2912: see bar
2913: 1 2 bar + .
2914: @end example
2915:
2916: You often want to parse a word during compilation and compile its XT so
2917: it will be pushed on the stack at run-time. @code{[']} does this:
2918:
2919: @example
2920: : xt-+ ( -- xt )
2921: ['] + ;
2922: see xt-+
2923: 1 2 xt-+ execute .
2924: @end example
2925:
2926: Many programmers tend to see @code{'} and the word it parses as one
2927: unit, and expect it to behave like @code{[']} when compiled, and are
2928: confused by the actual behaviour. If you are, just remember that the
2929: Forth system just takes @code{'} as one unit and has no idea that it is
2930: a parsing word (attempts to convenience programmers in this issue have
2931: usually resulted in even worse pitfalls, see
2932: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2933: @code{State}-smartness---Why it is evil and How to Exorcise it}).
2934:
2935: Note that the state of the interpreter does not come into play when
2936: creating and executing XTs. I.e., even when you execute @code{'} in
2937: compile state, it still gives you the interpretation semantics. And
2938: whatever that state is, @code{execute} performs the semantics
2939: represented by the XT (i.e., for XTs produced with @code{'} the
2940: interpretation semantics).
2941:
2942: Reference: @ref{Tokens for Words}.
2943:
2944:
2945: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2946: @section Exceptions
2947: @cindex exceptions tutorial
2948:
2949: @code{throw ( n -- )} causes an exception unless n is zero.
2950:
2951: @example
2952: 100 throw .s
2953: 0 throw .s
2954: @end example
2955:
2956: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2957: it catches exceptions and pushes the number of the exception on the
2958: stack (or 0, if the xt executed without exception). If there was an
2959: exception, the stacks have the same depth as when entering @code{catch}:
2960:
2961: @example
2962: .s
2963: 3 0 ' / catch .s
2964: 3 2 ' / catch .s
2965: @end example
2966:
2967: @quotation Assignment
2968: Try the same with @code{execute} instead of @code{catch}.
2969: @end quotation
2970:
2971: @code{Throw} always jumps to the dynamically next enclosing
2972: @code{catch}, even if it has to leave several call levels to achieve
2973: this:
2974:
2975: @example
2976: : foo 100 throw ;
2977: : foo1 foo ." after foo" ;
2978: : bar ['] foo1 catch ;
2979: bar .
2980: @end example
2981:
2982: It is often important to restore a value upon leaving a definition, even
2983: if the definition is left through an exception. You can ensure this
2984: like this:
2985:
2986: @example
2987: : ...
2988: save-x
2989: ['] word-changing-x catch ( ... n )
2990: restore-x
2991: ( ... n ) throw ;
2992: @end example
2993:
2994: However, this is still not safe against, e.g., the user pressing
2995: @kbd{Ctrl-C} when execution is between the @code{catch} and
2996: @code{restore-x}.
2997:
2998: Gforth provides an alternative exception handling syntax that is safe
2999: against such cases: @code{try ... restore ... endtry}. If the code
3000: between @code{try} and @code{endtry} has an exception, the stack
3001: depths are restored, the exception number is pushed on the stack, and
3002: the execution continues right after @code{restore}.
3003:
3004: The safer equivalent to the restoration code above is
3005:
3006: @example
3007: : ...
3008: save-x
3009: try
3010: word-changing-x 0
3011: restore
3012: restore-x
3013: endtry
3014: throw ;
3015: @end example
3016:
3017: Reference: @ref{Exception Handling}.
3018:
3019:
3020: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
3021: @section Defining Words
3022: @cindex defining words tutorial
3023: @cindex does> tutorial
3024: @cindex create...does> tutorial
3025:
3026: @c before semantics?
3027:
3028: @code{:}, @code{create}, and @code{variable} are definition words: They
3029: define other words. @code{Constant} is another definition word:
3030:
3031: @example
3032: 5 constant foo
3033: foo .
3034: @end example
3035:
3036: You can also use the prefixes @code{2} (double-cell) and @code{f}
3037: (floating point) with @code{variable} and @code{constant}.
3038:
3039: You can also define your own defining words. E.g.:
3040:
3041: @example
3042: : variable ( "name" -- )
3043: create 0 , ;
3044: @end example
3045:
3046: You can also define defining words that create words that do something
3047: other than just producing their address:
3048:
3049: @example
3050: : constant ( n "name" -- )
3051: create ,
3052: does> ( -- n )
3053: ( addr ) @@ ;
3054:
3055: 5 constant foo
3056: foo .
3057: @end example
3058:
3059: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3060: @code{does>} replaces @code{;}, but it also does something else: It
3061: changes the last defined word such that it pushes the address of the
3062: body of the word and then performs the code after the @code{does>}
3063: whenever it is called.
3064:
3065: In the example above, @code{constant} uses @code{,} to store 5 into the
3066: body of @code{foo}. When @code{foo} executes, it pushes the address of
3067: the body onto the stack, then (in the code after the @code{does>})
3068: fetches the 5 from there.
3069:
3070: The stack comment near the @code{does>} reflects the stack effect of the
3071: defined word, not the stack effect of the code after the @code{does>}
3072: (the difference is that the code expects the address of the body that
3073: the stack comment does not show).
3074:
3075: You can use these definition words to do factoring in cases that involve
3076: (other) definition words. E.g., a field offset is always added to an
3077: address. Instead of defining
3078:
3079: @example
3080: 2 cells constant offset-field1
3081: @end example
3082:
3083: and using this like
3084:
3085: @example
3086: ( addr ) offset-field1 +
3087: @end example
3088:
3089: you can define a definition word
3090:
3091: @example
3092: : simple-field ( n "name" -- )
3093: create ,
3094: does> ( n1 -- n1+n )
3095: ( addr ) @@ + ;
3096: @end example
3097:
3098: Definition and use of field offsets now look like this:
3099:
3100: @example
3101: 2 cells simple-field field1
3102: create mystruct 4 cells allot
3103: mystruct .s field1 .s drop
3104: @end example
3105:
3106: If you want to do something with the word without performing the code
3107: after the @code{does>}, you can access the body of a @code{create}d word
3108: with @code{>body ( xt -- addr )}:
3109:
3110: @example
3111: : value ( n "name" -- )
3112: create ,
3113: does> ( -- n1 )
3114: @@ ;
3115: : to ( n "name" -- )
3116: ' >body ! ;
3117:
3118: 5 value foo
3119: foo .
3120: 7 to foo
3121: foo .
3122: @end example
3123:
3124: @quotation Assignment
3125: Define @code{defer ( "name" -- )}, which creates a word that stores an
3126: XT (at the start the XT of @code{abort}), and upon execution
3127: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3128: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3129: recursion is one application of @code{defer}.
3130: @end quotation
3131:
3132: Reference: @ref{User-defined Defining Words}.
3133:
3134:
3135: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3136: @section Arrays and Records
3137: @cindex arrays tutorial
3138: @cindex records tutorial
3139: @cindex structs tutorial
3140:
3141: Forth has no standard words for defining data structures such as arrays
3142: and records (structs in C terminology), but you can build them yourself
3143: based on address arithmetic. You can also define words for defining
3144: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
3145:
3146: One of the first projects a Forth newcomer sets out upon when learning
3147: about defining words is an array defining word (possibly for
3148: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3149: learn something from it. However, don't be disappointed when you later
3150: learn that you have little use for these words (inappropriate use would
3151: be even worse). I have not found a set of useful array words yet;
3152: the needs are just too diverse, and named, global arrays (the result of
3153: naive use of defining words) are often not flexible enough (e.g.,
3154: consider how to pass them as parameters). Another such project is a set
3155: of words to help dealing with strings.
3156:
3157: On the other hand, there is a useful set of record words, and it has
3158: been defined in @file{compat/struct.fs}; these words are predefined in
3159: Gforth. They are explained in depth elsewhere in this manual (see
3160: @pxref{Structures}). The @code{simple-field} example above is
3161: simplified variant of fields in this package.
3162:
3163:
3164: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3165: @section @code{POSTPONE}
3166: @cindex postpone tutorial
3167:
3168: You can compile the compilation semantics (instead of compiling the
3169: interpretation semantics) of a word with @code{POSTPONE}:
3170:
3171: @example
3172: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3173: POSTPONE + ; immediate
3174: : foo ( n1 n2 -- n )
3175: MY-+ ;
3176: 1 2 foo .
3177: see foo
3178: @end example
3179:
3180: During the definition of @code{foo} the text interpreter performs the
3181: compilation semantics of @code{MY-+}, which performs the compilation
3182: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3183:
3184: This example also displays separate stack comments for the compilation
3185: semantics and for the stack effect of the compiled code. For words with
3186: default compilation semantics these stack effects are usually not
3187: displayed; the stack effect of the compilation semantics is always
3188: @code{( -- )} for these words, the stack effect for the compiled code is
3189: the stack effect of the interpretation semantics.
3190:
3191: Note that the state of the interpreter does not come into play when
3192: performing the compilation semantics in this way. You can also perform
3193: it interpretively, e.g.:
3194:
3195: @example
3196: : foo2 ( n1 n2 -- n )
3197: [ MY-+ ] ;
3198: 1 2 foo .
3199: see foo
3200: @end example
3201:
3202: However, there are some broken Forth systems where this does not always
3203: work, and therefore this practice was been declared non-standard in
3204: 1999.
3205: @c !! repair.fs
3206:
3207: Here is another example for using @code{POSTPONE}:
3208:
3209: @example
3210: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3211: POSTPONE negate POSTPONE + ; immediate compile-only
3212: : bar ( n1 n2 -- n )
3213: MY-- ;
3214: 2 1 bar .
3215: see bar
3216: @end example
3217:
3218: You can define @code{ENDIF} in this way:
3219:
3220: @example
3221: : ENDIF ( Compilation: orig -- )
3222: POSTPONE then ; immediate
3223: @end example
3224:
3225: @quotation Assignment
3226: Write @code{MY-2DUP} that has compilation semantics equivalent to
3227: @code{2dup}, but compiles @code{over over}.
3228: @end quotation
3229:
3230: @c !! @xref{Macros} for reference
3231:
3232:
3233: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3234: @section @code{Literal}
3235: @cindex literal tutorial
3236:
3237: You cannot @code{POSTPONE} numbers:
3238:
3239: @example
3240: : [FOO] POSTPONE 500 ; immediate
3241: @end example
3242:
3243: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
3244:
3245: @example
3246: : [FOO] ( compilation: --; run-time: -- n )
3247: 500 POSTPONE literal ; immediate
3248:
3249: : flip [FOO] ;
3250: flip .
3251: see flip
3252: @end example
3253:
3254: @code{LITERAL} consumes a number at compile-time (when it's compilation
3255: semantics are executed) and pushes it at run-time (when the code it
3256: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3257: number computed at compile time into the current word:
3258:
3259: @example
3260: : bar ( -- n )
3261: [ 2 2 + ] literal ;
3262: see bar
3263: @end example
3264:
3265: @quotation Assignment
3266: Write @code{]L} which allows writing the example above as @code{: bar (
3267: -- n ) [ 2 2 + ]L ;}
3268: @end quotation
3269:
3270: @c !! @xref{Macros} for reference
3271:
3272:
3273: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3274: @section Advanced macros
3275: @cindex macros, advanced tutorial
3276: @cindex run-time code generation, tutorial
3277:
3278: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3279: Execution Tokens}. It frequently performs @code{execute}, a relatively
3280: expensive operation in some Forth implementations. You can use
3281: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3282: and produce a word that contains the word to be performed directly:
3283:
3284: @c use ]] ... [[
3285: @example
3286: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3287: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3288: \ array beginning at addr and containing u elements
3289: @{ xt @}
3290: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
3291: POSTPONE i POSTPONE @@ xt compile,
3292: 1 cells POSTPONE literal POSTPONE +loop ;
3293:
3294: : sum-array ( addr u -- n )
3295: 0 rot rot [ ' + compile-map-array ] ;
3296: see sum-array
3297: a 5 sum-array .
3298: @end example
3299:
3300: You can use the full power of Forth for generating the code; here's an
3301: example where the code is generated in a loop:
3302:
3303: @example
3304: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3305: \ n2=n1+(addr1)*n, addr2=addr1+cell
3306: POSTPONE tuck POSTPONE @@
3307: POSTPONE literal POSTPONE * POSTPONE +
3308: POSTPONE swap POSTPONE cell+ ;
3309:
3310: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
3311: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
3312: 0 postpone literal postpone swap
3313: [ ' compile-vmul-step compile-map-array ]
3314: postpone drop ;
3315: see compile-vmul
3316:
3317: : a-vmul ( addr -- n )
3318: \ n=a*v, where v is a vector that's as long as a and starts at addr
3319: [ a 5 compile-vmul ] ;
3320: see a-vmul
3321: a a-vmul .
3322: @end example
3323:
3324: This example uses @code{compile-map-array} to show off, but you could
3325: also use @code{map-array} instead (try it now!).
3326:
3327: You can use this technique for efficient multiplication of large
3328: matrices. In matrix multiplication, you multiply every line of one
3329: matrix with every column of the other matrix. You can generate the code
3330: for one line once, and use it for every column. The only downside of
3331: this technique is that it is cumbersome to recover the memory consumed
3332: by the generated code when you are done (and in more complicated cases
3333: it is not possible portably).
3334:
3335: @c !! @xref{Macros} for reference
3336:
3337:
3338: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3339: @section Compilation Tokens
3340: @cindex compilation tokens, tutorial
3341: @cindex CT, tutorial
3342:
3343: This section is Gforth-specific. You can skip it.
3344:
3345: @code{' word compile,} compiles the interpretation semantics. For words
3346: with default compilation semantics this is the same as performing the
3347: compilation semantics. To represent the compilation semantics of other
3348: words (e.g., words like @code{if} that have no interpretation
3349: semantics), Gforth has the concept of a compilation token (CT,
3350: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3351: You can perform the compilation semantics represented by a CT with
3352: @code{execute}:
3353:
3354: @example
3355: : foo2 ( n1 n2 -- n )
3356: [ comp' + execute ] ;
3357: see foo
3358: @end example
3359:
3360: You can compile the compilation semantics represented by a CT with
3361: @code{postpone,}:
3362:
3363: @example
3364: : foo3 ( -- )
3365: [ comp' + postpone, ] ;
3366: see foo3
3367: @end example
3368:
3369: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
3370: @code{comp'} is particularly useful for words that have no
3371: interpretation semantics:
3372:
3373: @example
3374: ' if
3375: comp' if .s 2drop
3376: @end example
3377:
3378: Reference: @ref{Tokens for Words}.
3379:
3380:
3381: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3382: @section Wordlists and Search Order
3383: @cindex wordlists tutorial
3384: @cindex search order, tutorial
3385:
3386: The dictionary is not just a memory area that allows you to allocate
3387: memory with @code{allot}, it also contains the Forth words, arranged in
3388: several wordlists. When searching for a word in a wordlist,
3389: conceptually you start searching at the youngest and proceed towards
3390: older words (in reality most systems nowadays use hash-tables); i.e., if
3391: you define a word with the same name as an older word, the new word
3392: shadows the older word.
3393:
3394: Which wordlists are searched in which order is determined by the search
3395: order. You can display the search order with @code{order}. It displays
3396: first the search order, starting with the wordlist searched first, then
3397: it displays the wordlist that will contain newly defined words.
3398:
3399: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
3400:
3401: @example
3402: wordlist constant mywords
3403: @end example
3404:
3405: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3406: defined words (the @emph{current} wordlist):
3407:
3408: @example
3409: mywords set-current
3410: order
3411: @end example
3412:
3413: Gforth does not display a name for the wordlist in @code{mywords}
3414: because this wordlist was created anonymously with @code{wordlist}.
3415:
3416: You can get the current wordlist with @code{get-current ( -- wid)}. If
3417: you want to put something into a specific wordlist without overall
3418: effect on the current wordlist, this typically looks like this:
3419:
3420: @example
3421: get-current mywords set-current ( wid )
3422: create someword
3423: ( wid ) set-current
3424: @end example
3425:
3426: You can write the search order with @code{set-order ( wid1 .. widn n --
3427: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3428: searched wordlist is topmost.
3429:
3430: @example
3431: get-order mywords swap 1+ set-order
3432: order
3433: @end example
3434:
3435: Yes, the order of wordlists in the output of @code{order} is reversed
3436: from stack comments and the output of @code{.s} and thus unintuitive.
3437:
3438: @quotation Assignment
3439: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3440: wordlist to the search order. Define @code{previous ( -- )}, which
3441: removes the first searched wordlist from the search order. Experiment
3442: with boundary conditions (you will see some crashes or situations that
3443: are hard or impossible to leave).
3444: @end quotation
3445:
3446: The search order is a powerful foundation for providing features similar
3447: to Modula-2 modules and C++ namespaces. However, trying to modularize
3448: programs in this way has disadvantages for debugging and reuse/factoring
3449: that overcome the advantages in my experience (I don't do huge projects,
3450: though). These disadvantages are not so clear in other
3451: languages/programming environments, because these languages are not so
3452: strong in debugging and reuse.
3453:
3454: @c !! example
3455:
3456: Reference: @ref{Word Lists}.
3457:
3458: @c ******************************************************************
3459: @node Introduction, Words, Tutorial, Top
3460: @comment node-name, next, previous, up
3461: @chapter An Introduction to ANS Forth
3462: @cindex Forth - an introduction
3463:
3464: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3465: that it is slower-paced in its examples, but uses them to dive deep into
3466: explaining Forth internals (not covered by the Tutorial). Apart from
3467: that, this chapter covers far less material. It is suitable for reading
3468: without using a computer.
3469:
3470: The primary purpose of this manual is to document Gforth. However, since
3471: Forth is not a widely-known language and there is a lack of up-to-date
3472: teaching material, it seems worthwhile to provide some introductory
3473: material. For other sources of Forth-related
3474: information, see @ref{Forth-related information}.
3475:
3476: The examples in this section should work on any ANS Forth; the
3477: output shown was produced using Gforth. Each example attempts to
3478: reproduce the exact output that Gforth produces. If you try out the
3479: examples (and you should), what you should type is shown @kbd{like this}
3480: and Gforth's response is shown @code{like this}. The single exception is
3481: that, where the example shows @key{RET} it means that you should
3482: press the ``carriage return'' key. Unfortunately, some output formats for
3483: this manual cannot show the difference between @kbd{this} and
3484: @code{this} which will make trying out the examples harder (but not
3485: impossible).
3486:
3487: Forth is an unusual language. It provides an interactive development
3488: environment which includes both an interpreter and compiler. Forth
3489: programming style encourages you to break a problem down into many
3490: @cindex factoring
3491: small fragments (@dfn{factoring}), and then to develop and test each
3492: fragment interactively. Forth advocates assert that breaking the
3493: edit-compile-test cycle used by conventional programming languages can
3494: lead to great productivity improvements.
3495:
3496: @menu
3497: * Introducing the Text Interpreter::
3498: * Stacks and Postfix notation::
3499: * Your first definition::
3500: * How does that work?::
3501: * Forth is written in Forth::
3502: * Review - elements of a Forth system::
3503: * Where to go next::
3504: * Exercises::
3505: @end menu
3506:
3507: @comment ----------------------------------------------
3508: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3509: @section Introducing the Text Interpreter
3510: @cindex text interpreter
3511: @cindex outer interpreter
3512:
3513: @c IMO this is too detailed and the pace is too slow for
3514: @c an introduction. If you know German, take a look at
3515: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3516: @c to see how I do it - anton
3517:
3518: @c nac-> Where I have accepted your comments 100% and modified the text
3519: @c accordingly, I have deleted your comments. Elsewhere I have added a
3520: @c response like this to attempt to rationalise what I have done. Of
3521: @c course, this is a very clumsy mechanism for something that would be
3522: @c done far more efficiently over a beer. Please delete any dialogue
3523: @c you consider closed.
3524:
3525: When you invoke the Forth image, you will see a startup banner printed
3526: and nothing else (if you have Gforth installed on your system, try
3527: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
3528: its command line interpreter, which is called the @dfn{Text Interpreter}
3529: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
3530: about the text interpreter as you read through this chapter, for more
3531: detail @pxref{The Text Interpreter}).
3532:
3533: Although it's not obvious, Forth is actually waiting for your
3534: input. Type a number and press the @key{RET} key:
3535:
3536: @example
3537: @kbd{45@key{RET}} ok
3538: @end example
3539:
3540: Rather than give you a prompt to invite you to input something, the text
3541: interpreter prints a status message @i{after} it has processed a line
3542: of input. The status message in this case (``@code{ ok}'' followed by
3543: carriage-return) indicates that the text interpreter was able to process
3544: all of your input successfully. Now type something illegal:
3545:
3546: @example
3547: @kbd{qwer341@key{RET}}
3548: *the terminal*:2: Undefined word
3549: >>>qwer341<<<
3550: Backtrace:
3551: $2A95B42A20 throw
3552: $2A95B57FB8 no.extensions
3553: @end example
3554:
3555: The exact text, other than the ``Undefined word'' may differ slightly
3556: on your system, but the effect is the same; when the text interpreter
3557: detects an error, it discards any remaining text on a line, resets
3558: certain internal state and prints an error message. For a detailed
3559: description of error messages see @ref{Error messages}.
3560:
3561: The text interpreter waits for you to press carriage-return, and then
3562: processes your input line. Starting at the beginning of the line, it
3563: breaks the line into groups of characters separated by spaces. For each
3564: group of characters in turn, it makes two attempts to do something:
3565:
3566: @itemize @bullet
3567: @item
3568: @cindex name dictionary
3569: It tries to treat it as a command. It does this by searching a @dfn{name
3570: dictionary}. If the group of characters matches an entry in the name
3571: dictionary, the name dictionary provides the text interpreter with
3572: information that allows the text interpreter perform some actions. In
3573: Forth jargon, we say that the group
3574: @cindex word
3575: @cindex definition
3576: @cindex execution token
3577: @cindex xt
3578: of characters names a @dfn{word}, that the dictionary search returns an
3579: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3580: word, and that the text interpreter executes the xt. Often, the terms
3581: @dfn{word} and @dfn{definition} are used interchangeably.
3582: @item
3583: If the text interpreter fails to find a match in the name dictionary, it
3584: tries to treat the group of characters as a number in the current number
3585: base (when you start up Forth, the current number base is base 10). If
3586: the group of characters legitimately represents a number, the text
3587: interpreter pushes the number onto a stack (we'll learn more about that
3588: in the next section).
3589: @end itemize
3590:
3591: If the text interpreter is unable to do either of these things with any
3592: group of characters, it discards the group of characters and the rest of
3593: the line, then prints an error message. If the text interpreter reaches
3594: the end of the line without error, it prints the status message ``@code{ ok}''
3595: followed by carriage-return.
3596:
3597: This is the simplest command we can give to the text interpreter:
3598:
3599: @example
3600: @key{RET} ok
3601: @end example
3602:
3603: The text interpreter did everything we asked it to do (nothing) without
3604: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3605: command:
3606:
3607: @example
3608: @kbd{12 dup fred dup@key{RET}}
3609: *the terminal*:3: Undefined word
3610: 12 dup >>>fred<<< dup
3611: Backtrace:
3612: $2A95B42A20 throw
3613: $2A95B57FB8 no.extensions
3614: @end example
3615:
3616: When you press the carriage-return key, the text interpreter starts to
3617: work its way along the line:
3618:
3619: @itemize @bullet
3620: @item
3621: When it gets to the space after the @code{2}, it takes the group of
3622: characters @code{12} and looks them up in the name
3623: dictionary@footnote{We can't tell if it found them or not, but assume
3624: for now that it did not}. There is no match for this group of characters
3625: in the name dictionary, so it tries to treat them as a number. It is
3626: able to do this successfully, so it puts the number, 12, ``on the stack''
3627: (whatever that means).
3628: @item
3629: The text interpreter resumes scanning the line and gets the next group
3630: of characters, @code{dup}. It looks it up in the name dictionary and
3631: (you'll have to take my word for this) finds it, and executes the word
3632: @code{dup} (whatever that means).
3633: @item
3634: Once again, the text interpreter resumes scanning the line and gets the
3635: group of characters @code{fred}. It looks them up in the name
3636: dictionary, but can't find them. It tries to treat them as a number, but
3637: they don't represent any legal number.
3638: @end itemize
3639:
3640: At this point, the text interpreter gives up and prints an error
3641: message. The error message shows exactly how far the text interpreter
3642: got in processing the line. In particular, it shows that the text
3643: interpreter made no attempt to do anything with the final character
3644: group, @code{dup}, even though we have good reason to believe that the
3645: text interpreter would have no problem looking that word up and
3646: executing it a second time.
3647:
3648:
3649: @comment ----------------------------------------------
3650: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3651: @section Stacks, postfix notation and parameter passing
3652: @cindex text interpreter
3653: @cindex outer interpreter
3654:
3655: In procedural programming languages (like C and Pascal), the
3656: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3657: functions or procedures are called with @dfn{explicit parameters}. For
3658: example, in C we might write:
3659:
3660: @example
3661: total = total + new_volume(length,height,depth);
3662: @end example
3663:
3664: @noindent
3665: where new_volume is a function-call to another piece of code, and total,
3666: length, height and depth are all variables. length, height and depth are
3667: parameters to the function-call.
3668:
3669: In Forth, the equivalent of the function or procedure is the
3670: @dfn{definition} and parameters are implicitly passed between
3671: definitions using a shared stack that is visible to the
3672: programmer. Although Forth does support variables, the existence of the
3673: stack means that they are used far less often than in most other
3674: programming languages. When the text interpreter encounters a number, it
3675: will place (@dfn{push}) it on the stack. There are several stacks (the
3676: actual number is implementation-dependent ...) and the particular stack
3677: used for any operation is implied unambiguously by the operation being
3678: performed. The stack used for all integer operations is called the @dfn{data
3679: stack} and, since this is the stack used most commonly, references to
3680: ``the data stack'' are often abbreviated to ``the stack''.
3681:
3682: The stacks have a last-in, first-out (LIFO) organisation. If you type:
3683:
3684: @example
3685: @kbd{1 2 3@key{RET}} ok
3686: @end example
3687:
3688: Then this instructs the text interpreter to placed three numbers on the
3689: (data) stack. An analogy for the behaviour of the stack is to take a
3690: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3691: the table. The 3 was the last card onto the pile (``last-in'') and if
3692: you take a card off the pile then, unless you're prepared to fiddle a
3693: bit, the card that you take off will be the 3 (``first-out''). The
3694: number that will be first-out of the stack is called the @dfn{top of
3695: stack}, which
3696: @cindex TOS definition
3697: is often abbreviated to @dfn{TOS}.
3698:
3699: To understand how parameters are passed in Forth, consider the
3700: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3701: be surprised to learn that this definition performs addition. More
3702: precisely, it adds two number together and produces a result. Where does
3703: it get the two numbers from? It takes the top two numbers off the
3704: stack. Where does it place the result? On the stack. You can act-out the
3705: behaviour of @code{+} with your playing cards like this:
3706:
3707: @itemize @bullet
3708: @item
3709: Pick up two cards from the stack on the table
3710: @item
3711: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3712: numbers''
3713: @item
3714: Decide that the answer is 5
3715: @item
3716: Shuffle the two cards back into the pack and find a 5
3717: @item
3718: Put a 5 on the remaining ace that's on the table.
3719: @end itemize
3720:
3721: If you don't have a pack of cards handy but you do have Forth running,
3722: you can use the definition @code{.s} to show the current state of the stack,
3723: without affecting the stack. Type:
3724:
3725: @example
3726: @kbd{clearstacks 1 2 3@key{RET}} ok
3727: @kbd{.s@key{RET}} <3> 1 2 3 ok
3728: @end example
3729:
3730: The text interpreter looks up the word @code{clearstacks} and executes
3731: it; it tidies up the stacks and removes any entries that may have been
3732: left on it by earlier examples. The text interpreter pushes each of the
3733: three numbers in turn onto the stack. Finally, the text interpreter
3734: looks up the word @code{.s} and executes it. The effect of executing
3735: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3736: followed by a list of all the items on the stack; the item on the far
3737: right-hand side is the TOS.
3738:
3739: You can now type:
3740:
3741: @example
3742: @kbd{+ .s@key{RET}} <2> 1 5 ok
3743: @end example
3744:
3745: @noindent
3746: which is correct; there are now 2 items on the stack and the result of
3747: the addition is 5.
3748:
3749: If you're playing with cards, try doing a second addition: pick up the
3750: two cards, work out that their sum is 6, shuffle them into the pack,
3751: look for a 6 and place that on the table. You now have just one item on
3752: the stack. What happens if you try to do a third addition? Pick up the
3753: first card, pick up the second card -- ah! There is no second card. This
3754: is called a @dfn{stack underflow} and consitutes an error. If you try to
3755: do the same thing with Forth it often reports an error (probably a Stack
3756: Underflow or an Invalid Memory Address error).
3757:
3758: The opposite situation to a stack underflow is a @dfn{stack overflow},
3759: which simply accepts that there is a finite amount of storage space
3760: reserved for the stack. To stretch the playing card analogy, if you had
3761: enough packs of cards and you piled the cards up on the table, you would
3762: eventually be unable to add another card; you'd hit the ceiling. Gforth
3763: allows you to set the maximum size of the stacks. In general, the only
3764: time that you will get a stack overflow is because a definition has a
3765: bug in it and is generating data on the stack uncontrollably.
3766:
3767: There's one final use for the playing card analogy. If you model your
3768: stack using a pack of playing cards, the maximum number of items on
3769: your stack will be 52 (I assume you didn't use the Joker). The maximum
3770: @i{value} of any item on the stack is 13 (the King). In fact, the only
3771: possible numbers are positive integer numbers 1 through 13; you can't
3772: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3773: think about some of the cards, you can accommodate different
3774: numbers. For example, you could think of the Jack as representing 0,
3775: the Queen as representing -1 and the King as representing -2. Your
3776: @i{range} remains unchanged (you can still only represent a total of 13
3777: numbers) but the numbers that you can represent are -2 through 10.
3778:
3779: In that analogy, the limit was the amount of information that a single
3780: stack entry could hold, and Forth has a similar limit. In Forth, the
3781: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3782: implementation dependent and affects the maximum value that a stack
3783: entry can hold. A Standard Forth provides a cell size of at least
3784: 16-bits, and most desktop systems use a cell size of 32-bits.
3785:
3786: Forth does not do any type checking for you, so you are free to
3787: manipulate and combine stack items in any way you wish. A convenient way
3788: of treating stack items is as 2's complement signed integers, and that
3789: is what Standard words like @code{+} do. Therefore you can type:
3790:
3791: @example
3792: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
3793: @end example
3794:
3795: If you use numbers and definitions like @code{+} in order to turn Forth
3796: into a great big pocket calculator, you will realise that it's rather
3797: different from a normal calculator. Rather than typing 2 + 3 = you had
3798: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3799: result). The terminology used to describe this difference is to say that
3800: your calculator uses @dfn{Infix Notation} (parameters and operators are
3801: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3802: operators are separate), also called @dfn{Reverse Polish Notation}.
3803:
3804: Whilst postfix notation might look confusing to begin with, it has
3805: several important advantages:
3806:
3807: @itemize @bullet
3808: @item
3809: it is unambiguous
3810: @item
3811: it is more concise
3812: @item
3813: it fits naturally with a stack-based system
3814: @end itemize
3815:
3816: To examine these claims in more detail, consider these sums:
3817:
3818: @example
3819: 6 + 5 * 4 =
3820: 4 * 5 + 6 =
3821: @end example
3822:
3823: If you're just learning maths or your maths is very rusty, you will
3824: probably come up with the answer 44 for the first and 26 for the
3825: second. If you are a bit of a whizz at maths you will remember the
3826: @i{convention} that multiplication takes precendence over addition, and
3827: you'd come up with the answer 26 both times. To explain the answer 26
3828: to someone who got the answer 44, you'd probably rewrite the first sum
3829: like this:
3830:
3831: @example
3832: 6 + (5 * 4) =
3833: @end example
3834:
3835: If what you really wanted was to perform the addition before the
3836: multiplication, you would have to use parentheses to force it.
3837:
3838: If you did the first two sums on a pocket calculator you would probably
3839: get the right answers, unless you were very cautious and entered them using
3840: these keystroke sequences:
3841:
3842: 6 + 5 = * 4 =
3843: 4 * 5 = + 6 =
3844:
3845: Postfix notation is unambiguous because the order that the operators
3846: are applied is always explicit; that also means that parentheses are
3847: never required. The operators are @i{active} (the act of quoting the
3848: operator makes the operation occur) which removes the need for ``=''.
3849:
3850: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3851: equivalent ways:
3852:
3853: @example
3854: 6 5 4 * + or:
3855: 5 4 * 6 +
3856: @end example
3857:
3858: An important thing that you should notice about this notation is that
3859: the @i{order} of the numbers does not change; if you want to subtract
3860: 2 from 10 you type @code{10 2 -}.
3861:
3862: The reason that Forth uses postfix notation is very simple to explain: it
3863: makes the implementation extremely simple, and it follows naturally from
3864: using the stack as a mechanism for passing parameters. Another way of
3865: thinking about this is to realise that all Forth definitions are
3866: @i{active}; they execute as they are encountered by the text
3867: interpreter. The result of this is that the syntax of Forth is trivially
3868: simple.
3869:
3870:
3871:
3872: @comment ----------------------------------------------
3873: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3874: @section Your first Forth definition
3875: @cindex first definition
3876:
3877: Until now, the examples we've seen have been trivial; we've just been
3878: using Forth as a bigger-than-pocket calculator. Also, each calculation
3879: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3880: again@footnote{That's not quite true. If you press the up-arrow key on
3881: your keyboard you should be able to scroll back to any earlier command,
3882: edit it and re-enter it.} In this section we'll see how to add new
3883: words to Forth's vocabulary.
3884:
3885: The easiest way to create a new word is to use a @dfn{colon
3886: definition}. We'll define a few and try them out before worrying too
3887: much about how they work. Try typing in these examples; be careful to
3888: copy the spaces accurately:
3889:
3890: @example
3891: : add-two 2 + . ;
3892: : greet ." Hello and welcome" ;
3893: : demo 5 add-two ;
3894: @end example
3895:
3896: @noindent
3897: Now try them out:
3898:
3899: @example
3900: @kbd{greet@key{RET}} Hello and welcome ok
3901: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3902: @kbd{4 add-two@key{RET}} 6 ok
3903: @kbd{demo@key{RET}} 7 ok
3904: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
3905: @end example
3906:
3907: The first new thing that we've introduced here is the pair of words
3908: @code{:} and @code{;}. These are used to start and terminate a new
3909: definition, respectively. The first word after the @code{:} is the name
3910: for the new definition.
3911:
3912: As you can see from the examples, a definition is built up of words that
3913: have already been defined; Forth makes no distinction between
3914: definitions that existed when you started the system up, and those that
3915: you define yourself.
3916:
3917: The examples also introduce the words @code{.} (dot), @code{."}
3918: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3919: the stack and displays it. It's like @code{.s} except that it only
3920: displays the top item of the stack and it is destructive; after it has
3921: executed, the number is no longer on the stack. There is always one
3922: space printed after the number, and no spaces before it. Dot-quote
3923: defines a string (a sequence of characters) that will be printed when
3924: the word is executed. The string can contain any printable characters
3925: except @code{"}. A @code{"} has a special function; it is not a Forth
3926: word but it acts as a delimiter (the way that delimiters work is
3927: described in the next section). Finally, @code{dup} duplicates the value
3928: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
3929:
3930: We already know that the text interpreter searches through the
3931: dictionary to locate names. If you've followed the examples earlier, you
3932: will already have a definition called @code{add-two}. Lets try modifying
3933: it by typing in a new definition:
3934:
3935: @example
3936: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
3937: @end example
3938:
3939: Forth recognised that we were defining a word that already exists, and
3940: printed a message to warn us of that fact. Let's try out the new
3941: definition:
3942:
3943: @example
3944: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
3945: @end example
3946:
3947: @noindent
3948: All that we've actually done here, though, is to create a new
3949: definition, with a particular name. The fact that there was already a
3950: definition with the same name did not make any difference to the way
3951: that the new definition was created (except that Forth printed a warning
3952: message). The old definition of add-two still exists (try @code{demo}
3953: again to see that this is true). Any new definition will use the new
3954: definition of @code{add-two}, but old definitions continue to use the
3955: version that already existed at the time that they were @code{compiled}.
3956:
3957: Before you go on to the next section, try defining and redefining some
3958: words of your own.
3959:
3960: @comment ----------------------------------------------
3961: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3962: @section How does that work?
3963: @cindex parsing words
3964:
3965: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3966:
3967: @c Is it a good idea to talk about the interpretation semantics of a
3968: @c number? We don't have an xt to go along with it. - anton
3969:
3970: @c Now that I have eliminated execution semantics, I wonder if it would not
3971: @c be better to keep them (or add run-time semantics), to make it easier to
3972: @c explain what compilation semantics usually does. - anton
3973:
3974: @c nac-> I removed the term ``default compilation sematics'' from the
3975: @c introductory chapter. Removing ``execution semantics'' was making
3976: @c everything simpler to explain, then I think the use of this term made
3977: @c everything more complex again. I replaced it with ``default
3978: @c semantics'' (which is used elsewhere in the manual) by which I mean
3979: @c ``a definition that has neither the immediate nor the compile-only
3980: @c flag set''.
3981:
3982: @c anton: I have eliminated default semantics (except in one place where it
3983: @c means "default interpretation and compilation semantics"), because it
3984: @c makes no sense in the presence of combined words. I reverted to
3985: @c "execution semantics" where necessary.
3986:
3987: @c nac-> I reworded big chunks of the ``how does that work''
3988: @c section (and, unusually for me, I think I even made it shorter!). See
3989: @c what you think -- I know I have not addressed your primary concern
3990: @c that it is too heavy-going for an introduction. From what I understood
3991: @c of your course notes it looks as though they might be a good framework.
3992: @c Things that I've tried to capture here are some things that came as a
3993: @c great revelation here when I first understood them. Also, I like the
3994: @c fact that a very simple code example shows up almost all of the issues
3995: @c that you need to understand to see how Forth works. That's unique and
3996: @c worthwhile to emphasise.
3997:
3998: @c anton: I think it's a good idea to present the details, especially those
3999: @c that you found to be a revelation, and probably the tutorial tries to be
4000: @c too superficial and does not get some of the things across that make
4001: @c Forth special. I do believe that most of the time these things should
4002: @c be discussed at the end of a section or in separate sections instead of
4003: @c in the middle of a section (e.g., the stuff you added in "User-defined
4004: @c defining words" leads in a completely different direction from the rest
4005: @c of the section).
4006:
4007: Now we're going to take another look at the definition of @code{add-two}
4008: from the previous section. From our knowledge of the way that the text
4009: interpreter works, we would have expected this result when we tried to
4010: define @code{add-two}:
4011:
4012: @example
4013: @kbd{: add-two 2 + . ;@key{RET}}
4014: *the terminal*:4: Undefined word
4015: : >>>add-two<<< 2 + . ;
4016: @end example
4017:
4018: The reason that this didn't happen is bound up in the way that @code{:}
4019: works. The word @code{:} does two special things. The first special
4020: thing that it does prevents the text interpreter from ever seeing the
4021: characters @code{add-two}. The text interpreter uses a variable called
4022: @cindex modifying >IN
4023: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
4024: input line. When it encounters the word @code{:} it behaves in exactly
4025: the same way as it does for any other word; it looks it up in the name
4026: dictionary, finds its xt and executes it. When @code{:} executes, it
4027: looks at the input buffer, finds the word @code{add-two} and advances the
4028: value of @code{>IN} to point past it. It then does some other stuff
4029: associated with creating the new definition (including creating an entry
4030: for @code{add-two} in the name dictionary). When the execution of @code{:}
4031: completes, control returns to the text interpreter, which is oblivious
4032: to the fact that it has been tricked into ignoring part of the input
4033: line.
4034:
4035: @cindex parsing words
4036: Words like @code{:} -- words that advance the value of @code{>IN} and so
4037: prevent the text interpreter from acting on the whole of the input line
4038: -- are called @dfn{parsing words}.
4039:
4040: @cindex @code{state} - effect on the text interpreter
4041: @cindex text interpreter - effect of state
4042: The second special thing that @code{:} does is change the value of a
4043: variable called @code{state}, which affects the way that the text
4044: interpreter behaves. When Gforth starts up, @code{state} has the value
4045: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4046: colon definition (started with @code{:}), @code{state} is set to -1 and
4047: the text interpreter is said to be @dfn{compiling}.
4048:
4049: In this example, the text interpreter is compiling when it processes the
4050: string ``@code{2 + . ;}''. It still breaks the string down into
4051: character sequences in the same way. However, instead of pushing the
4052: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4053: into the definition of @code{add-two} that will make the number @code{2} get
4054: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4055: the behaviours of @code{+} and @code{.} are also compiled into the
4056: definition.
4057:
4058: One category of words don't get compiled. These so-called @dfn{immediate
4059: words} get executed (performed @i{now}) regardless of whether the text
4060: interpreter is interpreting or compiling. The word @code{;} is an
4061: immediate word. Rather than being compiled into the definition, it
4062: executes. Its effect is to terminate the current definition, which
4063: includes changing the value of @code{state} back to 0.
4064:
4065: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4066: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4067: definition.
4068:
4069: In Forth, every word or number can be described in terms of two
4070: properties:
4071:
4072: @itemize @bullet
4073: @item
4074: @cindex interpretation semantics
4075: Its @dfn{interpretation semantics} describe how it will behave when the
4076: text interpreter encounters it in @dfn{interpret} state. The
4077: interpretation semantics of a word are represented by an @dfn{execution
4078: token}.
4079: @item
4080: @cindex compilation semantics
4081: Its @dfn{compilation semantics} describe how it will behave when the
4082: text interpreter encounters it in @dfn{compile} state. The compilation
4083: semantics of a word are represented in an implementation-dependent way;
4084: Gforth uses a @dfn{compilation token}.
4085: @end itemize
4086:
4087: @noindent
4088: Numbers are always treated in a fixed way:
4089:
4090: @itemize @bullet
4091: @item
4092: When the number is @dfn{interpreted}, its behaviour is to push the
4093: number onto the stack.
4094: @item
4095: When the number is @dfn{compiled}, a piece of code is appended to the
4096: current definition that pushes the number when it runs. (In other words,
4097: the compilation semantics of a number are to postpone its interpretation
4098: semantics until the run-time of the definition that it is being compiled
4099: into.)
4100: @end itemize
4101:
4102: Words don't behave in such a regular way, but most have @i{default
4103: semantics} which means that they behave like this:
4104:
4105: @itemize @bullet
4106: @item
4107: The @dfn{interpretation semantics} of the word are to do something useful.
4108: @item
4109: The @dfn{compilation semantics} of the word are to append its
4110: @dfn{interpretation semantics} to the current definition (so that its
4111: run-time behaviour is to do something useful).
4112: @end itemize
4113:
4114: @cindex immediate words
4115: The actual behaviour of any particular word can be controlled by using
4116: the words @code{immediate} and @code{compile-only} when the word is
4117: defined. These words set flags in the name dictionary entry of the most
4118: recently defined word, and these flags are retrieved by the text
4119: interpreter when it finds the word in the name dictionary.
4120:
4121: A word that is marked as @dfn{immediate} has compilation semantics that
4122: are identical to its interpretation semantics. In other words, it
4123: behaves like this:
4124:
4125: @itemize @bullet
4126: @item
4127: The @dfn{interpretation semantics} of the word are to do something useful.
4128: @item
4129: The @dfn{compilation semantics} of the word are to do something useful
4130: (and actually the same thing); i.e., it is executed during compilation.
4131: @end itemize
4132:
4133: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4134: performing the interpretation semantics of the word directly; an attempt
4135: to do so will generate an error. It is never necessary to use
4136: @code{compile-only} (and it is not even part of ANS Forth, though it is
4137: provided by many implementations) but it is good etiquette to apply it
4138: to a word that will not behave correctly (and might have unexpected
4139: side-effects) in interpret state. For example, it is only legal to use
4140: the conditional word @code{IF} within a definition. If you forget this
4141: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4142: @code{compile-only} allows the text interpreter to generate a helpful
4143: error message rather than subjecting you to the consequences of your
4144: folly.
4145:
4146: This example shows the difference between an immediate and a
4147: non-immediate word:
4148:
4149: @example
4150: : show-state state @@ . ;
4151: : show-state-now show-state ; immediate
4152: : word1 show-state ;
4153: : word2 show-state-now ;
4154: @end example
4155:
4156: The word @code{immediate} after the definition of @code{show-state-now}
4157: makes that word an immediate word. These definitions introduce a new
4158: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4159: variable, and leaves it on the stack. Therefore, the behaviour of
4160: @code{show-state} is to print a number that represents the current value
4161: of @code{state}.
4162:
4163: When you execute @code{word1}, it prints the number 0, indicating that
4164: the system is interpreting. When the text interpreter compiled the
4165: definition of @code{word1}, it encountered @code{show-state} whose
4166: compilation semantics are to append its interpretation semantics to the
4167: current definition. When you execute @code{word1}, it performs the
4168: interpretation semantics of @code{show-state}. At the time that @code{word1}
4169: (and therefore @code{show-state}) are executed, the system is
4170: interpreting.
4171:
4172: When you pressed @key{RET} after entering the definition of @code{word2},
4173: you should have seen the number -1 printed, followed by ``@code{
4174: ok}''. When the text interpreter compiled the definition of
4175: @code{word2}, it encountered @code{show-state-now}, an immediate word,
4176: whose compilation semantics are therefore to perform its interpretation
4177: semantics. It is executed straight away (even before the text
4178: interpreter has moved on to process another group of characters; the
4179: @code{;} in this example). The effect of executing it are to display the
4180: value of @code{state} @i{at the time that the definition of}
4181: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4182: system is compiling at this time. If you execute @code{word2} it does
4183: nothing at all.
4184:
4185: @cindex @code{."}, how it works
4186: Before leaving the subject of immediate words, consider the behaviour of
4187: @code{."} in the definition of @code{greet}, in the previous
4188: section. This word is both a parsing word and an immediate word. Notice
4189: that there is a space between @code{."} and the start of the text
4190: @code{Hello and welcome}, but that there is no space between the last
4191: letter of @code{welcome} and the @code{"} character. The reason for this
4192: is that @code{."} is a Forth word; it must have a space after it so that
4193: the text interpreter can identify it. The @code{"} is not a Forth word;
4194: it is a @dfn{delimiter}. The examples earlier show that, when the string
4195: is displayed, there is neither a space before the @code{H} nor after the
4196: @code{e}. Since @code{."} is an immediate word, it executes at the time
4197: that @code{greet} is defined. When it executes, its behaviour is to
4198: search forward in the input line looking for the delimiter. When it
4199: finds the delimiter, it updates @code{>IN} to point past the
4200: delimiter. It also compiles some magic code into the definition of
4201: @code{greet}; the xt of a run-time routine that prints a text string. It
4202: compiles the string @code{Hello and welcome} into memory so that it is
4203: available to be printed later. When the text interpreter gains control,
4204: the next word it finds in the input stream is @code{;} and so it
4205: terminates the definition of @code{greet}.
4206:
4207:
4208: @comment ----------------------------------------------
4209: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4210: @section Forth is written in Forth
4211: @cindex structure of Forth programs
4212:
4213: When you start up a Forth compiler, a large number of definitions
4214: already exist. In Forth, you develop a new application using bottom-up
4215: programming techniques to create new definitions that are defined in
4216: terms of existing definitions. As you create each definition you can
4217: test and debug it interactively.
4218:
4219: If you have tried out the examples in this section, you will probably
4220: have typed them in by hand; when you leave Gforth, your definitions will
4221: be lost. You can avoid this by using a text editor to enter Forth source
4222: code into a file, and then loading code from the file using
4223: @code{include} (@pxref{Forth source files}). A Forth source file is
4224: processed by the text interpreter, just as though you had typed it in by
4225: hand@footnote{Actually, there are some subtle differences -- see
4226: @ref{The Text Interpreter}.}.
4227:
4228: Gforth also supports the traditional Forth alternative to using text
4229: files for program entry (@pxref{Blocks}).
4230:
4231: In common with many, if not most, Forth compilers, most of Gforth is
4232: actually written in Forth. All of the @file{.fs} files in the
4233: installation directory@footnote{For example,
4234: @file{/usr/local/share/gforth...}} are Forth source files, which you can
4235: study to see examples of Forth programming.
4236:
4237: Gforth maintains a history file that records every line that you type to
4238: the text interpreter. This file is preserved between sessions, and is
4239: used to provide a command-line recall facility. If you enter long
4240: definitions by hand, you can use a text editor to paste them out of the
4241: history file into a Forth source file for reuse at a later time
4242: (for more information @pxref{Command-line editing}).
4243:
4244:
4245: @comment ----------------------------------------------
4246: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4247: @section Review - elements of a Forth system
4248: @cindex elements of a Forth system
4249:
4250: To summarise this chapter:
4251:
4252: @itemize @bullet
4253: @item
4254: Forth programs use @dfn{factoring} to break a problem down into small
4255: fragments called @dfn{words} or @dfn{definitions}.
4256: @item
4257: Forth program development is an interactive process.
4258: @item
4259: The main command loop that accepts input, and controls both
4260: interpretation and compilation, is called the @dfn{text interpreter}
4261: (also known as the @dfn{outer interpreter}).
4262: @item
4263: Forth has a very simple syntax, consisting of words and numbers
4264: separated by spaces or carriage-return characters. Any additional syntax
4265: is imposed by @dfn{parsing words}.
4266: @item
4267: Forth uses a stack to pass parameters between words. As a result, it
4268: uses postfix notation.
4269: @item
4270: To use a word that has previously been defined, the text interpreter
4271: searches for the word in the @dfn{name dictionary}.
4272: @item
4273: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
4274: @item
4275: The text interpreter uses the value of @code{state} to select between
4276: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4277: semantics} of a word that it encounters.
4278: @item
4279: The relationship between the @dfn{interpretation semantics} and
4280: @dfn{compilation semantics} for a word
4281: depend upon the way in which the word was defined (for example, whether
4282: it is an @dfn{immediate} word).
4283: @item
4284: Forth definitions can be implemented in Forth (called @dfn{high-level
4285: definitions}) or in some other way (usually a lower-level language and
4286: as a result often called @dfn{low-level definitions}, @dfn{code
4287: definitions} or @dfn{primitives}).
4288: @item
4289: Many Forth systems are implemented mainly in Forth.
4290: @end itemize
4291:
4292:
4293: @comment ----------------------------------------------
4294: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
4295: @section Where To Go Next
4296: @cindex where to go next
4297:
4298: Amazing as it may seem, if you have read (and understood) this far, you
4299: know almost all the fundamentals about the inner workings of a Forth
4300: system. You certainly know enough to be able to read and understand the
4301: rest of this manual and the ANS Forth document, to learn more about the
4302: facilities that Forth in general and Gforth in particular provide. Even
4303: scarier, you know almost enough to implement your own Forth system.
4304: However, that's not a good idea just yet... better to try writing some
4305: programs in Gforth.
4306:
4307: Forth has such a rich vocabulary that it can be hard to know where to
4308: start in learning it. This section suggests a few sets of words that are
4309: enough to write small but useful programs. Use the word index in this
4310: document to learn more about each word, then try it out and try to write
4311: small definitions using it. Start by experimenting with these words:
4312:
4313: @itemize @bullet
4314: @item
4315: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4316: @item
4317: Comparison: @code{MIN MAX =}
4318: @item
4319: Logic: @code{AND OR XOR NOT}
4320: @item
4321: Stack manipulation: @code{DUP DROP SWAP OVER}
4322: @item
4323: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
4324: @item
4325: Input/Output: @code{. ." EMIT CR KEY}
4326: @item
4327: Defining words: @code{: ; CREATE}
4328: @item
4329: Memory allocation words: @code{ALLOT ,}
4330: @item
4331: Tools: @code{SEE WORDS .S MARKER}
4332: @end itemize
4333:
4334: When you have mastered those, go on to:
4335:
4336: @itemize @bullet
4337: @item
4338: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
4339: @item
4340: Memory access: @code{@@ !}
4341: @end itemize
4342:
4343: When you have mastered these, there's nothing for it but to read through
4344: the whole of this manual and find out what you've missed.
4345:
4346: @comment ----------------------------------------------
4347: @node Exercises, , Where to go next, Introduction
4348: @section Exercises
4349: @cindex exercises
4350:
4351: TODO: provide a set of programming excercises linked into the stuff done
4352: already and into other sections of the manual. Provide solutions to all
4353: the exercises in a .fs file in the distribution.
4354:
4355: @c Get some inspiration from Starting Forth and Kelly&Spies.
4356:
4357: @c excercises:
4358: @c 1. take inches and convert to feet and inches.
4359: @c 2. take temperature and convert from fahrenheight to celcius;
4360: @c may need to care about symmetric vs floored??
4361: @c 3. take input line and do character substitution
4362: @c to encipher or decipher
4363: @c 4. as above but work on a file for in and out
4364: @c 5. take input line and convert to pig-latin
4365: @c
4366: @c thing of sets of things to exercise then come up with
4367: @c problems that need those things.
4368:
4369:
4370: @c ******************************************************************
4371: @node Words, Error messages, Introduction, Top
4372: @chapter Forth Words
4373: @cindex words
4374:
4375: @menu
4376: * Notation::
4377: * Case insensitivity::
4378: * Comments::
4379: * Boolean Flags::
4380: * Arithmetic::
4381: * Stack Manipulation::
4382: * Memory::
4383: * Control Structures::
4384: * Defining Words::
4385: * Interpretation and Compilation Semantics::
4386: * Tokens for Words::
4387: * Compiling words::
4388: * The Text Interpreter::
4389: * The Input Stream::
4390: * Word Lists::
4391: * Environmental Queries::
4392: * Files::
4393: * Blocks::
4394: * Other I/O::
4395: * OS command line arguments::
4396: * Locals::
4397: * Structures::
4398: * Object-oriented Forth::
4399: * Programming Tools::
4400: * C Interface::
4401: * Assembler and Code Words::
4402: * Threading Words::
4403: * Passing Commands to the OS::
4404: * Keeping track of Time::
4405: * Miscellaneous Words::
4406: @end menu
4407:
4408: @node Notation, Case insensitivity, Words, Words
4409: @section Notation
4410: @cindex notation of glossary entries
4411: @cindex format of glossary entries
4412: @cindex glossary notation format
4413: @cindex word glossary entry format
4414:
4415: The Forth words are described in this section in the glossary notation
4416: that has become a de-facto standard for Forth texts:
4417:
4418: @format
4419: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
4420: @end format
4421: @i{Description}
4422:
4423: @table @var
4424: @item word
4425: The name of the word.
4426:
4427: @item Stack effect
4428: @cindex stack effect
4429: The stack effect is written in the notation @code{@i{before} --
4430: @i{after}}, where @i{before} and @i{after} describe the top of
4431: stack entries before and after the execution of the word. The rest of
4432: the stack is not touched by the word. The top of stack is rightmost,
4433: i.e., a stack sequence is written as it is typed in. Note that Gforth
4434: uses a separate floating point stack, but a unified stack
4435: notation. Also, return stack effects are not shown in @i{stack
4436: effect}, but in @i{Description}. The name of a stack item describes
4437: the type and/or the function of the item. See below for a discussion of
4438: the types.
4439:
4440: All words have two stack effects: A compile-time stack effect and a
4441: run-time stack effect. The compile-time stack-effect of most words is
4442: @i{ -- }. If the compile-time stack-effect of a word deviates from
4443: this standard behaviour, or the word does other unusual things at
4444: compile time, both stack effects are shown; otherwise only the run-time
4445: stack effect is shown.
4446:
4447: Also note that in code templates or examples there can be comments in
4448: parentheses that display the stack picture at this point; there is no
4449: @code{--} in these places, because there is no before-after situation.
4450:
4451: @cindex pronounciation of words
4452: @item pronunciation
4453: How the word is pronounced.
4454:
4455: @cindex wordset
4456: @cindex environment wordset
4457: @item wordset
4458: The ANS Forth standard is divided into several word sets. A standard
4459: system need not support all of them. Therefore, in theory, the fewer
4460: word sets your program uses the more portable it will be. However, we
4461: suspect that most ANS Forth systems on personal machines will feature
4462: all word sets. Words that are not defined in ANS Forth have
4463: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
4464: describes words that will work in future releases of Gforth;
4465: @code{gforth-internal} words are more volatile. Environmental query
4466: strings are also displayed like words; you can recognize them by the
4467: @code{environment} in the word set field.
4468:
4469: @item Description
4470: A description of the behaviour of the word.
4471: @end table
4472:
4473: @cindex types of stack items
4474: @cindex stack item types
4475: The type of a stack item is specified by the character(s) the name
4476: starts with:
4477:
4478: @table @code
4479: @item f
4480: @cindex @code{f}, stack item type
4481: Boolean flags, i.e. @code{false} or @code{true}.
4482: @item c
4483: @cindex @code{c}, stack item type
4484: Char
4485: @item w
4486: @cindex @code{w}, stack item type
4487: Cell, can contain an integer or an address
4488: @item n
4489: @cindex @code{n}, stack item type
4490: signed integer
4491: @item u
4492: @cindex @code{u}, stack item type
4493: unsigned integer
4494: @item d
4495: @cindex @code{d}, stack item type
4496: double sized signed integer
4497: @item ud
4498: @cindex @code{ud}, stack item type
4499: double sized unsigned integer
4500: @item r
4501: @cindex @code{r}, stack item type
4502: Float (on the FP stack)
4503: @item a-
4504: @cindex @code{a_}, stack item type
4505: Cell-aligned address
4506: @item c-
4507: @cindex @code{c_}, stack item type
4508: Char-aligned address (note that a Char may have two bytes in Windows NT)
4509: @item f-
4510: @cindex @code{f_}, stack item type
4511: Float-aligned address
4512: @item df-
4513: @cindex @code{df_}, stack item type
4514: Address aligned for IEEE double precision float
4515: @item sf-
4516: @cindex @code{sf_}, stack item type
4517: Address aligned for IEEE single precision float
4518: @item xt
4519: @cindex @code{xt}, stack item type
4520: Execution token, same size as Cell
4521: @item wid
4522: @cindex @code{wid}, stack item type
4523: Word list ID, same size as Cell
4524: @item ior, wior
4525: @cindex ior type description
4526: @cindex wior type description
4527: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
4528: @item f83name
4529: @cindex @code{f83name}, stack item type
4530: Pointer to a name structure
4531: @item "
4532: @cindex @code{"}, stack item type
4533: string in the input stream (not on the stack). The terminating character
4534: is a blank by default. If it is not a blank, it is shown in @code{<>}
4535: quotes.
4536: @end table
4537:
4538: @comment ----------------------------------------------
4539: @node Case insensitivity, Comments, Notation, Words
4540: @section Case insensitivity
4541: @cindex case sensitivity
4542: @cindex upper and lower case
4543:
4544: Gforth is case-insensitive; you can enter definitions and invoke
4545: Standard words using upper, lower or mixed case (however,
4546: @pxref{core-idef, Implementation-defined options, Implementation-defined
4547: options}).
4548:
4549: ANS Forth only @i{requires} implementations to recognise Standard words
4550: when they are typed entirely in upper case. Therefore, a Standard
4551: program must use upper case for all Standard words. You can use whatever
4552: case you like for words that you define, but in a Standard program you
4553: have to use the words in the same case that you defined them.
4554:
4555: Gforth supports case sensitivity through @code{table}s (case-sensitive
4556: wordlists, @pxref{Word Lists}).
4557:
4558: Two people have asked how to convert Gforth to be case-sensitive; while
4559: we think this is a bad idea, you can change all wordlists into tables
4560: like this:
4561:
4562: @example
4563: ' table-find forth-wordlist wordlist-map @ !
4564: @end example
4565:
4566: Note that you now have to type the predefined words in the same case
4567: that we defined them, which are varying. You may want to convert them
4568: to your favourite case before doing this operation (I won't explain how,
4569: because if you are even contemplating doing this, you'd better have
4570: enough knowledge of Forth systems to know this already).
4571:
4572: @node Comments, Boolean Flags, Case insensitivity, Words
4573: @section Comments
4574: @cindex comments
4575:
4576: Forth supports two styles of comment; the traditional @i{in-line} comment,
4577: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
4578:
4579:
4580: doc-(
4581: doc-\
4582: doc-\G
4583:
4584:
4585: @node Boolean Flags, Arithmetic, Comments, Words
4586: @section Boolean Flags
4587: @cindex Boolean flags
4588:
4589: A Boolean flag is cell-sized. A cell with all bits clear represents the
4590: flag @code{false} and a flag with all bits set represents the flag
4591: @code{true}. Words that check a flag (for example, @code{IF}) will treat
4592: a cell that has @i{any} bit set as @code{true}.
4593: @c on and off to Memory?
4594: @c true and false to "Bitwise operations" or "Numeric comparison"?
4595:
4596: doc-true
4597: doc-false
4598: doc-on
4599: doc-off
4600:
4601:
4602: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
4603: @section Arithmetic
4604: @cindex arithmetic words
4605:
4606: @cindex division with potentially negative operands
4607: Forth arithmetic is not checked, i.e., you will not hear about integer
4608: overflow on addition or multiplication, you may hear about division by
4609: zero if you are lucky. The operator is written after the operands, but
4610: the operands are still in the original order. I.e., the infix @code{2-1}
4611: corresponds to @code{2 1 -}. Forth offers a variety of division
4612: operators. If you perform division with potentially negative operands,
4613: you do not want to use @code{/} or @code{/mod} with its undefined
4614: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4615: former, @pxref{Mixed precision}).
4616: @comment TODO discuss the different division forms and the std approach
4617:
4618: @menu
4619: * Single precision::
4620: * Double precision:: Double-cell integer arithmetic
4621: * Bitwise operations::
4622: * Numeric comparison::
4623: * Mixed precision:: Operations with single and double-cell integers
4624: * Floating Point::
4625: @end menu
4626:
4627: @node Single precision, Double precision, Arithmetic, Arithmetic
4628: @subsection Single precision
4629: @cindex single precision arithmetic words
4630:
4631: @c !! cell undefined
4632:
4633: By default, numbers in Forth are single-precision integers that are one
4634: cell in size. They can be signed or unsigned, depending upon how you
4635: treat them. For the rules used by the text interpreter for recognising
4636: single-precision integers see @ref{Number Conversion}.
4637:
4638: These words are all defined for signed operands, but some of them also
4639: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4640: @code{*}.
4641:
4642: doc-+
4643: doc-1+
4644: doc-under+
4645: doc--
4646: doc-1-
4647: doc-*
4648: doc-/
4649: doc-mod
4650: doc-/mod
4651: doc-negate
4652: doc-abs
4653: doc-min
4654: doc-max
4655: doc-floored
4656:
4657:
4658: @node Double precision, Bitwise operations, Single precision, Arithmetic
4659: @subsection Double precision
4660: @cindex double precision arithmetic words
4661:
4662: For the rules used by the text interpreter for
4663: recognising double-precision integers, see @ref{Number Conversion}.
4664:
4665: A double precision number is represented by a cell pair, with the most
4666: significant cell at the TOS. It is trivial to convert an unsigned single
4667: to a double: simply push a @code{0} onto the TOS. Since numbers are
4668: represented by Gforth using 2's complement arithmetic, converting a
4669: signed single to a (signed) double requires sign-extension across the
4670: most significant cell. This can be achieved using @code{s>d}. The moral
4671: of the story is that you cannot convert a number without knowing whether
4672: it represents an unsigned or a signed number.
4673:
4674: These words are all defined for signed operands, but some of them also
4675: work for unsigned numbers: @code{d+}, @code{d-}.
4676:
4677: doc-s>d
4678: doc-d>s
4679: doc-d+
4680: doc-d-
4681: doc-dnegate
4682: doc-dabs
4683: doc-dmin
4684: doc-dmax
4685:
4686:
4687: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4688: @subsection Bitwise operations
4689: @cindex bitwise operation words
4690:
4691:
4692: doc-and
4693: doc-or
4694: doc-xor
4695: doc-invert
4696: doc-lshift
4697: doc-rshift
4698: doc-2*
4699: doc-d2*
4700: doc-2/
4701: doc-d2/
4702:
4703:
4704: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
4705: @subsection Numeric comparison
4706: @cindex numeric comparison words
4707:
4708: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4709: d0= d0<>}) work for for both signed and unsigned numbers.
4710:
4711: doc-<
4712: doc-<=
4713: doc-<>
4714: doc-=
4715: doc->
4716: doc->=
4717:
4718: doc-0<
4719: doc-0<=
4720: doc-0<>
4721: doc-0=
4722: doc-0>
4723: doc-0>=
4724:
4725: doc-u<
4726: doc-u<=
4727: @c u<> and u= exist but are the same as <> and =
4728: @c doc-u<>
4729: @c doc-u=
4730: doc-u>
4731: doc-u>=
4732:
4733: doc-within
4734:
4735: doc-d<
4736: doc-d<=
4737: doc-d<>
4738: doc-d=
4739: doc-d>
4740: doc-d>=
4741:
4742: doc-d0<
4743: doc-d0<=
4744: doc-d0<>
4745: doc-d0=
4746: doc-d0>
4747: doc-d0>=
4748:
4749: doc-du<
4750: doc-du<=
4751: @c du<> and du= exist but are the same as d<> and d=
4752: @c doc-du<>
4753: @c doc-du=
4754: doc-du>
4755: doc-du>=
4756:
4757:
4758: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
4759: @subsection Mixed precision
4760: @cindex mixed precision arithmetic words
4761:
4762:
4763: doc-m+
4764: doc-*/
4765: doc-*/mod
4766: doc-m*
4767: doc-um*
4768: doc-m*/
4769: doc-um/mod
4770: doc-fm/mod
4771: doc-sm/rem
4772:
4773:
4774: @node Floating Point, , Mixed precision, Arithmetic
4775: @subsection Floating Point
4776: @cindex floating point arithmetic words
4777:
4778: For the rules used by the text interpreter for
4779: recognising floating-point numbers see @ref{Number Conversion}.
4780:
4781: Gforth has a separate floating point stack, but the documentation uses
4782: the unified notation.@footnote{It's easy to generate the separate
4783: notation from that by just separating the floating-point numbers out:
4784: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4785: r3 )}.}
4786:
4787: @cindex floating-point arithmetic, pitfalls
4788: Floating point numbers have a number of unpleasant surprises for the
4789: unwary (e.g., floating point addition is not associative) and even a
4790: few for the wary. You should not use them unless you know what you are
4791: doing or you don't care that the results you get are totally bogus. If
4792: you want to learn about the problems of floating point numbers (and
4793: how to avoid them), you might start with @cite{David Goldberg,
4794: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
4795: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
4796: Computing Surveys 23(1):5@minus{}48, March 1991}.
4797:
4798:
4799: doc-d>f
4800: doc-f>d
4801: doc-f+
4802: doc-f-
4803: doc-f*
4804: doc-f/
4805: doc-fnegate
4806: doc-fabs
4807: doc-fmax
4808: doc-fmin
4809: doc-floor
4810: doc-fround
4811: doc-f**
4812: doc-fsqrt
4813: doc-fexp
4814: doc-fexpm1
4815: doc-fln
4816: doc-flnp1
4817: doc-flog
4818: doc-falog
4819: doc-f2*
4820: doc-f2/
4821: doc-1/f
4822: doc-precision
4823: doc-set-precision
4824:
4825: @cindex angles in trigonometric operations
4826: @cindex trigonometric operations
4827: Angles in floating point operations are given in radians (a full circle
4828: has 2 pi radians).
4829:
4830: doc-fsin
4831: doc-fcos
4832: doc-fsincos
4833: doc-ftan
4834: doc-fasin
4835: doc-facos
4836: doc-fatan
4837: doc-fatan2
4838: doc-fsinh
4839: doc-fcosh
4840: doc-ftanh
4841: doc-fasinh
4842: doc-facosh
4843: doc-fatanh
4844: doc-pi
4845:
4846: @cindex equality of floats
4847: @cindex floating-point comparisons
4848: One particular problem with floating-point arithmetic is that comparison
4849: for equality often fails when you would expect it to succeed. For this
4850: reason approximate equality is often preferred (but you still have to
4851: know what you are doing). Also note that IEEE NaNs may compare
4852: differently from what you might expect. The comparison words are:
4853:
4854: doc-f~rel
4855: doc-f~abs
4856: doc-f~
4857: doc-f=
4858: doc-f<>
4859:
4860: doc-f<
4861: doc-f<=
4862: doc-f>
4863: doc-f>=
4864:
4865: doc-f0<
4866: doc-f0<=
4867: doc-f0<>
4868: doc-f0=
4869: doc-f0>
4870: doc-f0>=
4871:
4872:
4873: @node Stack Manipulation, Memory, Arithmetic, Words
4874: @section Stack Manipulation
4875: @cindex stack manipulation words
4876:
4877: @cindex floating-point stack in the standard
4878: Gforth maintains a number of separate stacks:
4879:
4880: @cindex data stack
4881: @cindex parameter stack
4882: @itemize @bullet
4883: @item
4884: A data stack (also known as the @dfn{parameter stack}) -- for
4885: characters, cells, addresses, and double cells.
4886:
4887: @cindex floating-point stack
4888: @item
4889: A floating point stack -- for holding floating point (FP) numbers.
4890:
4891: @cindex return stack
4892: @item
4893: A return stack -- for holding the return addresses of colon
4894: definitions and other (non-FP) data.
4895:
4896: @cindex locals stack
4897: @item
4898: A locals stack -- for holding local variables.
4899: @end itemize
4900:
4901: @menu
4902: * Data stack::
4903: * Floating point stack::
4904: * Return stack::
4905: * Locals stack::
4906: * Stack pointer manipulation::
4907: @end menu
4908:
4909: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4910: @subsection Data stack
4911: @cindex data stack manipulation words
4912: @cindex stack manipulations words, data stack
4913:
4914:
4915: doc-drop
4916: doc-nip
4917: doc-dup
4918: doc-over
4919: doc-tuck
4920: doc-swap
4921: doc-pick
4922: doc-rot
4923: doc--rot
4924: doc-?dup
4925: doc-roll
4926: doc-2drop
4927: doc-2nip
4928: doc-2dup
4929: doc-2over
4930: doc-2tuck
4931: doc-2swap
4932: doc-2rot
4933:
4934:
4935: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4936: @subsection Floating point stack
4937: @cindex floating-point stack manipulation words
4938: @cindex stack manipulation words, floating-point stack
4939:
4940: Whilst every sane Forth has a separate floating-point stack, it is not
4941: strictly required; an ANS Forth system could theoretically keep
4942: floating-point numbers on the data stack. As an additional difficulty,
4943: you don't know how many cells a floating-point number takes. It is
4944: reportedly possible to write words in a way that they work also for a
4945: unified stack model, but we do not recommend trying it. Instead, just
4946: say that your program has an environmental dependency on a separate
4947: floating-point stack.
4948:
4949: doc-floating-stack
4950:
4951: doc-fdrop
4952: doc-fnip
4953: doc-fdup
4954: doc-fover
4955: doc-ftuck
4956: doc-fswap
4957: doc-fpick
4958: doc-frot
4959:
4960:
4961: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4962: @subsection Return stack
4963: @cindex return stack manipulation words
4964: @cindex stack manipulation words, return stack
4965:
4966: @cindex return stack and locals
4967: @cindex locals and return stack
4968: A Forth system is allowed to keep local variables on the
4969: return stack. This is reasonable, as local variables usually eliminate
4970: the need to use the return stack explicitly. So, if you want to produce
4971: a standard compliant program and you are using local variables in a
4972: word, forget about return stack manipulations in that word (refer to the
4973: standard document for the exact rules).
4974:
4975: doc->r
4976: doc-r>
4977: doc-r@
4978: doc-rdrop
4979: doc-2>r
4980: doc-2r>
4981: doc-2r@
4982: doc-2rdrop
4983:
4984:
4985: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4986: @subsection Locals stack
4987:
4988: Gforth uses an extra locals stack. It is described, along with the
4989: reasons for its existence, in @ref{Locals implementation}.
4990:
4991: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4992: @subsection Stack pointer manipulation
4993: @cindex stack pointer manipulation words
4994:
4995: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
4996: doc-sp0
4997: doc-sp@
4998: doc-sp!
4999: doc-fp0
5000: doc-fp@
5001: doc-fp!
5002: doc-rp0
5003: doc-rp@
5004: doc-rp!
5005: doc-lp0
5006: doc-lp@
5007: doc-lp!
5008:
5009:
5010: @node Memory, Control Structures, Stack Manipulation, Words
5011: @section Memory
5012: @cindex memory words
5013:
5014: @menu
5015: * Memory model::
5016: * Dictionary allocation::
5017: * Heap Allocation::
5018: * Memory Access::
5019: * Address arithmetic::
5020: * Memory Blocks::
5021: @end menu
5022:
5023: In addition to the standard Forth memory allocation words, there is also
5024: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
5025: garbage collector}.
5026:
5027: @node Memory model, Dictionary allocation, Memory, Memory
5028: @subsection ANS Forth and Gforth memory models
5029:
5030: @c The ANS Forth description is a mess (e.g., is the heap part of
5031: @c the dictionary?), so let's not stick to closely with it.
5032:
5033: ANS Forth considers a Forth system as consisting of several address
5034: spaces, of which only @dfn{data space} is managed and accessible with
5035: the memory words. Memory not necessarily in data space includes the
5036: stacks, the code (called code space) and the headers (called name
5037: space). In Gforth everything is in data space, but the code for the
5038: primitives is usually read-only.
5039:
5040: Data space is divided into a number of areas: The (data space portion of
5041: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
5042: refer to the search data structure embodied in word lists and headers,
5043: because it is used for looking up names, just as you would in a
5044: conventional dictionary.}, the heap, and a number of system-allocated
5045: buffers.
5046:
5047: @cindex address arithmetic restrictions, ANS vs. Gforth
5048: @cindex contiguous regions, ANS vs. Gforth
5049: In ANS Forth data space is also divided into contiguous regions. You
5050: can only use address arithmetic within a contiguous region, not between
5051: them. Usually each allocation gives you one contiguous region, but the
5052: dictionary allocation words have additional rules (@pxref{Dictionary
5053: allocation}).
5054:
5055: Gforth provides one big address space, and address arithmetic can be
5056: performed between any addresses. However, in the dictionary headers or
5057: code are interleaved with data, so almost the only contiguous data space
5058: regions there are those described by ANS Forth as contiguous; but you
5059: can be sure that the dictionary is allocated towards increasing
5060: addresses even between contiguous regions. The memory order of
5061: allocations in the heap is platform-dependent (and possibly different
5062: from one run to the next).
5063:
5064:
5065: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5066: @subsection Dictionary allocation
5067: @cindex reserving data space
5068: @cindex data space - reserving some
5069:
5070: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5071: you want to deallocate X, you also deallocate everything
5072: allocated after X.
5073:
5074: @cindex contiguous regions in dictionary allocation
5075: The allocations using the words below are contiguous and grow the region
5076: towards increasing addresses. Other words that allocate dictionary
5077: memory of any kind (i.e., defining words including @code{:noname}) end
5078: the contiguous region and start a new one.
5079:
5080: In ANS Forth only @code{create}d words are guaranteed to produce an
5081: address that is the start of the following contiguous region. In
5082: particular, the cell allocated by @code{variable} is not guaranteed to
5083: be contiguous with following @code{allot}ed memory.
5084:
5085: You can deallocate memory by using @code{allot} with a negative argument
5086: (with some restrictions, see @code{allot}). For larger deallocations use
5087: @code{marker}.
5088:
5089:
5090: doc-here
5091: doc-unused
5092: doc-allot
5093: doc-c,
5094: doc-f,
5095: doc-,
5096: doc-2,
5097:
5098: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5099: course you should allocate memory in an aligned way, too. I.e., before
5100: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5101: The words below align @code{here} if it is not already. Basically it is
5102: only already aligned for a type, if the last allocation was a multiple
5103: of the size of this type and if @code{here} was aligned for this type
5104: before.
5105:
5106: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5107: ANS Forth (@code{maxalign}ed in Gforth).
5108:
5109: doc-align
5110: doc-falign
5111: doc-sfalign
5112: doc-dfalign
5113: doc-maxalign
5114: doc-cfalign
5115:
5116:
5117: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5118: @subsection Heap allocation
5119: @cindex heap allocation
5120: @cindex dynamic allocation of memory
5121: @cindex memory-allocation word set
5122:
5123: @cindex contiguous regions and heap allocation
5124: Heap allocation supports deallocation of allocated memory in any
5125: order. Dictionary allocation is not affected by it (i.e., it does not
5126: end a contiguous region). In Gforth, these words are implemented using
5127: the standard C library calls malloc(), free() and resize().
5128:
5129: The memory region produced by one invocation of @code{allocate} or
5130: @code{resize} is internally contiguous. There is no contiguity between
5131: such a region and any other region (including others allocated from the
5132: heap).
5133:
5134: doc-allocate
5135: doc-free
5136: doc-resize
5137:
5138:
5139: @node Memory Access, Address arithmetic, Heap Allocation, Memory
5140: @subsection Memory Access
5141: @cindex memory access words
5142:
5143: doc-@
5144: doc-!
5145: doc-+!
5146: doc-c@
5147: doc-c!
5148: doc-2@
5149: doc-2!
5150: doc-f@
5151: doc-f!
5152: doc-sf@
5153: doc-sf!
5154: doc-df@
5155: doc-df!
5156: doc-sw@
5157: doc-uw@
5158: doc-w!
5159: doc-sl@
5160: doc-ul@
5161: doc-l!
5162:
5163: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5164: @subsection Address arithmetic
5165: @cindex address arithmetic words
5166:
5167: Address arithmetic is the foundation on which you can build data
5168: structures like arrays, records (@pxref{Structures}) and objects
5169: (@pxref{Object-oriented Forth}).
5170:
5171: @cindex address unit
5172: @cindex au (address unit)
5173: ANS Forth does not specify the sizes of the data types. Instead, it
5174: offers a number of words for computing sizes and doing address
5175: arithmetic. Address arithmetic is performed in terms of address units
5176: (aus); on most systems the address unit is one byte. Note that a
5177: character may have more than one au, so @code{chars} is no noop (on
5178: platforms where it is a noop, it compiles to nothing).
5179:
5180: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5181: you have the address of a cell, perform @code{1 cells +}, and you will
5182: have the address of the next cell.
5183:
5184: @cindex contiguous regions and address arithmetic
5185: In ANS Forth you can perform address arithmetic only within a contiguous
5186: region, i.e., if you have an address into one region, you can only add
5187: and subtract such that the result is still within the region; you can
5188: only subtract or compare addresses from within the same contiguous
5189: region. Reasons: several contiguous regions can be arranged in memory
5190: in any way; on segmented systems addresses may have unusual
5191: representations, such that address arithmetic only works within a
5192: region. Gforth provides a few more guarantees (linear address space,
5193: dictionary grows upwards), but in general I have found it easy to stay
5194: within contiguous regions (exception: computing and comparing to the
5195: address just beyond the end of an array).
5196:
5197: @cindex alignment of addresses for types
5198: ANS Forth also defines words for aligning addresses for specific
5199: types. Many computers require that accesses to specific data types
5200: must only occur at specific addresses; e.g., that cells may only be
5201: accessed at addresses divisible by 4. Even if a machine allows unaligned
5202: accesses, it can usually perform aligned accesses faster.
5203:
5204: For the performance-conscious: alignment operations are usually only
5205: necessary during the definition of a data structure, not during the
5206: (more frequent) accesses to it.
5207:
5208: ANS Forth defines no words for character-aligning addresses. This is not
5209: an oversight, but reflects the fact that addresses that are not
5210: char-aligned have no use in the standard and therefore will not be
5211: created.
5212:
5213: @cindex @code{CREATE} and alignment
5214: ANS Forth guarantees that addresses returned by @code{CREATE}d words
5215: are cell-aligned; in addition, Gforth guarantees that these addresses
5216: are aligned for all purposes.
5217:
5218: Note that the ANS Forth word @code{char} has nothing to do with address
5219: arithmetic.
5220:
5221:
5222: doc-chars
5223: doc-char+
5224: doc-cells
5225: doc-cell+
5226: doc-cell
5227: doc-aligned
5228: doc-floats
5229: doc-float+
5230: doc-float
5231: doc-faligned
5232: doc-sfloats
5233: doc-sfloat+
5234: doc-sfaligned
5235: doc-dfloats
5236: doc-dfloat+
5237: doc-dfaligned
5238: doc-maxaligned
5239: doc-cfaligned
5240: doc-address-unit-bits
5241: doc-/w
5242: doc-/l
5243:
5244: @node Memory Blocks, , Address arithmetic, Memory
5245: @subsection Memory Blocks
5246: @cindex memory block words
5247: @cindex character strings - moving and copying
5248:
5249: Memory blocks often represent character strings; For ways of storing
5250: character strings in memory see @ref{String Formats}. For other
5251: string-processing words see @ref{Displaying characters and strings}.
5252:
5253: A few of these words work on address unit blocks. In that case, you
5254: usually have to insert @code{CHARS} before the word when working on
5255: character strings. Most words work on character blocks, and expect a
5256: char-aligned address.
5257:
5258: When copying characters between overlapping memory regions, use
5259: @code{chars move} or choose carefully between @code{cmove} and
5260: @code{cmove>}.
5261:
5262: doc-move
5263: doc-erase
5264: doc-cmove
5265: doc-cmove>
5266: doc-fill
5267: doc-blank
5268: doc-compare
5269: doc-str=
5270: doc-str<
5271: doc-string-prefix?
5272: doc-search
5273: doc--trailing
5274: doc-/string
5275: doc-bounds
5276: doc-pad
5277:
5278: @comment TODO examples
5279:
5280:
5281: @node Control Structures, Defining Words, Memory, Words
5282: @section Control Structures
5283: @cindex control structures
5284:
5285: Control structures in Forth cannot be used interpretively, only in a
5286: colon definition@footnote{To be precise, they have no interpretation
5287: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5288: not like this limitation, but have not seen a satisfying way around it
5289: yet, although many schemes have been proposed.
5290:
5291: @menu
5292: * Selection:: IF ... ELSE ... ENDIF
5293: * Simple Loops:: BEGIN ...
5294: * Counted Loops:: DO
5295: * Arbitrary control structures::
5296: * Calls and returns::
5297: * Exception Handling::
5298: @end menu
5299:
5300: @node Selection, Simple Loops, Control Structures, Control Structures
5301: @subsection Selection
5302: @cindex selection control structures
5303: @cindex control structures for selection
5304:
5305: @cindex @code{IF} control structure
5306: @example
5307: @i{flag}
5308: IF
5309: @i{code}
5310: ENDIF
5311: @end example
5312: @noindent
5313:
5314: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5315: with any bit set represents truth) @i{code} is executed.
5316:
5317: @example
5318: @i{flag}
5319: IF
5320: @i{code1}
5321: ELSE
5322: @i{code2}
5323: ENDIF
5324: @end example
5325:
5326: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5327: executed.
5328:
5329: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5330: standard, and @code{ENDIF} is not, although it is quite popular. We
5331: recommend using @code{ENDIF}, because it is less confusing for people
5332: who also know other languages (and is not prone to reinforcing negative
5333: prejudices against Forth in these people). Adding @code{ENDIF} to a
5334: system that only supplies @code{THEN} is simple:
5335: @example
5336: : ENDIF POSTPONE then ; immediate
5337: @end example
5338:
5339: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5340: (adv.)} has the following meanings:
5341: @quotation
5342: ... 2b: following next after in order ... 3d: as a necessary consequence
5343: (if you were there, then you saw them).
5344: @end quotation
5345: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5346: and many other programming languages has the meaning 3d.]
5347:
5348: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
5349: you can avoid using @code{?dup}. Using these alternatives is also more
5350: efficient than using @code{?dup}. Definitions in ANS Forth
5351: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5352: @file{compat/control.fs}.
5353:
5354: @cindex @code{CASE} control structure
5355: @example
5356: @i{x}
5357: CASE
5358: @i{x1} OF @i{code1} ENDOF
5359: @i{x2} OF @i{code2} ENDOF
5360: @dots{}
5361: ( x ) @i{default-code} ( x )
5362: ENDCASE ( )
5363: @end example
5364:
5365: Executes the first @i{codei}, where the @i{xi} is equal to @i{x}. If no
5366: @i{xi} matches, the optional @i{default-code} is executed. The optional
5367: default case can be added by simply writing the code after the last
5368: @code{ENDOF}. It may use @i{x}, which is on top of the stack, but must
5369: not consume it. The value @i{x} is consumed by this construction
5370: (either by an @code{OF} that matches, or by the @code{ENDCASE}, if no OF
5371: matches). Example:
5372:
5373: @example
5374: : num-name ( n -- c-addr u )
5375: case
5376: 0 of s" zero " endof
5377: 1 of s" one " endof
5378: 2 of s" two " endof
5379: \ default case:
5380: s" other number"
5381: rot \ get n on top so ENDCASE can drop it
5382: endcase ;
5383: @end example
5384:
5385: @progstyle
5386: To keep the code understandable, you should ensure that you change the
5387: stack in the same way (wrt. number and types of stack items consumed
5388: and pushed) on all paths through a selection construct.
5389:
5390: @node Simple Loops, Counted Loops, Selection, Control Structures
5391: @subsection Simple Loops
5392: @cindex simple loops
5393: @cindex loops without count
5394:
5395: @cindex @code{WHILE} loop
5396: @example
5397: BEGIN
5398: @i{code1}
5399: @i{flag}
5400: WHILE
5401: @i{code2}
5402: REPEAT
5403: @end example
5404:
5405: @i{code1} is executed and @i{flag} is computed. If it is true,
5406: @i{code2} is executed and the loop is restarted; If @i{flag} is
5407: false, execution continues after the @code{REPEAT}.
5408:
5409: @cindex @code{UNTIL} loop
5410: @example
5411: BEGIN
5412: @i{code}
5413: @i{flag}
5414: UNTIL
5415: @end example
5416:
5417: @i{code} is executed. The loop is restarted if @code{flag} is false.
5418:
5419: @progstyle
5420: To keep the code understandable, a complete iteration of the loop should
5421: not change the number and types of the items on the stacks.
5422:
5423: @cindex endless loop
5424: @cindex loops, endless
5425: @example
5426: BEGIN
5427: @i{code}
5428: AGAIN
5429: @end example
5430:
5431: This is an endless loop.
5432:
5433: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5434: @subsection Counted Loops
5435: @cindex counted loops
5436: @cindex loops, counted
5437: @cindex @code{DO} loops
5438:
5439: The basic counted loop is:
5440: @example
5441: @i{limit} @i{start}
5442: ?DO
5443: @i{body}
5444: LOOP
5445: @end example
5446:
5447: This performs one iteration for every integer, starting from @i{start}
5448: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
5449: accessed with @code{i}. For example, the loop:
5450: @example
5451: 10 0 ?DO
5452: i .
5453: LOOP
5454: @end example
5455: @noindent
5456: prints @code{0 1 2 3 4 5 6 7 8 9}
5457:
5458: The index of the innermost loop can be accessed with @code{i}, the index
5459: of the next loop with @code{j}, and the index of the third loop with
5460: @code{k}.
5461:
5462:
5463: doc-i
5464: doc-j
5465: doc-k
5466:
5467:
5468: The loop control data are kept on the return stack, so there are some
5469: restrictions on mixing return stack accesses and counted loop words. In
5470: particuler, if you put values on the return stack outside the loop, you
5471: cannot read them inside the loop@footnote{well, not in a way that is
5472: portable.}. If you put values on the return stack within a loop, you
5473: have to remove them before the end of the loop and before accessing the
5474: index of the loop.
5475:
5476: There are several variations on the counted loop:
5477:
5478: @itemize @bullet
5479: @item
5480: @code{LEAVE} leaves the innermost counted loop immediately; execution
5481: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5482:
5483: @example
5484: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5485: @end example
5486: prints @code{0 1 2 3}
5487:
5488:
5489: @item
5490: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5491: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5492: return stack so @code{EXIT} can get to its return address. For example:
5493:
5494: @example
5495: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5496: @end example
5497: prints @code{0 1 2 3}
5498:
5499:
5500: @item
5501: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
5502: (and @code{LOOP} iterates until they become equal by wrap-around
5503: arithmetic). This behaviour is usually not what you want. Therefore,
5504: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
5505: @code{?DO}), which do not enter the loop if @i{start} is greater than
5506: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
5507: unsigned loop parameters.
5508:
5509: @item
5510: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5511: the loop, independent of the loop parameters. Do not use @code{DO}, even
5512: if you know that the loop is entered in any case. Such knowledge tends
5513: to become invalid during maintenance of a program, and then the
5514: @code{DO} will make trouble.
5515:
5516: @item
5517: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5518: index by @i{n} instead of by 1. The loop is terminated when the border
5519: between @i{limit-1} and @i{limit} is crossed. E.g.:
5520:
5521: @example
5522: 4 0 +DO i . 2 +LOOP
5523: @end example
5524: @noindent
5525: prints @code{0 2}
5526:
5527: @example
5528: 4 1 +DO i . 2 +LOOP
5529: @end example
5530: @noindent
5531: prints @code{1 3}
5532:
5533: @item
5534: @cindex negative increment for counted loops
5535: @cindex counted loops with negative increment
5536: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
5537:
5538: @example
5539: -1 0 ?DO i . -1 +LOOP
5540: @end example
5541: @noindent
5542: prints @code{0 -1}
5543:
5544: @example
5545: 0 0 ?DO i . -1 +LOOP
5546: @end example
5547: prints nothing.
5548:
5549: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5550: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5551: index by @i{u} each iteration. The loop is terminated when the border
5552: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
5553: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5554:
5555: @example
5556: -2 0 -DO i . 1 -LOOP
5557: @end example
5558: @noindent
5559: prints @code{0 -1}
5560:
5561: @example
5562: -1 0 -DO i . 1 -LOOP
5563: @end example
5564: @noindent
5565: prints @code{0}
5566:
5567: @example
5568: 0 0 -DO i . 1 -LOOP
5569: @end example
5570: @noindent
5571: prints nothing.
5572:
5573: @end itemize
5574:
5575: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
5576: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5577: for these words that uses only standard words is provided in
5578: @file{compat/loops.fs}.
5579:
5580:
5581: @cindex @code{FOR} loops
5582: Another counted loop is:
5583: @example
5584: @i{n}
5585: FOR
5586: @i{body}
5587: NEXT
5588: @end example
5589: This is the preferred loop of native code compiler writers who are too
5590: lazy to optimize @code{?DO} loops properly. This loop structure is not
5591: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5592: @code{i} produces values starting with @i{n} and ending with 0. Other
5593: Forth systems may behave differently, even if they support @code{FOR}
5594: loops. To avoid problems, don't use @code{FOR} loops.
5595:
5596: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5597: @subsection Arbitrary control structures
5598: @cindex control structures, user-defined
5599:
5600: @cindex control-flow stack
5601: ANS Forth permits and supports using control structures in a non-nested
5602: way. Information about incomplete control structures is stored on the
5603: control-flow stack. This stack may be implemented on the Forth data
5604: stack, and this is what we have done in Gforth.
5605:
5606: @cindex @code{orig}, control-flow stack item
5607: @cindex @code{dest}, control-flow stack item
5608: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5609: entry represents a backward branch target. A few words are the basis for
5610: building any control structure possible (except control structures that
5611: need storage, like calls, coroutines, and backtracking).
5612:
5613:
5614: doc-if
5615: doc-ahead
5616: doc-then
5617: doc-begin
5618: doc-until
5619: doc-again
5620: doc-cs-pick
5621: doc-cs-roll
5622:
5623:
5624: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5625: manipulate the control-flow stack in a portable way. Without them, you
5626: would need to know how many stack items are occupied by a control-flow
5627: entry (many systems use one cell. In Gforth they currently take three,
5628: but this may change in the future).
5629:
5630: Some standard control structure words are built from these words:
5631:
5632:
5633: doc-else
5634: doc-while
5635: doc-repeat
5636:
5637:
5638: @noindent
5639: Gforth adds some more control-structure words:
5640:
5641:
5642: doc-endif
5643: doc-?dup-if
5644: doc-?dup-0=-if
5645:
5646:
5647: @noindent
5648: Counted loop words constitute a separate group of words:
5649:
5650:
5651: doc-?do
5652: doc-+do
5653: doc-u+do
5654: doc--do
5655: doc-u-do
5656: doc-do
5657: doc-for
5658: doc-loop
5659: doc-+loop
5660: doc--loop
5661: doc-next
5662: doc-leave
5663: doc-?leave
5664: doc-unloop
5665: doc-done
5666:
5667:
5668: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5669: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
5670: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5671: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5672: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5673: resolved (by using one of the loop-ending words or @code{DONE}).
5674:
5675: @noindent
5676: Another group of control structure words are:
5677:
5678:
5679: doc-case
5680: doc-endcase
5681: doc-of
5682: doc-endof
5683:
5684:
5685: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5686: @code{CS-ROLL}.
5687:
5688: @subsubsection Programming Style
5689: @cindex control structures programming style
5690: @cindex programming style, arbitrary control structures
5691:
5692: In order to ensure readability we recommend that you do not create
5693: arbitrary control structures directly, but define new control structure
5694: words for the control structure you want and use these words in your
5695: program. For example, instead of writing:
5696:
5697: @example
5698: BEGIN
5699: ...
5700: IF [ 1 CS-ROLL ]
5701: ...
5702: AGAIN THEN
5703: @end example
5704:
5705: @noindent
5706: we recommend defining control structure words, e.g.,
5707:
5708: @example
5709: : WHILE ( DEST -- ORIG DEST )
5710: POSTPONE IF
5711: 1 CS-ROLL ; immediate
5712:
5713: : REPEAT ( orig dest -- )
5714: POSTPONE AGAIN
5715: POSTPONE THEN ; immediate
5716: @end example
5717:
5718: @noindent
5719: and then using these to create the control structure:
5720:
5721: @example
5722: BEGIN
5723: ...
5724: WHILE
5725: ...
5726: REPEAT
5727: @end example
5728:
5729: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5730: @code{WHILE} are predefined, so in this example it would not be
5731: necessary to define them.
5732:
5733: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5734: @subsection Calls and returns
5735: @cindex calling a definition
5736: @cindex returning from a definition
5737:
5738: @cindex recursive definitions
5739: A definition can be called simply be writing the name of the definition
5740: to be called. Normally a definition is invisible during its own
5741: definition. If you want to write a directly recursive definition, you
5742: can use @code{recursive} to make the current definition visible, or
5743: @code{recurse} to call the current definition directly.
5744:
5745:
5746: doc-recursive
5747: doc-recurse
5748:
5749:
5750: @comment TODO add example of the two recursion methods
5751: @quotation
5752: @progstyle
5753: I prefer using @code{recursive} to @code{recurse}, because calling the
5754: definition by name is more descriptive (if the name is well-chosen) than
5755: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5756: implementation, it is much better to read (and think) ``now sort the
5757: partitions'' than to read ``now do a recursive call''.
5758: @end quotation
5759:
5760: For mutual recursion, use @code{Defer}red words, like this:
5761:
5762: @example
5763: Defer foo
5764:
5765: : bar ( ... -- ... )
5766: ... foo ... ;
5767:
5768: :noname ( ... -- ... )
5769: ... bar ... ;
5770: IS foo
5771: @end example
5772:
5773: Deferred words are discussed in more detail in @ref{Deferred Words}.
5774:
5775: The current definition returns control to the calling definition when
5776: the end of the definition is reached or @code{EXIT} is encountered.
5777:
5778: doc-exit
5779: doc-;s
5780:
5781:
5782: @node Exception Handling, , Calls and returns, Control Structures
5783: @subsection Exception Handling
5784: @cindex exceptions
5785:
5786: @c quit is a very bad idea for error handling,
5787: @c because it does not translate into a THROW
5788: @c it also does not belong into this chapter
5789:
5790: If a word detects an error condition that it cannot handle, it can
5791: @code{throw} an exception. In the simplest case, this will terminate
5792: your program, and report an appropriate error.
5793:
5794: doc-throw
5795:
5796: @code{Throw} consumes a cell-sized error number on the stack. There are
5797: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5798: Gforth (and most other systems) you can use the iors produced by various
5799: words as error numbers (e.g., a typical use of @code{allocate} is
5800: @code{allocate throw}). Gforth also provides the word @code{exception}
5801: to define your own error numbers (with decent error reporting); an ANS
5802: Forth version of this word (but without the error messages) is available
5803: in @code{compat/except.fs}. And finally, you can use your own error
5804: numbers (anything outside the range -4095..0), but won't get nice error
5805: messages, only numbers. For example, try:
5806:
5807: @example
5808: -10 throw \ ANS defined
5809: -267 throw \ system defined
5810: s" my error" exception throw \ user defined
5811: 7 throw \ arbitrary number
5812: @end example
5813:
5814: doc---exception-exception
5815:
5816: A common idiom to @code{THROW} a specific error if a flag is true is
5817: this:
5818:
5819: @example
5820: @code{( flag ) 0<> @i{errno} and throw}
5821: @end example
5822:
5823: Your program can provide exception handlers to catch exceptions. An
5824: exception handler can be used to correct the problem, or to clean up
5825: some data structures and just throw the exception to the next exception
5826: handler. Note that @code{throw} jumps to the dynamically innermost
5827: exception handler. The system's exception handler is outermost, and just
5828: prints an error and restarts command-line interpretation (or, in batch
5829: mode (i.e., while processing the shell command line), leaves Gforth).
5830:
5831: The ANS Forth way to catch exceptions is @code{catch}:
5832:
5833: doc-catch
5834: doc-nothrow
5835:
5836: The most common use of exception handlers is to clean up the state when
5837: an error happens. E.g.,
5838:
5839: @example
5840: base @ >r hex \ actually the hex should be inside foo, or we h
5841: ['] foo catch ( nerror|0 )
5842: r> base !
5843: ( nerror|0 ) throw \ pass it on
5844: @end example
5845:
5846: A use of @code{catch} for handling the error @code{myerror} might look
5847: like this:
5848:
5849: @example
5850: ['] foo catch
5851: CASE
5852: myerror OF ... ( do something about it ) nothrow ENDOF
5853: dup throw \ default: pass other errors on, do nothing on non-errors
5854: ENDCASE
5855: @end example
5856:
5857: Having to wrap the code into a separate word is often cumbersome,
5858: therefore Gforth provides an alternative syntax:
5859:
5860: @example
5861: TRY
5862: @i{code1}
5863: IFERROR
5864: @i{code2}
5865: THEN
5866: @i{code3}
5867: ENDTRY
5868: @end example
5869:
5870: This performs @i{code1}. If @i{code1} completes normally, execution
5871: continues with @i{code3}. If there is an exception in @i{code1} or
5872: before @code{endtry}, the stacks are reset to the depth during
5873: @code{try}, the throw value is pushed on the data stack, and execution
5874: constinues at @i{code2}, and finally falls through to @i{code3}.
5875:
5876: doc-try
5877: doc-endtry
5878: doc-iferror
5879:
5880: If you don't need @i{code2}, you can write @code{restore} instead of
5881: @code{iferror then}:
5882:
5883: @example
5884: TRY
5885: @i{code1}
5886: RESTORE
5887: @i{code3}
5888: ENDTRY
5889: @end example
5890:
5891: @cindex unwind-protect
5892: The cleanup example from above in this syntax:
5893:
5894: @example
5895: base @@ @{ oldbase @}
5896: TRY
5897: hex foo \ now the hex is placed correctly
5898: 0 \ value for throw
5899: RESTORE
5900: oldbase base !
5901: ENDTRY
5902: throw
5903: @end example
5904:
5905: An additional advantage of this variant is that an exception between
5906: @code{restore} and @code{endtry} (e.g., from the user pressing
5907: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
5908: so the base will be restored under all circumstances.
5909:
5910: However, you have to ensure that this code does not cause an exception
5911: itself, otherwise the @code{iferror}/@code{restore} code will loop.
5912: Moreover, you should also make sure that the stack contents needed by
5913: the @code{iferror}/@code{restore} code exist everywhere between
5914: @code{try} and @code{endtry}; in our example this is achived by
5915: putting the data in a local before the @code{try} (you cannot use the
5916: return stack because the exception frame (@i{sys1}) is in the way
5917: there).
5918:
5919: This kind of usage corresponds to Lisp's @code{unwind-protect}.
5920:
5921: @cindex @code{recover} (old Gforth versions)
5922: If you do not want this exception-restarting behaviour, you achieve
5923: this as follows:
5924:
5925: @example
5926: TRY
5927: @i{code1}
5928: ENDTRY-IFERROR
5929: @i{code2}
5930: THEN
5931: @end example
5932:
5933: If there is an exception in @i{code1}, then @i{code2} is executed,
5934: otherwise execution continues behind the @code{then} (or in a possible
5935: @code{else} branch). This corresponds to the construct
5936:
5937: @example
5938: TRY
5939: @i{code1}
5940: RECOVER
5941: @i{code2}
5942: ENDTRY
5943: @end example
5944:
5945: in Gforth before version 0.7. So you can directly replace
5946: @code{recover}-using code; however, we recommend that you check if it
5947: would not be better to use one of the other @code{try} variants while
5948: you are at it.
5949:
5950: To ease the transition, Gforth provides two compatibility files:
5951: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
5952: ... then} syntax (but not @code{iferror} or @code{restore}) for old
5953: systems; @file{recover-endtry.fs} provides the @code{try ... recover
5954: ... endtry} syntax on new systems, so you can use that file as a
5955: stopgap to run old programs. Both files work on any system (they just
5956: do nothing if the system already has the syntax it implements), so you
5957: can unconditionally @code{require} one of these files, even if you use
5958: a mix old and new systems.
5959:
5960: doc-restore
5961: doc-endtry-iferror
5962:
5963: Here's the error handling example:
5964:
5965: @example
5966: TRY
5967: foo
5968: ENDTRY-IFERROR
5969: CASE
5970: myerror OF ... ( do something about it ) nothrow ENDOF
5971: throw \ pass other errors on
5972: ENDCASE
5973: THEN
5974: @end example
5975:
5976: @progstyle
5977: As usual, you should ensure that the stack depth is statically known at
5978: the end: either after the @code{throw} for passing on errors, or after
5979: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5980: selection construct for handling the error).
5981:
5982: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5983: and you can provide an error message. @code{Abort} just produces an
5984: ``Aborted'' error.
5985:
5986: The problem with these words is that exception handlers cannot
5987: differentiate between different @code{abort"}s; they just look like
5988: @code{-2 throw} to them (the error message cannot be accessed by
5989: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5990: exception handlers.
5991:
5992: doc-abort"
5993: doc-abort
5994:
5995:
5996:
5997: @c -------------------------------------------------------------
5998: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
5999: @section Defining Words
6000: @cindex defining words
6001:
6002: Defining words are used to extend Forth by creating new entries in the dictionary.
6003:
6004: @menu
6005: * CREATE::
6006: * Variables:: Variables and user variables
6007: * Constants::
6008: * Values:: Initialised variables
6009: * Colon Definitions::
6010: * Anonymous Definitions:: Definitions without names
6011: * Supplying names:: Passing definition names as strings
6012: * User-defined Defining Words::
6013: * Deferred Words:: Allow forward references
6014: * Aliases::
6015: @end menu
6016:
6017: @node CREATE, Variables, Defining Words, Defining Words
6018: @subsection @code{CREATE}
6019: @cindex simple defining words
6020: @cindex defining words, simple
6021:
6022: Defining words are used to create new entries in the dictionary. The
6023: simplest defining word is @code{CREATE}. @code{CREATE} is used like
6024: this:
6025:
6026: @example
6027: CREATE new-word1
6028: @end example
6029:
6030: @code{CREATE} is a parsing word, i.e., it takes an argument from the
6031: input stream (@code{new-word1} in our example). It generates a
6032: dictionary entry for @code{new-word1}. When @code{new-word1} is
6033: executed, all that it does is leave an address on the stack. The address
6034: represents the value of the data space pointer (@code{HERE}) at the time
6035: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
6036: associating a name with the address of a region of memory.
6037:
6038: doc-create
6039:
6040: Note that in ANS Forth guarantees only for @code{create} that its body
6041: is in dictionary data space (i.e., where @code{here}, @code{allot}
6042: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
6043: @code{create}d words can be modified with @code{does>}
6044: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
6045: can only be applied to @code{create}d words.
6046:
6047: By extending this example to reserve some memory in data space, we end
6048: up with something like a @i{variable}. Here are two different ways to do
6049: it:
6050:
6051: @example
6052: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
6053: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
6054: @end example
6055:
6056: The variable can be examined and modified using @code{@@} (``fetch'') and
6057: @code{!} (``store'') like this:
6058:
6059: @example
6060: new-word2 @@ . \ get address, fetch from it and display
6061: 1234 new-word2 ! \ new value, get address, store to it
6062: @end example
6063:
6064: @cindex arrays
6065: A similar mechanism can be used to create arrays. For example, an
6066: 80-character text input buffer:
6067:
6068: @example
6069: CREATE text-buf 80 chars allot
6070:
6071: text-buf 0 chars + c@@ \ the 1st character (offset 0)
6072: text-buf 3 chars + c@@ \ the 4th character (offset 3)
6073: @end example
6074:
6075: You can build arbitrarily complex data structures by allocating
6076: appropriate areas of memory. For further discussions of this, and to
6077: learn about some Gforth tools that make it easier,
6078: @xref{Structures}.
6079:
6080:
6081: @node Variables, Constants, CREATE, Defining Words
6082: @subsection Variables
6083: @cindex variables
6084:
6085: The previous section showed how a sequence of commands could be used to
6086: generate a variable. As a final refinement, the whole code sequence can
6087: be wrapped up in a defining word (pre-empting the subject of the next
6088: section), making it easier to create new variables:
6089:
6090: @example
6091: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
6092: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
6093:
6094: myvariableX foo \ variable foo starts off with an unknown value
6095: myvariable0 joe \ whilst joe is initialised to 0
6096:
6097: 45 3 * foo ! \ set foo to 135
6098: 1234 joe ! \ set joe to 1234
6099: 3 joe +! \ increment joe by 3.. to 1237
6100: @end example
6101:
6102: Not surprisingly, there is no need to define @code{myvariable}, since
6103: Forth already has a definition @code{Variable}. ANS Forth does not
6104: guarantee that a @code{Variable} is initialised when it is created
6105: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
6106: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
6107: like @code{myvariable0}). Forth also provides @code{2Variable} and
6108: @code{fvariable} for double and floating-point variables, respectively
6109: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
6110: store a boolean, you can use @code{on} and @code{off} to toggle its
6111: state.
6112:
6113: doc-variable
6114: doc-2variable
6115: doc-fvariable
6116:
6117: @cindex user variables
6118: @cindex user space
6119: The defining word @code{User} behaves in the same way as @code{Variable}.
6120: The difference is that it reserves space in @i{user (data) space} rather
6121: than normal data space. In a Forth system that has a multi-tasker, each
6122: task has its own set of user variables.
6123:
6124: doc-user
6125: @c doc-udp
6126: @c doc-uallot
6127:
6128: @comment TODO is that stuff about user variables strictly correct? Is it
6129: @comment just terminal tasks that have user variables?
6130: @comment should document tasker.fs (with some examples) elsewhere
6131: @comment in this manual, then expand on user space and user variables.
6132:
6133: @node Constants, Values, Variables, Defining Words
6134: @subsection Constants
6135: @cindex constants
6136:
6137: @code{Constant} allows you to declare a fixed value and refer to it by
6138: name. For example:
6139:
6140: @example
6141: 12 Constant INCHES-PER-FOOT
6142: 3E+08 fconstant SPEED-O-LIGHT
6143: @end example
6144:
6145: A @code{Variable} can be both read and written, so its run-time
6146: behaviour is to supply an address through which its current value can be
6147: manipulated. In contrast, the value of a @code{Constant} cannot be
6148: changed once it has been declared@footnote{Well, often it can be -- but
6149: not in a Standard, portable way. It's safer to use a @code{Value} (read
6150: on).} so it's not necessary to supply the address -- it is more
6151: efficient to return the value of the constant directly. That's exactly
6152: what happens; the run-time effect of a constant is to put its value on
6153: the top of the stack (You can find one
6154: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
6155:
6156: Forth also provides @code{2Constant} and @code{fconstant} for defining
6157: double and floating-point constants, respectively.
6158:
6159: doc-constant
6160: doc-2constant
6161: doc-fconstant
6162:
6163: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
6164: @c nac-> How could that not be true in an ANS Forth? You can't define a
6165: @c constant, use it and then delete the definition of the constant..
6166:
6167: @c anton->An ANS Forth system can compile a constant to a literal; On
6168: @c decompilation you would see only the number, just as if it had been used
6169: @c in the first place. The word will stay, of course, but it will only be
6170: @c used by the text interpreter (no run-time duties, except when it is
6171: @c POSTPONEd or somesuch).
6172:
6173: @c nac:
6174: @c I agree that it's rather deep, but IMO it is an important difference
6175: @c relative to other programming languages.. often it's annoying: it
6176: @c certainly changes my programming style relative to C.
6177:
6178: @c anton: In what way?
6179:
6180: Constants in Forth behave differently from their equivalents in other
6181: programming languages. In other languages, a constant (such as an EQU in
6182: assembler or a #define in C) only exists at compile-time; in the
6183: executable program the constant has been translated into an absolute
6184: number and, unless you are using a symbolic debugger, it's impossible to
6185: know what abstract thing that number represents. In Forth a constant has
6186: an entry in the header space and remains there after the code that uses
6187: it has been defined. In fact, it must remain in the dictionary since it
6188: has run-time duties to perform. For example:
6189:
6190: @example
6191: 12 Constant INCHES-PER-FOOT
6192: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6193: @end example
6194:
6195: @cindex in-lining of constants
6196: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6197: associated with the constant @code{INCHES-PER-FOOT}. If you use
6198: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6199: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6200: attempt to optimise constants by in-lining them where they are used. You
6201: can force Gforth to in-line a constant like this:
6202:
6203: @example
6204: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6205: @end example
6206:
6207: If you use @code{see} to decompile @i{this} version of
6208: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
6209: longer present. To understand how this works, read
6210: @ref{Interpret/Compile states}, and @ref{Literals}.
6211:
6212: In-lining constants in this way might improve execution time
6213: fractionally, and can ensure that a constant is now only referenced at
6214: compile-time. However, the definition of the constant still remains in
6215: the dictionary. Some Forth compilers provide a mechanism for controlling
6216: a second dictionary for holding transient words such that this second
6217: dictionary can be deleted later in order to recover memory
6218: space. However, there is no standard way of doing this.
6219:
6220:
6221: @node Values, Colon Definitions, Constants, Defining Words
6222: @subsection Values
6223: @cindex values
6224:
6225: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6226: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6227: (not in ANS Forth) you can access (and change) a @code{value} also with
6228: @code{>body}.
6229:
6230: Here are some
6231: examples:
6232:
6233: @example
6234: 12 Value APPLES \ Define APPLES with an initial value of 12
6235: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6236: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6237: APPLES \ puts 35 on the top of the stack.
6238: @end example
6239:
6240: doc-value
6241: doc-to
6242:
6243:
6244:
6245: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6246: @subsection Colon Definitions
6247: @cindex colon definitions
6248:
6249: @example
6250: : name ( ... -- ... )
6251: word1 word2 word3 ;
6252: @end example
6253:
6254: @noindent
6255: Creates a word called @code{name} that, upon execution, executes
6256: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
6257:
6258: The explanation above is somewhat superficial. For simple examples of
6259: colon definitions see @ref{Your first definition}. For an in-depth
6260: discussion of some of the issues involved, @xref{Interpretation and
6261: Compilation Semantics}.
6262:
6263: doc-:
6264: doc-;
6265:
6266:
6267: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
6268: @subsection Anonymous Definitions
6269: @cindex colon definitions
6270: @cindex defining words without name
6271:
6272: Sometimes you want to define an @dfn{anonymous word}; a word without a
6273: name. You can do this with:
6274:
6275: doc-:noname
6276:
6277: This leaves the execution token for the word on the stack after the
6278: closing @code{;}. Here's an example in which a deferred word is
6279: initialised with an @code{xt} from an anonymous colon definition:
6280:
6281: @example
6282: Defer deferred
6283: :noname ( ... -- ... )
6284: ... ;
6285: IS deferred
6286: @end example
6287:
6288: @noindent
6289: Gforth provides an alternative way of doing this, using two separate
6290: words:
6291:
6292: doc-noname
6293: @cindex execution token of last defined word
6294: doc-latestxt
6295:
6296: @noindent
6297: The previous example can be rewritten using @code{noname} and
6298: @code{latestxt}:
6299:
6300: @example
6301: Defer deferred
6302: noname : ( ... -- ... )
6303: ... ;
6304: latestxt IS deferred
6305: @end example
6306:
6307: @noindent
6308: @code{noname} works with any defining word, not just @code{:}.
6309:
6310: @code{latestxt} also works when the last word was not defined as
6311: @code{noname}. It does not work for combined words, though. It also has
6312: the useful property that is is valid as soon as the header for a
6313: definition has been built. Thus:
6314:
6315: @example
6316: latestxt . : foo [ latestxt . ] ; ' foo .
6317: @end example
6318:
6319: @noindent
6320: prints 3 numbers; the last two are the same.
6321:
6322: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6323: @subsection Supplying the name of a defined word
6324: @cindex names for defined words
6325: @cindex defining words, name given in a string
6326:
6327: By default, a defining word takes the name for the defined word from the
6328: input stream. Sometimes you want to supply the name from a string. You
6329: can do this with:
6330:
6331: doc-nextname
6332:
6333: For example:
6334:
6335: @example
6336: s" foo" nextname create
6337: @end example
6338:
6339: @noindent
6340: is equivalent to:
6341:
6342: @example
6343: create foo
6344: @end example
6345:
6346: @noindent
6347: @code{nextname} works with any defining word.
6348:
6349:
6350: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
6351: @subsection User-defined Defining Words
6352: @cindex user-defined defining words
6353: @cindex defining words, user-defined
6354:
6355: You can create a new defining word by wrapping defining-time code around
6356: an existing defining word and putting the sequence in a colon
6357: definition.
6358:
6359: @c anton: This example is very complex and leads in a quite different
6360: @c direction from the CREATE-DOES> stuff that follows. It should probably
6361: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6362: @c subsection of Defining Words)
6363:
6364: For example, suppose that you have a word @code{stats} that
6365: gathers statistics about colon definitions given the @i{xt} of the
6366: definition, and you want every colon definition in your application to
6367: make a call to @code{stats}. You can define and use a new version of
6368: @code{:} like this:
6369:
6370: @example
6371: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6372: ... ; \ other code
6373:
6374: : my: : latestxt postpone literal ['] stats compile, ;
6375:
6376: my: foo + - ;
6377: @end example
6378:
6379: When @code{foo} is defined using @code{my:} these steps occur:
6380:
6381: @itemize @bullet
6382: @item
6383: @code{my:} is executed.
6384: @item
6385: The @code{:} within the definition (the one between @code{my:} and
6386: @code{latestxt}) is executed, and does just what it always does; it parses
6387: the input stream for a name, builds a dictionary header for the name
6388: @code{foo} and switches @code{state} from interpret to compile.
6389: @item
6390: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
6391: being defined -- @code{foo} -- onto the stack.
6392: @item
6393: The code that was produced by @code{postpone literal} is executed; this
6394: causes the value on the stack to be compiled as a literal in the code
6395: area of @code{foo}.
6396: @item
6397: The code @code{['] stats} compiles a literal into the definition of
6398: @code{my:}. When @code{compile,} is executed, that literal -- the
6399: execution token for @code{stats} -- is layed down in the code area of
6400: @code{foo} , following the literal@footnote{Strictly speaking, the
6401: mechanism that @code{compile,} uses to convert an @i{xt} into something
6402: in the code area is implementation-dependent. A threaded implementation
6403: might spit out the execution token directly whilst another
6404: implementation might spit out a native code sequence.}.
6405: @item
6406: At this point, the execution of @code{my:} is complete, and control
6407: returns to the text interpreter. The text interpreter is in compile
6408: state, so subsequent text @code{+ -} is compiled into the definition of
6409: @code{foo} and the @code{;} terminates the definition as always.
6410: @end itemize
6411:
6412: You can use @code{see} to decompile a word that was defined using
6413: @code{my:} and see how it is different from a normal @code{:}
6414: definition. For example:
6415:
6416: @example
6417: : bar + - ; \ like foo but using : rather than my:
6418: see bar
6419: : bar
6420: + - ;
6421: see foo
6422: : foo
6423: 107645672 stats + - ;
6424:
6425: \ use ' foo . to show that 107645672 is the xt for foo
6426: @end example
6427:
6428: You can use techniques like this to make new defining words in terms of
6429: @i{any} existing defining word.
6430:
6431:
6432: @cindex defining defining words
6433: @cindex @code{CREATE} ... @code{DOES>}
6434: If you want the words defined with your defining words to behave
6435: differently from words defined with standard defining words, you can
6436: write your defining word like this:
6437:
6438: @example
6439: : def-word ( "name" -- )
6440: CREATE @i{code1}
6441: DOES> ( ... -- ... )
6442: @i{code2} ;
6443:
6444: def-word name
6445: @end example
6446:
6447: @cindex child words
6448: This fragment defines a @dfn{defining word} @code{def-word} and then
6449: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6450: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6451: is not executed at this time. The word @code{name} is sometimes called a
6452: @dfn{child} of @code{def-word}.
6453:
6454: When you execute @code{name}, the address of the body of @code{name} is
6455: put on the data stack and @i{code2} is executed (the address of the body
6456: of @code{name} is the address @code{HERE} returns immediately after the
6457: @code{CREATE}, i.e., the address a @code{create}d word returns by
6458: default).
6459:
6460: @c anton:
6461: @c www.dictionary.com says:
6462: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6463: @c several generations of absence, usually caused by the chance
6464: @c recombination of genes. 2.An individual or a part that exhibits
6465: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6466: @c of previous behavior after a period of absence.
6467: @c
6468: @c Doesn't seem to fit.
6469:
6470: @c @cindex atavism in child words
6471: You can use @code{def-word} to define a set of child words that behave
6472: similarly; they all have a common run-time behaviour determined by
6473: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6474: body of the child word. The structure of the data is common to all
6475: children of @code{def-word}, but the data values are specific -- and
6476: private -- to each child word. When a child word is executed, the
6477: address of its private data area is passed as a parameter on TOS to be
6478: used and manipulated@footnote{It is legitimate both to read and write to
6479: this data area.} by @i{code2}.
6480:
6481: The two fragments of code that make up the defining words act (are
6482: executed) at two completely separate times:
6483:
6484: @itemize @bullet
6485: @item
6486: At @i{define time}, the defining word executes @i{code1} to generate a
6487: child word
6488: @item
6489: At @i{child execution time}, when a child word is invoked, @i{code2}
6490: is executed, using parameters (data) that are private and specific to
6491: the child word.
6492: @end itemize
6493:
6494: Another way of understanding the behaviour of @code{def-word} and
6495: @code{name} is to say that, if you make the following definitions:
6496: @example
6497: : def-word1 ( "name" -- )
6498: CREATE @i{code1} ;
6499:
6500: : action1 ( ... -- ... )
6501: @i{code2} ;
6502:
6503: def-word1 name1
6504: @end example
6505:
6506: @noindent
6507: Then using @code{name1 action1} is equivalent to using @code{name}.
6508:
6509: The classic example is that you can define @code{CONSTANT} in this way:
6510:
6511: @example
6512: : CONSTANT ( w "name" -- )
6513: CREATE ,
6514: DOES> ( -- w )
6515: @@ ;
6516: @end example
6517:
6518: @comment There is a beautiful description of how this works and what
6519: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6520: @comment commentary on the Counting Fruits problem.
6521:
6522: When you create a constant with @code{5 CONSTANT five}, a set of
6523: define-time actions take place; first a new word @code{five} is created,
6524: then the value 5 is laid down in the body of @code{five} with
6525: @code{,}. When @code{five} is executed, the address of the body is put on
6526: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6527: no code of its own; it simply contains a data field and a pointer to the
6528: code that follows @code{DOES>} in its defining word. That makes words
6529: created in this way very compact.
6530:
6531: The final example in this section is intended to remind you that space
6532: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6533: both read and written by a Standard program@footnote{Exercise: use this
6534: example as a starting point for your own implementation of @code{Value}
6535: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6536: @code{[']}.}:
6537:
6538: @example
6539: : foo ( "name" -- )
6540: CREATE -1 ,
6541: DOES> ( -- )
6542: @@ . ;
6543:
6544: foo first-word
6545: foo second-word
6546:
6547: 123 ' first-word >BODY !
6548: @end example
6549:
6550: If @code{first-word} had been a @code{CREATE}d word, we could simply
6551: have executed it to get the address of its data field. However, since it
6552: was defined to have @code{DOES>} actions, its execution semantics are to
6553: perform those @code{DOES>} actions. To get the address of its data field
6554: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6555: translate the xt into the address of the data field. When you execute
6556: @code{first-word}, it will display @code{123}. When you execute
6557: @code{second-word} it will display @code{-1}.
6558:
6559: @cindex stack effect of @code{DOES>}-parts
6560: @cindex @code{DOES>}-parts, stack effect
6561: In the examples above the stack comment after the @code{DOES>} specifies
6562: the stack effect of the defined words, not the stack effect of the
6563: following code (the following code expects the address of the body on
6564: the top of stack, which is not reflected in the stack comment). This is
6565: the convention that I use and recommend (it clashes a bit with using
6566: locals declarations for stack effect specification, though).
6567:
6568: @menu
6569: * CREATE..DOES> applications::
6570: * CREATE..DOES> details::
6571: * Advanced does> usage example::
6572: * Const-does>::
6573: @end menu
6574:
6575: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
6576: @subsubsection Applications of @code{CREATE..DOES>}
6577: @cindex @code{CREATE} ... @code{DOES>}, applications
6578:
6579: You may wonder how to use this feature. Here are some usage patterns:
6580:
6581: @cindex factoring similar colon definitions
6582: When you see a sequence of code occurring several times, and you can
6583: identify a meaning, you will factor it out as a colon definition. When
6584: you see similar colon definitions, you can factor them using
6585: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6586: that look very similar:
6587: @example
6588: : ori, ( reg-target reg-source n -- )
6589: 0 asm-reg-reg-imm ;
6590: : andi, ( reg-target reg-source n -- )
6591: 1 asm-reg-reg-imm ;
6592: @end example
6593:
6594: @noindent
6595: This could be factored with:
6596: @example
6597: : reg-reg-imm ( op-code -- )
6598: CREATE ,
6599: DOES> ( reg-target reg-source n -- )
6600: @@ asm-reg-reg-imm ;
6601:
6602: 0 reg-reg-imm ori,
6603: 1 reg-reg-imm andi,
6604: @end example
6605:
6606: @cindex currying
6607: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6608: supply a part of the parameters for a word (known as @dfn{currying} in
6609: the functional language community). E.g., @code{+} needs two
6610: parameters. Creating versions of @code{+} with one parameter fixed can
6611: be done like this:
6612:
6613: @example
6614: : curry+ ( n1 "name" -- )
6615: CREATE ,
6616: DOES> ( n2 -- n1+n2 )
6617: @@ + ;
6618:
6619: 3 curry+ 3+
6620: -2 curry+ 2-
6621: @end example
6622:
6623:
6624: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
6625: @subsubsection The gory details of @code{CREATE..DOES>}
6626: @cindex @code{CREATE} ... @code{DOES>}, details
6627:
6628: doc-does>
6629:
6630: @cindex @code{DOES>} in a separate definition
6631: This means that you need not use @code{CREATE} and @code{DOES>} in the
6632: same definition; you can put the @code{DOES>}-part in a separate
6633: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
6634: @example
6635: : does1
6636: DOES> ( ... -- ... )
6637: ... ;
6638:
6639: : does2
6640: DOES> ( ... -- ... )
6641: ... ;
6642:
6643: : def-word ( ... -- ... )
6644: create ...
6645: IF
6646: does1
6647: ELSE
6648: does2
6649: ENDIF ;
6650: @end example
6651:
6652: In this example, the selection of whether to use @code{does1} or
6653: @code{does2} is made at definition-time; at the time that the child word is
6654: @code{CREATE}d.
6655:
6656: @cindex @code{DOES>} in interpretation state
6657: In a standard program you can apply a @code{DOES>}-part only if the last
6658: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6659: will override the behaviour of the last word defined in any case. In a
6660: standard program, you can use @code{DOES>} only in a colon
6661: definition. In Gforth, you can also use it in interpretation state, in a
6662: kind of one-shot mode; for example:
6663: @example
6664: CREATE name ( ... -- ... )
6665: @i{initialization}
6666: DOES>
6667: @i{code} ;
6668: @end example
6669:
6670: @noindent
6671: is equivalent to the standard:
6672: @example
6673: :noname
6674: DOES>
6675: @i{code} ;
6676: CREATE name EXECUTE ( ... -- ... )
6677: @i{initialization}
6678: @end example
6679:
6680: doc->body
6681:
6682: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
6683: @subsubsection Advanced does> usage example
6684:
6685: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6686: for disassembling instructions, that follow a very repetetive scheme:
6687:
6688: @example
6689: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6690: @var{entry-num} cells @var{table} + !
6691: @end example
6692:
6693: Of course, this inspires the idea to factor out the commonalities to
6694: allow a definition like
6695:
6696: @example
6697: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6698: @end example
6699:
6700: The parameters @var{disasm-operands} and @var{table} are usually
6701: correlated. Moreover, before I wrote the disassembler, there already
6702: existed code that defines instructions like this:
6703:
6704: @example
6705: @var{entry-num} @var{inst-format} @var{inst-name}
6706: @end example
6707:
6708: This code comes from the assembler and resides in
6709: @file{arch/mips/insts.fs}.
6710:
6711: So I had to define the @var{inst-format} words that performed the scheme
6712: above when executed. At first I chose to use run-time code-generation:
6713:
6714: @example
6715: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6716: :noname Postpone @var{disasm-operands}
6717: name Postpone sliteral Postpone type Postpone ;
6718: swap cells @var{table} + ! ;
6719: @end example
6720:
6721: Note that this supplies the other two parameters of the scheme above.
6722:
6723: An alternative would have been to write this using
6724: @code{create}/@code{does>}:
6725:
6726: @example
6727: : @var{inst-format} ( entry-num "name" -- )
6728: here name string, ( entry-num c-addr ) \ parse and save "name"
6729: noname create , ( entry-num )
6730: latestxt swap cells @var{table} + !
6731: does> ( addr w -- )
6732: \ disassemble instruction w at addr
6733: @@ >r
6734: @var{disasm-operands}
6735: r> count type ;
6736: @end example
6737:
6738: Somehow the first solution is simpler, mainly because it's simpler to
6739: shift a string from definition-time to use-time with @code{sliteral}
6740: than with @code{string,} and friends.
6741:
6742: I wrote a lot of words following this scheme and soon thought about
6743: factoring out the commonalities among them. Note that this uses a
6744: two-level defining word, i.e., a word that defines ordinary defining
6745: words.
6746:
6747: This time a solution involving @code{postpone} and friends seemed more
6748: difficult (try it as an exercise), so I decided to use a
6749: @code{create}/@code{does>} word; since I was already at it, I also used
6750: @code{create}/@code{does>} for the lower level (try using
6751: @code{postpone} etc. as an exercise), resulting in the following
6752: definition:
6753:
6754: @example
6755: : define-format ( disasm-xt table-xt -- )
6756: \ define an instruction format that uses disasm-xt for
6757: \ disassembling and enters the defined instructions into table
6758: \ table-xt
6759: create 2,
6760: does> ( u "inst" -- )
6761: \ defines an anonymous word for disassembling instruction inst,
6762: \ and enters it as u-th entry into table-xt
6763: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6764: noname create 2, \ define anonymous word
6765: execute latestxt swap ! \ enter xt of defined word into table-xt
6766: does> ( addr w -- )
6767: \ disassemble instruction w at addr
6768: 2@@ >r ( addr w disasm-xt R: c-addr )
6769: execute ( R: c-addr ) \ disassemble operands
6770: r> count type ; \ print name
6771: @end example
6772:
6773: Note that the tables here (in contrast to above) do the @code{cells +}
6774: by themselves (that's why you have to pass an xt). This word is used in
6775: the following way:
6776:
6777: @example
6778: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6779: @end example
6780:
6781: As shown above, the defined instruction format is then used like this:
6782:
6783: @example
6784: @var{entry-num} @var{inst-format} @var{inst-name}
6785: @end example
6786:
6787: In terms of currying, this kind of two-level defining word provides the
6788: parameters in three stages: first @var{disasm-operands} and @var{table},
6789: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6790: the instruction to be disassembled.
6791:
6792: Of course this did not quite fit all the instruction format names used
6793: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6794: the parameters into the right form.
6795:
6796: If you have trouble following this section, don't worry. First, this is
6797: involved and takes time (and probably some playing around) to
6798: understand; second, this is the first two-level
6799: @code{create}/@code{does>} word I have written in seventeen years of
6800: Forth; and if I did not have @file{insts.fs} to start with, I may well
6801: have elected to use just a one-level defining word (with some repeating
6802: of parameters when using the defining word). So it is not necessary to
6803: understand this, but it may improve your understanding of Forth.
6804:
6805:
6806: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
6807: @subsubsection @code{Const-does>}
6808:
6809: A frequent use of @code{create}...@code{does>} is for transferring some
6810: values from definition-time to run-time. Gforth supports this use with
6811:
6812: doc-const-does>
6813:
6814: A typical use of this word is:
6815:
6816: @example
6817: : curry+ ( n1 "name" -- )
6818: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6819: + ;
6820:
6821: 3 curry+ 3+
6822: @end example
6823:
6824: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6825: definition to run-time.
6826:
6827: The advantages of using @code{const-does>} are:
6828:
6829: @itemize
6830:
6831: @item
6832: You don't have to deal with storing and retrieving the values, i.e.,
6833: your program becomes more writable and readable.
6834:
6835: @item
6836: When using @code{does>}, you have to introduce a @code{@@} that cannot
6837: be optimized away (because you could change the data using
6838: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6839:
6840: @end itemize
6841:
6842: An ANS Forth implementation of @code{const-does>} is available in
6843: @file{compat/const-does.fs}.
6844:
6845:
6846: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
6847: @subsection Deferred Words
6848: @cindex deferred words
6849:
6850: The defining word @code{Defer} allows you to define a word by name
6851: without defining its behaviour; the definition of its behaviour is
6852: deferred. Here are two situation where this can be useful:
6853:
6854: @itemize @bullet
6855: @item
6856: Where you want to allow the behaviour of a word to be altered later, and
6857: for all precompiled references to the word to change when its behaviour
6858: is changed.
6859: @item
6860: For mutual recursion; @xref{Calls and returns}.
6861: @end itemize
6862:
6863: In the following example, @code{foo} always invokes the version of
6864: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6865: always invokes the version that prints ``@code{Hello}''. There is no way
6866: of getting @code{foo} to use the later version without re-ordering the
6867: source code and recompiling it.
6868:
6869: @example
6870: : greet ." Good morning" ;
6871: : foo ... greet ... ;
6872: : greet ." Hello" ;
6873: : bar ... greet ... ;
6874: @end example
6875:
6876: This problem can be solved by defining @code{greet} as a @code{Defer}red
6877: word. The behaviour of a @code{Defer}red word can be defined and
6878: redefined at any time by using @code{IS} to associate the xt of a
6879: previously-defined word with it. The previous example becomes:
6880:
6881: @example
6882: Defer greet ( -- )
6883: : foo ... greet ... ;
6884: : bar ... greet ... ;
6885: : greet1 ( -- ) ." Good morning" ;
6886: : greet2 ( -- ) ." Hello" ;
6887: ' greet2 IS greet \ make greet behave like greet2
6888: @end example
6889:
6890: @progstyle
6891: You should write a stack comment for every deferred word, and put only
6892: XTs into deferred words that conform to this stack effect. Otherwise
6893: it's too difficult to use the deferred word.
6894:
6895: A deferred word can be used to improve the statistics-gathering example
6896: from @ref{User-defined Defining Words}; rather than edit the
6897: application's source code to change every @code{:} to a @code{my:}, do
6898: this:
6899:
6900: @example
6901: : real: : ; \ retain access to the original
6902: defer : \ redefine as a deferred word
6903: ' my: IS : \ use special version of :
6904: \
6905: \ load application here
6906: \
6907: ' real: IS : \ go back to the original
6908: @end example
6909:
6910:
6911: One thing to note is that @code{IS} has special compilation semantics,
6912: such that it parses the name at compile time (like @code{TO}):
6913:
6914: @example
6915: : set-greet ( xt -- )
6916: IS greet ;
6917:
6918: ' greet1 set-greet
6919: @end example
6920:
6921: In situations where @code{IS} does not fit, use @code{defer!} instead.
6922:
6923: A deferred word can only inherit execution semantics from the xt
6924: (because that is all that an xt can represent -- for more discussion of
6925: this @pxref{Tokens for Words}); by default it will have default
6926: interpretation and compilation semantics deriving from this execution
6927: semantics. However, you can change the interpretation and compilation
6928: semantics of the deferred word in the usual ways:
6929:
6930: @example
6931: : bar .... ; immediate
6932: Defer fred immediate
6933: Defer jim
6934:
6935: ' bar IS jim \ jim has default semantics
6936: ' bar IS fred \ fred is immediate
6937: @end example
6938:
6939: doc-defer
6940: doc-defer!
6941: doc-is
6942: doc-defer@
6943: doc-action-of
6944: @comment TODO document these: what's defers [is]
6945: doc-defers
6946:
6947: @c Use @code{words-deferred} to see a list of deferred words.
6948:
6949: Definitions of these words (except @code{defers}) in ANS Forth are
6950: provided in @file{compat/defer.fs}.
6951:
6952:
6953: @node Aliases, , Deferred Words, Defining Words
6954: @subsection Aliases
6955: @cindex aliases
6956:
6957: The defining word @code{Alias} allows you to define a word by name that
6958: has the same behaviour as some other word. Here are two situation where
6959: this can be useful:
6960:
6961: @itemize @bullet
6962: @item
6963: When you want access to a word's definition from a different word list
6964: (for an example of this, see the definition of the @code{Root} word list
6965: in the Gforth source).
6966: @item
6967: When you want to create a synonym; a definition that can be known by
6968: either of two names (for example, @code{THEN} and @code{ENDIF} are
6969: aliases).
6970: @end itemize
6971:
6972: Like deferred words, an alias has default compilation and interpretation
6973: semantics at the beginning (not the modifications of the other word),
6974: but you can change them in the usual ways (@code{immediate},
6975: @code{compile-only}). For example:
6976:
6977: @example
6978: : foo ... ; immediate
6979:
6980: ' foo Alias bar \ bar is not an immediate word
6981: ' foo Alias fooby immediate \ fooby is an immediate word
6982: @end example
6983:
6984: Words that are aliases have the same xt, different headers in the
6985: dictionary, and consequently different name tokens (@pxref{Tokens for
6986: Words}) and possibly different immediate flags. An alias can only have
6987: default or immediate compilation semantics; you can define aliases for
6988: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
6989:
6990: doc-alias
6991:
6992:
6993: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6994: @section Interpretation and Compilation Semantics
6995: @cindex semantics, interpretation and compilation
6996:
6997: @c !! state and ' are used without explanation
6998: @c example for immediate/compile-only? or is the tutorial enough
6999:
7000: @cindex interpretation semantics
7001: The @dfn{interpretation semantics} of a (named) word are what the text
7002: interpreter does when it encounters the word in interpret state. It also
7003: appears in some other contexts, e.g., the execution token returned by
7004: @code{' @i{word}} identifies the interpretation semantics of @i{word}
7005: (in other words, @code{' @i{word} execute} is equivalent to
7006: interpret-state text interpretation of @code{@i{word}}).
7007:
7008: @cindex compilation semantics
7009: The @dfn{compilation semantics} of a (named) word are what the text
7010: interpreter does when it encounters the word in compile state. It also
7011: appears in other contexts, e.g, @code{POSTPONE @i{word}}
7012: compiles@footnote{In standard terminology, ``appends to the current
7013: definition''.} the compilation semantics of @i{word}.
7014:
7015: @cindex execution semantics
7016: The standard also talks about @dfn{execution semantics}. They are used
7017: only for defining the interpretation and compilation semantics of many
7018: words. By default, the interpretation semantics of a word are to
7019: @code{execute} its execution semantics, and the compilation semantics of
7020: a word are to @code{compile,} its execution semantics.@footnote{In
7021: standard terminology: The default interpretation semantics are its
7022: execution semantics; the default compilation semantics are to append its
7023: execution semantics to the execution semantics of the current
7024: definition.}
7025:
7026: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
7027: the text interpreter, ticked, or @code{postpone}d, so they have no
7028: interpretation or compilation semantics. Their behaviour is represented
7029: by their XT (@pxref{Tokens for Words}), and we call it execution
7030: semantics, too.
7031:
7032: @comment TODO expand, make it co-operate with new sections on text interpreter.
7033:
7034: @cindex immediate words
7035: @cindex compile-only words
7036: You can change the semantics of the most-recently defined word:
7037:
7038:
7039: doc-immediate
7040: doc-compile-only
7041: doc-restrict
7042:
7043: By convention, words with non-default compilation semantics (e.g.,
7044: immediate words) often have names surrounded with brackets (e.g.,
7045: @code{[']}, @pxref{Execution token}).
7046:
7047: Note that ticking (@code{'}) a compile-only word gives an error
7048: (``Interpreting a compile-only word'').
7049:
7050: @menu
7051: * Combined words::
7052: @end menu
7053:
7054:
7055: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
7056: @subsection Combined Words
7057: @cindex combined words
7058:
7059: Gforth allows you to define @dfn{combined words} -- words that have an
7060: arbitrary combination of interpretation and compilation semantics.
7061:
7062: doc-interpret/compile:
7063:
7064: This feature was introduced for implementing @code{TO} and @code{S"}. I
7065: recommend that you do not define such words, as cute as they may be:
7066: they make it hard to get at both parts of the word in some contexts.
7067: E.g., assume you want to get an execution token for the compilation
7068: part. Instead, define two words, one that embodies the interpretation
7069: part, and one that embodies the compilation part. Once you have done
7070: that, you can define a combined word with @code{interpret/compile:} for
7071: the convenience of your users.
7072:
7073: You might try to use this feature to provide an optimizing
7074: implementation of the default compilation semantics of a word. For
7075: example, by defining:
7076: @example
7077: :noname
7078: foo bar ;
7079: :noname
7080: POSTPONE foo POSTPONE bar ;
7081: interpret/compile: opti-foobar
7082: @end example
7083:
7084: @noindent
7085: as an optimizing version of:
7086:
7087: @example
7088: : foobar
7089: foo bar ;
7090: @end example
7091:
7092: Unfortunately, this does not work correctly with @code{[compile]},
7093: because @code{[compile]} assumes that the compilation semantics of all
7094: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
7095: opti-foobar} would compile compilation semantics, whereas
7096: @code{[compile] foobar} would compile interpretation semantics.
7097:
7098: @cindex state-smart words (are a bad idea)
7099: @anchor{state-smartness}
7100: Some people try to use @dfn{state-smart} words to emulate the feature provided
7101: by @code{interpret/compile:} (words are state-smart if they check
7102: @code{STATE} during execution). E.g., they would try to code
7103: @code{foobar} like this:
7104:
7105: @example
7106: : foobar
7107: STATE @@
7108: IF ( compilation state )
7109: POSTPONE foo POSTPONE bar
7110: ELSE
7111: foo bar
7112: ENDIF ; immediate
7113: @end example
7114:
7115: Although this works if @code{foobar} is only processed by the text
7116: interpreter, it does not work in other contexts (like @code{'} or
7117: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
7118: for a state-smart word, not for the interpretation semantics of the
7119: original @code{foobar}; when you execute this execution token (directly
7120: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
7121: state, the result will not be what you expected (i.e., it will not
7122: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
7123: write them@footnote{For a more detailed discussion of this topic, see
7124: M. Anton Ertl,
7125: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
7126: it is Evil and How to Exorcise it}}, EuroForth '98.}!
7127:
7128: @cindex defining words with arbitrary semantics combinations
7129: It is also possible to write defining words that define words with
7130: arbitrary combinations of interpretation and compilation semantics. In
7131: general, they look like this:
7132:
7133: @example
7134: : def-word
7135: create-interpret/compile
7136: @i{code1}
7137: interpretation>
7138: @i{code2}
7139: <interpretation
7140: compilation>
7141: @i{code3}
7142: <compilation ;
7143: @end example
7144:
7145: For a @i{word} defined with @code{def-word}, the interpretation
7146: semantics are to push the address of the body of @i{word} and perform
7147: @i{code2}, and the compilation semantics are to push the address of
7148: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
7149: can also be defined like this (except that the defined constants don't
7150: behave correctly when @code{[compile]}d):
7151:
7152: @example
7153: : constant ( n "name" -- )
7154: create-interpret/compile
7155: ,
7156: interpretation> ( -- n )
7157: @@
7158: <interpretation
7159: compilation> ( compilation. -- ; run-time. -- n )
7160: @@ postpone literal
7161: <compilation ;
7162: @end example
7163:
7164:
7165: doc-create-interpret/compile
7166: doc-interpretation>
7167: doc-<interpretation
7168: doc-compilation>
7169: doc-<compilation
7170:
7171:
7172: Words defined with @code{interpret/compile:} and
7173: @code{create-interpret/compile} have an extended header structure that
7174: differs from other words; however, unless you try to access them with
7175: plain address arithmetic, you should not notice this. Words for
7176: accessing the header structure usually know how to deal with this; e.g.,
7177: @code{'} @i{word} @code{>body} also gives you the body of a word created
7178: with @code{create-interpret/compile}.
7179:
7180:
7181: @c -------------------------------------------------------------
7182: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
7183: @section Tokens for Words
7184: @cindex tokens for words
7185:
7186: This section describes the creation and use of tokens that represent
7187: words.
7188:
7189: @menu
7190: * Execution token:: represents execution/interpretation semantics
7191: * Compilation token:: represents compilation semantics
7192: * Name token:: represents named words
7193: @end menu
7194:
7195: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7196: @subsection Execution token
7197:
7198: @cindex xt
7199: @cindex execution token
7200: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7201: You can use @code{execute} to invoke this behaviour.
7202:
7203: @cindex tick (')
7204: You can use @code{'} to get an execution token that represents the
7205: interpretation semantics of a named word:
7206:
7207: @example
7208: 5 ' . ( n xt )
7209: execute ( ) \ execute the xt (i.e., ".")
7210: @end example
7211:
7212: doc-'
7213:
7214: @code{'} parses at run-time; there is also a word @code{[']} that parses
7215: when it is compiled, and compiles the resulting XT:
7216:
7217: @example
7218: : foo ['] . execute ;
7219: 5 foo
7220: : bar ' execute ; \ by contrast,
7221: 5 bar . \ ' parses "." when bar executes
7222: @end example
7223:
7224: doc-[']
7225:
7226: If you want the execution token of @i{word}, write @code{['] @i{word}}
7227: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7228: @code{'} and @code{[']} behave somewhat unusually by complaining about
7229: compile-only words (because these words have no interpretation
7230: semantics). You might get what you want by using @code{COMP' @i{word}
7231: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7232: token}).
7233:
7234: Another way to get an XT is @code{:noname} or @code{latestxt}
7235: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7236: for the only behaviour the word has (the execution semantics). For
7237: named words, @code{latestxt} produces an XT for the same behaviour it
7238: would produce if the word was defined anonymously.
7239:
7240: @example
7241: :noname ." hello" ;
7242: execute
7243: @end example
7244:
7245: An XT occupies one cell and can be manipulated like any other cell.
7246:
7247: @cindex code field address
7248: @cindex CFA
7249: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7250: operations that produce or consume it). For old hands: In Gforth, the
7251: XT is implemented as a code field address (CFA).
7252:
7253: doc-execute
7254: doc-perform
7255:
7256: @node Compilation token, Name token, Execution token, Tokens for Words
7257: @subsection Compilation token
7258:
7259: @cindex compilation token
7260: @cindex CT (compilation token)
7261: Gforth represents the compilation semantics of a named word by a
7262: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7263: @i{xt} is an execution token. The compilation semantics represented by
7264: the compilation token can be performed with @code{execute}, which
7265: consumes the whole compilation token, with an additional stack effect
7266: determined by the represented compilation semantics.
7267:
7268: At present, the @i{w} part of a compilation token is an execution token,
7269: and the @i{xt} part represents either @code{execute} or
7270: @code{compile,}@footnote{Depending upon the compilation semantics of the
7271: word. If the word has default compilation semantics, the @i{xt} will
7272: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7273: @i{xt} will represent @code{execute}.}. However, don't rely on that
7274: knowledge, unless necessary; future versions of Gforth may introduce
7275: unusual compilation tokens (e.g., a compilation token that represents
7276: the compilation semantics of a literal).
7277:
7278: You can perform the compilation semantics represented by the compilation
7279: token with @code{execute}. You can compile the compilation semantics
7280: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7281: equivalent to @code{postpone @i{word}}.
7282:
7283: doc-[comp']
7284: doc-comp'
7285: doc-postpone,
7286:
7287: @node Name token, , Compilation token, Tokens for Words
7288: @subsection Name token
7289:
7290: @cindex name token
7291: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7292: token is an abstract data type that occurs as argument or result of the
7293: words below.
7294:
7295: @c !! put this elswhere?
7296: @cindex name field address
7297: @cindex NFA
7298: The closest thing to the nt in older Forth systems is the name field
7299: address (NFA), but there are significant differences: in older Forth
7300: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7301: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7302: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7303: is a link field in the structure identified by the name token, but
7304: searching usually uses a hash table external to these structures; the
7305: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7306: implemented as the address of that count field.
7307:
7308: doc-find-name
7309: doc-latest
7310: doc->name
7311: doc-name>int
7312: doc-name?int
7313: doc-name>comp
7314: doc-name>string
7315: doc-id.
7316: doc-.name
7317: doc-.id
7318:
7319: @c ----------------------------------------------------------
7320: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7321: @section Compiling words
7322: @cindex compiling words
7323: @cindex macros
7324:
7325: In contrast to most other languages, Forth has no strict boundary
7326: between compilation and run-time. E.g., you can run arbitrary code
7327: between defining words (or for computing data used by defining words
7328: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7329: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7330: running arbitrary code while compiling a colon definition (exception:
7331: you must not allot dictionary space).
7332:
7333: @menu
7334: * Literals:: Compiling data values
7335: * Macros:: Compiling words
7336: @end menu
7337:
7338: @node Literals, Macros, Compiling words, Compiling words
7339: @subsection Literals
7340: @cindex Literals
7341:
7342: The simplest and most frequent example is to compute a literal during
7343: compilation. E.g., the following definition prints an array of strings,
7344: one string per line:
7345:
7346: @example
7347: : .strings ( addr u -- ) \ gforth
7348: 2* cells bounds U+DO
7349: cr i 2@@ type
7350: 2 cells +LOOP ;
7351: @end example
7352:
7353: With a simple-minded compiler like Gforth's, this computes @code{2
7354: cells} on every loop iteration. You can compute this value once and for
7355: all at compile time and compile it into the definition like this:
7356:
7357: @example
7358: : .strings ( addr u -- ) \ gforth
7359: 2* cells bounds U+DO
7360: cr i 2@@ type
7361: [ 2 cells ] literal +LOOP ;
7362: @end example
7363:
7364: @code{[} switches the text interpreter to interpret state (you will get
7365: an @code{ok} prompt if you type this example interactively and insert a
7366: newline between @code{[} and @code{]}), so it performs the
7367: interpretation semantics of @code{2 cells}; this computes a number.
7368: @code{]} switches the text interpreter back into compile state. It then
7369: performs @code{Literal}'s compilation semantics, which are to compile
7370: this number into the current word. You can decompile the word with
7371: @code{see .strings} to see the effect on the compiled code.
7372:
7373: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7374: *} in this way.
7375:
7376: doc-[
7377: doc-]
7378: doc-literal
7379: doc-]L
7380:
7381: There are also words for compiling other data types than single cells as
7382: literals:
7383:
7384: doc-2literal
7385: doc-fliteral
7386: doc-sliteral
7387:
7388: @cindex colon-sys, passing data across @code{:}
7389: @cindex @code{:}, passing data across
7390: You might be tempted to pass data from outside a colon definition to the
7391: inside on the data stack. This does not work, because @code{:} puhes a
7392: colon-sys, making stuff below unaccessible. E.g., this does not work:
7393:
7394: @example
7395: 5 : foo literal ; \ error: "unstructured"
7396: @end example
7397:
7398: Instead, you have to pass the value in some other way, e.g., through a
7399: variable:
7400:
7401: @example
7402: variable temp
7403: 5 temp !
7404: : foo [ temp @@ ] literal ;
7405: @end example
7406:
7407:
7408: @node Macros, , Literals, Compiling words
7409: @subsection Macros
7410: @cindex Macros
7411: @cindex compiling compilation semantics
7412:
7413: @code{Literal} and friends compile data values into the current
7414: definition. You can also write words that compile other words into the
7415: current definition. E.g.,
7416:
7417: @example
7418: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7419: POSTPONE + ;
7420:
7421: : foo ( n1 n2 -- n )
7422: [ compile-+ ] ;
7423: 1 2 foo .
7424: @end example
7425:
7426: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7427: What happens in this example? @code{Postpone} compiles the compilation
7428: semantics of @code{+} into @code{compile-+}; later the text interpreter
7429: executes @code{compile-+} and thus the compilation semantics of +, which
7430: compile (the execution semantics of) @code{+} into
7431: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7432: should only be executed in compile state, so this example is not
7433: guaranteed to work on all standard systems, but on any decent system it
7434: will work.}
7435:
7436: doc-postpone
7437:
7438: Compiling words like @code{compile-+} are usually immediate (or similar)
7439: so you do not have to switch to interpret state to execute them;
7440: modifying the last example accordingly produces:
7441:
7442: @example
7443: : [compile-+] ( compilation: --; interpretation: -- )
7444: \ compiled code: ( n1 n2 -- n )
7445: POSTPONE + ; immediate
7446:
7447: : foo ( n1 n2 -- n )
7448: [compile-+] ;
7449: 1 2 foo .
7450: @end example
7451:
7452: You will occassionally find the need to POSTPONE several words;
7453: putting POSTPONE before each such word is cumbersome, so Gforth
7454: provides a more convenient syntax: @code{]] ... [[}. This
7455: allows us to write @code{[compile-+]} as:
7456:
7457: @example
7458: : [compile-+] ( compilation: --; interpretation: -- )
7459: ]] + [[ ; immediate
7460: @end example
7461:
7462: doc-]]
7463: doc-[[
7464:
7465: The unusual direction of the brackets indicates their function:
7466: @code{]]} switches from compilation to postponing (i.e., compilation
7467: of compilation), just like @code{]} switches from immediate execution
7468: (interpretation) to compilation. Conversely, @code{[[} switches from
7469: postponing to compilation, ananlogous to @code{[} which switches from
7470: compilation to immediate execution.
7471:
7472: The real advantage of @code{]] }...@code{ [[} becomes apparent when
7473: there are many words to POSTPONE. E.g., the word
7474: @code{compile-map-array} (@pxref{Advanced macros Tutorial}) can be
7475: written much shorter as follows:
7476:
7477: @example
7478: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
7479: \ at run-time, execute xt ( ... x -- ... ) for each element of the
7480: \ array beginning at addr and containing u elements
7481: @{ xt @}
7482: ]] cells over + swap ?do
7483: i @@ [[ xt compile,
7484: 1 cells ]]L +loop [[ ;
7485: @end example
7486:
7487: This example also uses @code{]]L} as a shortcut for @code{]] literal}.
7488: There are also other shortcuts
7489:
7490: doc-]]L
7491: doc-]]2L
7492: doc-]]FL
7493: doc-]]SL
7494:
7495: Note that parsing words don't parse at postpone time; if you want to
7496: provide the parsed string right away, you have to switch back to
7497: compilation:
7498:
7499: @example
7500: ]] ... [[ s" some string" ]]2L ... [[
7501: ]] ... [[ ['] + ]]L ... [[
7502: @end example
7503:
7504: Definitions of @code{]]} and friends in ANS Forth are provided in
7505: @file{compat/macros.fs}.
7506:
7507: Immediate compiling words are similar to macros in other languages (in
7508: particular, Lisp). The important differences to macros in, e.g., C are:
7509:
7510: @itemize @bullet
7511:
7512: @item
7513: You use the same language for defining and processing macros, not a
7514: separate preprocessing language and processor.
7515:
7516: @item
7517: Consequently, the full power of Forth is available in macro definitions.
7518: E.g., you can perform arbitrarily complex computations, or generate
7519: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7520: Tutorial}). This power is very useful when writing a parser generators
7521: or other code-generating software.
7522:
7523: @item
7524: Macros defined using @code{postpone} etc. deal with the language at a
7525: higher level than strings; name binding happens at macro definition
7526: time, so you can avoid the pitfalls of name collisions that can happen
7527: in C macros. Of course, Forth is a liberal language and also allows to
7528: shoot yourself in the foot with text-interpreted macros like
7529:
7530: @example
7531: : [compile-+] s" +" evaluate ; immediate
7532: @end example
7533:
7534: Apart from binding the name at macro use time, using @code{evaluate}
7535: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7536: @end itemize
7537:
7538: You may want the macro to compile a number into a word. The word to do
7539: it is @code{literal}, but you have to @code{postpone} it, so its
7540: compilation semantics take effect when the macro is executed, not when
7541: it is compiled:
7542:
7543: @example
7544: : [compile-5] ( -- ) \ compiled code: ( -- n )
7545: 5 POSTPONE literal ; immediate
7546:
7547: : foo [compile-5] ;
7548: foo .
7549: @end example
7550:
7551: You may want to pass parameters to a macro, that the macro should
7552: compile into the current definition. If the parameter is a number, then
7553: you can use @code{postpone literal} (similar for other values).
7554:
7555: If you want to pass a word that is to be compiled, the usual way is to
7556: pass an execution token and @code{compile,} it:
7557:
7558: @example
7559: : twice1 ( xt -- ) \ compiled code: ... -- ...
7560: dup compile, compile, ;
7561:
7562: : 2+ ( n1 -- n2 )
7563: [ ' 1+ twice1 ] ;
7564: @end example
7565:
7566: doc-compile,
7567:
7568: An alternative available in Gforth, that allows you to pass compile-only
7569: words as parameters is to use the compilation token (@pxref{Compilation
7570: token}). The same example in this technique:
7571:
7572: @example
7573: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7574: 2dup 2>r execute 2r> execute ;
7575:
7576: : 2+ ( n1 -- n2 )
7577: [ comp' 1+ twice ] ;
7578: @end example
7579:
7580: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7581: works even if the executed compilation semantics has an effect on the
7582: data stack.
7583:
7584: You can also define complete definitions with these words; this provides
7585: an alternative to using @code{does>} (@pxref{User-defined Defining
7586: Words}). E.g., instead of
7587:
7588: @example
7589: : curry+ ( n1 "name" -- )
7590: CREATE ,
7591: DOES> ( n2 -- n1+n2 )
7592: @@ + ;
7593: @end example
7594:
7595: you could define
7596:
7597: @example
7598: : curry+ ( n1 "name" -- )
7599: \ name execution: ( n2 -- n1+n2 )
7600: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
7601:
7602: -3 curry+ 3-
7603: see 3-
7604: @end example
7605:
7606: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7607: colon-sys on the data stack that makes everything below it unaccessible.
7608:
7609: This way of writing defining words is sometimes more, sometimes less
7610: convenient than using @code{does>} (@pxref{Advanced does> usage
7611: example}). One advantage of this method is that it can be optimized
7612: better, because the compiler knows that the value compiled with
7613: @code{literal} is fixed, whereas the data associated with a
7614: @code{create}d word can be changed.
7615:
7616: @c doc-[compile] !! not properly documented
7617:
7618: @c ----------------------------------------------------------
7619: @node The Text Interpreter, The Input Stream, Compiling words, Words
7620: @section The Text Interpreter
7621: @cindex interpreter - outer
7622: @cindex text interpreter
7623: @cindex outer interpreter
7624:
7625: @c Should we really describe all these ugly details? IMO the text
7626: @c interpreter should be much cleaner, but that may not be possible within
7627: @c ANS Forth. - anton
7628: @c nac-> I wanted to explain how it works to show how you can exploit
7629: @c it in your own programs. When I was writing a cross-compiler, figuring out
7630: @c some of these gory details was very helpful to me. None of the textbooks
7631: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7632: @c seems to positively avoid going into too much detail for some of
7633: @c the internals.
7634:
7635: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7636: @c it is; for the ugly details, I would prefer another place. I wonder
7637: @c whether we should have a chapter before "Words" that describes some
7638: @c basic concepts referred to in words, and a chapter after "Words" that
7639: @c describes implementation details.
7640:
7641: The text interpreter@footnote{This is an expanded version of the
7642: material in @ref{Introducing the Text Interpreter}.} is an endless loop
7643: that processes input from the current input device. It is also called
7644: the outer interpreter, in contrast to the inner interpreter
7645: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7646: implementations.
7647:
7648: @cindex interpret state
7649: @cindex compile state
7650: The text interpreter operates in one of two states: @dfn{interpret
7651: state} and @dfn{compile state}. The current state is defined by the
7652: aptly-named variable @code{state}.
7653:
7654: This section starts by describing how the text interpreter behaves when
7655: it is in interpret state, processing input from the user input device --
7656: the keyboard. This is the mode that a Forth system is in after it starts
7657: up.
7658:
7659: @cindex input buffer
7660: @cindex terminal input buffer
7661: The text interpreter works from an area of memory called the @dfn{input
7662: buffer}@footnote{When the text interpreter is processing input from the
7663: keyboard, this area of memory is called the @dfn{terminal input buffer}
7664: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7665: @code{#TIB}.}, which stores your keyboard input when you press the
7666: @key{RET} key. Starting at the beginning of the input buffer, it skips
7667: leading spaces (called @dfn{delimiters}) then parses a string (a
7668: sequence of non-space characters) until it reaches either a space
7669: character or the end of the buffer. Having parsed a string, it makes two
7670: attempts to process it:
7671:
7672: @cindex dictionary
7673: @itemize @bullet
7674: @item
7675: It looks for the string in a @dfn{dictionary} of definitions. If the
7676: string is found, the string names a @dfn{definition} (also known as a
7677: @dfn{word}) and the dictionary search returns information that allows
7678: the text interpreter to perform the word's @dfn{interpretation
7679: semantics}. In most cases, this simply means that the word will be
7680: executed.
7681: @item
7682: If the string is not found in the dictionary, the text interpreter
7683: attempts to treat it as a number, using the rules described in
7684: @ref{Number Conversion}. If the string represents a legal number in the
7685: current radix, the number is pushed onto a parameter stack (the data
7686: stack for integers, the floating-point stack for floating-point
7687: numbers).
7688: @end itemize
7689:
7690: If both attempts fail, or if the word is found in the dictionary but has
7691: no interpretation semantics@footnote{This happens if the word was
7692: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7693: remainder of the input buffer, issues an error message and waits for
7694: more input. If one of the attempts succeeds, the text interpreter
7695: repeats the parsing process until the whole of the input buffer has been
7696: processed, at which point it prints the status message ``@code{ ok}''
7697: and waits for more input.
7698:
7699: @c anton: this should be in the input stream subsection (or below it)
7700:
7701: @cindex parse area
7702: The text interpreter keeps track of its position in the input buffer by
7703: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7704: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7705: of the input buffer. The region from offset @code{>IN @@} to the end of
7706: the input buffer is called the @dfn{parse area}@footnote{In other words,
7707: the text interpreter processes the contents of the input buffer by
7708: parsing strings from the parse area until the parse area is empty.}.
7709: This example shows how @code{>IN} changes as the text interpreter parses
7710: the input buffer:
7711:
7712: @example
7713: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7714: CR ." ->" TYPE ." <-" ; IMMEDIATE
7715:
7716: 1 2 3 remaining + remaining .
7717:
7718: : foo 1 2 3 remaining SWAP remaining ;
7719: @end example
7720:
7721: @noindent
7722: The result is:
7723:
7724: @example
7725: ->+ remaining .<-
7726: ->.<-5 ok
7727:
7728: ->SWAP remaining ;-<
7729: ->;<- ok
7730: @end example
7731:
7732: @cindex parsing words
7733: The value of @code{>IN} can also be modified by a word in the input
7734: buffer that is executed by the text interpreter. This means that a word
7735: can ``trick'' the text interpreter into either skipping a section of the
7736: input buffer@footnote{This is how parsing words work.} or into parsing a
7737: section twice. For example:
7738:
7739: @example
7740: : lat ." <<foo>>" ;
7741: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
7742: @end example
7743:
7744: @noindent
7745: When @code{flat} is executed, this output is produced@footnote{Exercise
7746: for the reader: what would happen if the @code{3} were replaced with
7747: @code{4}?}:
7748:
7749: @example
7750: <<bar>><<foo>>
7751: @end example
7752:
7753: This technique can be used to work around some of the interoperability
7754: problems of parsing words. Of course, it's better to avoid parsing
7755: words where possible.
7756:
7757: @noindent
7758: Two important notes about the behaviour of the text interpreter:
7759:
7760: @itemize @bullet
7761: @item
7762: It processes each input string to completion before parsing additional
7763: characters from the input buffer.
7764: @item
7765: It treats the input buffer as a read-only region (and so must your code).
7766: @end itemize
7767:
7768: @noindent
7769: When the text interpreter is in compile state, its behaviour changes in
7770: these ways:
7771:
7772: @itemize @bullet
7773: @item
7774: If a parsed string is found in the dictionary, the text interpreter will
7775: perform the word's @dfn{compilation semantics}. In most cases, this
7776: simply means that the execution semantics of the word will be appended
7777: to the current definition.
7778: @item
7779: When a number is encountered, it is compiled into the current definition
7780: (as a literal) rather than being pushed onto a parameter stack.
7781: @item
7782: If an error occurs, @code{state} is modified to put the text interpreter
7783: back into interpret state.
7784: @item
7785: Each time a line is entered from the keyboard, Gforth prints
7786: ``@code{ compiled}'' rather than `` @code{ok}''.
7787: @end itemize
7788:
7789: @cindex text interpreter - input sources
7790: When the text interpreter is using an input device other than the
7791: keyboard, its behaviour changes in these ways:
7792:
7793: @itemize @bullet
7794: @item
7795: When the parse area is empty, the text interpreter attempts to refill
7796: the input buffer from the input source. When the input source is
7797: exhausted, the input source is set back to the previous input source.
7798: @item
7799: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7800: time the parse area is emptied.
7801: @item
7802: If an error occurs, the input source is set back to the user input
7803: device.
7804: @end itemize
7805:
7806: You can read about this in more detail in @ref{Input Sources}.
7807:
7808: doc->in
7809: doc-source
7810:
7811: doc-tib
7812: doc-#tib
7813:
7814:
7815: @menu
7816: * Input Sources::
7817: * Number Conversion::
7818: * Interpret/Compile states::
7819: * Interpreter Directives::
7820: @end menu
7821:
7822: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7823: @subsection Input Sources
7824: @cindex input sources
7825: @cindex text interpreter - input sources
7826:
7827: By default, the text interpreter processes input from the user input
7828: device (the keyboard) when Forth starts up. The text interpreter can
7829: process input from any of these sources:
7830:
7831: @itemize @bullet
7832: @item
7833: The user input device -- the keyboard.
7834: @item
7835: A file, using the words described in @ref{Forth source files}.
7836: @item
7837: A block, using the words described in @ref{Blocks}.
7838: @item
7839: A text string, using @code{evaluate}.
7840: @end itemize
7841:
7842: A program can identify the current input device from the values of
7843: @code{source-id} and @code{blk}.
7844:
7845:
7846: doc-source-id
7847: doc-blk
7848:
7849: doc-save-input
7850: doc-restore-input
7851:
7852: doc-evaluate
7853: doc-query
7854:
7855:
7856:
7857: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
7858: @subsection Number Conversion
7859: @cindex number conversion
7860: @cindex double-cell numbers, input format
7861: @cindex input format for double-cell numbers
7862: @cindex single-cell numbers, input format
7863: @cindex input format for single-cell numbers
7864: @cindex floating-point numbers, input format
7865: @cindex input format for floating-point numbers
7866:
7867: This section describes the rules that the text interpreter uses when it
7868: tries to convert a string into a number.
7869:
7870: Let <digit> represent any character that is a legal digit in the current
7871: number base@footnote{For example, 0-9 when the number base is decimal or
7872: 0-9, A-F when the number base is hexadecimal.}.
7873:
7874: Let <decimal digit> represent any character in the range 0-9.
7875:
7876: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7877: in the braces (@i{a} or @i{b} or neither).
7878:
7879: Let * represent any number of instances of the previous character
7880: (including none).
7881:
7882: Let any other character represent itself.
7883:
7884: @noindent
7885: Now, the conversion rules are:
7886:
7887: @itemize @bullet
7888: @item
7889: A string of the form <digit><digit>* is treated as a single-precision
7890: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
7891: @item
7892: A string of the form -<digit><digit>* is treated as a single-precision
7893: (cell-sized) negative integer, and is represented using 2's-complement
7894: arithmetic. Examples are -45 -5681 -0
7895: @item
7896: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
7897: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7898: (all three of these represent the same number).
7899: @item
7900: A string of the form -<digit><digit>*.<digit>* is treated as a
7901: double-precision (double-cell-sized) negative integer, and is
7902: represented using 2's-complement arithmetic. Examples are -3465. -3.465
7903: -34.65 (all three of these represent the same number).
7904: @item
7905: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7906: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
7907: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
7908: number) +12.E-4
7909: @end itemize
7910:
7911: By default, the number base used for integer number conversion is
7912: given by the contents of the variable @code{base}. Note that a lot of
7913: confusion can result from unexpected values of @code{base}. If you
7914: change @code{base} anywhere, make sure to save the old value and
7915: restore it afterwards; better yet, use @code{base-execute}, which does
7916: this for you. In general I recommend keeping @code{base} decimal, and
7917: using the prefixes described below for the popular non-decimal bases.
7918:
7919: doc-dpl
7920: doc-base-execute
7921: doc-base
7922: doc-hex
7923: doc-decimal
7924:
7925: @cindex '-prefix for character strings
7926: @cindex &-prefix for decimal numbers
7927: @cindex #-prefix for decimal numbers
7928: @cindex %-prefix for binary numbers
7929: @cindex $-prefix for hexadecimal numbers
7930: @cindex 0x-prefix for hexadecimal numbers
7931: Gforth allows you to override the value of @code{base} by using a
7932: prefix@footnote{Some Forth implementations provide a similar scheme by
7933: implementing @code{$} etc. as parsing words that process the subsequent
7934: number in the input stream and push it onto the stack. For example, see
7935: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7936: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7937: is required between the prefix and the number.} before the first digit
7938: of an (integer) number. The following prefixes are supported:
7939:
7940: @itemize @bullet
7941: @item
7942: @code{&} -- decimal
7943: @item
7944: @code{#} -- decimal
7945: @item
7946: @code{%} -- binary
7947: @item
7948: @code{$} -- hexadecimal
7949: @item
7950: @code{0x} -- hexadecimal, if base<33.
7951: @item
7952: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7953: optional @code{'} may be present after the character.
7954: @end itemize
7955:
7956: Here are some examples, with the equivalent decimal number shown after
7957: in braces:
7958:
7959: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
7960: 'A (65),
7961: -'a' (-97),
7962: &905 (905), $abc (2478), $ABC (2478).
7963:
7964: @cindex number conversion - traps for the unwary
7965: @noindent
7966: Number conversion has a number of traps for the unwary:
7967:
7968: @itemize @bullet
7969: @item
7970: You cannot determine the current number base using the code sequence
7971: @code{base @@ .} -- the number base is always 10 in the current number
7972: base. Instead, use something like @code{base @@ dec.}
7973: @item
7974: If the number base is set to a value greater than 14 (for example,
7975: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7976: it to be intepreted as either a single-precision integer or a
7977: floating-point number (Gforth treats it as an integer). The ambiguity
7978: can be resolved by explicitly stating the sign of the mantissa and/or
7979: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7980: ambiguity arises; either representation will be treated as a
7981: floating-point number.
7982: @item
7983: There is a word @code{bin} but it does @i{not} set the number base!
7984: It is used to specify file types.
7985: @item
7986: ANS Forth requires the @code{.} of a double-precision number to be the
7987: final character in the string. Gforth allows the @code{.} to be
7988: anywhere after the first digit.
7989: @item
7990: The number conversion process does not check for overflow.
7991: @item
7992: In an ANS Forth program @code{base} is required to be decimal when
7993: converting floating-point numbers. In Gforth, number conversion to
7994: floating-point numbers always uses base &10, irrespective of the value
7995: of @code{base}.
7996: @end itemize
7997:
7998: You can read numbers into your programs with the words described in
7999: @ref{Line input and conversion}.
8000:
8001: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
8002: @subsection Interpret/Compile states
8003: @cindex Interpret/Compile states
8004:
8005: A standard program is not permitted to change @code{state}
8006: explicitly. However, it can change @code{state} implicitly, using the
8007: words @code{[} and @code{]}. When @code{[} is executed it switches
8008: @code{state} to interpret state, and therefore the text interpreter
8009: starts interpreting. When @code{]} is executed it switches @code{state}
8010: to compile state and therefore the text interpreter starts
8011: compiling. The most common usage for these words is for switching into
8012: interpret state and back from within a colon definition; this technique
8013: can be used to compile a literal (for an example, @pxref{Literals}) or
8014: for conditional compilation (for an example, @pxref{Interpreter
8015: Directives}).
8016:
8017:
8018: @c This is a bad example: It's non-standard, and it's not necessary.
8019: @c However, I can't think of a good example for switching into compile
8020: @c state when there is no current word (@code{state}-smart words are not a
8021: @c good reason). So maybe we should use an example for switching into
8022: @c interpret @code{state} in a colon def. - anton
8023: @c nac-> I agree. I started out by putting in the example, then realised
8024: @c that it was non-ANS, so wrote more words around it. I hope this
8025: @c re-written version is acceptable to you. I do want to keep the example
8026: @c as it is helpful for showing what is and what is not portable, particularly
8027: @c where it outlaws a style in common use.
8028:
8029: @c anton: it's more important to show what's portable. After we have done
8030: @c that, we can also show what's not. In any case, I have written a
8031: @c section Compiling Words which also deals with [ ].
8032:
8033: @c !! The following example does not work in Gforth 0.5.9 or later.
8034:
8035: @c @code{[} and @code{]} also give you the ability to switch into compile
8036: @c state and back, but we cannot think of any useful Standard application
8037: @c for this ability. Pre-ANS Forth textbooks have examples like this:
8038:
8039: @c @example
8040: @c : AA ." this is A" ;
8041: @c : BB ." this is B" ;
8042: @c : CC ." this is C" ;
8043:
8044: @c create table ] aa bb cc [
8045:
8046: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
8047: @c cells table + @@ execute ;
8048: @c @end example
8049:
8050: @c This example builds a jump table; @code{0 go} will display ``@code{this
8051: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
8052: @c defining @code{table} like this:
8053:
8054: @c @example
8055: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
8056: @c @end example
8057:
8058: @c The problem with this code is that the definition of @code{table} is not
8059: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
8060: @c @i{may} work on systems where code space and data space co-incide, the
8061: @c Standard only allows data space to be assigned for a @code{CREATE}d
8062: @c word. In addition, the Standard only allows @code{@@} to access data
8063: @c space, whilst this example is using it to access code space. The only
8064: @c portable, Standard way to build this table is to build it in data space,
8065: @c like this:
8066:
8067: @c @example
8068: @c create table ' aa , ' bb , ' cc ,
8069: @c @end example
8070:
8071: @c doc-state
8072:
8073:
8074: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
8075: @subsection Interpreter Directives
8076: @cindex interpreter directives
8077: @cindex conditional compilation
8078:
8079: These words are usually used in interpret state; typically to control
8080: which parts of a source file are processed by the text
8081: interpreter. There are only a few ANS Forth Standard words, but Gforth
8082: supplements these with a rich set of immediate control structure words
8083: to compensate for the fact that the non-immediate versions can only be
8084: used in compile state (@pxref{Control Structures}). Typical usages:
8085:
8086: @example
8087: FALSE Constant HAVE-ASSEMBLER
8088: .
8089: .
8090: HAVE-ASSEMBLER [IF]
8091: : ASSEMBLER-FEATURE
8092: ...
8093: ;
8094: [ENDIF]
8095: .
8096: .
8097: : SEE
8098: ... \ general-purpose SEE code
8099: [ HAVE-ASSEMBLER [IF] ]
8100: ... \ assembler-specific SEE code
8101: [ [ENDIF] ]
8102: ;
8103: @end example
8104:
8105:
8106: doc-[IF]
8107: doc-[ELSE]
8108: doc-[THEN]
8109: doc-[ENDIF]
8110:
8111: doc-[IFDEF]
8112: doc-[IFUNDEF]
8113:
8114: doc-[?DO]
8115: doc-[DO]
8116: doc-[FOR]
8117: doc-[LOOP]
8118: doc-[+LOOP]
8119: doc-[NEXT]
8120:
8121: doc-[BEGIN]
8122: doc-[UNTIL]
8123: doc-[AGAIN]
8124: doc-[WHILE]
8125: doc-[REPEAT]
8126:
8127:
8128: @c -------------------------------------------------------------
8129: @node The Input Stream, Word Lists, The Text Interpreter, Words
8130: @section The Input Stream
8131: @cindex input stream
8132:
8133: @c !! integrate this better with the "Text Interpreter" section
8134: The text interpreter reads from the input stream, which can come from
8135: several sources (@pxref{Input Sources}). Some words, in particular
8136: defining words, but also words like @code{'}, read parameters from the
8137: input stream instead of from the stack.
8138:
8139: Such words are called parsing words, because they parse the input
8140: stream. Parsing words are hard to use in other words, because it is
8141: hard to pass program-generated parameters through the input stream.
8142: They also usually have an unintuitive combination of interpretation and
8143: compilation semantics when implemented naively, leading to various
8144: approaches that try to produce a more intuitive behaviour
8145: (@pxref{Combined words}).
8146:
8147: It should be obvious by now that parsing words are a bad idea. If you
8148: want to implement a parsing word for convenience, also provide a factor
8149: of the word that does not parse, but takes the parameters on the stack.
8150: To implement the parsing word on top if it, you can use the following
8151: words:
8152:
8153: @c anton: these belong in the input stream section
8154: doc-parse
8155: doc-parse-name
8156: doc-parse-word
8157: doc-name
8158: doc-word
8159: doc-refill
8160:
8161: Conversely, if you have the bad luck (or lack of foresight) to have to
8162: deal with parsing words without having such factors, how do you pass a
8163: string that is not in the input stream to it?
8164:
8165: doc-execute-parsing
8166:
8167: A definition of this word in ANS Forth is provided in
8168: @file{compat/execute-parsing.fs}.
8169:
8170: If you want to run a parsing word on a file, the following word should
8171: help:
8172:
8173: doc-execute-parsing-file
8174:
8175: @c -------------------------------------------------------------
8176: @node Word Lists, Environmental Queries, The Input Stream, Words
8177: @section Word Lists
8178: @cindex word lists
8179: @cindex header space
8180:
8181: A wordlist is a list of named words; you can add new words and look up
8182: words by name (and you can remove words in a restricted way with
8183: markers). Every named (and @code{reveal}ed) word is in one wordlist.
8184:
8185: @cindex search order stack
8186: The text interpreter searches the wordlists present in the search order
8187: (a stack of wordlists), from the top to the bottom. Within each
8188: wordlist, the search starts conceptually at the newest word; i.e., if
8189: two words in a wordlist have the same name, the newer word is found.
8190:
8191: @cindex compilation word list
8192: New words are added to the @dfn{compilation wordlist} (aka current
8193: wordlist).
8194:
8195: @cindex wid
8196: A word list is identified by a cell-sized word list identifier (@i{wid})
8197: in much the same way as a file is identified by a file handle. The
8198: numerical value of the wid has no (portable) meaning, and might change
8199: from session to session.
8200:
8201: The ANS Forth ``Search order'' word set is intended to provide a set of
8202: low-level tools that allow various different schemes to be
8203: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
8204: word. @file{compat/vocabulary.fs} provides an implementation in ANS
8205: Forth.
8206:
8207: @comment TODO: locals section refers to here, saying that every word list (aka
8208: @comment vocabulary) has its own methods for searching etc. Need to document that.
8209: @c anton: but better in a separate subsection on wordlist internals
8210:
8211: @comment TODO: document markers, reveal, tables, mappedwordlist
8212:
8213: @comment the gforthman- prefix is used to pick out the true definition of a
8214: @comment word from the source files, rather than some alias.
8215:
8216: doc-forth-wordlist
8217: doc-definitions
8218: doc-get-current
8219: doc-set-current
8220: doc-get-order
8221: doc-set-order
8222: doc-wordlist
8223: doc-table
8224: doc->order
8225: doc-previous
8226: doc-also
8227: doc-forth
8228: doc-only
8229: doc-order
8230:
8231: doc-find
8232: doc-search-wordlist
8233:
8234: doc-words
8235: doc-vlist
8236: @c doc-words-deferred
8237:
8238: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
8239: doc-root
8240: doc-vocabulary
8241: doc-seal
8242: doc-vocs
8243: doc-current
8244: doc-context
8245:
8246:
8247: @menu
8248: * Vocabularies::
8249: * Why use word lists?::
8250: * Word list example::
8251: @end menu
8252:
8253: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8254: @subsection Vocabularies
8255: @cindex Vocabularies, detailed explanation
8256:
8257: Here is an example of creating and using a new wordlist using ANS
8258: Forth words:
8259:
8260: @example
8261: wordlist constant my-new-words-wordlist
8262: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8263:
8264: \ add it to the search order
8265: also my-new-words
8266:
8267: \ alternatively, add it to the search order and make it
8268: \ the compilation word list
8269: also my-new-words definitions
8270: \ type "order" to see the problem
8271: @end example
8272:
8273: The problem with this example is that @code{order} has no way to
8274: associate the name @code{my-new-words} with the wid of the word list (in
8275: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8276: that has no associated name). There is no Standard way of associating a
8277: name with a wid.
8278:
8279: In Gforth, this example can be re-coded using @code{vocabulary}, which
8280: associates a name with a wid:
8281:
8282: @example
8283: vocabulary my-new-words
8284:
8285: \ add it to the search order
8286: also my-new-words
8287:
8288: \ alternatively, add it to the search order and make it
8289: \ the compilation word list
8290: my-new-words definitions
8291: \ type "order" to see that the problem is solved
8292: @end example
8293:
8294:
8295: @node Why use word lists?, Word list example, Vocabularies, Word Lists
8296: @subsection Why use word lists?
8297: @cindex word lists - why use them?
8298:
8299: Here are some reasons why people use wordlists:
8300:
8301: @itemize @bullet
8302:
8303: @c anton: Gforth's hashing implementation makes the search speed
8304: @c independent from the number of words. But it is linear with the number
8305: @c of wordlists that have to be searched, so in effect using more wordlists
8306: @c actually slows down compilation.
8307:
8308: @c @item
8309: @c To improve compilation speed by reducing the number of header space
8310: @c entries that must be searched. This is achieved by creating a new
8311: @c word list that contains all of the definitions that are used in the
8312: @c definition of a Forth system but which would not usually be used by
8313: @c programs running on that system. That word list would be on the search
8314: @c list when the Forth system was compiled but would be removed from the
8315: @c search list for normal operation. This can be a useful technique for
8316: @c low-performance systems (for example, 8-bit processors in embedded
8317: @c systems) but is unlikely to be necessary in high-performance desktop
8318: @c systems.
8319:
8320: @item
8321: To prevent a set of words from being used outside the context in which
8322: they are valid. Two classic examples of this are an integrated editor
8323: (all of the edit commands are defined in a separate word list; the
8324: search order is set to the editor word list when the editor is invoked;
8325: the old search order is restored when the editor is terminated) and an
8326: integrated assembler (the op-codes for the machine are defined in a
8327: separate word list which is used when a @code{CODE} word is defined).
8328:
8329: @item
8330: To organize the words of an application or library into a user-visible
8331: set (in @code{forth-wordlist} or some other common wordlist) and a set
8332: of helper words used just for the implementation (hidden in a separate
8333: wordlist). This keeps @code{words}' output smaller, separates
8334: implementation and interface, and reduces the chance of name conflicts
8335: within the common wordlist.
8336:
8337: @item
8338: To prevent a name-space clash between multiple definitions with the same
8339: name. For example, when building a cross-compiler you might have a word
8340: @code{IF} that generates conditional code for your target system. By
8341: placing this definition in a different word list you can control whether
8342: the host system's @code{IF} or the target system's @code{IF} get used in
8343: any particular context by controlling the order of the word lists on the
8344: search order stack.
8345:
8346: @end itemize
8347:
8348: The downsides of using wordlists are:
8349:
8350: @itemize
8351:
8352: @item
8353: Debugging becomes more cumbersome.
8354:
8355: @item
8356: Name conflicts worked around with wordlists are still there, and you
8357: have to arrange the search order carefully to get the desired results;
8358: if you forget to do that, you get hard-to-find errors (as in any case
8359: where you read the code differently from the compiler; @code{see} can
8360: help seeing which of several possible words the name resolves to in such
8361: cases). @code{See} displays just the name of the words, not what
8362: wordlist they belong to, so it might be misleading. Using unique names
8363: is a better approach to avoid name conflicts.
8364:
8365: @item
8366: You have to explicitly undo any changes to the search order. In many
8367: cases it would be more convenient if this happened implicitly. Gforth
8368: currently does not provide such a feature, but it may do so in the
8369: future.
8370: @end itemize
8371:
8372:
8373: @node Word list example, , Why use word lists?, Word Lists
8374: @subsection Word list example
8375: @cindex word lists - example
8376:
8377: The following example is from the
8378: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8379: garbage collector} and uses wordlists to separate public words from
8380: helper words:
8381:
8382: @example
8383: get-current ( wid )
8384: vocabulary garbage-collector also garbage-collector definitions
8385: ... \ define helper words
8386: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8387: ... \ define the public (i.e., API) words
8388: \ they can refer to the helper words
8389: previous \ restore original search order (helper words become invisible)
8390: @end example
8391:
8392: @c -------------------------------------------------------------
8393: @node Environmental Queries, Files, Word Lists, Words
8394: @section Environmental Queries
8395: @cindex environmental queries
8396:
8397: ANS Forth introduced the idea of ``environmental queries'' as a way
8398: for a program running on a system to determine certain characteristics of the system.
8399: The Standard specifies a number of strings that might be recognised by a system.
8400:
8401: The Standard requires that the header space used for environmental queries
8402: be distinct from the header space used for definitions.
8403:
8404: Typically, environmental queries are supported by creating a set of
8405: definitions in a word list that is @i{only} used during environmental
8406: queries; that is what Gforth does. There is no Standard way of adding
8407: definitions to the set of recognised environmental queries, but any
8408: implementation that supports the loading of optional word sets must have
8409: some mechanism for doing this (after loading the word set, the
8410: associated environmental query string must return @code{true}). In
8411: Gforth, the word list used to honour environmental queries can be
8412: manipulated just like any other word list.
8413:
8414:
8415: doc-environment?
8416: doc-environment-wordlist
8417:
8418: doc-gforth
8419: doc-os-class
8420:
8421:
8422: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8423: returning two items on the stack, querying it using @code{environment?}
8424: will return an additional item; the @code{true} flag that shows that the
8425: string was recognised.
8426:
8427: @comment TODO Document the standard strings or note where they are documented herein
8428:
8429: Here are some examples of using environmental queries:
8430:
8431: @example
8432: s" address-unit-bits" environment? 0=
8433: [IF]
8434: cr .( environmental attribute address-units-bits unknown... ) cr
8435: [ELSE]
8436: drop \ ensure balanced stack effect
8437: [THEN]
8438:
8439: \ this might occur in the prelude of a standard program that uses THROW
8440: s" exception" environment? [IF]
8441: 0= [IF]
8442: : throw abort" exception thrown" ;
8443: [THEN]
8444: [ELSE] \ we don't know, so make sure
8445: : throw abort" exception thrown" ;
8446: [THEN]
8447:
8448: s" gforth" environment? [IF] .( Gforth version ) TYPE
8449: [ELSE] .( Not Gforth..) [THEN]
8450:
8451: \ a program using v*
8452: s" gforth" environment? [IF]
8453: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8454: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8455: >r swap 2swap swap 0e r> 0 ?DO
8456: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
8457: LOOP
8458: 2drop 2drop ;
8459: [THEN]
8460: [ELSE] \
8461: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8462: ...
8463: [THEN]
8464: @end example
8465:
8466: Here is an example of adding a definition to the environment word list:
8467:
8468: @example
8469: get-current environment-wordlist set-current
8470: true constant block
8471: true constant block-ext
8472: set-current
8473: @end example
8474:
8475: You can see what definitions are in the environment word list like this:
8476:
8477: @example
8478: environment-wordlist >order words previous
8479: @end example
8480:
8481:
8482: @c -------------------------------------------------------------
8483: @node Files, Blocks, Environmental Queries, Words
8484: @section Files
8485: @cindex files
8486: @cindex I/O - file-handling
8487:
8488: Gforth provides facilities for accessing files that are stored in the
8489: host operating system's file-system. Files that are processed by Gforth
8490: can be divided into two categories:
8491:
8492: @itemize @bullet
8493: @item
8494: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
8495: @item
8496: Files that are processed by some other program (@dfn{general files}).
8497: @end itemize
8498:
8499: @menu
8500: * Forth source files::
8501: * General files::
8502: * Redirection::
8503: * Search Paths::
8504: @end menu
8505:
8506: @c -------------------------------------------------------------
8507: @node Forth source files, General files, Files, Files
8508: @subsection Forth source files
8509: @cindex including files
8510: @cindex Forth source files
8511:
8512: The simplest way to interpret the contents of a file is to use one of
8513: these two formats:
8514:
8515: @example
8516: include mysource.fs
8517: s" mysource.fs" included
8518: @end example
8519:
8520: You usually want to include a file only if it is not included already
8521: (by, say, another source file). In that case, you can use one of these
8522: three formats:
8523:
8524: @example
8525: require mysource.fs
8526: needs mysource.fs
8527: s" mysource.fs" required
8528: @end example
8529:
8530: @cindex stack effect of included files
8531: @cindex including files, stack effect
8532: It is good practice to write your source files such that interpreting them
8533: does not change the stack. Source files designed in this way can be used with
8534: @code{required} and friends without complications. For example:
8535:
8536: @example
8537: 1024 require foo.fs drop
8538: @end example
8539:
8540: Here you want to pass the argument 1024 (e.g., a buffer size) to
8541: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8542: ), which allows its use with @code{require}. Of course with such
8543: parameters to required files, you have to ensure that the first
8544: @code{require} fits for all uses (i.e., @code{require} it early in the
8545: master load file).
8546:
8547: doc-include-file
8548: doc-included
8549: doc-included?
8550: doc-include
8551: doc-required
8552: doc-require
8553: doc-needs
8554: @c doc-init-included-files @c internal
8555: doc-sourcefilename
8556: doc-sourceline#
8557:
8558: A definition in ANS Forth for @code{required} is provided in
8559: @file{compat/required.fs}.
8560:
8561: @c -------------------------------------------------------------
8562: @node General files, Redirection, Forth source files, Files
8563: @subsection General files
8564: @cindex general files
8565: @cindex file-handling
8566:
8567: Files are opened/created by name and type. The following file access
8568: methods (FAMs) are recognised:
8569:
8570: @cindex fam (file access method)
8571: doc-r/o
8572: doc-r/w
8573: doc-w/o
8574: doc-bin
8575:
8576:
8577: When a file is opened/created, it returns a file identifier,
8578: @i{wfileid} that is used for all other file commands. All file
8579: commands also return a status value, @i{wior}, that is 0 for a
8580: successful operation and an implementation-defined non-zero value in the
8581: case of an error.
8582:
8583:
8584: doc-open-file
8585: doc-create-file
8586:
8587: doc-close-file
8588: doc-delete-file
8589: doc-rename-file
8590: doc-read-file
8591: doc-read-line
8592: doc-key-file
8593: doc-key?-file
8594: doc-write-file
8595: doc-write-line
8596: doc-emit-file
8597: doc-flush-file
8598:
8599: doc-file-status
8600: doc-file-position
8601: doc-reposition-file
8602: doc-file-size
8603: doc-resize-file
8604:
8605: doc-slurp-file
8606: doc-slurp-fid
8607: doc-stdin
8608: doc-stdout
8609: doc-stderr
8610:
8611: @c ---------------------------------------------------------
8612: @node Redirection, Search Paths, General files, Files
8613: @subsection Redirection
8614: @cindex Redirection
8615: @cindex Input Redirection
8616: @cindex Output Redirection
8617:
8618: You can redirect the output of @code{type} and @code{emit} and all the
8619: words that use them (all output words that don't have an explicit
8620: target file) to an arbitrary file with the @code{outfile-execute},
8621: used like this:
8622:
8623: @example
8624: : some-warning ( n -- )
8625: cr ." warning# " . ;
8626:
8627: : print-some-warning ( n -- )
8628: ['] some-warning stderr outfile-execute ;
8629: @end example
8630:
8631: After @code{some-warning} is executed, the original output direction
8632: is restored; this construct is safe against exceptions. Similarly,
8633: there is @code{infile-execute} for redirecting the input of @code{key}
8634: and its users (any input word that does not take a file explicitly).
8635:
8636: doc-outfile-execute
8637: doc-infile-execute
8638:
8639: If you do not want to redirect the input or output to a file, you can
8640: also make use of the fact that @code{key}, @code{emit} and @code{type}
8641: are deferred words (@pxref{Deferred Words}). However, in that case
8642: you have to worry about the restoration and the protection against
8643: exceptions yourself; also, note that for redirecting the output in
8644: this way, you have to redirect both @code{emit} and @code{type}.
8645:
8646: @c ---------------------------------------------------------
8647: @node Search Paths, , Redirection, Files
8648: @subsection Search Paths
8649: @cindex path for @code{included}
8650: @cindex file search path
8651: @cindex @code{include} search path
8652: @cindex search path for files
8653:
8654: If you specify an absolute filename (i.e., a filename starting with
8655: @file{/} or @file{~}, or with @file{:} in the second position (as in
8656: @samp{C:...})) for @code{included} and friends, that file is included
8657: just as you would expect.
8658:
8659: If the filename starts with @file{./}, this refers to the directory that
8660: the present file was @code{included} from. This allows files to include
8661: other files relative to their own position (irrespective of the current
8662: working directory or the absolute position). This feature is essential
8663: for libraries consisting of several files, where a file may include
8664: other files from the library. It corresponds to @code{#include "..."}
8665: in C. If the current input source is not a file, @file{.} refers to the
8666: directory of the innermost file being included, or, if there is no file
8667: being included, to the current working directory.
8668:
8669: For relative filenames (not starting with @file{./}), Gforth uses a
8670: search path similar to Forth's search order (@pxref{Word Lists}). It
8671: tries to find the given filename in the directories present in the path,
8672: and includes the first one it finds. There are separate search paths for
8673: Forth source files and general files. If the search path contains the
8674: directory @file{.}, this refers to the directory of the current file, or
8675: the working directory, as if the file had been specified with @file{./}.
8676:
8677: Use @file{~+} to refer to the current working directory (as in the
8678: @code{bash}).
8679:
8680: @c anton: fold the following subsubsections into this subsection?
8681:
8682: @menu
8683: * Source Search Paths::
8684: * General Search Paths::
8685: @end menu
8686:
8687: @c ---------------------------------------------------------
8688: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8689: @subsubsection Source Search Paths
8690: @cindex search path control, source files
8691:
8692: The search path is initialized when you start Gforth (@pxref{Invoking
8693: Gforth}). You can display it and change it using @code{fpath} in
8694: combination with the general path handling words.
8695:
8696: doc-fpath
8697: @c the functionality of the following words is easily available through
8698: @c fpath and the general path words. The may go away.
8699: @c doc-.fpath
8700: @c doc-fpath+
8701: @c doc-fpath=
8702: @c doc-open-fpath-file
8703:
8704: @noindent
8705: Here is an example of using @code{fpath} and @code{require}:
8706:
8707: @example
8708: fpath path= /usr/lib/forth/|./
8709: require timer.fs
8710: @end example
8711:
8712:
8713: @c ---------------------------------------------------------
8714: @node General Search Paths, , Source Search Paths, Search Paths
8715: @subsubsection General Search Paths
8716: @cindex search path control, source files
8717:
8718: Your application may need to search files in several directories, like
8719: @code{included} does. To facilitate this, Gforth allows you to define
8720: and use your own search paths, by providing generic equivalents of the
8721: Forth search path words:
8722:
8723: doc-open-path-file
8724: doc-path-allot
8725: doc-clear-path
8726: doc-also-path
8727: doc-.path
8728: doc-path+
8729: doc-path=
8730:
8731: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
8732:
8733: Here's an example of creating an empty search path:
8734: @c
8735: @example
8736: create mypath 500 path-allot \ maximum length 500 chars (is checked)
8737: @end example
8738:
8739: @c -------------------------------------------------------------
8740: @node Blocks, Other I/O, Files, Words
8741: @section Blocks
8742: @cindex I/O - blocks
8743: @cindex blocks
8744:
8745: When you run Gforth on a modern desk-top computer, it runs under the
8746: control of an operating system which provides certain services. One of
8747: these services is @var{file services}, which allows Forth source code
8748: and data to be stored in files and read into Gforth (@pxref{Files}).
8749:
8750: Traditionally, Forth has been an important programming language on
8751: systems where it has interfaced directly to the underlying hardware with
8752: no intervening operating system. Forth provides a mechanism, called
8753: @dfn{blocks}, for accessing mass storage on such systems.
8754:
8755: A block is a 1024-byte data area, which can be used to hold data or
8756: Forth source code. No structure is imposed on the contents of the
8757: block. A block is identified by its number; blocks are numbered
8758: contiguously from 1 to an implementation-defined maximum.
8759:
8760: A typical system that used blocks but no operating system might use a
8761: single floppy-disk drive for mass storage, with the disks formatted to
8762: provide 256-byte sectors. Blocks would be implemented by assigning the
8763: first four sectors of the disk to block 1, the second four sectors to
8764: block 2 and so on, up to the limit of the capacity of the disk. The disk
8765: would not contain any file system information, just the set of blocks.
8766:
8767: @cindex blocks file
8768: On systems that do provide file services, blocks are typically
8769: implemented by storing a sequence of blocks within a single @dfn{blocks
8770: file}. The size of the blocks file will be an exact multiple of 1024
8771: bytes, corresponding to the number of blocks it contains. This is the
8772: mechanism that Gforth uses.
8773:
8774: @cindex @file{blocks.fb}
8775: Only one blocks file can be open at a time. If you use block words without
8776: having specified a blocks file, Gforth defaults to the blocks file
8777: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
8778: locate a blocks file (@pxref{Source Search Paths}).
8779:
8780: @cindex block buffers
8781: When you read and write blocks under program control, Gforth uses a
8782: number of @dfn{block buffers} as intermediate storage. These buffers are
8783: not used when you use @code{load} to interpret the contents of a block.
8784:
8785: The behaviour of the block buffers is analagous to that of a cache.
8786: Each block buffer has three states:
8787:
8788: @itemize @bullet
8789: @item
8790: Unassigned
8791: @item
8792: Assigned-clean
8793: @item
8794: Assigned-dirty
8795: @end itemize
8796:
8797: Initially, all block buffers are @i{unassigned}. In order to access a
8798: block, the block (specified by its block number) must be assigned to a
8799: block buffer.
8800:
8801: The assignment of a block to a block buffer is performed by @code{block}
8802: or @code{buffer}. Use @code{block} when you wish to modify the existing
8803: contents of a block. Use @code{buffer} when you don't care about the
8804: existing contents of the block@footnote{The ANS Forth definition of
8805: @code{buffer} is intended not to cause disk I/O; if the data associated
8806: with the particular block is already stored in a block buffer due to an
8807: earlier @code{block} command, @code{buffer} will return that block
8808: buffer and the existing contents of the block will be
8809: available. Otherwise, @code{buffer} will simply assign a new, empty
8810: block buffer for the block.}.
8811:
8812: Once a block has been assigned to a block buffer using @code{block} or
8813: @code{buffer}, that block buffer becomes the @i{current block
8814: buffer}. Data may only be manipulated (read or written) within the
8815: current block buffer.
8816:
8817: When the contents of the current block buffer has been modified it is
8818: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
8819: either abandon the changes (by doing nothing) or mark the block as
8820: changed (assigned-dirty), using @code{update}. Using @code{update} does
8821: not change the blocks file; it simply changes a block buffer's state to
8822: @i{assigned-dirty}. The block will be written implicitly when it's
8823: buffer is needed for another block, or explicitly by @code{flush} or
8824: @code{save-buffers}.
8825:
8826: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8827: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8828: @code{flush}.
8829:
8830: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
8831: algorithm to assign a block buffer to a block. That means that any
8832: particular block can only be assigned to one specific block buffer,
8833: called (for the particular operation) the @i{victim buffer}. If the
8834: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8835: the new block immediately. If it is @i{assigned-dirty} its current
8836: contents are written back to the blocks file on disk before it is
8837: allocated to the new block.
8838:
8839: Although no structure is imposed on the contents of a block, it is
8840: traditional to display the contents as 16 lines each of 64 characters. A
8841: block provides a single, continuous stream of input (for example, it
8842: acts as a single parse area) -- there are no end-of-line characters
8843: within a block, and no end-of-file character at the end of a
8844: block. There are two consequences of this:
8845:
8846: @itemize @bullet
8847: @item
8848: The last character of one line wraps straight into the first character
8849: of the following line
8850: @item
8851: The word @code{\} -- comment to end of line -- requires special
8852: treatment; in the context of a block it causes all characters until the
8853: end of the current 64-character ``line'' to be ignored.
8854: @end itemize
8855:
8856: In Gforth, when you use @code{block} with a non-existent block number,
8857: the current blocks file will be extended to the appropriate size and the
8858: block buffer will be initialised with spaces.
8859:
8860: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8861: for details) but doesn't encourage the use of blocks; the mechanism is
8862: only provided for backward compatibility -- ANS Forth requires blocks to
8863: be available when files are.
8864:
8865: Common techniques that are used when working with blocks include:
8866:
8867: @itemize @bullet
8868: @item
8869: A screen editor that allows you to edit blocks without leaving the Forth
8870: environment.
8871: @item
8872: Shadow screens; where every code block has an associated block
8873: containing comments (for example: code in odd block numbers, comments in
8874: even block numbers). Typically, the block editor provides a convenient
8875: mechanism to toggle between code and comments.
8876: @item
8877: Load blocks; a single block (typically block 1) contains a number of
8878: @code{thru} commands which @code{load} the whole of the application.
8879: @end itemize
8880:
8881: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8882: integrated into a Forth programming environment.
8883:
8884: @comment TODO what about errors on open-blocks?
8885:
8886: doc-open-blocks
8887: doc-use
8888: doc-block-offset
8889: doc-get-block-fid
8890: doc-block-position
8891:
8892: doc-list
8893: doc-scr
8894:
8895: doc-block
8896: doc-buffer
8897:
8898: doc-empty-buffers
8899: doc-empty-buffer
8900: doc-update
8901: doc-updated?
8902: doc-save-buffers
8903: doc-save-buffer
8904: doc-flush
8905:
8906: doc-load
8907: doc-thru
8908: doc-+load
8909: doc-+thru
8910: doc---gforthman--->
8911: doc-block-included
8912:
8913:
8914: @c -------------------------------------------------------------
8915: @node Other I/O, OS command line arguments, Blocks, Words
8916: @section Other I/O
8917: @cindex I/O - keyboard and display
8918:
8919: @menu
8920: * Simple numeric output:: Predefined formats
8921: * Formatted numeric output:: Formatted (pictured) output
8922: * String Formats:: How Forth stores strings in memory
8923: * Displaying characters and strings:: Other stuff
8924: * Terminal output:: Cursor positioning etc.
8925: * Single-key input::
8926: * Line input and conversion::
8927: * Pipes:: How to create your own pipes
8928: * Xchars and Unicode:: Non-ASCII characters
8929: @end menu
8930:
8931: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8932: @subsection Simple numeric output
8933: @cindex numeric output - simple/free-format
8934:
8935: The simplest output functions are those that display numbers from the
8936: data or floating-point stacks. Floating-point output is always displayed
8937: using base 10. Numbers displayed from the data stack use the value stored
8938: in @code{base}.
8939:
8940:
8941: doc-.
8942: doc-dec.
8943: doc-hex.
8944: doc-u.
8945: doc-.r
8946: doc-u.r
8947: doc-d.
8948: doc-ud.
8949: doc-d.r
8950: doc-ud.r
8951: doc-f.
8952: doc-fe.
8953: doc-fs.
8954: doc-f.rdp
8955:
8956: Examples of printing the number 1234.5678E23 in the different floating-point output
8957: formats are shown below:
8958:
8959: @example
8960: f. 123456779999999000000000000.
8961: fe. 123.456779999999E24
8962: fs. 1.23456779999999E26
8963: @end example
8964:
8965:
8966: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8967: @subsection Formatted numeric output
8968: @cindex formatted numeric output
8969: @cindex pictured numeric output
8970: @cindex numeric output - formatted
8971:
8972: Forth traditionally uses a technique called @dfn{pictured numeric
8973: output} for formatted printing of integers. In this technique, digits
8974: are extracted from the number (using the current output radix defined by
8975: @code{base}), converted to ASCII codes and appended to a string that is
8976: built in a scratch-pad area of memory (@pxref{core-idef,
8977: Implementation-defined options, Implementation-defined
8978: options}). Arbitrary characters can be appended to the string during the
8979: extraction process. The completed string is specified by an address
8980: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8981: under program control.
8982:
8983: All of the integer output words described in the previous section
8984: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8985: numeric output.
8986:
8987: Three important things to remember about pictured numeric output:
8988:
8989: @itemize @bullet
8990: @item
8991: It always operates on double-precision numbers; to display a
8992: single-precision number, convert it first (for ways of doing this
8993: @pxref{Double precision}).
8994: @item
8995: It always treats the double-precision number as though it were
8996: unsigned. The examples below show ways of printing signed numbers.
8997: @item
8998: The string is built up from right to left; least significant digit first.
8999: @end itemize
9000:
9001:
9002: doc-<#
9003: doc-<<#
9004: doc-#
9005: doc-#s
9006: doc-hold
9007: doc-sign
9008: doc-#>
9009: doc-#>>
9010:
9011: doc-represent
9012: doc-f>str-rdp
9013: doc-f>buf-rdp
9014:
9015:
9016: @noindent
9017: Here are some examples of using pictured numeric output:
9018:
9019: @example
9020: : my-u. ( u -- )
9021: \ Simplest use of pns.. behaves like Standard u.
9022: 0 \ convert to unsigned double
9023: <<# \ start conversion
9024: #s \ convert all digits
9025: #> \ complete conversion
9026: TYPE SPACE \ display, with trailing space
9027: #>> ; \ release hold area
9028:
9029: : cents-only ( u -- )
9030: 0 \ convert to unsigned double
9031: <<# \ start conversion
9032: # # \ convert two least-significant digits
9033: #> \ complete conversion, discard other digits
9034: TYPE SPACE \ display, with trailing space
9035: #>> ; \ release hold area
9036:
9037: : dollars-and-cents ( u -- )
9038: 0 \ convert to unsigned double
9039: <<# \ start conversion
9040: # # \ convert two least-significant digits
9041: [char] . hold \ insert decimal point
9042: #s \ convert remaining digits
9043: [char] $ hold \ append currency symbol
9044: #> \ complete conversion
9045: TYPE SPACE \ display, with trailing space
9046: #>> ; \ release hold area
9047:
9048: : my-. ( n -- )
9049: \ handling negatives.. behaves like Standard .
9050: s>d \ convert to signed double
9051: swap over dabs \ leave sign byte followed by unsigned double
9052: <<# \ start conversion
9053: #s \ convert all digits
9054: rot sign \ get at sign byte, append "-" if needed
9055: #> \ complete conversion
9056: TYPE SPACE \ display, with trailing space
9057: #>> ; \ release hold area
9058:
9059: : account. ( n -- )
9060: \ accountants don't like minus signs, they use parentheses
9061: \ for negative numbers
9062: s>d \ convert to signed double
9063: swap over dabs \ leave sign byte followed by unsigned double
9064: <<# \ start conversion
9065: 2 pick \ get copy of sign byte
9066: 0< IF [char] ) hold THEN \ right-most character of output
9067: #s \ convert all digits
9068: rot \ get at sign byte
9069: 0< IF [char] ( hold THEN
9070: #> \ complete conversion
9071: TYPE SPACE \ display, with trailing space
9072: #>> ; \ release hold area
9073:
9074: @end example
9075:
9076: Here are some examples of using these words:
9077:
9078: @example
9079: 1 my-u. 1
9080: hex -1 my-u. decimal FFFFFFFF
9081: 1 cents-only 01
9082: 1234 cents-only 34
9083: 2 dollars-and-cents $0.02
9084: 1234 dollars-and-cents $12.34
9085: 123 my-. 123
9086: -123 my. -123
9087: 123 account. 123
9088: -456 account. (456)
9089: @end example
9090:
9091:
9092: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
9093: @subsection String Formats
9094: @cindex strings - see character strings
9095: @cindex character strings - formats
9096: @cindex I/O - see character strings
9097: @cindex counted strings
9098:
9099: @c anton: this does not really belong here; maybe the memory section,
9100: @c or the principles chapter
9101:
9102: Forth commonly uses two different methods for representing character
9103: strings:
9104:
9105: @itemize @bullet
9106: @item
9107: @cindex address of counted string
9108: @cindex counted string
9109: As a @dfn{counted string}, represented by a @i{c-addr}. The char
9110: addressed by @i{c-addr} contains a character-count, @i{n}, of the
9111: string and the string occupies the subsequent @i{n} char addresses in
9112: memory.
9113: @item
9114: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
9115: of the string in characters, and @i{c-addr} is the address of the
9116: first byte of the string.
9117: @end itemize
9118:
9119: ANS Forth encourages the use of the second format when representing
9120: strings.
9121:
9122:
9123: doc-count
9124:
9125:
9126: For words that move, copy and search for strings see @ref{Memory
9127: Blocks}. For words that display characters and strings see
9128: @ref{Displaying characters and strings}.
9129:
9130: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
9131: @subsection Displaying characters and strings
9132: @cindex characters - compiling and displaying
9133: @cindex character strings - compiling and displaying
9134:
9135: This section starts with a glossary of Forth words and ends with a set
9136: of examples.
9137:
9138: doc-bl
9139: doc-space
9140: doc-spaces
9141: doc-emit
9142: doc-toupper
9143: doc-."
9144: doc-.(
9145: doc-.\"
9146: doc-type
9147: doc-typewhite
9148: doc-cr
9149: @cindex cursor control
9150: doc-s"
9151: doc-s\"
9152: doc-c"
9153: doc-char
9154: doc-[char]
9155:
9156:
9157: @noindent
9158: As an example, consider the following text, stored in a file @file{test.fs}:
9159:
9160: @example
9161: .( text-1)
9162: : my-word
9163: ." text-2" cr
9164: .( text-3)
9165: ;
9166:
9167: ." text-4"
9168:
9169: : my-char
9170: [char] ALPHABET emit
9171: char emit
9172: ;
9173: @end example
9174:
9175: When you load this code into Gforth, the following output is generated:
9176:
9177: @example
9178: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
9179: @end example
9180:
9181: @itemize @bullet
9182: @item
9183: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
9184: is an immediate word; it behaves in the same way whether it is used inside
9185: or outside a colon definition.
9186: @item
9187: Message @code{text-4} is displayed because of Gforth's added interpretation
9188: semantics for @code{."}.
9189: @item
9190: Message @code{text-2} is @i{not} displayed, because the text interpreter
9191: performs the compilation semantics for @code{."} within the definition of
9192: @code{my-word}.
9193: @end itemize
9194:
9195: Here are some examples of executing @code{my-word} and @code{my-char}:
9196:
9197: @example
9198: @kbd{my-word @key{RET}} text-2
9199: ok
9200: @kbd{my-char fred @key{RET}} Af ok
9201: @kbd{my-char jim @key{RET}} Aj ok
9202: @end example
9203:
9204: @itemize @bullet
9205: @item
9206: Message @code{text-2} is displayed because of the run-time behaviour of
9207: @code{."}.
9208: @item
9209: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
9210: on the stack at run-time. @code{emit} always displays the character
9211: when @code{my-char} is executed.
9212: @item
9213: @code{char} parses a string at run-time and the second @code{emit} displays
9214: the first character of the string.
9215: @item
9216: If you type @code{see my-char} you can see that @code{[char]} discarded
9217: the text ``LPHABET'' and only compiled the display code for ``A'' into the
9218: definition of @code{my-char}.
9219: @end itemize
9220:
9221:
9222: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
9223: @subsection Terminal output
9224: @cindex output to terminal
9225: @cindex terminal output
9226:
9227: If you are outputting to a terminal, you may want to control the
9228: positioning of the cursor:
9229: @cindex cursor positioning
9230:
9231: doc-at-xy
9232:
9233: In order to know where to position the cursor, it is often helpful to
9234: know the size of the screen:
9235: @cindex terminal size
9236:
9237: doc-form
9238:
9239: And sometimes you want to use:
9240: @cindex clear screen
9241:
9242: doc-page
9243:
9244: Note that on non-terminals you should use @code{12 emit}, not
9245: @code{page}, to get a form feed.
9246:
9247:
9248: @node Single-key input, Line input and conversion, Terminal output, Other I/O
9249: @subsection Single-key input
9250: @cindex single-key input
9251: @cindex input, single-key
9252:
9253: If you want to get a single printable character, you can use
9254: @code{key}; to check whether a character is available for @code{key},
9255: you can use @code{key?}.
9256:
9257: doc-key
9258: doc-key?
9259:
9260: If you want to process a mix of printable and non-printable
9261: characters, you can do that with @code{ekey} and friends. @code{Ekey}
9262: produces a keyboard event that you have to convert into a character
9263: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
9264:
9265: Typical code for using EKEY looks like this:
9266:
9267: @example
9268: ekey ekey>char if ( c )
9269: ... \ do something with the character
9270: else ekey>fkey if ( key-id )
9271: case
9272: k-up of ... endof
9273: k-f1 of ... endof
9274: k-left k-shift-mask or k-ctrl-mask or of ... endof
9275: ...
9276: endcase
9277: else ( keyboard-event )
9278: drop \ just ignore an unknown keyboard event type
9279: then then
9280: @end example
9281:
9282: doc-ekey
9283: doc-ekey>char
9284: doc-ekey>fkey
9285: doc-ekey?
9286:
9287: The key identifiers for cursor keys are:
9288:
9289: doc-k-left
9290: doc-k-right
9291: doc-k-up
9292: doc-k-down
9293: doc-k-home
9294: doc-k-end
9295: doc-k-prior
9296: doc-k-next
9297: doc-k-insert
9298: doc-k-delete
9299:
9300: The key identifiers for function keys (aka keypad keys) are:
9301:
9302: doc-k-f1
9303: doc-k-f2
9304: doc-k-f3
9305: doc-k-f4
9306: doc-k-f5
9307: doc-k-f6
9308: doc-k-f7
9309: doc-k-f8
9310: doc-k-f9
9311: doc-k-f10
9312: doc-k-f11
9313: doc-k-f12
9314:
9315: Note that @code{k-f11} and @code{k-f12} are not as widely available.
9316:
9317: You can combine these key identifiers with masks for various shift keys:
9318:
9319: doc-k-shift-mask
9320: doc-k-ctrl-mask
9321: doc-k-alt-mask
9322:
9323: Note that, even if a Forth system has @code{ekey>fkey} and the key
9324: identifier words, the keys are not necessarily available or it may not
9325: necessarily be able to report all the keys and all the possible
9326: combinations with shift masks. Therefore, write your programs in such
9327: a way that they are still useful even if the keys and key combinations
9328: cannot be pressed or are not recognized.
9329:
9330: Examples: Older keyboards often do not have an F11 and F12 key. If
9331: you run Gforth in an xterm, the xterm catches a number of combinations
9332: (e.g., @key{Shift-Up}), and never passes it to Gforth. Finally,
9333: Gforth currently does not recognize and report combinations with
9334: multiple shift keys (so the @key{shift-ctrl-left} case in the example
9335: above would never be entered).
9336:
9337: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
9338: you need the ANSI.SYS driver to get that behaviour); it works by
9339: recognizing the escape sequences that ANSI terminals send when such a
9340: key is pressed. If you have a terminal that sends other escape
9341: sequences, you will not get useful results on Gforth. Other Forth
9342: systems may work in a different way.
9343:
9344: Gforth also provides a few words for outputting names of function
9345: keys:
9346:
9347: doc-fkey.
9348: doc-simple-fkey-string
9349:
9350:
9351: @node Line input and conversion, Pipes, Single-key input, Other I/O
9352: @subsection Line input and conversion
9353: @cindex line input from terminal
9354: @cindex input, linewise from terminal
9355: @cindex convertin strings to numbers
9356: @cindex I/O - see input
9357:
9358: For ways of storing character strings in memory see @ref{String Formats}.
9359:
9360: @comment TODO examples for >number >float accept key key? pad parse word refill
9361: @comment then index them
9362:
9363: Words for inputting one line from the keyboard:
9364:
9365: doc-accept
9366: doc-edit-line
9367:
9368: Conversion words:
9369:
9370: doc-s>number?
9371: doc-s>unumber?
9372: doc->number
9373: doc->float
9374:
9375:
9376: @comment obsolescent words..
9377: Obsolescent input and conversion words:
9378:
9379: doc-convert
9380: doc-expect
9381: doc-span
9382:
9383:
9384: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
9385: @subsection Pipes
9386: @cindex pipes, creating your own
9387:
9388: In addition to using Gforth in pipes created by other processes
9389: (@pxref{Gforth in pipes}), you can create your own pipe with
9390: @code{open-pipe}, and read from or write to it.
9391:
9392: doc-open-pipe
9393: doc-close-pipe
9394:
9395: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
9396: you don't catch this exception, Gforth will catch it and exit, usually
9397: silently (@pxref{Gforth in pipes}). Since you probably do not want
9398: this, you should wrap a @code{catch} or @code{try} block around the code
9399: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9400: problem yourself, and then return to regular processing.
9401:
9402: doc-broken-pipe-error
9403:
9404: @node Xchars and Unicode, , Pipes, Other I/O
9405: @subsection Xchars and Unicode
9406:
9407: ASCII is only appropriate for the English language. Most western
9408: languages however fit somewhat into the Forth frame, since a byte is
9409: sufficient to encode the few special characters in each (though not
9410: always the same encoding can be used; latin-1 is most widely used,
9411: though). For other languages, different char-sets have to be used,
9412: several of them variable-width. Most prominent representant is
9413: UTF-8. Let's call these extended characters xchars. The primitive
9414: fixed-size characters stored as bytes are called pchars in this
9415: section.
9416:
9417: The xchar words add a few data types:
9418:
9419: @itemize
9420:
9421: @item
9422: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
9423: and is a subset of unsigned cell. Note: UTF-8 can not store more that
9424: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
9425: character set can be used.
9426:
9427: @item
9428: @var{xc-addr} is the address of an xchar in memory. Alignment
9429: requirements are the same as @var{c-addr}. The memory representation of an
9430: xchar differs from the stack representation, and depends on the
9431: encoding used. An xchar may use a variable number of pchars in memory.
9432:
9433: @item
9434: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
9435: @var{xc-addr}, @var{u} pchars long.
9436:
9437: @end itemize
9438:
9439: doc-xc-size
9440: doc-x-size
9441: doc-xc@+
9442: doc-xc!+?
9443: doc-xchar+
9444: doc-xchar-
9445: doc-+x/string
9446: doc-x\string-
9447: doc--trailing-garbage
9448: doc-x-width
9449: doc-xkey
9450: doc-xemit
9451:
9452: There's a new environment query
9453:
9454: doc-xchar-encoding
9455:
9456: @node OS command line arguments, Locals, Other I/O, Words
9457: @section OS command line arguments
9458: @cindex OS command line arguments
9459: @cindex command line arguments, OS
9460: @cindex arguments, OS command line
9461:
9462: The usual way to pass arguments to Gforth programs on the command line
9463: is via the @option{-e} option, e.g.
9464:
9465: @example
9466: gforth -e "123 456" foo.fs -e bye
9467: @end example
9468:
9469: However, you may want to interpret the command-line arguments directly.
9470: In that case, you can access the (image-specific) command-line arguments
9471: through @code{next-arg}:
9472:
9473: doc-next-arg
9474:
9475: Here's an example program @file{echo.fs} for @code{next-arg}:
9476:
9477: @example
9478: : echo ( -- )
9479: begin
9480: next-arg 2dup 0 0 d<> while
9481: type space
9482: repeat
9483: 2drop ;
9484:
9485: echo cr bye
9486: @end example
9487:
9488: This can be invoked with
9489:
9490: @example
9491: gforth echo.fs hello world
9492: @end example
9493:
9494: and it will print
9495:
9496: @example
9497: hello world
9498: @end example
9499:
9500: The next lower level of dealing with the OS command line are the
9501: following words:
9502:
9503: doc-arg
9504: doc-shift-args
9505:
9506: Finally, at the lowest level Gforth provides the following words:
9507:
9508: doc-argc
9509: doc-argv
9510:
9511: @c -------------------------------------------------------------
9512: @node Locals, Structures, OS command line arguments, Words
9513: @section Locals
9514: @cindex locals
9515:
9516: Local variables can make Forth programming more enjoyable and Forth
9517: programs easier to read. Unfortunately, the locals of ANS Forth are
9518: laden with restrictions. Therefore, we provide not only the ANS Forth
9519: locals wordset, but also our own, more powerful locals wordset (we
9520: implemented the ANS Forth locals wordset through our locals wordset).
9521:
9522: The ideas in this section have also been published in M. Anton Ertl,
9523: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9524: Automatic Scoping of Local Variables}}, EuroForth '94.
9525:
9526: @menu
9527: * Gforth locals::
9528: * ANS Forth locals::
9529: @end menu
9530:
9531: @node Gforth locals, ANS Forth locals, Locals, Locals
9532: @subsection Gforth locals
9533: @cindex Gforth locals
9534: @cindex locals, Gforth style
9535:
9536: Locals can be defined with
9537:
9538: @example
9539: @{ local1 local2 ... -- comment @}
9540: @end example
9541: or
9542: @example
9543: @{ local1 local2 ... @}
9544: @end example
9545:
9546: E.g.,
9547: @example
9548: : max @{ n1 n2 -- n3 @}
9549: n1 n2 > if
9550: n1
9551: else
9552: n2
9553: endif ;
9554: @end example
9555:
9556: The similarity of locals definitions with stack comments is intended. A
9557: locals definition often replaces the stack comment of a word. The order
9558: of the locals corresponds to the order in a stack comment and everything
9559: after the @code{--} is really a comment.
9560:
9561: This similarity has one disadvantage: It is too easy to confuse locals
9562: declarations with stack comments, causing bugs and making them hard to
9563: find. However, this problem can be avoided by appropriate coding
9564: conventions: Do not use both notations in the same program. If you do,
9565: they should be distinguished using additional means, e.g. by position.
9566:
9567: @cindex types of locals
9568: @cindex locals types
9569: The name of the local may be preceded by a type specifier, e.g.,
9570: @code{F:} for a floating point value:
9571:
9572: @example
9573: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9574: \ complex multiplication
9575: Ar Br f* Ai Bi f* f-
9576: Ar Bi f* Ai Br f* f+ ;
9577: @end example
9578:
9579: @cindex flavours of locals
9580: @cindex locals flavours
9581: @cindex value-flavoured locals
9582: @cindex variable-flavoured locals
9583: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9584: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9585: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9586: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9587: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9588: produces its address (which becomes invalid when the variable's scope is
9589: left). E.g., the standard word @code{emit} can be defined in terms of
9590: @code{type} like this:
9591:
9592: @example
9593: : emit @{ C^ char* -- @}
9594: char* 1 type ;
9595: @end example
9596:
9597: @cindex default type of locals
9598: @cindex locals, default type
9599: A local without type specifier is a @code{W:} local. Both flavours of
9600: locals are initialized with values from the data or FP stack.
9601:
9602: Currently there is no way to define locals with user-defined data
9603: structures, but we are working on it.
9604:
9605: Gforth allows defining locals everywhere in a colon definition. This
9606: poses the following questions:
9607:
9608: @menu
9609: * Where are locals visible by name?::
9610: * How long do locals live?::
9611: * Locals programming style::
9612: * Locals implementation::
9613: @end menu
9614:
9615: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9616: @subsubsection Where are locals visible by name?
9617: @cindex locals visibility
9618: @cindex visibility of locals
9619: @cindex scope of locals
9620:
9621: Basically, the answer is that locals are visible where you would expect
9622: it in block-structured languages, and sometimes a little longer. If you
9623: want to restrict the scope of a local, enclose its definition in
9624: @code{SCOPE}...@code{ENDSCOPE}.
9625:
9626:
9627: doc-scope
9628: doc-endscope
9629:
9630:
9631: These words behave like control structure words, so you can use them
9632: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9633: arbitrary ways.
9634:
9635: If you want a more exact answer to the visibility question, here's the
9636: basic principle: A local is visible in all places that can only be
9637: reached through the definition of the local@footnote{In compiler
9638: construction terminology, all places dominated by the definition of the
9639: local.}. In other words, it is not visible in places that can be reached
9640: without going through the definition of the local. E.g., locals defined
9641: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9642: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9643: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
9644:
9645: The reasoning behind this solution is: We want to have the locals
9646: visible as long as it is meaningful. The user can always make the
9647: visibility shorter by using explicit scoping. In a place that can
9648: only be reached through the definition of a local, the meaning of a
9649: local name is clear. In other places it is not: How is the local
9650: initialized at the control flow path that does not contain the
9651: definition? Which local is meant, if the same name is defined twice in
9652: two independent control flow paths?
9653:
9654: This should be enough detail for nearly all users, so you can skip the
9655: rest of this section. If you really must know all the gory details and
9656: options, read on.
9657:
9658: In order to implement this rule, the compiler has to know which places
9659: are unreachable. It knows this automatically after @code{AHEAD},
9660: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9661: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9662: compiler that the control flow never reaches that place. If
9663: @code{UNREACHABLE} is not used where it could, the only consequence is
9664: that the visibility of some locals is more limited than the rule above
9665: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9666: lie to the compiler), buggy code will be produced.
9667:
9668:
9669: doc-unreachable
9670:
9671:
9672: Another problem with this rule is that at @code{BEGIN}, the compiler
9673: does not know which locals will be visible on the incoming
9674: back-edge. All problems discussed in the following are due to this
9675: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9676: loops as examples; the discussion also applies to @code{?DO} and other
9677: loops). Perhaps the most insidious example is:
9678: @example
9679: AHEAD
9680: BEGIN
9681: x
9682: [ 1 CS-ROLL ] THEN
9683: @{ x @}
9684: ...
9685: UNTIL
9686: @end example
9687:
9688: This should be legal according to the visibility rule. The use of
9689: @code{x} can only be reached through the definition; but that appears
9690: textually below the use.
9691:
9692: From this example it is clear that the visibility rules cannot be fully
9693: implemented without major headaches. Our implementation treats common
9694: cases as advertised and the exceptions are treated in a safe way: The
9695: compiler makes a reasonable guess about the locals visible after a
9696: @code{BEGIN}; if it is too pessimistic, the
9697: user will get a spurious error about the local not being defined; if the
9698: compiler is too optimistic, it will notice this later and issue a
9699: warning. In the case above the compiler would complain about @code{x}
9700: being undefined at its use. You can see from the obscure examples in
9701: this section that it takes quite unusual control structures to get the
9702: compiler into trouble, and even then it will often do fine.
9703:
9704: If the @code{BEGIN} is reachable from above, the most optimistic guess
9705: is that all locals visible before the @code{BEGIN} will also be
9706: visible after the @code{BEGIN}. This guess is valid for all loops that
9707: are entered only through the @code{BEGIN}, in particular, for normal
9708: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9709: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9710: compiler. When the branch to the @code{BEGIN} is finally generated by
9711: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9712: warns the user if it was too optimistic:
9713: @example
9714: IF
9715: @{ x @}
9716: BEGIN
9717: \ x ?
9718: [ 1 cs-roll ] THEN
9719: ...
9720: UNTIL
9721: @end example
9722:
9723: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9724: optimistically assumes that it lives until the @code{THEN}. It notices
9725: this difference when it compiles the @code{UNTIL} and issues a
9726: warning. The user can avoid the warning, and make sure that @code{x}
9727: is not used in the wrong area by using explicit scoping:
9728: @example
9729: IF
9730: SCOPE
9731: @{ x @}
9732: ENDSCOPE
9733: BEGIN
9734: [ 1 cs-roll ] THEN
9735: ...
9736: UNTIL
9737: @end example
9738:
9739: Since the guess is optimistic, there will be no spurious error messages
9740: about undefined locals.
9741:
9742: If the @code{BEGIN} is not reachable from above (e.g., after
9743: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9744: optimistic guess, as the locals visible after the @code{BEGIN} may be
9745: defined later. Therefore, the compiler assumes that no locals are
9746: visible after the @code{BEGIN}. However, the user can use
9747: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9748: visible at the BEGIN as at the point where the top control-flow stack
9749: item was created.
9750:
9751:
9752: doc-assume-live
9753:
9754:
9755: @noindent
9756: E.g.,
9757: @example
9758: @{ x @}
9759: AHEAD
9760: ASSUME-LIVE
9761: BEGIN
9762: x
9763: [ 1 CS-ROLL ] THEN
9764: ...
9765: UNTIL
9766: @end example
9767:
9768: Other cases where the locals are defined before the @code{BEGIN} can be
9769: handled by inserting an appropriate @code{CS-ROLL} before the
9770: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9771: behind the @code{ASSUME-LIVE}).
9772:
9773: Cases where locals are defined after the @code{BEGIN} (but should be
9774: visible immediately after the @code{BEGIN}) can only be handled by
9775: rearranging the loop. E.g., the ``most insidious'' example above can be
9776: arranged into:
9777: @example
9778: BEGIN
9779: @{ x @}
9780: ... 0=
9781: WHILE
9782: x
9783: REPEAT
9784: @end example
9785:
9786: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9787: @subsubsection How long do locals live?
9788: @cindex locals lifetime
9789: @cindex lifetime of locals
9790:
9791: The right answer for the lifetime question would be: A local lives at
9792: least as long as it can be accessed. For a value-flavoured local this
9793: means: until the end of its visibility. However, a variable-flavoured
9794: local could be accessed through its address far beyond its visibility
9795: scope. Ultimately, this would mean that such locals would have to be
9796: garbage collected. Since this entails un-Forth-like implementation
9797: complexities, I adopted the same cowardly solution as some other
9798: languages (e.g., C): The local lives only as long as it is visible;
9799: afterwards its address is invalid (and programs that access it
9800: afterwards are erroneous).
9801:
9802: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9803: @subsubsection Locals programming style
9804: @cindex locals programming style
9805: @cindex programming style, locals
9806:
9807: The freedom to define locals anywhere has the potential to change
9808: programming styles dramatically. In particular, the need to use the
9809: return stack for intermediate storage vanishes. Moreover, all stack
9810: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9811: determined arguments) can be eliminated: If the stack items are in the
9812: wrong order, just write a locals definition for all of them; then
9813: write the items in the order you want.
9814:
9815: This seems a little far-fetched and eliminating stack manipulations is
9816: unlikely to become a conscious programming objective. Still, the number
9817: of stack manipulations will be reduced dramatically if local variables
9818: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9819: a traditional implementation of @code{max}).
9820:
9821: This shows one potential benefit of locals: making Forth programs more
9822: readable. Of course, this benefit will only be realized if the
9823: programmers continue to honour the principle of factoring instead of
9824: using the added latitude to make the words longer.
9825:
9826: @cindex single-assignment style for locals
9827: Using @code{TO} can and should be avoided. Without @code{TO},
9828: every value-flavoured local has only a single assignment and many
9829: advantages of functional languages apply to Forth. I.e., programs are
9830: easier to analyse, to optimize and to read: It is clear from the
9831: definition what the local stands for, it does not turn into something
9832: different later.
9833:
9834: E.g., a definition using @code{TO} might look like this:
9835: @example
9836: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9837: u1 u2 min 0
9838: ?do
9839: addr1 c@@ addr2 c@@ -
9840: ?dup-if
9841: unloop exit
9842: then
9843: addr1 char+ TO addr1
9844: addr2 char+ TO addr2
9845: loop
9846: u1 u2 - ;
9847: @end example
9848: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9849: every loop iteration. @code{strcmp} is a typical example of the
9850: readability problems of using @code{TO}. When you start reading
9851: @code{strcmp}, you think that @code{addr1} refers to the start of the
9852: string. Only near the end of the loop you realize that it is something
9853: else.
9854:
9855: This can be avoided by defining two locals at the start of the loop that
9856: are initialized with the right value for the current iteration.
9857: @example
9858: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9859: addr1 addr2
9860: u1 u2 min 0
9861: ?do @{ s1 s2 @}
9862: s1 c@@ s2 c@@ -
9863: ?dup-if
9864: unloop exit
9865: then
9866: s1 char+ s2 char+
9867: loop
9868: 2drop
9869: u1 u2 - ;
9870: @end example
9871: Here it is clear from the start that @code{s1} has a different value
9872: in every loop iteration.
9873:
9874: @node Locals implementation, , Locals programming style, Gforth locals
9875: @subsubsection Locals implementation
9876: @cindex locals implementation
9877: @cindex implementation of locals
9878:
9879: @cindex locals stack
9880: Gforth uses an extra locals stack. The most compelling reason for
9881: this is that the return stack is not float-aligned; using an extra stack
9882: also eliminates the problems and restrictions of using the return stack
9883: as locals stack. Like the other stacks, the locals stack grows toward
9884: lower addresses. A few primitives allow an efficient implementation:
9885:
9886:
9887: doc-@local#
9888: doc-f@local#
9889: doc-laddr#
9890: doc-lp+!#
9891: doc-lp!
9892: doc->l
9893: doc-f>l
9894:
9895:
9896: In addition to these primitives, some specializations of these
9897: primitives for commonly occurring inline arguments are provided for
9898: efficiency reasons, e.g., @code{@@local0} as specialization of
9899: @code{@@local#} for the inline argument 0. The following compiling words
9900: compile the right specialized version, or the general version, as
9901: appropriate:
9902:
9903:
9904: @c doc-compile-@local
9905: @c doc-compile-f@local
9906: doc-compile-lp+!
9907:
9908:
9909: Combinations of conditional branches and @code{lp+!#} like
9910: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9911: is taken) are provided for efficiency and correctness in loops.
9912:
9913: A special area in the dictionary space is reserved for keeping the
9914: local variable names. @code{@{} switches the dictionary pointer to this
9915: area and @code{@}} switches it back and generates the locals
9916: initializing code. @code{W:} etc.@ are normal defining words. This
9917: special area is cleared at the start of every colon definition.
9918:
9919: @cindex word list for defining locals
9920: A special feature of Gforth's dictionary is used to implement the
9921: definition of locals without type specifiers: every word list (aka
9922: vocabulary) has its own methods for searching
9923: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9924: with a special search method: When it is searched for a word, it
9925: actually creates that word using @code{W:}. @code{@{} changes the search
9926: order to first search the word list containing @code{@}}, @code{W:} etc.,
9927: and then the word list for defining locals without type specifiers.
9928:
9929: The lifetime rules support a stack discipline within a colon
9930: definition: The lifetime of a local is either nested with other locals
9931: lifetimes or it does not overlap them.
9932:
9933: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9934: pointer manipulation is generated. Between control structure words
9935: locals definitions can push locals onto the locals stack. @code{AGAIN}
9936: is the simplest of the other three control flow words. It has to
9937: restore the locals stack depth of the corresponding @code{BEGIN}
9938: before branching. The code looks like this:
9939: @format
9940: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9941: @code{branch} <begin>
9942: @end format
9943:
9944: @code{UNTIL} is a little more complicated: If it branches back, it
9945: must adjust the stack just like @code{AGAIN}. But if it falls through,
9946: the locals stack must not be changed. The compiler generates the
9947: following code:
9948: @format
9949: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9950: @end format
9951: The locals stack pointer is only adjusted if the branch is taken.
9952:
9953: @code{THEN} can produce somewhat inefficient code:
9954: @format
9955: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9956: <orig target>:
9957: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9958: @end format
9959: The second @code{lp+!#} adjusts the locals stack pointer from the
9960: level at the @i{orig} point to the level after the @code{THEN}. The
9961: first @code{lp+!#} adjusts the locals stack pointer from the current
9962: level to the level at the orig point, so the complete effect is an
9963: adjustment from the current level to the right level after the
9964: @code{THEN}.
9965:
9966: @cindex locals information on the control-flow stack
9967: @cindex control-flow stack items, locals information
9968: In a conventional Forth implementation a dest control-flow stack entry
9969: is just the target address and an orig entry is just the address to be
9970: patched. Our locals implementation adds a word list to every orig or dest
9971: item. It is the list of locals visible (or assumed visible) at the point
9972: described by the entry. Our implementation also adds a tag to identify
9973: the kind of entry, in particular to differentiate between live and dead
9974: (reachable and unreachable) orig entries.
9975:
9976: A few unusual operations have to be performed on locals word lists:
9977:
9978:
9979: doc-common-list
9980: doc-sub-list?
9981: doc-list-size
9982:
9983:
9984: Several features of our locals word list implementation make these
9985: operations easy to implement: The locals word lists are organised as
9986: linked lists; the tails of these lists are shared, if the lists
9987: contain some of the same locals; and the address of a name is greater
9988: than the address of the names behind it in the list.
9989:
9990: Another important implementation detail is the variable
9991: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9992: determine if they can be reached directly or only through the branch
9993: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9994: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9995: definition, by @code{BEGIN} and usually by @code{THEN}.
9996:
9997: Counted loops are similar to other loops in most respects, but
9998: @code{LEAVE} requires special attention: It performs basically the same
9999: service as @code{AHEAD}, but it does not create a control-flow stack
10000: entry. Therefore the information has to be stored elsewhere;
10001: traditionally, the information was stored in the target fields of the
10002: branches created by the @code{LEAVE}s, by organizing these fields into a
10003: linked list. Unfortunately, this clever trick does not provide enough
10004: space for storing our extended control flow information. Therefore, we
10005: introduce another stack, the leave stack. It contains the control-flow
10006: stack entries for all unresolved @code{LEAVE}s.
10007:
10008: Local names are kept until the end of the colon definition, even if
10009: they are no longer visible in any control-flow path. In a few cases
10010: this may lead to increased space needs for the locals name area, but
10011: usually less than reclaiming this space would cost in code size.
10012:
10013:
10014: @node ANS Forth locals, , Gforth locals, Locals
10015: @subsection ANS Forth locals
10016: @cindex locals, ANS Forth style
10017:
10018: The ANS Forth locals wordset does not define a syntax for locals, but
10019: words that make it possible to define various syntaxes. One of the
10020: possible syntaxes is a subset of the syntax we used in the Gforth locals
10021: wordset, i.e.:
10022:
10023: @example
10024: @{ local1 local2 ... -- comment @}
10025: @end example
10026: @noindent
10027: or
10028: @example
10029: @{ local1 local2 ... @}
10030: @end example
10031:
10032: The order of the locals corresponds to the order in a stack comment. The
10033: restrictions are:
10034:
10035: @itemize @bullet
10036: @item
10037: Locals can only be cell-sized values (no type specifiers are allowed).
10038: @item
10039: Locals can be defined only outside control structures.
10040: @item
10041: Locals can interfere with explicit usage of the return stack. For the
10042: exact (and long) rules, see the standard. If you don't use return stack
10043: accessing words in a definition using locals, you will be all right. The
10044: purpose of this rule is to make locals implementation on the return
10045: stack easier.
10046: @item
10047: The whole definition must be in one line.
10048: @end itemize
10049:
10050: Locals defined in ANS Forth behave like @code{VALUE}s
10051: (@pxref{Values}). I.e., they are initialized from the stack. Using their
10052: name produces their value. Their value can be changed using @code{TO}.
10053:
10054: Since the syntax above is supported by Gforth directly, you need not do
10055: anything to use it. If you want to port a program using this syntax to
10056: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
10057: syntax on the other system.
10058:
10059: Note that a syntax shown in the standard, section A.13 looks
10060: similar, but is quite different in having the order of locals
10061: reversed. Beware!
10062:
10063: The ANS Forth locals wordset itself consists of one word:
10064:
10065: doc-(local)
10066:
10067: The ANS Forth locals extension wordset defines a syntax using
10068: @code{locals|}, but it is so awful that we strongly recommend not to use
10069: it. We have implemented this syntax to make porting to Gforth easy, but
10070: do not document it here. The problem with this syntax is that the locals
10071: are defined in an order reversed with respect to the standard stack
10072: comment notation, making programs harder to read, and easier to misread
10073: and miswrite. The only merit of this syntax is that it is easy to
10074: implement using the ANS Forth locals wordset.
10075:
10076:
10077: @c ----------------------------------------------------------
10078: @node Structures, Object-oriented Forth, Locals, Words
10079: @section Structures
10080: @cindex structures
10081: @cindex records
10082:
10083: This section presents the structure package that comes with Gforth. A
10084: version of the package implemented in ANS Forth is available in
10085: @file{compat/struct.fs}. This package was inspired by a posting on
10086: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
10087: possibly John Hayes). A version of this section has been published in
10088: M. Anton Ertl,
10089: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
10090: Another Forth Structures Package}, Forth Dimensions 19(3), pages
10091: 13--16. Marcel Hendrix provided helpful comments.
10092:
10093: @menu
10094: * Why explicit structure support?::
10095: * Structure Usage::
10096: * Structure Naming Convention::
10097: * Structure Implementation::
10098: * Structure Glossary::
10099: * Forth200x Structures::
10100: @end menu
10101:
10102: @node Why explicit structure support?, Structure Usage, Structures, Structures
10103: @subsection Why explicit structure support?
10104:
10105: @cindex address arithmetic for structures
10106: @cindex structures using address arithmetic
10107: If we want to use a structure containing several fields, we could simply
10108: reserve memory for it, and access the fields using address arithmetic
10109: (@pxref{Address arithmetic}). As an example, consider a structure with
10110: the following fields
10111:
10112: @table @code
10113: @item a
10114: is a float
10115: @item b
10116: is a cell
10117: @item c
10118: is a float
10119: @end table
10120:
10121: Given the (float-aligned) base address of the structure we get the
10122: address of the field
10123:
10124: @table @code
10125: @item a
10126: without doing anything further.
10127: @item b
10128: with @code{float+}
10129: @item c
10130: with @code{float+ cell+ faligned}
10131: @end table
10132:
10133: It is easy to see that this can become quite tiring.
10134:
10135: Moreover, it is not very readable, because seeing a
10136: @code{cell+} tells us neither which kind of structure is
10137: accessed nor what field is accessed; we have to somehow infer the kind
10138: of structure, and then look up in the documentation, which field of
10139: that structure corresponds to that offset.
10140:
10141: Finally, this kind of address arithmetic also causes maintenance
10142: troubles: If you add or delete a field somewhere in the middle of the
10143: structure, you have to find and change all computations for the fields
10144: afterwards.
10145:
10146: So, instead of using @code{cell+} and friends directly, how
10147: about storing the offsets in constants:
10148:
10149: @example
10150: 0 constant a-offset
10151: 0 float+ constant b-offset
10152: 0 float+ cell+ faligned c-offset
10153: @end example
10154:
10155: Now we can get the address of field @code{x} with @code{x-offset
10156: +}. This is much better in all respects. Of course, you still
10157: have to change all later offset definitions if you add a field. You can
10158: fix this by declaring the offsets in the following way:
10159:
10160: @example
10161: 0 constant a-offset
10162: a-offset float+ constant b-offset
10163: b-offset cell+ faligned constant c-offset
10164: @end example
10165:
10166: Since we always use the offsets with @code{+}, we could use a defining
10167: word @code{cfield} that includes the @code{+} in the action of the
10168: defined word:
10169:
10170: @example
10171: : cfield ( n "name" -- )
10172: create ,
10173: does> ( name execution: addr1 -- addr2 )
10174: @@ + ;
10175:
10176: 0 cfield a
10177: 0 a float+ cfield b
10178: 0 b cell+ faligned cfield c
10179: @end example
10180:
10181: Instead of @code{x-offset +}, we now simply write @code{x}.
10182:
10183: The structure field words now can be used quite nicely. However,
10184: their definition is still a bit cumbersome: We have to repeat the
10185: name, the information about size and alignment is distributed before
10186: and after the field definitions etc. The structure package presented
10187: here addresses these problems.
10188:
10189: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10190: @subsection Structure Usage
10191: @cindex structure usage
10192:
10193: @cindex @code{field} usage
10194: @cindex @code{struct} usage
10195: @cindex @code{end-struct} usage
10196: You can define a structure for a (data-less) linked list with:
10197: @example
10198: struct
10199: cell% field list-next
10200: end-struct list%
10201: @end example
10202:
10203: With the address of the list node on the stack, you can compute the
10204: address of the field that contains the address of the next node with
10205: @code{list-next}. E.g., you can determine the length of a list
10206: with:
10207:
10208: @example
10209: : list-length ( list -- n )
10210: \ "list" is a pointer to the first element of a linked list
10211: \ "n" is the length of the list
10212: 0 BEGIN ( list1 n1 )
10213: over
10214: WHILE ( list1 n1 )
10215: 1+ swap list-next @@ swap
10216: REPEAT
10217: nip ;
10218: @end example
10219:
10220: You can reserve memory for a list node in the dictionary with
10221: @code{list% %allot}, which leaves the address of the list node on the
10222: stack. For the equivalent allocation on the heap you can use @code{list%
10223: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10224: use @code{list% %allocate}). You can get the the size of a list
10225: node with @code{list% %size} and its alignment with @code{list%
10226: %alignment}.
10227:
10228: Note that in ANS Forth the body of a @code{create}d word is
10229: @code{aligned} but not necessarily @code{faligned};
10230: therefore, if you do a:
10231:
10232: @example
10233: create @emph{name} foo% %allot drop
10234: @end example
10235:
10236: @noindent
10237: then the memory alloted for @code{foo%} is guaranteed to start at the
10238: body of @code{@emph{name}} only if @code{foo%} contains only character,
10239: cell and double fields. Therefore, if your structure contains floats,
10240: better use
10241:
10242: @example
10243: foo% %allot constant @emph{name}
10244: @end example
10245:
10246: @cindex structures containing structures
10247: You can include a structure @code{foo%} as a field of
10248: another structure, like this:
10249: @example
10250: struct
10251: ...
10252: foo% field ...
10253: ...
10254: end-struct ...
10255: @end example
10256:
10257: @cindex structure extension
10258: @cindex extended records
10259: Instead of starting with an empty structure, you can extend an
10260: existing structure. E.g., a plain linked list without data, as defined
10261: above, is hardly useful; You can extend it to a linked list of integers,
10262: like this:@footnote{This feature is also known as @emph{extended
10263: records}. It is the main innovation in the Oberon language; in other
10264: words, adding this feature to Modula-2 led Wirth to create a new
10265: language, write a new compiler etc. Adding this feature to Forth just
10266: required a few lines of code.}
10267:
10268: @example
10269: list%
10270: cell% field intlist-int
10271: end-struct intlist%
10272: @end example
10273:
10274: @code{intlist%} is a structure with two fields:
10275: @code{list-next} and @code{intlist-int}.
10276:
10277: @cindex structures containing arrays
10278: You can specify an array type containing @emph{n} elements of
10279: type @code{foo%} like this:
10280:
10281: @example
10282: foo% @emph{n} *
10283: @end example
10284:
10285: You can use this array type in any place where you can use a normal
10286: type, e.g., when defining a @code{field}, or with
10287: @code{%allot}.
10288:
10289: @cindex first field optimization
10290: The first field is at the base address of a structure and the word for
10291: this field (e.g., @code{list-next}) actually does not change the address
10292: on the stack. You may be tempted to leave it away in the interest of
10293: run-time and space efficiency. This is not necessary, because the
10294: structure package optimizes this case: If you compile a first-field
10295: words, no code is generated. So, in the interest of readability and
10296: maintainability you should include the word for the field when accessing
10297: the field.
10298:
10299:
10300: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10301: @subsection Structure Naming Convention
10302: @cindex structure naming convention
10303:
10304: The field names that come to (my) mind are often quite generic, and,
10305: if used, would cause frequent name clashes. E.g., many structures
10306: probably contain a @code{counter} field. The structure names
10307: that come to (my) mind are often also the logical choice for the names
10308: of words that create such a structure.
10309:
10310: Therefore, I have adopted the following naming conventions:
10311:
10312: @itemize @bullet
10313: @cindex field naming convention
10314: @item
10315: The names of fields are of the form
10316: @code{@emph{struct}-@emph{field}}, where
10317: @code{@emph{struct}} is the basic name of the structure, and
10318: @code{@emph{field}} is the basic name of the field. You can
10319: think of field words as converting the (address of the)
10320: structure into the (address of the) field.
10321:
10322: @cindex structure naming convention
10323: @item
10324: The names of structures are of the form
10325: @code{@emph{struct}%}, where
10326: @code{@emph{struct}} is the basic name of the structure.
10327: @end itemize
10328:
10329: This naming convention does not work that well for fields of extended
10330: structures; e.g., the integer list structure has a field
10331: @code{intlist-int}, but has @code{list-next}, not
10332: @code{intlist-next}.
10333:
10334: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10335: @subsection Structure Implementation
10336: @cindex structure implementation
10337: @cindex implementation of structures
10338:
10339: The central idea in the implementation is to pass the data about the
10340: structure being built on the stack, not in some global
10341: variable. Everything else falls into place naturally once this design
10342: decision is made.
10343:
10344: The type description on the stack is of the form @emph{align
10345: size}. Keeping the size on the top-of-stack makes dealing with arrays
10346: very simple.
10347:
10348: @code{field} is a defining word that uses @code{Create}
10349: and @code{DOES>}. The body of the field contains the offset
10350: of the field, and the normal @code{DOES>} action is simply:
10351:
10352: @example
10353: @@ +
10354: @end example
10355:
10356: @noindent
10357: i.e., add the offset to the address, giving the stack effect
10358: @i{addr1 -- addr2} for a field.
10359:
10360: @cindex first field optimization, implementation
10361: This simple structure is slightly complicated by the optimization
10362: for fields with offset 0, which requires a different
10363: @code{DOES>}-part (because we cannot rely on there being
10364: something on the stack if such a field is invoked during
10365: compilation). Therefore, we put the different @code{DOES>}-parts
10366: in separate words, and decide which one to invoke based on the
10367: offset. For a zero offset, the field is basically a noop; it is
10368: immediate, and therefore no code is generated when it is compiled.
10369:
10370: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
10371: @subsection Structure Glossary
10372: @cindex structure glossary
10373:
10374:
10375: doc-%align
10376: doc-%alignment
10377: doc-%alloc
10378: doc-%allocate
10379: doc-%allot
10380: doc-cell%
10381: doc-char%
10382: doc-dfloat%
10383: doc-double%
10384: doc-end-struct
10385: doc-field
10386: doc-float%
10387: doc-naligned
10388: doc-sfloat%
10389: doc-%size
10390: doc-struct
10391:
10392:
10393: @node Forth200x Structures, , Structure Glossary, Structures
10394: @subsection Forth200x Structures
10395: @cindex Structures in Forth200x
10396:
10397: The Forth 200x standard defines a slightly less convenient form of
10398: structures. In general (when using @code{field+}, you have to perform
10399: the alignment yourself, but there are a number of convenience words
10400: (e.g., @code{field:} that perform the alignment for you.
10401:
10402: A typical usage example is:
10403:
10404: @example
10405: 0
10406: field: s-a
10407: faligned 2 floats +field s-b
10408: constant s-struct
10409: @end example
10410:
10411: An alternative way of writing this structure is:
10412:
10413: @example
10414: begin-structure s-struct
10415: field: s-a
10416: faligned 2 floats +field s-b
10417: end-structure
10418: @end example
10419:
10420: doc-begin-structure
10421: doc-end-structure
10422: doc-+field
10423: doc-cfield:
10424: doc-field:
10425: doc-2field:
10426: doc-ffield:
10427: doc-sffield:
10428: doc-dffield:
10429:
10430: @c -------------------------------------------------------------
10431: @node Object-oriented Forth, Programming Tools, Structures, Words
10432: @section Object-oriented Forth
10433:
10434: Gforth comes with three packages for object-oriented programming:
10435: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10436: is preloaded, so you have to @code{include} them before use. The most
10437: important differences between these packages (and others) are discussed
10438: in @ref{Comparison with other object models}. All packages are written
10439: in ANS Forth and can be used with any other ANS Forth.
10440:
10441: @menu
10442: * Why object-oriented programming?::
10443: * Object-Oriented Terminology::
10444: * Objects::
10445: * OOF::
10446: * Mini-OOF::
10447: * Comparison with other object models::
10448: @end menu
10449:
10450: @c ----------------------------------------------------------------
10451: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10452: @subsection Why object-oriented programming?
10453: @cindex object-oriented programming motivation
10454: @cindex motivation for object-oriented programming
10455:
10456: Often we have to deal with several data structures (@emph{objects}),
10457: that have to be treated similarly in some respects, but differently in
10458: others. Graphical objects are the textbook example: circles, triangles,
10459: dinosaurs, icons, and others, and we may want to add more during program
10460: development. We want to apply some operations to any graphical object,
10461: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10462: has to do something different for every kind of object.
10463: @comment TODO add some other operations eg perimeter, area
10464: @comment and tie in to concrete examples later..
10465:
10466: We could implement @code{draw} as a big @code{CASE}
10467: control structure that executes the appropriate code depending on the
10468: kind of object to be drawn. This would be not be very elegant, and,
10469: moreover, we would have to change @code{draw} every time we add
10470: a new kind of graphical object (say, a spaceship).
10471:
10472: What we would rather do is: When defining spaceships, we would tell
10473: the system: ``Here's how you @code{draw} a spaceship; you figure
10474: out the rest''.
10475:
10476: This is the problem that all systems solve that (rightfully) call
10477: themselves object-oriented; the object-oriented packages presented here
10478: solve this problem (and not much else).
10479: @comment TODO ?list properties of oo systems.. oo vs o-based?
10480:
10481: @c ------------------------------------------------------------------------
10482: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10483: @subsection Object-Oriented Terminology
10484: @cindex object-oriented terminology
10485: @cindex terminology for object-oriented programming
10486:
10487: This section is mainly for reference, so you don't have to understand
10488: all of it right away. The terminology is mainly Smalltalk-inspired. In
10489: short:
10490:
10491: @table @emph
10492: @cindex class
10493: @item class
10494: a data structure definition with some extras.
10495:
10496: @cindex object
10497: @item object
10498: an instance of the data structure described by the class definition.
10499:
10500: @cindex instance variables
10501: @item instance variables
10502: fields of the data structure.
10503:
10504: @cindex selector
10505: @cindex method selector
10506: @cindex virtual function
10507: @item selector
10508: (or @emph{method selector}) a word (e.g.,
10509: @code{draw}) that performs an operation on a variety of data
10510: structures (classes). A selector describes @emph{what} operation to
10511: perform. In C++ terminology: a (pure) virtual function.
10512:
10513: @cindex method
10514: @item method
10515: the concrete definition that performs the operation
10516: described by the selector for a specific class. A method specifies
10517: @emph{how} the operation is performed for a specific class.
10518:
10519: @cindex selector invocation
10520: @cindex message send
10521: @cindex invoking a selector
10522: @item selector invocation
10523: a call of a selector. One argument of the call (the TOS (top-of-stack))
10524: is used for determining which method is used. In Smalltalk terminology:
10525: a message (consisting of the selector and the other arguments) is sent
10526: to the object.
10527:
10528: @cindex receiving object
10529: @item receiving object
10530: the object used for determining the method executed by a selector
10531: invocation. In the @file{objects.fs} model, it is the object that is on
10532: the TOS when the selector is invoked. (@emph{Receiving} comes from
10533: the Smalltalk @emph{message} terminology.)
10534:
10535: @cindex child class
10536: @cindex parent class
10537: @cindex inheritance
10538: @item child class
10539: a class that has (@emph{inherits}) all properties (instance variables,
10540: selectors, methods) from a @emph{parent class}. In Smalltalk
10541: terminology: The subclass inherits from the superclass. In C++
10542: terminology: The derived class inherits from the base class.
10543:
10544: @end table
10545:
10546: @c If you wonder about the message sending terminology, it comes from
10547: @c a time when each object had it's own task and objects communicated via
10548: @c message passing; eventually the Smalltalk developers realized that
10549: @c they can do most things through simple (indirect) calls. They kept the
10550: @c terminology.
10551:
10552: @c --------------------------------------------------------------
10553: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10554: @subsection The @file{objects.fs} model
10555: @cindex objects
10556: @cindex object-oriented programming
10557:
10558: @cindex @file{objects.fs}
10559: @cindex @file{oof.fs}
10560:
10561: This section describes the @file{objects.fs} package. This material also
10562: has been published in M. Anton Ertl,
10563: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10564: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10565: 37--43.
10566: @c McKewan's and Zsoter's packages
10567:
10568: This section assumes that you have read @ref{Structures}.
10569:
10570: The techniques on which this model is based have been used to implement
10571: the parser generator, Gray, and have also been used in Gforth for
10572: implementing the various flavours of word lists (hashed or not,
10573: case-sensitive or not, special-purpose word lists for locals etc.).
10574:
10575:
10576: @menu
10577: * Properties of the Objects model::
10578: * Basic Objects Usage::
10579: * The Objects base class::
10580: * Creating objects::
10581: * Object-Oriented Programming Style::
10582: * Class Binding::
10583: * Method conveniences::
10584: * Classes and Scoping::
10585: * Dividing classes::
10586: * Object Interfaces::
10587: * Objects Implementation::
10588: * Objects Glossary::
10589: @end menu
10590:
10591: Marcel Hendrix provided helpful comments on this section.
10592:
10593: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10594: @subsubsection Properties of the @file{objects.fs} model
10595: @cindex @file{objects.fs} properties
10596:
10597: @itemize @bullet
10598: @item
10599: It is straightforward to pass objects on the stack. Passing
10600: selectors on the stack is a little less convenient, but possible.
10601:
10602: @item
10603: Objects are just data structures in memory, and are referenced by their
10604: address. You can create words for objects with normal defining words
10605: like @code{constant}. Likewise, there is no difference between instance
10606: variables that contain objects and those that contain other data.
10607:
10608: @item
10609: Late binding is efficient and easy to use.
10610:
10611: @item
10612: It avoids parsing, and thus avoids problems with state-smartness
10613: and reduced extensibility; for convenience there are a few parsing
10614: words, but they have non-parsing counterparts. There are also a few
10615: defining words that parse. This is hard to avoid, because all standard
10616: defining words parse (except @code{:noname}); however, such
10617: words are not as bad as many other parsing words, because they are not
10618: state-smart.
10619:
10620: @item
10621: It does not try to incorporate everything. It does a few things and does
10622: them well (IMO). In particular, this model was not designed to support
10623: information hiding (although it has features that may help); you can use
10624: a separate package for achieving this.
10625:
10626: @item
10627: It is layered; you don't have to learn and use all features to use this
10628: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10629: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10630: are optional and independent of each other.
10631:
10632: @item
10633: An implementation in ANS Forth is available.
10634:
10635: @end itemize
10636:
10637:
10638: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10639: @subsubsection Basic @file{objects.fs} Usage
10640: @cindex basic objects usage
10641: @cindex objects, basic usage
10642:
10643: You can define a class for graphical objects like this:
10644:
10645: @cindex @code{class} usage
10646: @cindex @code{end-class} usage
10647: @cindex @code{selector} usage
10648: @example
10649: object class \ "object" is the parent class
10650: selector draw ( x y graphical -- )
10651: end-class graphical
10652: @end example
10653:
10654: This code defines a class @code{graphical} with an
10655: operation @code{draw}. We can perform the operation
10656: @code{draw} on any @code{graphical} object, e.g.:
10657:
10658: @example
10659: 100 100 t-rex draw
10660: @end example
10661:
10662: @noindent
10663: where @code{t-rex} is a word (say, a constant) that produces a
10664: graphical object.
10665:
10666: @comment TODO add a 2nd operation eg perimeter.. and use for
10667: @comment a concrete example
10668:
10669: @cindex abstract class
10670: How do we create a graphical object? With the present definitions,
10671: we cannot create a useful graphical object. The class
10672: @code{graphical} describes graphical objects in general, but not
10673: any concrete graphical object type (C++ users would call it an
10674: @emph{abstract class}); e.g., there is no method for the selector
10675: @code{draw} in the class @code{graphical}.
10676:
10677: For concrete graphical objects, we define child classes of the
10678: class @code{graphical}, e.g.:
10679:
10680: @cindex @code{overrides} usage
10681: @cindex @code{field} usage in class definition
10682: @example
10683: graphical class \ "graphical" is the parent class
10684: cell% field circle-radius
10685:
10686: :noname ( x y circle -- )
10687: circle-radius @@ draw-circle ;
10688: overrides draw
10689:
10690: :noname ( n-radius circle -- )
10691: circle-radius ! ;
10692: overrides construct
10693:
10694: end-class circle
10695: @end example
10696:
10697: Here we define a class @code{circle} as a child of @code{graphical},
10698: with field @code{circle-radius} (which behaves just like a field
10699: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10700: for the selectors @code{draw} and @code{construct} (@code{construct} is
10701: defined in @code{object}, the parent class of @code{graphical}).
10702:
10703: Now we can create a circle on the heap (i.e.,
10704: @code{allocate}d memory) with:
10705:
10706: @cindex @code{heap-new} usage
10707: @example
10708: 50 circle heap-new constant my-circle
10709: @end example
10710:
10711: @noindent
10712: @code{heap-new} invokes @code{construct}, thus
10713: initializing the field @code{circle-radius} with 50. We can draw
10714: this new circle at (100,100) with:
10715:
10716: @example
10717: 100 100 my-circle draw
10718: @end example
10719:
10720: @cindex selector invocation, restrictions
10721: @cindex class definition, restrictions
10722: Note: You can only invoke a selector if the object on the TOS
10723: (the receiving object) belongs to the class where the selector was
10724: defined or one of its descendents; e.g., you can invoke
10725: @code{draw} only for objects belonging to @code{graphical}
10726: or its descendents (e.g., @code{circle}). Immediately before
10727: @code{end-class}, the search order has to be the same as
10728: immediately after @code{class}.
10729:
10730: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10731: @subsubsection The @file{object.fs} base class
10732: @cindex @code{object} class
10733:
10734: When you define a class, you have to specify a parent class. So how do
10735: you start defining classes? There is one class available from the start:
10736: @code{object}. It is ancestor for all classes and so is the
10737: only class that has no parent. It has two selectors: @code{construct}
10738: and @code{print}.
10739:
10740: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10741: @subsubsection Creating objects
10742: @cindex creating objects
10743: @cindex object creation
10744: @cindex object allocation options
10745:
10746: @cindex @code{heap-new} discussion
10747: @cindex @code{dict-new} discussion
10748: @cindex @code{construct} discussion
10749: You can create and initialize an object of a class on the heap with
10750: @code{heap-new} ( ... class -- object ) and in the dictionary
10751: (allocation with @code{allot}) with @code{dict-new} (
10752: ... class -- object ). Both words invoke @code{construct}, which
10753: consumes the stack items indicated by "..." above.
10754:
10755: @cindex @code{init-object} discussion
10756: @cindex @code{class-inst-size} discussion
10757: If you want to allocate memory for an object yourself, you can get its
10758: alignment and size with @code{class-inst-size 2@@} ( class --
10759: align size ). Once you have memory for an object, you can initialize
10760: it with @code{init-object} ( ... class object -- );
10761: @code{construct} does only a part of the necessary work.
10762:
10763: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10764: @subsubsection Object-Oriented Programming Style
10765: @cindex object-oriented programming style
10766: @cindex programming style, object-oriented
10767:
10768: This section is not exhaustive.
10769:
10770: @cindex stack effects of selectors
10771: @cindex selectors and stack effects
10772: In general, it is a good idea to ensure that all methods for the
10773: same selector have the same stack effect: when you invoke a selector,
10774: you often have no idea which method will be invoked, so, unless all
10775: methods have the same stack effect, you will not know the stack effect
10776: of the selector invocation.
10777:
10778: One exception to this rule is methods for the selector
10779: @code{construct}. We know which method is invoked, because we
10780: specify the class to be constructed at the same place. Actually, I
10781: defined @code{construct} as a selector only to give the users a
10782: convenient way to specify initialization. The way it is used, a
10783: mechanism different from selector invocation would be more natural
10784: (but probably would take more code and more space to explain).
10785:
10786: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10787: @subsubsection Class Binding
10788: @cindex class binding
10789: @cindex early binding
10790:
10791: @cindex late binding
10792: Normal selector invocations determine the method at run-time depending
10793: on the class of the receiving object. This run-time selection is called
10794: @i{late binding}.
10795:
10796: Sometimes it's preferable to invoke a different method. For example,
10797: you might want to use the simple method for @code{print}ing
10798: @code{object}s instead of the possibly long-winded @code{print} method
10799: of the receiver class. You can achieve this by replacing the invocation
10800: of @code{print} with:
10801:
10802: @cindex @code{[bind]} usage
10803: @example
10804: [bind] object print
10805: @end example
10806:
10807: @noindent
10808: in compiled code or:
10809:
10810: @cindex @code{bind} usage
10811: @example
10812: bind object print
10813: @end example
10814:
10815: @cindex class binding, alternative to
10816: @noindent
10817: in interpreted code. Alternatively, you can define the method with a
10818: name (e.g., @code{print-object}), and then invoke it through the
10819: name. Class binding is just a (often more convenient) way to achieve
10820: the same effect; it avoids name clutter and allows you to invoke
10821: methods directly without naming them first.
10822:
10823: @cindex superclass binding
10824: @cindex parent class binding
10825: A frequent use of class binding is this: When we define a method
10826: for a selector, we often want the method to do what the selector does
10827: in the parent class, and a little more. There is a special word for
10828: this purpose: @code{[parent]}; @code{[parent]
10829: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10830: selector}}, where @code{@emph{parent}} is the parent
10831: class of the current class. E.g., a method definition might look like:
10832:
10833: @cindex @code{[parent]} usage
10834: @example
10835: :noname
10836: dup [parent] foo \ do parent's foo on the receiving object
10837: ... \ do some more
10838: ; overrides foo
10839: @end example
10840:
10841: @cindex class binding as optimization
10842: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10843: March 1997), Andrew McKewan presents class binding as an optimization
10844: technique. I recommend not using it for this purpose unless you are in
10845: an emergency. Late binding is pretty fast with this model anyway, so the
10846: benefit of using class binding is small; the cost of using class binding
10847: where it is not appropriate is reduced maintainability.
10848:
10849: While we are at programming style questions: You should bind
10850: selectors only to ancestor classes of the receiving object. E.g., say,
10851: you know that the receiving object is of class @code{foo} or its
10852: descendents; then you should bind only to @code{foo} and its
10853: ancestors.
10854:
10855: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10856: @subsubsection Method conveniences
10857: @cindex method conveniences
10858:
10859: In a method you usually access the receiving object pretty often. If
10860: you define the method as a plain colon definition (e.g., with
10861: @code{:noname}), you may have to do a lot of stack
10862: gymnastics. To avoid this, you can define the method with @code{m:
10863: ... ;m}. E.g., you could define the method for
10864: @code{draw}ing a @code{circle} with
10865:
10866: @cindex @code{this} usage
10867: @cindex @code{m:} usage
10868: @cindex @code{;m} usage
10869: @example
10870: m: ( x y circle -- )
10871: ( x y ) this circle-radius @@ draw-circle ;m
10872: @end example
10873:
10874: @cindex @code{exit} in @code{m: ... ;m}
10875: @cindex @code{exitm} discussion
10876: @cindex @code{catch} in @code{m: ... ;m}
10877: When this method is executed, the receiver object is removed from the
10878: stack; you can access it with @code{this} (admittedly, in this
10879: example the use of @code{m: ... ;m} offers no advantage). Note
10880: that I specify the stack effect for the whole method (i.e. including
10881: the receiver object), not just for the code between @code{m:}
10882: and @code{;m}. You cannot use @code{exit} in
10883: @code{m:...;m}; instead, use
10884: @code{exitm}.@footnote{Moreover, for any word that calls
10885: @code{catch} and was defined before loading
10886: @code{objects.fs}, you have to redefine it like I redefined
10887: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10888:
10889: @cindex @code{inst-var} usage
10890: You will frequently use sequences of the form @code{this
10891: @emph{field}} (in the example above: @code{this
10892: circle-radius}). If you use the field only in this way, you can
10893: define it with @code{inst-var} and eliminate the
10894: @code{this} before the field name. E.g., the @code{circle}
10895: class above could also be defined with:
10896:
10897: @example
10898: graphical class
10899: cell% inst-var radius
10900:
10901: m: ( x y circle -- )
10902: radius @@ draw-circle ;m
10903: overrides draw
10904:
10905: m: ( n-radius circle -- )
10906: radius ! ;m
10907: overrides construct
10908:
10909: end-class circle
10910: @end example
10911:
10912: @code{radius} can only be used in @code{circle} and its
10913: descendent classes and inside @code{m:...;m}.
10914:
10915: @cindex @code{inst-value} usage
10916: You can also define fields with @code{inst-value}, which is
10917: to @code{inst-var} what @code{value} is to
10918: @code{variable}. You can change the value of such a field with
10919: @code{[to-inst]}. E.g., we could also define the class
10920: @code{circle} like this:
10921:
10922: @example
10923: graphical class
10924: inst-value radius
10925:
10926: m: ( x y circle -- )
10927: radius draw-circle ;m
10928: overrides draw
10929:
10930: m: ( n-radius circle -- )
10931: [to-inst] radius ;m
10932: overrides construct
10933:
10934: end-class circle
10935: @end example
10936:
10937: @c !! :m is easy to confuse with m:. Another name would be better.
10938:
10939: @c Finally, you can define named methods with @code{:m}. One use of this
10940: @c feature is the definition of words that occur only in one class and are
10941: @c not intended to be overridden, but which still need method context
10942: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10943: @c would be bound frequently, if defined anonymously.
10944:
10945:
10946: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10947: @subsubsection Classes and Scoping
10948: @cindex classes and scoping
10949: @cindex scoping and classes
10950:
10951: Inheritance is frequent, unlike structure extension. This exacerbates
10952: the problem with the field name convention (@pxref{Structure Naming
10953: Convention}): One always has to remember in which class the field was
10954: originally defined; changing a part of the class structure would require
10955: changes for renaming in otherwise unaffected code.
10956:
10957: @cindex @code{inst-var} visibility
10958: @cindex @code{inst-value} visibility
10959: To solve this problem, I added a scoping mechanism (which was not in my
10960: original charter): A field defined with @code{inst-var} (or
10961: @code{inst-value}) is visible only in the class where it is defined and in
10962: the descendent classes of this class. Using such fields only makes
10963: sense in @code{m:}-defined methods in these classes anyway.
10964:
10965: This scoping mechanism allows us to use the unadorned field name,
10966: because name clashes with unrelated words become much less likely.
10967:
10968: @cindex @code{protected} discussion
10969: @cindex @code{private} discussion
10970: Once we have this mechanism, we can also use it for controlling the
10971: visibility of other words: All words defined after
10972: @code{protected} are visible only in the current class and its
10973: descendents. @code{public} restores the compilation
10974: (i.e. @code{current}) word list that was in effect before. If you
10975: have several @code{protected}s without an intervening
10976: @code{public} or @code{set-current}, @code{public}
10977: will restore the compilation word list in effect before the first of
10978: these @code{protected}s.
10979:
10980: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10981: @subsubsection Dividing classes
10982: @cindex Dividing classes
10983: @cindex @code{methods}...@code{end-methods}
10984:
10985: You may want to do the definition of methods separate from the
10986: definition of the class, its selectors, fields, and instance variables,
10987: i.e., separate the implementation from the definition. You can do this
10988: in the following way:
10989:
10990: @example
10991: graphical class
10992: inst-value radius
10993: end-class circle
10994:
10995: ... \ do some other stuff
10996:
10997: circle methods \ now we are ready
10998:
10999: m: ( x y circle -- )
11000: radius draw-circle ;m
11001: overrides draw
11002:
11003: m: ( n-radius circle -- )
11004: [to-inst] radius ;m
11005: overrides construct
11006:
11007: end-methods
11008: @end example
11009:
11010: You can use several @code{methods}...@code{end-methods} sections. The
11011: only things you can do to the class in these sections are: defining
11012: methods, and overriding the class's selectors. You must not define new
11013: selectors or fields.
11014:
11015: Note that you often have to override a selector before using it. In
11016: particular, you usually have to override @code{construct} with a new
11017: method before you can invoke @code{heap-new} and friends. E.g., you
11018: must not create a circle before the @code{overrides construct} sequence
11019: in the example above.
11020:
11021: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
11022: @subsubsection Object Interfaces
11023: @cindex object interfaces
11024: @cindex interfaces for objects
11025:
11026: In this model you can only call selectors defined in the class of the
11027: receiving objects or in one of its ancestors. If you call a selector
11028: with a receiving object that is not in one of these classes, the
11029: result is undefined; if you are lucky, the program crashes
11030: immediately.
11031:
11032: @cindex selectors common to hardly-related classes
11033: Now consider the case when you want to have a selector (or several)
11034: available in two classes: You would have to add the selector to a
11035: common ancestor class, in the worst case to @code{object}. You
11036: may not want to do this, e.g., because someone else is responsible for
11037: this ancestor class.
11038:
11039: The solution for this problem is interfaces. An interface is a
11040: collection of selectors. If a class implements an interface, the
11041: selectors become available to the class and its descendents. A class
11042: can implement an unlimited number of interfaces. For the problem
11043: discussed above, we would define an interface for the selector(s), and
11044: both classes would implement the interface.
11045:
11046: As an example, consider an interface @code{storage} for
11047: writing objects to disk and getting them back, and a class
11048: @code{foo} that implements it. The code would look like this:
11049:
11050: @cindex @code{interface} usage
11051: @cindex @code{end-interface} usage
11052: @cindex @code{implementation} usage
11053: @example
11054: interface
11055: selector write ( file object -- )
11056: selector read1 ( file object -- )
11057: end-interface storage
11058:
11059: bar class
11060: storage implementation
11061:
11062: ... overrides write
11063: ... overrides read1
11064: ...
11065: end-class foo
11066: @end example
11067:
11068: @noindent
11069: (I would add a word @code{read} @i{( file -- object )} that uses
11070: @code{read1} internally, but that's beyond the point illustrated
11071: here.)
11072:
11073: Note that you cannot use @code{protected} in an interface; and
11074: of course you cannot define fields.
11075:
11076: In the Neon model, all selectors are available for all classes;
11077: therefore it does not need interfaces. The price you pay in this model
11078: is slower late binding, and therefore, added complexity to avoid late
11079: binding.
11080:
11081: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
11082: @subsubsection @file{objects.fs} Implementation
11083: @cindex @file{objects.fs} implementation
11084:
11085: @cindex @code{object-map} discussion
11086: An object is a piece of memory, like one of the data structures
11087: described with @code{struct...end-struct}. It has a field
11088: @code{object-map} that points to the method map for the object's
11089: class.
11090:
11091: @cindex method map
11092: @cindex virtual function table
11093: The @emph{method map}@footnote{This is Self terminology; in C++
11094: terminology: virtual function table.} is an array that contains the
11095: execution tokens (@i{xt}s) of the methods for the object's class. Each
11096: selector contains an offset into a method map.
11097:
11098: @cindex @code{selector} implementation, class
11099: @code{selector} is a defining word that uses
11100: @code{CREATE} and @code{DOES>}. The body of the
11101: selector contains the offset; the @code{DOES>} action for a
11102: class selector is, basically:
11103:
11104: @example
11105: ( object addr ) @@ over object-map @@ + @@ execute
11106: @end example
11107:
11108: Since @code{object-map} is the first field of the object, it
11109: does not generate any code. As you can see, calling a selector has a
11110: small, constant cost.
11111:
11112: @cindex @code{current-interface} discussion
11113: @cindex class implementation and representation
11114: A class is basically a @code{struct} combined with a method
11115: map. During the class definition the alignment and size of the class
11116: are passed on the stack, just as with @code{struct}s, so
11117: @code{field} can also be used for defining class
11118: fields. However, passing more items on the stack would be
11119: inconvenient, so @code{class} builds a data structure in memory,
11120: which is accessed through the variable
11121: @code{current-interface}. After its definition is complete, the
11122: class is represented on the stack by a pointer (e.g., as parameter for
11123: a child class definition).
11124:
11125: A new class starts off with the alignment and size of its parent,
11126: and a copy of the parent's method map. Defining new fields extends the
11127: size and alignment; likewise, defining new selectors extends the
11128: method map. @code{overrides} just stores a new @i{xt} in the method
11129: map at the offset given by the selector.
11130:
11131: @cindex class binding, implementation
11132: Class binding just gets the @i{xt} at the offset given by the selector
11133: from the class's method map and @code{compile,}s (in the case of
11134: @code{[bind]}) it.
11135:
11136: @cindex @code{this} implementation
11137: @cindex @code{catch} and @code{this}
11138: @cindex @code{this} and @code{catch}
11139: I implemented @code{this} as a @code{value}. At the
11140: start of an @code{m:...;m} method the old @code{this} is
11141: stored to the return stack and restored at the end; and the object on
11142: the TOS is stored @code{TO this}. This technique has one
11143: disadvantage: If the user does not leave the method via
11144: @code{;m}, but via @code{throw} or @code{exit},
11145: @code{this} is not restored (and @code{exit} may
11146: crash). To deal with the @code{throw} problem, I have redefined
11147: @code{catch} to save and restore @code{this}; the same
11148: should be done with any word that can catch an exception. As for
11149: @code{exit}, I simply forbid it (as a replacement, there is
11150: @code{exitm}).
11151:
11152: @cindex @code{inst-var} implementation
11153: @code{inst-var} is just the same as @code{field}, with
11154: a different @code{DOES>} action:
11155: @example
11156: @@ this +
11157: @end example
11158: Similar for @code{inst-value}.
11159:
11160: @cindex class scoping implementation
11161: Each class also has a word list that contains the words defined with
11162: @code{inst-var} and @code{inst-value}, and its protected
11163: words. It also has a pointer to its parent. @code{class} pushes
11164: the word lists of the class and all its ancestors onto the search order stack,
11165: and @code{end-class} drops them.
11166:
11167: @cindex interface implementation
11168: An interface is like a class without fields, parent and protected
11169: words; i.e., it just has a method map. If a class implements an
11170: interface, its method map contains a pointer to the method map of the
11171: interface. The positive offsets in the map are reserved for class
11172: methods, therefore interface map pointers have negative
11173: offsets. Interfaces have offsets that are unique throughout the
11174: system, unlike class selectors, whose offsets are only unique for the
11175: classes where the selector is available (invokable).
11176:
11177: This structure means that interface selectors have to perform one
11178: indirection more than class selectors to find their method. Their body
11179: contains the interface map pointer offset in the class method map, and
11180: the method offset in the interface method map. The
11181: @code{does>} action for an interface selector is, basically:
11182:
11183: @example
11184: ( object selector-body )
11185: 2dup selector-interface @@ ( object selector-body object interface-offset )
11186: swap object-map @@ + @@ ( object selector-body map )
11187: swap selector-offset @@ + @@ execute
11188: @end example
11189:
11190: where @code{object-map} and @code{selector-offset} are
11191: first fields and generate no code.
11192:
11193: As a concrete example, consider the following code:
11194:
11195: @example
11196: interface
11197: selector if1sel1
11198: selector if1sel2
11199: end-interface if1
11200:
11201: object class
11202: if1 implementation
11203: selector cl1sel1
11204: cell% inst-var cl1iv1
11205:
11206: ' m1 overrides construct
11207: ' m2 overrides if1sel1
11208: ' m3 overrides if1sel2
11209: ' m4 overrides cl1sel2
11210: end-class cl1
11211:
11212: create obj1 object dict-new drop
11213: create obj2 cl1 dict-new drop
11214: @end example
11215:
11216: The data structure created by this code (including the data structure
11217: for @code{object}) is shown in the
11218: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11219: @comment TODO add this diagram..
11220:
11221: @node Objects Glossary, , Objects Implementation, Objects
11222: @subsubsection @file{objects.fs} Glossary
11223: @cindex @file{objects.fs} Glossary
11224:
11225:
11226: doc---objects-bind
11227: doc---objects-<bind>
11228: doc---objects-bind'
11229: doc---objects-[bind]
11230: doc---objects-class
11231: doc---objects-class->map
11232: doc---objects-class-inst-size
11233: doc---objects-class-override!
11234: doc---objects-class-previous
11235: doc---objects-class>order
11236: doc---objects-construct
11237: doc---objects-current'
11238: doc---objects-[current]
11239: doc---objects-current-interface
11240: doc---objects-dict-new
11241: doc---objects-end-class
11242: doc---objects-end-class-noname
11243: doc---objects-end-interface
11244: doc---objects-end-interface-noname
11245: doc---objects-end-methods
11246: doc---objects-exitm
11247: doc---objects-heap-new
11248: doc---objects-implementation
11249: doc---objects-init-object
11250: doc---objects-inst-value
11251: doc---objects-inst-var
11252: doc---objects-interface
11253: doc---objects-m:
11254: doc---objects-:m
11255: doc---objects-;m
11256: doc---objects-method
11257: doc---objects-methods
11258: doc---objects-object
11259: doc---objects-overrides
11260: doc---objects-[parent]
11261: doc---objects-print
11262: doc---objects-protected
11263: doc---objects-public
11264: doc---objects-selector
11265: doc---objects-this
11266: doc---objects-<to-inst>
11267: doc---objects-[to-inst]
11268: doc---objects-to-this
11269: doc---objects-xt-new
11270:
11271:
11272: @c -------------------------------------------------------------
11273: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11274: @subsection The @file{oof.fs} model
11275: @cindex oof
11276: @cindex object-oriented programming
11277:
11278: @cindex @file{objects.fs}
11279: @cindex @file{oof.fs}
11280:
11281: This section describes the @file{oof.fs} package.
11282:
11283: The package described in this section has been used in bigFORTH since 1991, and
11284: used for two large applications: a chromatographic system used to
11285: create new medicaments, and a graphic user interface library (MINOS).
11286:
11287: You can find a description (in German) of @file{oof.fs} in @cite{Object
11288: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11289: 10(2), 1994.
11290:
11291: @menu
11292: * Properties of the OOF model::
11293: * Basic OOF Usage::
11294: * The OOF base class::
11295: * Class Declaration::
11296: * Class Implementation::
11297: @end menu
11298:
11299: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11300: @subsubsection Properties of the @file{oof.fs} model
11301: @cindex @file{oof.fs} properties
11302:
11303: @itemize @bullet
11304: @item
11305: This model combines object oriented programming with information
11306: hiding. It helps you writing large application, where scoping is
11307: necessary, because it provides class-oriented scoping.
11308:
11309: @item
11310: Named objects, object pointers, and object arrays can be created,
11311: selector invocation uses the ``object selector'' syntax. Selector invocation
11312: to objects and/or selectors on the stack is a bit less convenient, but
11313: possible.
11314:
11315: @item
11316: Selector invocation and instance variable usage of the active object is
11317: straightforward, since both make use of the active object.
11318:
11319: @item
11320: Late binding is efficient and easy to use.
11321:
11322: @item
11323: State-smart objects parse selectors. However, extensibility is provided
11324: using a (parsing) selector @code{postpone} and a selector @code{'}.
11325:
11326: @item
11327: An implementation in ANS Forth is available.
11328:
11329: @end itemize
11330:
11331:
11332: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11333: @subsubsection Basic @file{oof.fs} Usage
11334: @cindex @file{oof.fs} usage
11335:
11336: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
11337:
11338: You can define a class for graphical objects like this:
11339:
11340: @cindex @code{class} usage
11341: @cindex @code{class;} usage
11342: @cindex @code{method} usage
11343: @example
11344: object class graphical \ "object" is the parent class
11345: method draw ( x y -- )
11346: class;
11347: @end example
11348:
11349: This code defines a class @code{graphical} with an
11350: operation @code{draw}. We can perform the operation
11351: @code{draw} on any @code{graphical} object, e.g.:
11352:
11353: @example
11354: 100 100 t-rex draw
11355: @end example
11356:
11357: @noindent
11358: where @code{t-rex} is an object or object pointer, created with e.g.
11359: @code{graphical : t-rex}.
11360:
11361: @cindex abstract class
11362: How do we create a graphical object? With the present definitions,
11363: we cannot create a useful graphical object. The class
11364: @code{graphical} describes graphical objects in general, but not
11365: any concrete graphical object type (C++ users would call it an
11366: @emph{abstract class}); e.g., there is no method for the selector
11367: @code{draw} in the class @code{graphical}.
11368:
11369: For concrete graphical objects, we define child classes of the
11370: class @code{graphical}, e.g.:
11371:
11372: @example
11373: graphical class circle \ "graphical" is the parent class
11374: cell var circle-radius
11375: how:
11376: : draw ( x y -- )
11377: circle-radius @@ draw-circle ;
11378:
11379: : init ( n-radius -- )
11380: circle-radius ! ;
11381: class;
11382: @end example
11383:
11384: Here we define a class @code{circle} as a child of @code{graphical},
11385: with a field @code{circle-radius}; it defines new methods for the
11386: selectors @code{draw} and @code{init} (@code{init} is defined in
11387: @code{object}, the parent class of @code{graphical}).
11388:
11389: Now we can create a circle in the dictionary with:
11390:
11391: @example
11392: 50 circle : my-circle
11393: @end example
11394:
11395: @noindent
11396: @code{:} invokes @code{init}, thus initializing the field
11397: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11398: with:
11399:
11400: @example
11401: 100 100 my-circle draw
11402: @end example
11403:
11404: @cindex selector invocation, restrictions
11405: @cindex class definition, restrictions
11406: Note: You can only invoke a selector if the receiving object belongs to
11407: the class where the selector was defined or one of its descendents;
11408: e.g., you can invoke @code{draw} only for objects belonging to
11409: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11410: mechanism will check if you try to invoke a selector that is not
11411: defined in this class hierarchy, so you'll get an error at compilation
11412: time.
11413:
11414:
11415: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11416: @subsubsection The @file{oof.fs} base class
11417: @cindex @file{oof.fs} base class
11418:
11419: When you define a class, you have to specify a parent class. So how do
11420: you start defining classes? There is one class available from the start:
11421: @code{object}. You have to use it as ancestor for all classes. It is the
11422: only class that has no parent. Classes are also objects, except that
11423: they don't have instance variables; class manipulation such as
11424: inheritance or changing definitions of a class is handled through
11425: selectors of the class @code{object}.
11426:
11427: @code{object} provides a number of selectors:
11428:
11429: @itemize @bullet
11430: @item
11431: @code{class} for subclassing, @code{definitions} to add definitions
11432: later on, and @code{class?} to get type informations (is the class a
11433: subclass of the class passed on the stack?).
11434:
11435: doc---object-class
11436: doc---object-definitions
11437: doc---object-class?
11438:
11439:
11440: @item
11441: @code{init} and @code{dispose} as constructor and destructor of the
11442: object. @code{init} is invocated after the object's memory is allocated,
11443: while @code{dispose} also handles deallocation. Thus if you redefine
11444: @code{dispose}, you have to call the parent's dispose with @code{super
11445: dispose}, too.
11446:
11447: doc---object-init
11448: doc---object-dispose
11449:
11450:
11451: @item
11452: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11453: @code{[]} to create named and unnamed objects and object arrays or
11454: object pointers.
11455:
11456: doc---object-new
11457: doc---object-new[]
11458: doc---object-:
11459: doc---object-ptr
11460: doc---object-asptr
11461: doc---object-[]
11462:
11463:
11464: @item
11465: @code{::} and @code{super} for explicit scoping. You should use explicit
11466: scoping only for super classes or classes with the same set of instance
11467: variables. Explicitly-scoped selectors use early binding.
11468:
11469: doc---object-::
11470: doc---object-super
11471:
11472:
11473: @item
11474: @code{self} to get the address of the object
11475:
11476: doc---object-self
11477:
11478:
11479: @item
11480: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11481: pointers and instance defers.
11482:
11483: doc---object-bind
11484: doc---object-bound
11485: doc---object-link
11486: doc---object-is
11487:
11488:
11489: @item
11490: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11491: form the stack, and @code{postpone} to generate selector invocation code.
11492:
11493: doc---object-'
11494: doc---object-postpone
11495:
11496:
11497: @item
11498: @code{with} and @code{endwith} to select the active object from the
11499: stack, and enable its scope. Using @code{with} and @code{endwith}
11500: also allows you to create code using selector @code{postpone} without being
11501: trapped by the state-smart objects.
11502:
11503: doc---object-with
11504: doc---object-endwith
11505:
11506:
11507: @end itemize
11508:
11509: @node Class Declaration, Class Implementation, The OOF base class, OOF
11510: @subsubsection Class Declaration
11511: @cindex class declaration
11512:
11513: @itemize @bullet
11514: @item
11515: Instance variables
11516:
11517: doc---oof-var
11518:
11519:
11520: @item
11521: Object pointers
11522:
11523: doc---oof-ptr
11524: doc---oof-asptr
11525:
11526:
11527: @item
11528: Instance defers
11529:
11530: doc---oof-defer
11531:
11532:
11533: @item
11534: Method selectors
11535:
11536: doc---oof-early
11537: doc---oof-method
11538:
11539:
11540: @item
11541: Class-wide variables
11542:
11543: doc---oof-static
11544:
11545:
11546: @item
11547: End declaration
11548:
11549: doc---oof-how:
11550: doc---oof-class;
11551:
11552:
11553: @end itemize
11554:
11555: @c -------------------------------------------------------------
11556: @node Class Implementation, , Class Declaration, OOF
11557: @subsubsection Class Implementation
11558: @cindex class implementation
11559:
11560: @c -------------------------------------------------------------
11561: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11562: @subsection The @file{mini-oof.fs} model
11563: @cindex mini-oof
11564:
11565: Gforth's third object oriented Forth package is a 12-liner. It uses a
11566: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
11567: and reduces to the bare minimum of features. This is based on a posting
11568: of Bernd Paysan in comp.lang.forth.
11569:
11570: @menu
11571: * Basic Mini-OOF Usage::
11572: * Mini-OOF Example::
11573: * Mini-OOF Implementation::
11574: @end menu
11575:
11576: @c -------------------------------------------------------------
11577: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11578: @subsubsection Basic @file{mini-oof.fs} Usage
11579: @cindex mini-oof usage
11580:
11581: There is a base class (@code{class}, which allocates one cell for the
11582: object pointer) plus seven other words: to define a method, a variable,
11583: a class; to end a class, to resolve binding, to allocate an object and
11584: to compile a class method.
11585: @comment TODO better description of the last one
11586:
11587:
11588: doc-object
11589: doc-method
11590: doc-var
11591: doc-class
11592: doc-end-class
11593: doc-defines
11594: doc-new
11595: doc-::
11596:
11597:
11598:
11599: @c -------------------------------------------------------------
11600: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11601: @subsubsection Mini-OOF Example
11602: @cindex mini-oof example
11603:
11604: A short example shows how to use this package. This example, in slightly
11605: extended form, is supplied as @file{moof-exm.fs}
11606: @comment TODO could flesh this out with some comments from the Forthwrite article
11607:
11608: @example
11609: object class
11610: method init
11611: method draw
11612: end-class graphical
11613: @end example
11614:
11615: This code defines a class @code{graphical} with an
11616: operation @code{draw}. We can perform the operation
11617: @code{draw} on any @code{graphical} object, e.g.:
11618:
11619: @example
11620: 100 100 t-rex draw
11621: @end example
11622:
11623: where @code{t-rex} is an object or object pointer, created with e.g.
11624: @code{graphical new Constant t-rex}.
11625:
11626: For concrete graphical objects, we define child classes of the
11627: class @code{graphical}, e.g.:
11628:
11629: @example
11630: graphical class
11631: cell var circle-radius
11632: end-class circle \ "graphical" is the parent class
11633:
11634: :noname ( x y -- )
11635: circle-radius @@ draw-circle ; circle defines draw
11636: :noname ( r -- )
11637: circle-radius ! ; circle defines init
11638: @end example
11639:
11640: There is no implicit init method, so we have to define one. The creation
11641: code of the object now has to call init explicitely.
11642:
11643: @example
11644: circle new Constant my-circle
11645: 50 my-circle init
11646: @end example
11647:
11648: It is also possible to add a function to create named objects with
11649: automatic call of @code{init}, given that all objects have @code{init}
11650: on the same place:
11651:
11652: @example
11653: : new: ( .. o "name" -- )
11654: new dup Constant init ;
11655: 80 circle new: large-circle
11656: @end example
11657:
11658: We can draw this new circle at (100,100) with:
11659:
11660: @example
11661: 100 100 my-circle draw
11662: @end example
11663:
11664: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11665: @subsubsection @file{mini-oof.fs} Implementation
11666:
11667: Object-oriented systems with late binding typically use a
11668: ``vtable''-approach: the first variable in each object is a pointer to a
11669: table, which contains the methods as function pointers. The vtable
11670: may also contain other information.
11671:
11672: So first, let's declare selectors:
11673:
11674: @example
11675: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
11676: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11677: @end example
11678:
11679: During selector declaration, the number of selectors and instance
11680: variables is on the stack (in address units). @code{method} creates one
11681: selector and increments the selector number. To execute a selector, it
11682: takes the object, fetches the vtable pointer, adds the offset, and
11683: executes the method @i{xt} stored there. Each selector takes the object
11684: it is invoked with as top of stack parameter; it passes the parameters
11685: (including the object) unchanged to the appropriate method which should
11686: consume that object.
11687:
11688: Now, we also have to declare instance variables
11689:
11690: @example
11691: : var ( m v size "name" -- m v' ) Create over , +
11692: DOES> ( o -- addr ) @@ + ;
11693: @end example
11694:
11695: As before, a word is created with the current offset. Instance
11696: variables can have different sizes (cells, floats, doubles, chars), so
11697: all we do is take the size and add it to the offset. If your machine
11698: has alignment restrictions, put the proper @code{aligned} or
11699: @code{faligned} before the variable, to adjust the variable
11700: offset. That's why it is on the top of stack.
11701:
11702: We need a starting point (the base object) and some syntactic sugar:
11703:
11704: @example
11705: Create object 1 cells , 2 cells ,
11706: : class ( class -- class selectors vars ) dup 2@@ ;
11707: @end example
11708:
11709: For inheritance, the vtable of the parent object has to be
11710: copied when a new, derived class is declared. This gives all the
11711: methods of the parent class, which can be overridden, though.
11712:
11713: @example
11714: : end-class ( class selectors vars "name" -- )
11715: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11716: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11717: @end example
11718:
11719: The first line creates the vtable, initialized with
11720: @code{noop}s. The second line is the inheritance mechanism, it
11721: copies the xts from the parent vtable.
11722:
11723: We still have no way to define new methods, let's do that now:
11724:
11725: @example
11726: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11727: @end example
11728:
11729: To allocate a new object, we need a word, too:
11730:
11731: @example
11732: : new ( class -- o ) here over @@ allot swap over ! ;
11733: @end example
11734:
11735: Sometimes derived classes want to access the method of the
11736: parent object. There are two ways to achieve this with Mini-OOF:
11737: first, you could use named words, and second, you could look up the
11738: vtable of the parent object.
11739:
11740: @example
11741: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11742: @end example
11743:
11744:
11745: Nothing can be more confusing than a good example, so here is
11746: one. First let's declare a text object (called
11747: @code{button}), that stores text and position:
11748:
11749: @example
11750: object class
11751: cell var text
11752: cell var len
11753: cell var x
11754: cell var y
11755: method init
11756: method draw
11757: end-class button
11758: @end example
11759:
11760: @noindent
11761: Now, implement the two methods, @code{draw} and @code{init}:
11762:
11763: @example
11764: :noname ( o -- )
11765: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11766: button defines draw
11767: :noname ( addr u o -- )
11768: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11769: button defines init
11770: @end example
11771:
11772: @noindent
11773: To demonstrate inheritance, we define a class @code{bold-button}, with no
11774: new data and no new selectors:
11775:
11776: @example
11777: button class
11778: end-class bold-button
11779:
11780: : bold 27 emit ." [1m" ;
11781: : normal 27 emit ." [0m" ;
11782: @end example
11783:
11784: @noindent
11785: The class @code{bold-button} has a different draw method to
11786: @code{button}, but the new method is defined in terms of the draw method
11787: for @code{button}:
11788:
11789: @example
11790: :noname bold [ button :: draw ] normal ; bold-button defines draw
11791: @end example
11792:
11793: @noindent
11794: Finally, create two objects and apply selectors:
11795:
11796: @example
11797: button new Constant foo
11798: s" thin foo" foo init
11799: page
11800: foo draw
11801: bold-button new Constant bar
11802: s" fat bar" bar init
11803: 1 bar y !
11804: bar draw
11805: @end example
11806:
11807:
11808: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11809: @subsection Comparison with other object models
11810: @cindex comparison of object models
11811: @cindex object models, comparison
11812:
11813: Many object-oriented Forth extensions have been proposed (@cite{A survey
11814: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11815: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11816: relation of the object models described here to two well-known and two
11817: closely-related (by the use of method maps) models. Andras Zsoter
11818: helped us with this section.
11819:
11820: @cindex Neon model
11821: The most popular model currently seems to be the Neon model (see
11822: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11823: 1997) by Andrew McKewan) but this model has a number of limitations
11824: @footnote{A longer version of this critique can be
11825: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11826: Dimensions, May 1997) by Anton Ertl.}:
11827:
11828: @itemize @bullet
11829: @item
11830: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11831: to pass objects on the stack.
11832:
11833: @item
11834: It requires that the selector parses the input stream (at
11835: compile time); this leads to reduced extensibility and to bugs that are
11836: hard to find.
11837:
11838: @item
11839: It allows using every selector on every object; this eliminates the
11840: need for interfaces, but makes it harder to create efficient
11841: implementations.
11842: @end itemize
11843:
11844: @cindex Pountain's object-oriented model
11845: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11846: Press, London, 1987) by Dick Pountain. However, it is not really about
11847: object-oriented programming, because it hardly deals with late
11848: binding. Instead, it focuses on features like information hiding and
11849: overloading that are characteristic of modular languages like Ada (83).
11850:
11851: @cindex Zsoter's object-oriented model
11852: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11853: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11854: describes a model that makes heavy use of an active object (like
11855: @code{this} in @file{objects.fs}): The active object is not only used
11856: for accessing all fields, but also specifies the receiving object of
11857: every selector invocation; you have to change the active object
11858: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11859: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11860: the method entry point is unnecessary with Zsoter's model, because the
11861: receiving object is the active object already. On the other hand, the
11862: explicit change is absolutely necessary in that model, because otherwise
11863: no one could ever change the active object. An ANS Forth implementation
11864: of this model is available through
11865: @uref{http://www.forth.org/oopf.html}.
11866:
11867: @cindex @file{oof.fs}, differences to other models
11868: The @file{oof.fs} model combines information hiding and overloading
11869: resolution (by keeping names in various word lists) with object-oriented
11870: programming. It sets the active object implicitly on method entry, but
11871: also allows explicit changing (with @code{>o...o>} or with
11872: @code{with...endwith}). It uses parsing and state-smart objects and
11873: classes for resolving overloading and for early binding: the object or
11874: class parses the selector and determines the method from this. If the
11875: selector is not parsed by an object or class, it performs a call to the
11876: selector for the active object (late binding), like Zsoter's model.
11877: Fields are always accessed through the active object. The big
11878: disadvantage of this model is the parsing and the state-smartness, which
11879: reduces extensibility and increases the opportunities for subtle bugs;
11880: essentially, you are only safe if you never tick or @code{postpone} an
11881: object or class (Bernd disagrees, but I (Anton) am not convinced).
11882:
11883: @cindex @file{mini-oof.fs}, differences to other models
11884: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11885: version of the @file{objects.fs} model, but syntactically it is a
11886: mixture of the @file{objects.fs} and @file{oof.fs} models.
11887:
11888:
11889: @c -------------------------------------------------------------
11890: @node Programming Tools, C Interface, Object-oriented Forth, Words
11891: @section Programming Tools
11892: @cindex programming tools
11893:
11894: @c !! move this and assembler down below OO stuff.
11895:
11896: @menu
11897: * Examining:: Data and Code.
11898: * Forgetting words:: Usually before reloading.
11899: * Debugging:: Simple and quick.
11900: * Assertions:: Making your programs self-checking.
11901: * Singlestep Debugger:: Executing your program word by word.
11902: @end menu
11903:
11904: @node Examining, Forgetting words, Programming Tools, Programming Tools
11905: @subsection Examining data and code
11906: @cindex examining data and code
11907: @cindex data examination
11908: @cindex code examination
11909:
11910: The following words inspect the stack non-destructively:
11911:
11912: doc-.s
11913: doc-f.s
11914: doc-maxdepth-.s
11915:
11916: There is a word @code{.r} but it does @i{not} display the return stack!
11917: It is used for formatted numeric output (@pxref{Simple numeric output}).
11918:
11919: doc-depth
11920: doc-fdepth
11921: doc-clearstack
11922: doc-clearstacks
11923:
11924: The following words inspect memory.
11925:
11926: doc-?
11927: doc-dump
11928:
11929: And finally, @code{see} allows to inspect code:
11930:
11931: doc-see
11932: doc-xt-see
11933: doc-simple-see
11934: doc-simple-see-range
11935: doc-see-code
11936: doc-see-code-range
11937:
11938: @node Forgetting words, Debugging, Examining, Programming Tools
11939: @subsection Forgetting words
11940: @cindex words, forgetting
11941: @cindex forgeting words
11942:
11943: @c anton: other, maybe better places for this subsection: Defining Words;
11944: @c Dictionary allocation. At least a reference should be there.
11945:
11946: Forth allows you to forget words (and everything that was alloted in the
11947: dictonary after them) in a LIFO manner.
11948:
11949: doc-marker
11950:
11951: The most common use of this feature is during progam development: when
11952: you change a source file, forget all the words it defined and load it
11953: again (since you also forget everything defined after the source file
11954: was loaded, you have to reload that, too). Note that effects like
11955: storing to variables and destroyed system words are not undone when you
11956: forget words. With a system like Gforth, that is fast enough at
11957: starting up and compiling, I find it more convenient to exit and restart
11958: Gforth, as this gives me a clean slate.
11959:
11960: Here's an example of using @code{marker} at the start of a source file
11961: that you are debugging; it ensures that you only ever have one copy of
11962: the file's definitions compiled at any time:
11963:
11964: @example
11965: [IFDEF] my-code
11966: my-code
11967: [ENDIF]
11968:
11969: marker my-code
11970: init-included-files
11971:
11972: \ .. definitions start here
11973: \ .
11974: \ .
11975: \ end
11976: @end example
11977:
11978:
11979: @node Debugging, Assertions, Forgetting words, Programming Tools
11980: @subsection Debugging
11981: @cindex debugging
11982:
11983: Languages with a slow edit/compile/link/test development loop tend to
11984: require sophisticated tracing/stepping debuggers to facilate debugging.
11985:
11986: A much better (faster) way in fast-compiling languages is to add
11987: printing code at well-selected places, let the program run, look at
11988: the output, see where things went wrong, add more printing code, etc.,
11989: until the bug is found.
11990:
11991: The simple debugging aids provided in @file{debugs.fs}
11992: are meant to support this style of debugging.
11993:
11994: The word @code{~~} prints debugging information (by default the source
11995: location and the stack contents). It is easy to insert. If you use Emacs
11996: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11997: query-replace them with nothing). The deferred words
11998: @code{printdebugdata} and @code{.debugline} control the output of
11999: @code{~~}. The default source location output format works well with
12000: Emacs' compilation mode, so you can step through the program at the
12001: source level using @kbd{C-x `} (the advantage over a stepping debugger
12002: is that you can step in any direction and you know where the crash has
12003: happened or where the strange data has occurred).
12004:
12005: doc-~~
12006: doc-printdebugdata
12007: doc-.debugline
12008: doc-debug-fid
12009:
12010: @cindex filenames in @code{~~} output
12011: @code{~~} (and assertions) will usually print the wrong file name if a
12012: marker is executed in the same file after their occurance. They will
12013: print @samp{*somewhere*} as file name if a marker is executed in the
12014: same file before their occurance.
12015:
12016:
12017: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
12018: @subsection Assertions
12019: @cindex assertions
12020:
12021: It is a good idea to make your programs self-checking, especially if you
12022: make an assumption that may become invalid during maintenance (for
12023: example, that a certain field of a data structure is never zero). Gforth
12024: supports @dfn{assertions} for this purpose. They are used like this:
12025:
12026: @example
12027: assert( @i{flag} )
12028: @end example
12029:
12030: The code between @code{assert(} and @code{)} should compute a flag, that
12031: should be true if everything is alright and false otherwise. It should
12032: not change anything else on the stack. The overall stack effect of the
12033: assertion is @code{( -- )}. E.g.
12034:
12035: @example
12036: assert( 1 1 + 2 = ) \ what we learn in school
12037: assert( dup 0<> ) \ assert that the top of stack is not zero
12038: assert( false ) \ this code should not be reached
12039: @end example
12040:
12041: The need for assertions is different at different times. During
12042: debugging, we want more checking, in production we sometimes care more
12043: for speed. Therefore, assertions can be turned off, i.e., the assertion
12044: becomes a comment. Depending on the importance of an assertion and the
12045: time it takes to check it, you may want to turn off some assertions and
12046: keep others turned on. Gforth provides several levels of assertions for
12047: this purpose:
12048:
12049:
12050: doc-assert0(
12051: doc-assert1(
12052: doc-assert2(
12053: doc-assert3(
12054: doc-assert(
12055: doc-)
12056:
12057:
12058: The variable @code{assert-level} specifies the highest assertions that
12059: are turned on. I.e., at the default @code{assert-level} of one,
12060: @code{assert0(} and @code{assert1(} assertions perform checking, while
12061: @code{assert2(} and @code{assert3(} assertions are treated as comments.
12062:
12063: The value of @code{assert-level} is evaluated at compile-time, not at
12064: run-time. Therefore you cannot turn assertions on or off at run-time;
12065: you have to set the @code{assert-level} appropriately before compiling a
12066: piece of code. You can compile different pieces of code at different
12067: @code{assert-level}s (e.g., a trusted library at level 1 and
12068: newly-written code at level 3).
12069:
12070:
12071: doc-assert-level
12072:
12073:
12074: If an assertion fails, a message compatible with Emacs' compilation mode
12075: is produced and the execution is aborted (currently with @code{ABORT"}.
12076: If there is interest, we will introduce a special throw code. But if you
12077: intend to @code{catch} a specific condition, using @code{throw} is
12078: probably more appropriate than an assertion).
12079:
12080: @cindex filenames in assertion output
12081: Assertions (and @code{~~}) will usually print the wrong file name if a
12082: marker is executed in the same file after their occurance. They will
12083: print @samp{*somewhere*} as file name if a marker is executed in the
12084: same file before their occurance.
12085:
12086: Definitions in ANS Forth for these assertion words are provided
12087: in @file{compat/assert.fs}.
12088:
12089:
12090: @node Singlestep Debugger, , Assertions, Programming Tools
12091: @subsection Singlestep Debugger
12092: @cindex singlestep Debugger
12093: @cindex debugging Singlestep
12094:
12095: The singlestep debugger works only with the engine @code{gforth-itc}.
12096:
12097: When you create a new word there's often the need to check whether it
12098: behaves correctly or not. You can do this by typing @code{dbg
12099: badword}. A debug session might look like this:
12100:
12101: @example
12102: : badword 0 DO i . LOOP ; ok
12103: 2 dbg badword
12104: : badword
12105: Scanning code...
12106:
12107: Nesting debugger ready!
12108:
12109: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
12110: 400D4740 8049F68 DO -> [ 0 ]
12111: 400D4744 804A0C8 i -> [ 1 ] 00000
12112: 400D4748 400C5E60 . -> 0 [ 0 ]
12113: 400D474C 8049D0C LOOP -> [ 0 ]
12114: 400D4744 804A0C8 i -> [ 1 ] 00001
12115: 400D4748 400C5E60 . -> 1 [ 0 ]
12116: 400D474C 8049D0C LOOP -> [ 0 ]
12117: 400D4758 804B384 ; -> ok
12118: @end example
12119:
12120: Each line displayed is one step. You always have to hit return to
12121: execute the next word that is displayed. If you don't want to execute
12122: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
12123: an overview what keys are available:
12124:
12125: @table @i
12126:
12127: @item @key{RET}
12128: Next; Execute the next word.
12129:
12130: @item n
12131: Nest; Single step through next word.
12132:
12133: @item u
12134: Unnest; Stop debugging and execute rest of word. If we got to this word
12135: with nest, continue debugging with the calling word.
12136:
12137: @item d
12138: Done; Stop debugging and execute rest.
12139:
12140: @item s
12141: Stop; Abort immediately.
12142:
12143: @end table
12144:
12145: Debugging large application with this mechanism is very difficult, because
12146: you have to nest very deeply into the program before the interesting part
12147: begins. This takes a lot of time.
12148:
12149: To do it more directly put a @code{BREAK:} command into your source code.
12150: When program execution reaches @code{BREAK:} the single step debugger is
12151: invoked and you have all the features described above.
12152:
12153: If you have more than one part to debug it is useful to know where the
12154: program has stopped at the moment. You can do this by the
12155: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
12156: string is typed out when the ``breakpoint'' is reached.
12157:
12158:
12159: doc-dbg
12160: doc-break:
12161: doc-break"
12162:
12163: @c ------------------------------------------------------------
12164: @node C Interface, Assembler and Code Words, Programming Tools, Words
12165: @section C Interface
12166: @cindex C interface
12167: @cindex foreign language interface
12168: @cindex interface to C functions
12169:
12170: Note that the C interface is not yet complete; callbacks are missing,
12171: as well as a way of declaring structs, unions, and their fields.
12172:
12173: @menu
12174: * Calling C Functions::
12175: * Declaring C Functions::
12176: * Calling C function pointers::
12177: * Defining library interfaces::
12178: * Declaring OS-level libraries::
12179: * Callbacks::
12180: * C interface internals::
12181: * Low-Level C Interface Words::
12182: @end menu
12183:
12184: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
12185: @subsection Calling C functions
12186: @cindex C functions, calls to
12187: @cindex calling C functions
12188:
12189: Once a C function is declared (see @pxref{Declaring C Functions}), you
12190: can call it as follows: You push the arguments on the stack(s), and
12191: then call the word for the C function. The arguments have to be
12192: pushed in the same order as the arguments appear in the C
12193: documentation (i.e., the first argument is deepest on the stack).
12194: Integer and pointer arguments have to be pushed on the data stack,
12195: floating-point arguments on the FP stack; these arguments are consumed
12196: by the called C function.
12197:
12198: On returning from the C function, the return value, if any, resides on
12199: the appropriate stack: an integer return value is pushed on the data
12200: stack, an FP return value on the FP stack, and a void return value
12201: results in not pushing anything. Note that most C functions have a
12202: return value, even if that is often not used in C; in Forth, you have
12203: to @code{drop} this return value explicitly if you do not use it.
12204:
12205: The C interface automatically converts between the C type and the
12206: Forth type as necessary, on a best-effort basis (in some cases, there
12207: may be some loss).
12208:
12209: As an example, consider the POSIX function @code{lseek()}:
12210:
12211: @example
12212: off_t lseek(int fd, off_t offset, int whence);
12213: @end example
12214:
12215: This function takes three integer arguments, and returns an integer
12216: argument, so a Forth call for setting the current file offset to the
12217: start of the file could look like this:
12218:
12219: @example
12220: fd @@ 0 SEEK_SET lseek -1 = if
12221: ... \ error handling
12222: then
12223: @end example
12224:
12225: You might be worried that an @code{off_t} does not fit into a cell, so
12226: you could not pass larger offsets to lseek, and might get only a part
12227: of the return values. In that case, in your declaration of the
12228: function (@pxref{Declaring C Functions}) you should declare it to use
12229: double-cells for the off_t argument and return value, and maybe give
12230: the resulting Forth word a different name, like @code{dlseek}; the
12231: result could be called like this:
12232:
12233: @example
12234: fd @@ 0. SEEK_SET dlseek -1. d= if
12235: ... \ error handling
12236: then
12237: @end example
12238:
12239: Passing and returning structs or unions is currently not supported by
12240: our interface@footnote{If you know the calling convention of your C
12241: compiler, you usually can call such functions in some way, but that
12242: way is usually not portable between platforms, and sometimes not even
12243: between C compilers.}.
12244:
12245: Calling functions with a variable number of arguments (@emph{variadic}
12246: functions, e.g., @code{printf()}) is only supported by having you
12247: declare one function-calling word for each argument pattern, and
12248: calling the appropriate word for the desired pattern.
12249:
12250:
12251:
12252: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
12253: @subsection Declaring C Functions
12254: @cindex C functions, declarations
12255: @cindex declaring C functions
12256:
12257: Before you can call @code{lseek} or @code{dlseek}, you have to declare
12258: it. The declaration consists of two parts:
12259:
12260: @table @b
12261:
12262: @item The C part
12263: is the C declaration of the function, or more typically and portably,
12264: a C-style @code{#include} of a file that contains the declaration of
12265: the C function.
12266:
12267: @item The Forth part
12268: declares the Forth types of the parameters and the Forth word name
12269: corresponding to the C function.
12270:
12271: @end table
12272:
12273: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12274: declarations are:
12275:
12276: @example
12277: \c #define _FILE_OFFSET_BITS 64
12278: \c #include <sys/types.h>
12279: \c #include <unistd.h>
12280: c-function lseek lseek n n n -- n
12281: c-function dlseek lseek n d n -- d
12282: @end example
12283:
12284: The C part of the declarations is prefixed by @code{\c}, and the rest
12285: of the line is ordinary C code. You can use as many lines of C
12286: declarations as you like, and they are visible for all further
12287: function declarations.
12288:
12289: The Forth part declares each interface word with @code{c-function},
12290: followed by the Forth name of the word, the C name of the called
12291: function, and the stack effect of the word. The stack effect contains
12292: an arbitrary number of types of parameters, then @code{--}, and then
12293: exactly one type for the return value. The possible types are:
12294:
12295: @table @code
12296:
12297: @item n
12298: single-cell integer
12299:
12300: @item a
12301: address (single-cell)
12302:
12303: @item d
12304: double-cell integer
12305:
12306: @item r
12307: floating-point value
12308:
12309: @item func
12310: C function pointer
12311:
12312: @item void
12313: no value (used as return type for void functions)
12314:
12315: @end table
12316:
12317: @cindex variadic C functions
12318:
12319: To deal with variadic C functions, you can declare one Forth word for
12320: every pattern you want to use, e.g.:
12321:
12322: @example
12323: \c #include <stdio.h>
12324: c-function printf-nr printf a n r -- n
12325: c-function printf-rn printf a r n -- n
12326: @end example
12327:
12328: Note that with C functions declared as variadic (or if you don't
12329: provide a prototype), the C interface has no C type to convert to, so
12330: no automatic conversion happens, which may lead to portability
12331: problems in some cases. In such cases you can perform the conversion
12332: explicitly on the C level, e.g., as follows:
12333:
12334: @example
12335: \c #define printfll(s,ll) printf(s,(long long)ll)
12336: c-function printfll printfll a n -- n
12337: @end example
12338:
12339: Here, instead of calling @code{printf()} directly, we define a macro
12340: that casts (converts) the Forth single-cell integer into a
12341: C @code{long long} before calling @code{printf()}.
12342:
12343: doc-\c
12344: doc-c-function
12345: doc-c-value
12346: doc-c-variable
12347:
12348: In order to work, this C interface invokes GCC at run-time and uses
12349: dynamic linking. If these features are not available, there are
12350: other, less convenient and less portable C interfaces in @file{lib.fs}
12351: and @file{oldlib.fs}. These interfaces are mostly undocumented and
12352: mostly incompatible with each other and with the documented C
12353: interface; you can find some examples for the @file{lib.fs} interface
12354: in @file{lib.fs}.
12355:
12356:
12357: @node Calling C function pointers, Defining library interfaces, Declaring C Functions, C Interface
12358: @subsection Calling C function pointers from Forth
12359: @cindex C function pointers, calling from Forth
12360:
12361: If you come across a C function pointer (e.g., in some C-constructed
12362: structure) and want to call it from your Forth program, you can also
12363: use the features explained until now to achieve that, as follows:
12364:
12365: Let us assume that there is a C function pointer type @code{func1}
12366: defined in some header file @file{func1.h}, and you know that these
12367: functions take one integer argument and return an integer result; and
12368: you want to call functions through such pointers. Just define
12369:
12370: @example
12371: \c #include <func1.h>
12372: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12373: c-function call-func1 call_func1 n func -- n
12374: @end example
12375:
12376: and then you can call a function pointed to by, say @code{func1a} as
12377: follows:
12378:
12379: @example
12380: -5 func1a call-func1 .
12381: @end example
12382:
12383: In the C part, @code{call_func} is defined as a macro to avoid having
12384: to declare the exact parameter and return types, so the C compiler
12385: knows them from the declaration of @code{func1}.
12386:
12387: The Forth word @code{call-func1} is similar to @code{execute}, except
12388: that it takes a C @code{func1} pointer instead of a Forth execution
12389: token, and it is specific to @code{func1} pointers. For each type of
12390: function pointer you want to call from Forth, you have to define
12391: a separate calling word.
12392:
12393:
12394: @node Defining library interfaces, Declaring OS-level libraries, Calling C function pointers, C Interface
12395: @subsection Defining library interfaces
12396: @cindex giving a name to a library interface
12397: @cindex library interface names
12398:
12399: You can give a name to a bunch of C function declarations (a library
12400: interface), as follows:
12401:
12402: @example
12403: c-library lseek-lib
12404: \c #define _FILE_OFFSET_BITS 64
12405: ...
12406: end-c-library
12407: @end example
12408:
12409: The effect of giving such a name to the interface is that the names of
12410: the generated files will contain that name, and when you use the
12411: interface a second time, it will use the existing files instead of
12412: generating and compiling them again, saving you time. Note that even
12413: if you change the declarations, the old (stale) files will be used,
12414: probably leading to errors. So, during development of the
12415: declarations we recommend not using @code{c-library}. Normally these
12416: files are cached in @file{$HOME/.gforth/libcc-named}, so by deleting
12417: that directory you can get rid of stale files.
12418:
12419: Note that you should use @code{c-library} before everything else
12420: having anything to do with that library, as it resets some setup
12421: stuff. The idea is that the typical use is to put each
12422: @code{c-library}...@code{end-library} unit in its own file, and to be
12423: able to include these files in any order.
12424:
12425: Note that the library name is not allocated in the dictionary and
12426: therefore does not shadow dictionary names. It is used in the file
12427: system, so you have to use naming conventions appropriate for file
12428: systems. Also, you must not call a function you declare after
12429: @code{c-library} before you perform @code{end-c-library}.
12430:
12431: A major benefit of these named library interfaces is that, once they
12432: are generated, the tools used to generated them (in particular, the C
12433: compiler and libtool) are no longer needed, so the interface can be
12434: used even on machines that do not have the tools installed.
12435:
12436: doc-c-library-name
12437: doc-c-library
12438: doc-end-c-library
12439:
12440:
12441: @node Declaring OS-level libraries, Callbacks, Defining library interfaces, C Interface
12442: @subsection Declaring OS-level libraries
12443: @cindex Shared libraries in C interface
12444: @cindex Dynamically linked libraries in C interface
12445: @cindex Libraries in C interface
12446:
12447: For calling some C functions, you need to link with a specific
12448: OS-level library that contains that function. E.g., the @code{sin}
12449: function requires linking a special library by using the command line
12450: switch @code{-lm}. In our C iterface you do the equivalent thing by
12451: calling @code{add-lib} as follows:
12452:
12453: @example
12454: clear-libs
12455: s" m" add-lib
12456: \c #include <math.h>
12457: c-function sin sin r -- r
12458: @end example
12459:
12460: First, you clear any libraries that may have been declared earlier
12461: (you don't need them for @code{sin}); then you add the @code{m}
12462: library (actually @code{libm.so} or somesuch) to the currently
12463: declared libraries; you can add as many as you need. Finally you
12464: declare the function as shown above. Typically you will use the same
12465: set of library declarations for many function declarations; you need
12466: to write only one set for that, right at the beginning.
12467:
12468: Note that you must not call @code{clear-libs} inside
12469: @code{c-library...end-c-library}; however, @code{c-library} performs
12470: the function of @code{clear-libs}, so @code{clear-libs} is not
12471: necessary, and you usually want to put @code{add-lib} calls inside
12472: @code{c-library...end-c-library}.
12473:
12474: doc-clear-libs
12475: doc-add-lib
12476:
12477:
12478: @node Callbacks, C interface internals, Declaring OS-level libraries, C Interface
12479: @subsection Callbacks
12480: @cindex Callback functions written in Forth
12481: @cindex C function pointers to Forth words
12482:
12483: Callbacks are not yet supported by the documented C interface. You
12484: can use the undocumented @file{lib.fs} interface for callbacks.
12485:
12486: In some cases you have to pass a function pointer to a C function,
12487: i.e., the library wants to call back to your application (and the
12488: pointed-to function is called a callback function). You can pass the
12489: address of an existing C function (that you get with @code{lib-sym},
12490: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12491: function, you probably want to define the function as a Forth word.
12492:
12493: @c I don't understand the existing callback interface from the example - anton
12494:
12495:
12496: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12497: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12498: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12499: @c > > C-Funktionsadresse auf dem TOS).
12500: @c >
12501: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12502: @c > gesehen habe, wozu das gut ist.
12503: @c
12504: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch
12505: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen
12506: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit
12507: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte
12508: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit
12509: @c demselben Prototyp.
12510:
12511:
12512: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
12513: @subsection How the C interface works
12514:
12515: The documented C interface works by generating a C code out of the
12516: declarations.
12517:
12518: In particular, for every Forth word declared with @code{c-function},
12519: it generates a wrapper function in C that takes the Forth data from
12520: the Forth stacks, and calls the target C function with these data as
12521: arguments. The C compiler then performs an implicit conversion
12522: between the Forth type from the stack, and the C type for the
12523: parameter, which is given by the C function prototype. After the C
12524: function returns, the return value is likewise implicitly converted to
12525: a Forth type and written back on the stack.
12526:
12527: The @code{\c} lines are literally included in the C code (but without
12528: the @code{\c}), and provide the necessary declarations so that the C
12529: compiler knows the C types and has enough information to perform the
12530: conversion.
12531:
12532: These wrapper functions are eventually compiled and dynamically linked
12533: into Gforth, and then they can be called.
12534:
12535: The libraries added with @code{add-lib} are used in the compile
12536: command line to specify dependent libraries with @code{-l@var{lib}},
12537: causing these libraries to be dynamically linked when the wrapper
12538: function is linked.
12539:
12540:
12541: @node Low-Level C Interface Words, , C interface internals, C Interface
12542: @subsection Low-Level C Interface Words
12543:
12544: doc-open-lib
12545: doc-lib-sym
12546: doc-lib-error
12547: doc-call-c
12548:
12549: @c -------------------------------------------------------------
12550: @node Assembler and Code Words, Threading Words, C Interface, Words
12551: @section Assembler and Code Words
12552: @cindex assembler
12553: @cindex code words
12554:
12555: @menu
12556: * Code and ;code::
12557: * Common Assembler:: Assembler Syntax
12558: * Common Disassembler::
12559: * 386 Assembler:: Deviations and special cases
12560: * Alpha Assembler:: Deviations and special cases
12561: * MIPS assembler:: Deviations and special cases
12562: * PowerPC assembler:: Deviations and special cases
12563: * ARM Assembler:: Deviations and special cases
12564: * Other assemblers:: How to write them
12565: @end menu
12566:
12567: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
12568: @subsection @code{Code} and @code{;code}
12569:
12570: Gforth provides some words for defining primitives (words written in
12571: machine code), and for defining the machine-code equivalent of
12572: @code{DOES>}-based defining words. However, the machine-independent
12573: nature of Gforth poses a few problems: First of all, Gforth runs on
12574: several architectures, so it can provide no standard assembler. What's
12575: worse is that the register allocation not only depends on the
12576: processor, but also on the @code{gcc} version and options used (still
12577: this problem can be worked around by using @code{ABI-CODE}).
12578:
12579: The words that Gforth offers encapsulate some system dependences (e.g.,
12580: the header structure), so a system-independent assembler may be used in
12581: Gforth. If you do not have an assembler, you can compile machine code
12582: directly with @code{,} and @code{c,}@footnote{This isn't portable,
12583: because these words emit stuff in @i{data} space; it works because
12584: Gforth has unified code/data spaces. Assembler isn't likely to be
12585: portable anyway.}.
12586:
12587:
12588: doc-assembler
12589: doc-init-asm
12590: doc-code
12591: doc-abi-code
12592: doc-end-code
12593: doc-;code
12594: doc-flush-icache
12595:
12596:
12597: If @code{flush-icache} does not work correctly, @code{code} words
12598: etc. will not work (reliably), either.
12599:
12600: The typical usage of these @code{code} words can be shown most easily by
12601: analogy to the equivalent high-level defining words:
12602:
12603: @example
12604: : foo code foo
12605: <high-level Forth words> <assembler>
12606: ; end-code
12607:
12608: : bar : bar
12609: <high-level Forth words> <high-level Forth words>
12610: CREATE CREATE
12611: <high-level Forth words> <high-level Forth words>
12612: DOES> ;code
12613: <high-level Forth words> <assembler>
12614: ; end-code
12615: @end example
12616:
12617: @c anton: the following stuff is also in "Common Assembler", in less detail.
12618:
12619: @cindex registers of the inner interpreter
12620: In the assembly code you will want to refer to the inner interpreter's
12621: registers (e.g., the data stack pointer) and you may want to use other
12622: registers for temporary storage. Unfortunately, the register allocation
12623: is installation-dependent.
12624:
12625: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
12626: (return stack pointer) may be in different places in @code{gforth} and
12627: @code{gforth-fast}, or different installations. This means that you
12628: cannot write a @code{NEXT} routine that works reliably on both versions
12629: or different installations; so for doing @code{NEXT}, I recommend
12630: jumping to @code{' noop >code-address}, which contains nothing but a
12631: @code{NEXT}.
12632:
12633: @cindex code words, using platform's ABI
12634: If you do not want to bother with the complexities of the
12635: interpreter's registers, you may use @code{ABI-CODE} for defining
12636: native code instead. @code{ABI-CODE} definitions are called with the
12637: C-Language's application binary interface (ABI) conventions of the
12638: platform, passing the Forth virtual machine's SP and FP as arguments,
12639: While this approach involves some (minor) overhead, it allows you to
12640: write code that is portable across different versions of GForth.
12641:
12642: For general accesses to the inner interpreter's registers, the easiest
12643: solution is to use explicit register declarations (@pxref{Explicit Reg
12644: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
12645: all of the inner interpreter's registers: You have to compile Gforth
12646: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
12647: the appropriate declarations must be present in the @code{machine.h}
12648: file (see @code{mips.h} for an example; you can find a full list of all
12649: declarable register symbols with @code{grep register engine.c}). If you
12650: give explicit registers to all variables that are declared at the
12651: beginning of @code{engine()}, you should be able to use the other
12652: caller-saved registers for temporary storage. Alternatively, you can use
12653: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
12654: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
12655: reserve a register (however, this restriction on register allocation may
12656: slow Gforth significantly).
12657:
12658: If this solution is not viable (e.g., because @code{gcc} does not allow
12659: you to explicitly declare all the registers you need), you have to find
12660: out by looking at the code where the inner interpreter's registers
12661: reside and which registers can be used for temporary storage. You can
12662: get an assembly listing of the engine's code with @code{make engine.s}.
12663:
12664: In any case, it is good practice to abstract your assembly code from the
12665: actual register allocation. E.g., if the data stack pointer resides in
12666: register @code{$17}, create an alias for this register called @code{sp},
12667: and use that in your assembly code.
12668:
12669: @cindex code words, portable
12670: Another option for implementing normal and defining words efficiently
12671: is to add the desired functionality to the source of Gforth. For normal
12672: words you just have to edit @file{primitives} (@pxref{Automatic
12673: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
12674: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
12675: @file{prims2x.fs}, and possibly @file{cross.fs}.
12676:
12677: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12678: @subsection Common Assembler
12679:
12680: The assemblers in Gforth generally use a postfix syntax, i.e., the
12681: instruction name follows the operands.
12682:
12683: The operands are passed in the usual order (the same that is used in the
12684: manual of the architecture). Since they all are Forth words, they have
12685: to be separated by spaces; you can also use Forth words to compute the
12686: operands.
12687:
12688: The instruction names usually end with a @code{,}. This makes it easier
12689: to visually separate instructions if you put several of them on one
12690: line; it also avoids shadowing other Forth words (e.g., @code{and}).
12691:
12692: Registers are usually specified by number; e.g., (decimal) @code{11}
12693: specifies registers R11 and F11 on the Alpha architecture (which one,
12694: depends on the instruction). The usual names are also available, e.g.,
12695: @code{s2} for R11 on Alpha.
12696:
12697: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12698: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12699: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12700: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12701: conditions are specified in a way specific to each assembler.
12702:
12703: Note that the register assignments of the Gforth engine can change
12704: between Gforth versions, or even between different compilations of the
12705: same Gforth version (e.g., if you use a different GCC version). If
12706: you are using @code{CODE} instead of @code{ABI-CODE}, and you want to
12707: refer to Gforth's registers (e.g., the stack pointer or TOS), I
12708: recommend defining your own words for refering to these registers, and
12709: using them later on; then you can easily adapt to a changed register
12710: assignment. The stability of the register assignment is usually
12711: better if you build Gforth with @code{--enable-force-reg}.
12712:
12713: The most common use of these registers is to dispatch to the next word
12714: (the @code{next} routine). A portable way to do this is to jump to
12715: @code{' noop >code-address} (of course, this is less efficient than
12716: integrating the @code{next} code and scheduling it well). When using
12717: @code{ABI-CODE}, you can just assemble a normal subroutine return (but
12718: make sure you return SP and FP back to the caller).
12719:
12720: Another difference between Gforth version is that the top of stack is
12721: kept in memory in @code{gforth} and, on most platforms, in a register
12722: in @code{gforth-fast}. For @code{ABI-CODE} definitions, any stack
12723: caching registers are guaranteed to be flushed to the stack, allowing
12724: you to reliably access the top of stack as @code{sp[0]}.
12725:
12726: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12727: @subsection Common Disassembler
12728: @cindex disassembler, general
12729: @cindex gdb disassembler
12730:
12731: You can disassemble a @code{code} word with @code{see}
12732: (@pxref{Debugging}). You can disassemble a section of memory with
12733:
12734: doc-discode
12735:
12736: There are two kinds of disassembler for Gforth: The Forth disassembler
12737: (available on some CPUs) and the gdb disassembler (available on
12738: platforms with @command{gdb} and @command{mktemp}). If both are
12739: available, the Forth disassembler is used by default. If you prefer
12740: the gdb disassembler, say
12741:
12742: @example
12743: ' disasm-gdb is discode
12744: @end example
12745:
12746: If neither is available, @code{discode} performs @code{dump}.
12747:
12748: The Forth disassembler generally produces output that can be fed into the
12749: assembler (i.e., same syntax, etc.). It also includes additional
12750: information in comments. In particular, the address of the instruction
12751: is given in a comment before the instruction.
12752:
12753: The gdb disassembler produces output in the same format as the gdb
12754: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12755: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12756: the 386 and AMD64 architectures).
12757:
12758: @code{See} may display more or less than the actual code of the word,
12759: because the recognition of the end of the code is unreliable. You can
12760: use @code{discode} if it did not display enough. It may display more, if
12761: the code word is not immediately followed by a named word. If you have
12762: something else there, you can follow the word with @code{align latest ,}
12763: to ensure that the end is recognized.
12764:
12765: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12766: @subsection 386 Assembler
12767:
12768: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12769: available under GPL, and originally part of bigFORTH.
12770:
12771: The 386 disassembler included in Gforth was written by Andrew McKewan
12772: and is in the public domain.
12773:
12774: The disassembler displays code in an Intel-like prefix syntax.
12775:
12776: The assembler uses a postfix syntax with reversed parameters.
12777:
12778: The assembler includes all instruction of the Athlon, i.e. 486 core
12779: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12780: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12781: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
12782:
12783: There are several prefixes to switch between different operation sizes,
12784: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12785: double-word accesses. Addressing modes can be switched with @code{.wa}
12786: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12787: need a prefix for byte register names (@code{AL} et al).
12788:
12789: For floating point operations, the prefixes are @code{.fs} (IEEE
12790: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12791: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
12792:
12793: The MMX opcodes don't have size prefixes, they are spelled out like in
12794: the Intel assembler. Instead of move from and to memory, there are
12795: PLDQ/PLDD and PSTQ/PSTD.
12796:
12797: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12798: ax. Immediate values are indicated by postfixing them with @code{#},
12799: e.g., @code{3 #}. Here are some examples of addressing modes in various
12800: syntaxes:
12801:
12802: @example
12803: Gforth Intel (NASM) AT&T (gas) Name
12804: .w ax ax %ax register (16 bit)
12805: ax eax %eax register (32 bit)
12806: 3 # offset 3 $3 immediate
12807: 1000 #) byte ptr 1000 1000 displacement
12808: bx ) [ebx] (%ebx) base
12809: 100 di d) 100[edi] 100(%edi) base+displacement
12810: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12811: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12812: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12813: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12814: @end example
12815:
12816: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12817: @code{DI)} to enforce 32-bit displacement fields (useful for
12818: later patching).
12819:
12820: Some example of instructions are:
12821:
12822: @example
12823: ax bx mov \ move ebx,eax
12824: 3 # ax mov \ mov eax,3
12825: 100 di d) ax mov \ mov eax,100[edi]
12826: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12827: .w ax bx mov \ mov bx,ax
12828: @end example
12829:
12830: The following forms are supported for binary instructions:
12831:
12832: @example
12833: <reg> <reg> <inst>
12834: <n> # <reg> <inst>
12835: <mem> <reg> <inst>
12836: <reg> <mem> <inst>
12837: <n> # <mem> <inst>
12838: @end example
12839:
12840: The shift/rotate syntax is:
12841:
12842: @example
12843: <reg/mem> 1 # shl \ shortens to shift without immediate
12844: <reg/mem> 4 # shl
12845: <reg/mem> cl shl
12846: @end example
12847:
12848: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12849: the byte version.
12850:
12851: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12852: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12853: pc < >= <= >}. (Note that most of these words shadow some Forth words
12854: when @code{assembler} is in front of @code{forth} in the search path,
12855: e.g., in @code{code} words). Currently the control structure words use
12856: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12857: to shuffle them (you can also use @code{swap} etc.).
12858:
12859: Here is an example of a @code{code} word (assumes that the stack pointer
12860: is in esi and the TOS is in ebx):
12861:
12862: @example
12863: code my+ ( n1 n2 -- n )
12864: 4 si D) bx add
12865: 4 # si add
12866: Next
12867: end-code
12868: @end example
12869:
12870:
12871: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12872: @subsection Alpha Assembler
12873:
12874: The Alpha assembler and disassembler were originally written by Bernd
12875: Thallner.
12876:
12877: The register names @code{a0}--@code{a5} are not available to avoid
12878: shadowing hex numbers.
12879:
12880: Immediate forms of arithmetic instructions are distinguished by a
12881: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12882: does not count as arithmetic instruction).
12883:
12884: You have to specify all operands to an instruction, even those that
12885: other assemblers consider optional, e.g., the destination register for
12886: @code{br,}, or the destination register and hint for @code{jmp,}.
12887:
12888: You can specify conditions for @code{if,} by removing the first @code{b}
12889: and the trailing @code{,} from a branch with a corresponding name; e.g.,
12890:
12891: @example
12892: 11 fgt if, \ if F11>0e
12893: ...
12894: endif,
12895: @end example
12896:
12897: @code{fbgt,} gives @code{fgt}.
12898:
12899: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
12900: @subsection MIPS assembler
12901:
12902: The MIPS assembler was originally written by Christian Pirker.
12903:
12904: Currently the assembler and disassembler only cover the MIPS-I
12905: architecture (R3000), and don't support FP instructions.
12906:
12907: The register names @code{$a0}--@code{$a3} are not available to avoid
12908: shadowing hex numbers.
12909:
12910: Because there is no way to distinguish registers from immediate values,
12911: you have to explicitly use the immediate forms of instructions, i.e.,
12912: @code{addiu,}, not just @code{addu,} (@command{as} does this
12913: implicitly).
12914:
12915: If the architecture manual specifies several formats for the instruction
12916: (e.g., for @code{jalr,}), you usually have to use the one with more
12917: arguments (i.e., two for @code{jalr,}). When in doubt, see
12918: @code{arch/mips/testasm.fs} for an example of correct use.
12919:
12920: Branches and jumps in the MIPS architecture have a delay slot. You have
12921: to fill it yourself (the simplest way is to use @code{nop,}), the
12922: assembler does not do it for you (unlike @command{as}). Even
12923: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12924: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12925: and @code{then,} just specify branch targets, they are not affected.
12926:
12927: Note that you must not put branches, jumps, or @code{li,} into the delay
12928: slot: @code{li,} may expand to several instructions, and control flow
12929: instructions may not be put into the branch delay slot in any case.
12930:
12931: For branches the argument specifying the target is a relative address;
12932: You have to add the address of the delay slot to get the absolute
12933: address.
12934:
12935: The MIPS architecture also has load delay slots and restrictions on
12936: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12937: yourself to satisfy these restrictions, the assembler does not do it for
12938: you.
12939:
12940: You can specify the conditions for @code{if,} etc. by taking a
12941: conditional branch and leaving away the @code{b} at the start and the
12942: @code{,} at the end. E.g.,
12943:
12944: @example
12945: 4 5 eq if,
12946: ... \ do something if $4 equals $5
12947: then,
12948: @end example
12949:
12950:
12951: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
12952: @subsection PowerPC assembler
12953:
12954: The PowerPC assembler and disassembler were contributed by Michal
12955: Revucky.
12956:
12957: This assembler does not follow the convention of ending mnemonic names
12958: with a ``,'', so some mnemonic names shadow regular Forth words (in
12959: particular: @code{and or xor fabs}); so if you want to use the Forth
12960: words, you have to make them visible first, e.g., with @code{also
12961: forth}.
12962:
12963: Registers are referred to by their number, e.g., @code{9} means the
12964: integer register 9 or the FP register 9 (depending on the
12965: instruction).
12966:
12967: Because there is no way to distinguish registers from immediate values,
12968: you have to explicitly use the immediate forms of instructions, i.e.,
12969: @code{addi,}, not just @code{add,}.
12970:
12971: The assembler and disassembler usually support the most general form
12972: of an instruction, but usually not the shorter forms (especially for
12973: branches).
12974:
12975:
12976: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
12977: @subsection ARM Assembler
12978:
12979: The ARM assembler includes all instruction of ARM architecture version
12980: 4, and the BLX instruction from architecture 5. It does not (yet)
12981: have support for Thumb instructions. It also lacks support for any
12982: co-processors.
12983:
12984: The assembler uses a postfix syntax with the same operand order as
12985: used in the ARM Architecture Reference Manual. Mnemonics are suffixed
12986: by a comma.
12987:
12988: Registers are specified by their names @code{r0} through @code{r15},
12989: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
12990: @code{fp} provided for convenience. Note that @code{ip} refers to
12991: the``intra procedure call scratch register'' (@code{r12}) and does not
12992: refer to an instruction pointer. @code{sp} refers to the ARM ABI
12993: stack pointer (@code{r13}) and not the Forth stack pointer.
12994:
12995: Condition codes can be specified anywhere in the instruction, but will
12996: be most readable if specified just in front of the mnemonic. The 'S'
12997: flag is not a separate word, but encoded into instruction mnemonics,
12998: ie. just use @code{adds,} instead of @code{add,} if you want the
12999: status register to be updated.
13000:
13001: The following table lists the syntax of operands for general
13002: instructions:
13003:
13004: @example
13005: Gforth normal assembler description
13006: 123 # #123 immediate
13007: r12 r12 register
13008: r12 4 #LSL r12, LSL #4 shift left by immediate
13009: r12 r1 #LSL r12, LSL r1 shift left by register
13010: r12 4 #LSR r12, LSR #4 shift right by immediate
13011: r12 r1 #LSR r12, LSR r1 shift right by register
13012: r12 4 #ASR r12, ASR #4 arithmetic shift right
13013: r12 r1 #ASR r12, ASR r1 ... by register
13014: r12 4 #ROR r12, ROR #4 rotate right by immediate
13015: r12 r1 #ROR r12, ROR r1 ... by register
13016: r12 RRX r12, RRX rotate right with extend by 1
13017: @end example
13018:
13019: Memory operand syntax is listed in this table:
13020:
13021: @example
13022: Gforth normal assembler description
13023: r4 ] [r4] register
13024: r4 4 #] [r4, #+4] register with immediate offset
13025: r4 -4 #] [r4, #-4] with negative offset
13026: r4 r1 +] [r4, +r1] register with register offset
13027: r4 r1 -] [r4, -r1] with negated register offset
13028: r4 r1 2 #LSL -] [r4, -r1, LSL #2] with negated and shifted offset
13029: r4 4 #]! [r4, #+4]! immediate preincrement
13030: r4 r1 +]! [r4, +r1]! register preincrement
13031: r4 r1 -]! [r4, +r1]! register predecrement
13032: r4 r1 2 #LSL +]! [r4, +r1, LSL #2]! shifted preincrement
13033: r4 -4 ]# [r4], #-4 immediate postdecrement
13034: r4 r1 ]+ [r4], r1 register postincrement
13035: r4 r1 ]- [r4], -r1 register postdecrement
13036: r4 r1 2 #LSL ]- [r4], -r1, LSL #2 shifted postdecrement
13037: ' xyz >body [#] xyz PC-relative addressing
13038: @end example
13039:
13040: Register lists for load/store multiple instructions are started and
13041: terminated by using the words @code{@{} and @code{@}} respectivly.
13042: Between braces, register names can be listed one by one or register
13043: ranges can be formed by using the postfix operator @code{r-r}. The
13044: @code{^} flag is not encoded in the register list operand, but instead
13045: directly encoded into the instruction mnemonic, ie. use @code{^ldm,}
13046: and @code{^stm,}.
13047:
13048: Addressing modes for load/store multiple are not encoded as
13049: instruction suffixes, but instead specified like an addressing mode,
13050: Use one of @code{DA}, @code{IA}, @code{DB}, @code{IB}, @code{DA!},
13051: @code{IA!}, @code{DB!} or @code{IB!}.
13052:
13053: The following table gives some examples:
13054:
13055: @example
13056: Gforth normal assembler
13057: r4 ia @{ r0 r7 r8 @} stm, stmia r4, @{r0,r7,r8@}
13058: r4 db! @{ r0 r7 r8 @} ldm, ldmdb r4!, @{r0,r7,r8@}
13059: sp ia! @{ r0 r15 r-r @} ^ldm, ldmfd sp!, @{r0-r15@}^
13060: @end example
13061:
13062: Control structure words typical for Forth assemblers are available:
13063: @code{if,} @code{ahead,} @code{then,} @code{else,} @code{begin,}
13064: @code{until,} @code{again,} @code{while,} @code{repeat,}
13065: @code{repeat-until,}. Conditions are specified in front of these words:
13066:
13067: @example
13068: r1 r2 cmp, \ compare r1 and r2
13069: eq if, \ equal?
13070: ... \ code executed if r1 == r2
13071: then,
13072: @end example
13073:
13074: Example of a definition using the ARM assembler:
13075:
13076: @example
13077: abi-code my+ ( n1 n2 -- n3 )
13078: \ arm abi: r0=return_stuct, r1=sp, r2=fp, r3,r12 saved by caller
13079: r1 IA! @{ r3 r12 @} ldm, \ pop r2 = n2, r3 = n1
13080: r12 r3 r12 add, \ r12 = n2+n1
13081: r12 r1 -4 #]! str, \ push r12
13082: r0 IA! @{ r1 r2 @} stm, \ return r1 and r2 via [r0] memory
13083: pc lr mov, \ return to caller
13084: end-code
13085: @end example
13086:
13087: @node Other assemblers, , ARM Assembler, Assembler and Code Words
13088: @subsection Other assemblers
13089:
13090: If you want to contribute another assembler/disassembler, please contact
13091: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
13092: an assembler already. If you are writing them from scratch, please use
13093: a similar syntax style as the one we use (i.e., postfix, commas at the
13094: end of the instruction names, @pxref{Common Assembler}); make the output
13095: of the disassembler be valid input for the assembler, and keep the style
13096: similar to the style we used.
13097:
13098: Hints on implementation: The most important part is to have a good test
13099: suite that contains all instructions. Once you have that, the rest is
13100: easy. For actual coding you can take a look at
13101: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
13102: the assembler and disassembler, avoiding redundancy and some potential
13103: bugs. You can also look at that file (and @pxref{Advanced does> usage
13104: example}) to get ideas how to factor a disassembler.
13105:
13106: Start with the disassembler, because it's easier to reuse data from the
13107: disassembler for the assembler than the other way round.
13108:
13109: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
13110: how simple it can be.
13111:
13112:
13113:
13114:
13115: @c -------------------------------------------------------------
13116: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
13117: @section Threading Words
13118: @cindex threading words
13119:
13120: @cindex code address
13121: These words provide access to code addresses and other threading stuff
13122: in Gforth (and, possibly, other interpretive Forths). It more or less
13123: abstracts away the differences between direct and indirect threading
13124: (and, for direct threading, the machine dependences). However, at
13125: present this wordset is still incomplete. It is also pretty low-level;
13126: some day it will hopefully be made unnecessary by an internals wordset
13127: that abstracts implementation details away completely.
13128:
13129: The terminology used here stems from indirect threaded Forth systems; in
13130: such a system, the XT of a word is represented by the CFA (code field
13131: address) of a word; the CFA points to a cell that contains the code
13132: address. The code address is the address of some machine code that
13133: performs the run-time action of invoking the word (e.g., the
13134: @code{dovar:} routine pushes the address of the body of the word (a
13135: variable) on the stack
13136: ).
13137:
13138: @cindex code address
13139: @cindex code field address
13140: In an indirect threaded Forth, you can get the code address of @i{name}
13141: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
13142: >code-address}, independent of the threading method.
13143:
13144: doc-threading-method
13145: doc->code-address
13146: doc-code-address!
13147:
13148: @cindex @code{does>}-handler
13149: @cindex @code{does>}-code
13150: For a word defined with @code{DOES>}, the code address usually points to
13151: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
13152: routine (in Gforth on some platforms, it can also point to the dodoes
13153: routine itself). What you are typically interested in, though, is
13154: whether a word is a @code{DOES>}-defined word, and what Forth code it
13155: executes; @code{>does-code} tells you that.
13156:
13157: doc->does-code
13158:
13159: To create a @code{DOES>}-defined word with the following basic words,
13160: you have to set up a @code{DOES>}-handler with @code{does-handler!};
13161: @code{/does-handler} aus behind you have to place your executable Forth
13162: code. Finally you have to create a word and modify its behaviour with
13163: @code{does-handler!}.
13164:
13165: doc-does-code!
13166: doc-does-handler!
13167: doc-/does-handler
13168:
13169: The code addresses produced by various defining words are produced by
13170: the following words:
13171:
13172: doc-docol:
13173: doc-docon:
13174: doc-dovar:
13175: doc-douser:
13176: doc-dodefer:
13177: doc-dofield:
13178:
13179: @cindex definer
13180: The following two words generalize @code{>code-address},
13181: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
13182:
13183: doc->definer
13184: doc-definer!
13185:
13186: @c -------------------------------------------------------------
13187: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
13188: @section Passing Commands to the Operating System
13189: @cindex operating system - passing commands
13190: @cindex shell commands
13191:
13192: Gforth allows you to pass an arbitrary string to the host operating
13193: system shell (if such a thing exists) for execution.
13194:
13195: doc-sh
13196: doc-system
13197: doc-$?
13198: doc-getenv
13199:
13200: @c -------------------------------------------------------------
13201: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
13202: @section Keeping track of Time
13203: @cindex time-related words
13204:
13205: doc-ms
13206: doc-time&date
13207: doc-utime
13208: doc-cputime
13209:
13210:
13211: @c -------------------------------------------------------------
13212: @node Miscellaneous Words, , Keeping track of Time, Words
13213: @section Miscellaneous Words
13214: @cindex miscellaneous words
13215:
13216: @comment TODO find homes for these
13217:
13218: These section lists the ANS Forth words that are not documented
13219: elsewhere in this manual. Ultimately, they all need proper homes.
13220:
13221: doc-quit
13222:
13223: The following ANS Forth words are not currently supported by Gforth
13224: (@pxref{ANS conformance}):
13225:
13226: @code{EDITOR}
13227: @code{EMIT?}
13228: @code{FORGET}
13229:
13230: @c ******************************************************************
13231: @node Error messages, Tools, Words, Top
13232: @chapter Error messages
13233: @cindex error messages
13234: @cindex backtrace
13235:
13236: A typical Gforth error message looks like this:
13237:
13238: @example
13239: in file included from \evaluated string/:-1
13240: in file included from ./yyy.fs:1
13241: ./xxx.fs:4: Invalid memory address
13242: >>>bar<<<
13243: Backtrace:
13244: $400E664C @@
13245: $400E6664 foo
13246: @end example
13247:
13248: The message identifying the error is @code{Invalid memory address}. The
13249: error happened when text-interpreting line 4 of the file
13250: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
13251: word on the line where the error happened, is pointed out (with
13252: @code{>>>} and @code{<<<}).
13253:
13254: The file containing the error was included in line 1 of @file{./yyy.fs},
13255: and @file{yyy.fs} was included from a non-file (in this case, by giving
13256: @file{yyy.fs} as command-line parameter to Gforth).
13257:
13258: At the end of the error message you find a return stack dump that can be
13259: interpreted as a backtrace (possibly empty). On top you find the top of
13260: the return stack when the @code{throw} happened, and at the bottom you
13261: find the return stack entry just above the return stack of the topmost
13262: text interpreter.
13263:
13264: To the right of most return stack entries you see a guess for the word
13265: that pushed that return stack entry as its return address. This gives a
13266: backtrace. In our case we see that @code{bar} called @code{foo}, and
13267: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
13268: address} exception).
13269:
13270: Note that the backtrace is not perfect: We don't know which return stack
13271: entries are return addresses (so we may get false positives); and in
13272: some cases (e.g., for @code{abort"}) we cannot determine from the return
13273: address the word that pushed the return address, so for some return
13274: addresses you see no names in the return stack dump.
13275:
13276: @cindex @code{catch} and backtraces
13277: The return stack dump represents the return stack at the time when a
13278: specific @code{throw} was executed. In programs that make use of
13279: @code{catch}, it is not necessarily clear which @code{throw} should be
13280: used for the return stack dump (e.g., consider one @code{throw} that
13281: indicates an error, which is caught, and during recovery another error
13282: happens; which @code{throw} should be used for the stack dump?).
13283: Gforth presents the return stack dump for the first @code{throw} after
13284: the last executed (not returned-to) @code{catch} or @code{nothrow};
13285: this works well in the usual case. To get the right backtrace, you
13286: usually want to insert @code{nothrow} or @code{['] false catch drop}
13287: after a @code{catch} if the error is not rethrown.
13288:
13289: @cindex @code{gforth-fast} and backtraces
13290: @cindex @code{gforth-fast}, difference from @code{gforth}
13291: @cindex backtraces with @code{gforth-fast}
13292: @cindex return stack dump with @code{gforth-fast}
13293: @code{Gforth} is able to do a return stack dump for throws generated
13294: from primitives (e.g., invalid memory address, stack empty etc.);
13295: @code{gforth-fast} is only able to do a return stack dump from a
13296: directly called @code{throw} (including @code{abort} etc.). Given an
13297: exception caused by a primitive in @code{gforth-fast}, you will
13298: typically see no return stack dump at all; however, if the exception is
13299: caught by @code{catch} (e.g., for restoring some state), and then
13300: @code{throw}n again, the return stack dump will be for the first such
13301: @code{throw}.
13302:
13303: @c ******************************************************************
13304: @node Tools, ANS conformance, Error messages, Top
13305: @chapter Tools
13306:
13307: @menu
13308: * ANS Report:: Report the words used, sorted by wordset.
13309: * Stack depth changes:: Where does this stack item come from?
13310: @end menu
13311:
13312: See also @ref{Emacs and Gforth}.
13313:
13314: @node ANS Report, Stack depth changes, Tools, Tools
13315: @section @file{ans-report.fs}: Report the words used, sorted by wordset
13316: @cindex @file{ans-report.fs}
13317: @cindex report the words used in your program
13318: @cindex words used in your program
13319:
13320: If you want to label a Forth program as ANS Forth Program, you must
13321: document which wordsets the program uses; for extension wordsets, it is
13322: helpful to list the words the program requires from these wordsets
13323: (because Forth systems are allowed to provide only some words of them).
13324:
13325: The @file{ans-report.fs} tool makes it easy for you to determine which
13326: words from which wordset and which non-ANS words your application
13327: uses. You simply have to include @file{ans-report.fs} before loading the
13328: program you want to check. After loading your program, you can get the
13329: report with @code{print-ans-report}. A typical use is to run this as
13330: batch job like this:
13331: @example
13332: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
13333: @end example
13334:
13335: The output looks like this (for @file{compat/control.fs}):
13336: @example
13337: The program uses the following words
13338: from CORE :
13339: : POSTPONE THEN ; immediate ?dup IF 0=
13340: from BLOCK-EXT :
13341: \
13342: from FILE :
13343: (
13344: @end example
13345:
13346: @subsection Caveats
13347:
13348: Note that @file{ans-report.fs} just checks which words are used, not whether
13349: they are used in an ANS Forth conforming way!
13350:
13351: Some words are defined in several wordsets in the
13352: standard. @file{ans-report.fs} reports them for only one of the
13353: wordsets, and not necessarily the one you expect. It depends on usage
13354: which wordset is the right one to specify. E.g., if you only use the
13355: compilation semantics of @code{S"}, it is a Core word; if you also use
13356: its interpretation semantics, it is a File word.
13357:
13358:
13359: @node Stack depth changes, , ANS Report, Tools
13360: @section Stack depth changes during interpretation
13361: @cindex @file{depth-changes.fs}
13362: @cindex depth changes during interpretation
13363: @cindex stack depth changes during interpretation
13364: @cindex items on the stack after interpretation
13365:
13366: Sometimes you notice that, after loading a file, there are items left
13367: on the stack. The tool @file{depth-changes.fs} helps you find out
13368: quickly where in the file these stack items are coming from.
13369:
13370: The simplest way of using @file{depth-changes.fs} is to include it
13371: before the file(s) you want to check, e.g.:
13372:
13373: @example
13374: gforth depth-changes.fs my-file.fs
13375: @end example
13376:
13377: This will compare the stack depths of the data and FP stack at every
13378: empty line (in interpretation state) against these depths at the last
13379: empty line (in interpretation state). If the depths are not equal,
13380: the position in the file and the stack contents are printed with
13381: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
13382: change has occured in the paragraph of non-empty lines before the
13383: indicated line. It is a good idea to leave an empty line at the end
13384: of the file, so the last paragraph is checked, too.
13385:
13386: Checking only at empty lines usually works well, but sometimes you
13387: have big blocks of non-empty lines (e.g., when building a big table),
13388: and you want to know where in this block the stack depth changed. You
13389: can check all interpreted lines with
13390:
13391: @example
13392: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
13393: @end example
13394:
13395: This checks the stack depth at every end-of-line. So the depth change
13396: occured in the line reported by the @code{~~} (not in the line
13397: before).
13398:
13399: Note that, while this offers better accuracy in indicating where the
13400: stack depth changes, it will often report many intentional stack depth
13401: changes (e.g., when an interpreted computation stretches across
13402: several lines). You can suppress the checking of some lines by
13403: putting backslashes at the end of these lines (not followed by white
13404: space), and using
13405:
13406: @example
13407: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
13408: @end example
13409:
13410: @c ******************************************************************
13411: @node ANS conformance, Standard vs Extensions, Tools, Top
13412: @chapter ANS conformance
13413: @cindex ANS conformance of Gforth
13414:
13415: To the best of our knowledge, Gforth is an
13416:
13417: ANS Forth System
13418: @itemize @bullet
13419: @item providing the Core Extensions word set
13420: @item providing the Block word set
13421: @item providing the Block Extensions word set
13422: @item providing the Double-Number word set
13423: @item providing the Double-Number Extensions word set
13424: @item providing the Exception word set
13425: @item providing the Exception Extensions word set
13426: @item providing the Facility word set
13427: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
13428: @item providing the File Access word set
13429: @item providing the File Access Extensions word set
13430: @item providing the Floating-Point word set
13431: @item providing the Floating-Point Extensions word set
13432: @item providing the Locals word set
13433: @item providing the Locals Extensions word set
13434: @item providing the Memory-Allocation word set
13435: @item providing the Memory-Allocation Extensions word set (that one's easy)
13436: @item providing the Programming-Tools word set
13437: @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
13438: @item providing the Search-Order word set
13439: @item providing the Search-Order Extensions word set
13440: @item providing the String word set
13441: @item providing the String Extensions word set (another easy one)
13442: @end itemize
13443:
13444: Gforth has the following environmental restrictions:
13445:
13446: @cindex environmental restrictions
13447: @itemize @bullet
13448: @item
13449: While processing the OS command line, if an exception is not caught,
13450: Gforth exits with a non-zero exit code instyead of performing QUIT.
13451:
13452: @item
13453: When an @code{throw} is performed after a @code{query}, Gforth does not
13454: allways restore the input source specification in effect at the
13455: corresponding catch.
13456:
13457: @end itemize
13458:
13459:
13460: @cindex system documentation
13461: In addition, ANS Forth systems are required to document certain
13462: implementation choices. This chapter tries to meet these
13463: requirements. In many cases it gives a way to ask the system for the
13464: information instead of providing the information directly, in
13465: particular, if the information depends on the processor, the operating
13466: system or the installation options chosen, or if they are likely to
13467: change during the maintenance of Gforth.
13468:
13469: @comment The framework for the rest has been taken from pfe.
13470:
13471: @menu
13472: * The Core Words::
13473: * The optional Block word set::
13474: * The optional Double Number word set::
13475: * The optional Exception word set::
13476: * The optional Facility word set::
13477: * The optional File-Access word set::
13478: * The optional Floating-Point word set::
13479: * The optional Locals word set::
13480: * The optional Memory-Allocation word set::
13481: * The optional Programming-Tools word set::
13482: * The optional Search-Order word set::
13483: @end menu
13484:
13485:
13486: @c =====================================================================
13487: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13488: @comment node-name, next, previous, up
13489: @section The Core Words
13490: @c =====================================================================
13491: @cindex core words, system documentation
13492: @cindex system documentation, core words
13493:
13494: @menu
13495: * core-idef:: Implementation Defined Options
13496: * core-ambcond:: Ambiguous Conditions
13497: * core-other:: Other System Documentation
13498: @end menu
13499:
13500: @c ---------------------------------------------------------------------
13501: @node core-idef, core-ambcond, The Core Words, The Core Words
13502: @subsection Implementation Defined Options
13503: @c ---------------------------------------------------------------------
13504: @cindex core words, implementation-defined options
13505: @cindex implementation-defined options, core words
13506:
13507:
13508: @table @i
13509: @item (Cell) aligned addresses:
13510: @cindex cell-aligned addresses
13511: @cindex aligned addresses
13512: processor-dependent. Gforth's alignment words perform natural alignment
13513: (e.g., an address aligned for a datum of size 8 is divisible by
13514: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13515:
13516: @item @code{EMIT} and non-graphic characters:
13517: @cindex @code{EMIT} and non-graphic characters
13518: @cindex non-graphic characters and @code{EMIT}
13519: The character is output using the C library function (actually, macro)
13520: @code{putc}.
13521:
13522: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13523: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13524: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13525: @cindex @code{ACCEPT}, editing
13526: @cindex @code{EXPECT}, editing
13527: This is modeled on the GNU readline library (@pxref{Readline
13528: Interaction, , Command Line Editing, readline, The GNU Readline
13529: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13530: producing a full word completion every time you type it (instead of
13531: producing the common prefix of all completions). @xref{Command-line editing}.
13532:
13533: @item character set:
13534: @cindex character set
13535: The character set of your computer and display device. Gforth is
13536: 8-bit-clean (but some other component in your system may make trouble).
13537:
13538: @item Character-aligned address requirements:
13539: @cindex character-aligned address requirements
13540: installation-dependent. Currently a character is represented by a C
13541: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13542: (Comments on that requested).
13543:
13544: @item character-set extensions and matching of names:
13545: @cindex character-set extensions and matching of names
13546: @cindex case-sensitivity for name lookup
13547: @cindex name lookup, case-sensitivity
13548: @cindex locale and case-sensitivity
13549: Any character except the ASCII NUL character can be used in a
13550: name. Matching is case-insensitive (except in @code{TABLE}s). The
13551: matching is performed using the C library function @code{strncasecmp}, whose
13552: function is probably influenced by the locale. E.g., the @code{C} locale
13553: does not know about accents and umlauts, so they are matched
13554: case-sensitively in that locale. For portability reasons it is best to
13555: write programs such that they work in the @code{C} locale. Then one can
13556: use libraries written by a Polish programmer (who might use words
13557: containing ISO Latin-2 encoded characters) and by a French programmer
13558: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13559: funny results for some of the words (which ones, depends on the font you
13560: are using)). Also, the locale you prefer may not be available in other
13561: operating systems. Hopefully, Unicode will solve these problems one day.
13562:
13563: @item conditions under which control characters match a space delimiter:
13564: @cindex space delimiters
13565: @cindex control characters as delimiters
13566: If @code{word} is called with the space character as a delimiter, all
13567: white-space characters (as identified by the C macro @code{isspace()})
13568: are delimiters. @code{Parse}, on the other hand, treats space like other
13569: delimiters. @code{Parse-name}, which is used by the outer
13570: interpreter (aka text interpreter) by default, treats all white-space
13571: characters as delimiters.
13572:
13573: @item format of the control-flow stack:
13574: @cindex control-flow stack, format
13575: The data stack is used as control-flow stack. The size of a control-flow
13576: stack item in cells is given by the constant @code{cs-item-size}. At the
13577: time of this writing, an item consists of a (pointer to a) locals list
13578: (third), an address in the code (second), and a tag for identifying the
13579: item (TOS). The following tags are used: @code{defstart},
13580: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13581: @code{scopestart}.
13582:
13583: @item conversion of digits > 35
13584: @cindex digits > 35
13585: The characters @code{[\]^_'} are the digits with the decimal value
13586: 36@minus{}41. There is no way to input many of the larger digits.
13587:
13588: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13589: @cindex @code{EXPECT}, display after end of input
13590: @cindex @code{ACCEPT}, display after end of input
13591: The cursor is moved to the end of the entered string. If the input is
13592: terminated using the @kbd{Return} key, a space is typed.
13593:
13594: @item exception abort sequence of @code{ABORT"}:
13595: @cindex exception abort sequence of @code{ABORT"}
13596: @cindex @code{ABORT"}, exception abort sequence
13597: The error string is stored into the variable @code{"error} and a
13598: @code{-2 throw} is performed.
13599:
13600: @item input line terminator:
13601: @cindex input line terminator
13602: @cindex line terminator on input
13603: @cindex newline character on input
13604: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13605: lines. One of these characters is typically produced when you type the
13606: @kbd{Enter} or @kbd{Return} key.
13607:
13608: @item maximum size of a counted string:
13609: @cindex maximum size of a counted string
13610: @cindex counted string, maximum size
13611: @code{s" /counted-string" environment? drop .}. Currently 255 characters
13612: on all platforms, but this may change.
13613:
13614: @item maximum size of a parsed string:
13615: @cindex maximum size of a parsed string
13616: @cindex parsed string, maximum size
13617: Given by the constant @code{/line}. Currently 255 characters.
13618:
13619: @item maximum size of a definition name, in characters:
13620: @cindex maximum size of a definition name, in characters
13621: @cindex name, maximum length
13622: MAXU/8
13623:
13624: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13625: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13626: @cindex @code{ENVIRONMENT?} string length, maximum
13627: MAXU/8
13628:
13629: @item method of selecting the user input device:
13630: @cindex user input device, method of selecting
13631: The user input device is the standard input. There is currently no way to
13632: change it from within Gforth. However, the input can typically be
13633: redirected in the command line that starts Gforth.
13634:
13635: @item method of selecting the user output device:
13636: @cindex user output device, method of selecting
13637: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
13638: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13639: output when the user output device is a terminal, otherwise the output
13640: is buffered.
13641:
13642: @item methods of dictionary compilation:
13643: What are we expected to document here?
13644:
13645: @item number of bits in one address unit:
13646: @cindex number of bits in one address unit
13647: @cindex address unit, size in bits
13648: @code{s" address-units-bits" environment? drop .}. 8 in all current
13649: platforms.
13650:
13651: @item number representation and arithmetic:
13652: @cindex number representation and arithmetic
13653: Processor-dependent. Binary two's complement on all current platforms.
13654:
13655: @item ranges for integer types:
13656: @cindex ranges for integer types
13657: @cindex integer types, ranges
13658: Installation-dependent. Make environmental queries for @code{MAX-N},
13659: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13660: unsigned (and positive) types is 0. The lower bound for signed types on
13661: two's complement and one's complement machines machines can be computed
13662: by adding 1 to the upper bound.
13663:
13664: @item read-only data space regions:
13665: @cindex read-only data space regions
13666: @cindex data-space, read-only regions
13667: The whole Forth data space is writable.
13668:
13669: @item size of buffer at @code{WORD}:
13670: @cindex size of buffer at @code{WORD}
13671: @cindex @code{WORD} buffer size
13672: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13673: shared with the pictured numeric output string. If overwriting
13674: @code{PAD} is acceptable, it is as large as the remaining dictionary
13675: space, although only as much can be sensibly used as fits in a counted
13676: string.
13677:
13678: @item size of one cell in address units:
13679: @cindex cell size
13680: @code{1 cells .}.
13681:
13682: @item size of one character in address units:
13683: @cindex char size
13684: @code{1 chars .}. 1 on all current platforms.
13685:
13686: @item size of the keyboard terminal buffer:
13687: @cindex size of the keyboard terminal buffer
13688: @cindex terminal buffer, size
13689: Varies. You can determine the size at a specific time using @code{lp@@
13690: tib - .}. It is shared with the locals stack and TIBs of files that
13691: include the current file. You can change the amount of space for TIBs
13692: and locals stack at Gforth startup with the command line option
13693: @code{-l}.
13694:
13695: @item size of the pictured numeric output buffer:
13696: @cindex size of the pictured numeric output buffer
13697: @cindex pictured numeric output buffer, size
13698: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13699: shared with @code{WORD}.
13700:
13701: @item size of the scratch area returned by @code{PAD}:
13702: @cindex size of the scratch area returned by @code{PAD}
13703: @cindex @code{PAD} size
13704: The remainder of dictionary space. @code{unused pad here - - .}.
13705:
13706: @item system case-sensitivity characteristics:
13707: @cindex case-sensitivity characteristics
13708: Dictionary searches are case-insensitive (except in
13709: @code{TABLE}s). However, as explained above under @i{character-set
13710: extensions}, the matching for non-ASCII characters is determined by the
13711: locale you are using. In the default @code{C} locale all non-ASCII
13712: characters are matched case-sensitively.
13713:
13714: @item system prompt:
13715: @cindex system prompt
13716: @cindex prompt
13717: @code{ ok} in interpret state, @code{ compiled} in compile state.
13718:
13719: @item division rounding:
13720: @cindex division rounding
13721: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13722: division (with the default installation of Gforth). You can check
13723: this with @code{s" floored" environment? drop .}. If you write
13724: programs that need a specific division rounding, best use
13725: @code{fm/mod} or @code{sm/rem} for portability.
13726:
13727: @item values of @code{STATE} when true:
13728: @cindex @code{STATE} values
13729: -1.
13730:
13731: @item values returned after arithmetic overflow:
13732: On two's complement machines, arithmetic is performed modulo
13733: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13734: arithmetic (with appropriate mapping for signed types). Division by
13735: zero typically results in a @code{-55 throw} (Floating-point
13736: unidentified fault) or @code{-10 throw} (divide by zero). Integer
13737: division overflow can result in these throws, or in @code{-11 throw};
13738: in @code{gforth-fast} division overflow and divide by zero may also
13739: result in returning bogus results without producing an exception.
13740:
13741: @item whether the current definition can be found after @t{DOES>}:
13742: @cindex @t{DOES>}, visibility of current definition
13743: No.
13744:
13745: @end table
13746:
13747: @c ---------------------------------------------------------------------
13748: @node core-ambcond, core-other, core-idef, The Core Words
13749: @subsection Ambiguous conditions
13750: @c ---------------------------------------------------------------------
13751: @cindex core words, ambiguous conditions
13752: @cindex ambiguous conditions, core words
13753:
13754: @table @i
13755:
13756: @item a name is neither a word nor a number:
13757: @cindex name not found
13758: @cindex undefined word
13759: @code{-13 throw} (Undefined word).
13760:
13761: @item a definition name exceeds the maximum length allowed:
13762: @cindex word name too long
13763: @code{-19 throw} (Word name too long)
13764:
13765: @item addressing a region not inside the various data spaces of the forth system:
13766: @cindex Invalid memory address
13767: The stacks, code space and header space are accessible. Machine code space is
13768: typically readable. Accessing other addresses gives results dependent on
13769: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13770: address).
13771:
13772: @item argument type incompatible with parameter:
13773: @cindex argument type mismatch
13774: This is usually not caught. Some words perform checks, e.g., the control
13775: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13776: mismatch).
13777:
13778: @item attempting to obtain the execution token of a word with undefined execution semantics:
13779: @cindex Interpreting a compile-only word, for @code{'} etc.
13780: @cindex execution token of words with undefined execution semantics
13781: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13782: get an execution token for @code{compile-only-error} (which performs a
13783: @code{-14 throw} when executed).
13784:
13785: @item dividing by zero:
13786: @cindex dividing by zero
13787: @cindex floating point unidentified fault, integer division
13788: On some platforms, this produces a @code{-10 throw} (Division by
13789: zero); on other systems, this typically results in a @code{-55 throw}
13790: (Floating-point unidentified fault).
13791:
13792: @item insufficient data stack or return stack space:
13793: @cindex insufficient data stack or return stack space
13794: @cindex stack overflow
13795: @cindex address alignment exception, stack overflow
13796: @cindex Invalid memory address, stack overflow
13797: Depending on the operating system, the installation, and the invocation
13798: of Gforth, this is either checked by the memory management hardware, or
13799: it is not checked. If it is checked, you typically get a @code{-3 throw}
13800: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13801: throw} (Invalid memory address) (depending on the platform and how you
13802: achieved the overflow) as soon as the overflow happens. If it is not
13803: checked, overflows typically result in mysterious illegal memory
13804: accesses, producing @code{-9 throw} (Invalid memory address) or
13805: @code{-23 throw} (Address alignment exception); they might also destroy
13806: the internal data structure of @code{ALLOCATE} and friends, resulting in
13807: various errors in these words.
13808:
13809: @item insufficient space for loop control parameters:
13810: @cindex insufficient space for loop control parameters
13811: Like other return stack overflows.
13812:
13813: @item insufficient space in the dictionary:
13814: @cindex insufficient space in the dictionary
13815: @cindex dictionary overflow
13816: If you try to allot (either directly with @code{allot}, or indirectly
13817: with @code{,}, @code{create} etc.) more memory than available in the
13818: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13819: to access memory beyond the end of the dictionary, the results are
13820: similar to stack overflows.
13821:
13822: @item interpreting a word with undefined interpretation semantics:
13823: @cindex interpreting a word with undefined interpretation semantics
13824: @cindex Interpreting a compile-only word
13825: For some words, we have defined interpretation semantics. For the
13826: others: @code{-14 throw} (Interpreting a compile-only word).
13827:
13828: @item modifying the contents of the input buffer or a string literal:
13829: @cindex modifying the contents of the input buffer or a string literal
13830: These are located in writable memory and can be modified.
13831:
13832: @item overflow of the pictured numeric output string:
13833: @cindex overflow of the pictured numeric output string
13834: @cindex pictured numeric output string, overflow
13835: @code{-17 throw} (Pictured numeric ouput string overflow).
13836:
13837: @item parsed string overflow:
13838: @cindex parsed string overflow
13839: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13840:
13841: @item producing a result out of range:
13842: @cindex result out of range
13843: On two's complement machines, arithmetic is performed modulo
13844: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13845: arithmetic (with appropriate mapping for signed types). Division by
13846: zero typically results in a @code{-10 throw} (divide by zero) or
13847: @code{-55 throw} (floating point unidentified fault). Overflow on
13848: division may result in these errors or in @code{-11 throw} (result out
13849: of range). @code{Gforth-fast} may silently produce bogus results on
13850: division overflow or division by zero. @code{Convert} and
13851: @code{>number} currently overflow silently.
13852:
13853: @item reading from an empty data or return stack:
13854: @cindex stack empty
13855: @cindex stack underflow
13856: @cindex return stack underflow
13857: The data stack is checked by the outer (aka text) interpreter after
13858: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13859: underflow) is performed. Apart from that, stacks may be checked or not,
13860: depending on operating system, installation, and invocation. If they are
13861: caught by a check, they typically result in @code{-4 throw} (Stack
13862: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13863: (Invalid memory address), depending on the platform and which stack
13864: underflows and by how much. Note that even if the system uses checking
13865: (through the MMU), your program may have to underflow by a significant
13866: number of stack items to trigger the reaction (the reason for this is
13867: that the MMU, and therefore the checking, works with a page-size
13868: granularity). If there is no checking, the symptoms resulting from an
13869: underflow are similar to those from an overflow. Unbalanced return
13870: stack errors can result in a variety of symptoms, including @code{-9 throw}
13871: (Invalid memory address) and Illegal Instruction (typically @code{-260
13872: throw}).
13873:
13874: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13875: @cindex unexpected end of the input buffer
13876: @cindex zero-length string as a name
13877: @cindex Attempt to use zero-length string as a name
13878: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13879: use zero-length string as a name). Words like @code{'} probably will not
13880: find what they search. Note that it is possible to create zero-length
13881: names with @code{nextname} (should it not?).
13882:
13883: @item @code{>IN} greater than input buffer:
13884: @cindex @code{>IN} greater than input buffer
13885: The next invocation of a parsing word returns a string with length 0.
13886:
13887: @item @code{RECURSE} appears after @code{DOES>}:
13888: @cindex @code{RECURSE} appears after @code{DOES>}
13889: Compiles a recursive call to the defining word, not to the defined word.
13890:
13891: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13892: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
13893: @cindex argument type mismatch, @code{RESTORE-INPUT}
13894: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13895: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13896: the end of the file was reached), its source-id may be
13897: reused. Therefore, restoring an input source specification referencing a
13898: closed file may lead to unpredictable results instead of a @code{-12
13899: THROW}.
13900:
13901: In the future, Gforth may be able to restore input source specifications
13902: from other than the current input source.
13903:
13904: @item data space containing definitions gets de-allocated:
13905: @cindex data space containing definitions gets de-allocated
13906: Deallocation with @code{allot} is not checked. This typically results in
13907: memory access faults or execution of illegal instructions.
13908:
13909: @item data space read/write with incorrect alignment:
13910: @cindex data space read/write with incorrect alignment
13911: @cindex alignment faults
13912: @cindex address alignment exception
13913: Processor-dependent. Typically results in a @code{-23 throw} (Address
13914: alignment exception). Under Linux-Intel on a 486 or later processor with
13915: alignment turned on, incorrect alignment results in a @code{-9 throw}
13916: (Invalid memory address). There are reportedly some processors with
13917: alignment restrictions that do not report violations.
13918:
13919: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13920: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13921: Like other alignment errors.
13922:
13923: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13924: Like other stack underflows.
13925:
13926: @item loop control parameters not available:
13927: @cindex loop control parameters not available
13928: Not checked. The counted loop words simply assume that the top of return
13929: stack items are loop control parameters and behave accordingly.
13930:
13931: @item most recent definition does not have a name (@code{IMMEDIATE}):
13932: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13933: @cindex last word was headerless
13934: @code{abort" last word was headerless"}.
13935:
13936: @item name not defined by @code{VALUE} used by @code{TO}:
13937: @cindex name not defined by @code{VALUE} used by @code{TO}
13938: @cindex @code{TO} on non-@code{VALUE}s
13939: @cindex Invalid name argument, @code{TO}
13940: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13941: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13942:
13943: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13944: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
13945: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
13946: @code{-13 throw} (Undefined word)
13947:
13948: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13949: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13950: Gforth behaves as if they were of the same type. I.e., you can predict
13951: the behaviour by interpreting all parameters as, e.g., signed.
13952:
13953: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13954: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13955: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13956: compilation semantics of @code{TO}.
13957:
13958: @item String longer than a counted string returned by @code{WORD}:
13959: @cindex string longer than a counted string returned by @code{WORD}
13960: @cindex @code{WORD}, string overflow
13961: Not checked. The string will be ok, but the count will, of course,
13962: contain only the least significant bits of the length.
13963:
13964: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13965: @cindex @code{LSHIFT}, large shift counts
13966: @cindex @code{RSHIFT}, large shift counts
13967: Processor-dependent. Typical behaviours are returning 0 and using only
13968: the low bits of the shift count.
13969:
13970: @item word not defined via @code{CREATE}:
13971: @cindex @code{>BODY} of non-@code{CREATE}d words
13972: @code{>BODY} produces the PFA of the word no matter how it was defined.
13973:
13974: @cindex @code{DOES>} of non-@code{CREATE}d words
13975: @code{DOES>} changes the execution semantics of the last defined word no
13976: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13977: @code{CREATE , DOES>}.
13978:
13979: @item words improperly used outside @code{<#} and @code{#>}:
13980: Not checked. As usual, you can expect memory faults.
13981:
13982: @end table
13983:
13984:
13985: @c ---------------------------------------------------------------------
13986: @node core-other, , core-ambcond, The Core Words
13987: @subsection Other system documentation
13988: @c ---------------------------------------------------------------------
13989: @cindex other system documentation, core words
13990: @cindex core words, other system documentation
13991:
13992: @table @i
13993: @item nonstandard words using @code{PAD}:
13994: @cindex @code{PAD} use by nonstandard words
13995: None.
13996:
13997: @item operator's terminal facilities available:
13998: @cindex operator's terminal facilities available
13999: After processing the OS's command line, Gforth goes into interactive mode,
14000: and you can give commands to Gforth interactively. The actual facilities
14001: available depend on how you invoke Gforth.
14002:
14003: @item program data space available:
14004: @cindex program data space available
14005: @cindex data space available
14006: @code{UNUSED .} gives the remaining dictionary space. The total
14007: dictionary space can be specified with the @code{-m} switch
14008: (@pxref{Invoking Gforth}) when Gforth starts up.
14009:
14010: @item return stack space available:
14011: @cindex return stack space available
14012: You can compute the total return stack space in cells with
14013: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
14014: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
14015:
14016: @item stack space available:
14017: @cindex stack space available
14018: You can compute the total data stack space in cells with
14019: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
14020: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
14021:
14022: @item system dictionary space required, in address units:
14023: @cindex system dictionary space required, in address units
14024: Type @code{here forthstart - .} after startup. At the time of this
14025: writing, this gives 80080 (bytes) on a 32-bit system.
14026: @end table
14027:
14028:
14029: @c =====================================================================
14030: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
14031: @section The optional Block word set
14032: @c =====================================================================
14033: @cindex system documentation, block words
14034: @cindex block words, system documentation
14035:
14036: @menu
14037: * block-idef:: Implementation Defined Options
14038: * block-ambcond:: Ambiguous Conditions
14039: * block-other:: Other System Documentation
14040: @end menu
14041:
14042:
14043: @c ---------------------------------------------------------------------
14044: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
14045: @subsection Implementation Defined Options
14046: @c ---------------------------------------------------------------------
14047: @cindex implementation-defined options, block words
14048: @cindex block words, implementation-defined options
14049:
14050: @table @i
14051: @item the format for display by @code{LIST}:
14052: @cindex @code{LIST} display format
14053: First the screen number is displayed, then 16 lines of 64 characters,
14054: each line preceded by the line number.
14055:
14056: @item the length of a line affected by @code{\}:
14057: @cindex length of a line affected by @code{\}
14058: @cindex @code{\}, line length in blocks
14059: 64 characters.
14060: @end table
14061:
14062:
14063: @c ---------------------------------------------------------------------
14064: @node block-ambcond, block-other, block-idef, The optional Block word set
14065: @subsection Ambiguous conditions
14066: @c ---------------------------------------------------------------------
14067: @cindex block words, ambiguous conditions
14068: @cindex ambiguous conditions, block words
14069:
14070: @table @i
14071: @item correct block read was not possible:
14072: @cindex block read not possible
14073: Typically results in a @code{throw} of some OS-derived value (between
14074: -512 and -2048). If the blocks file was just not long enough, blanks are
14075: supplied for the missing portion.
14076:
14077: @item I/O exception in block transfer:
14078: @cindex I/O exception in block transfer
14079: @cindex block transfer, I/O exception
14080: Typically results in a @code{throw} of some OS-derived value (between
14081: -512 and -2048).
14082:
14083: @item invalid block number:
14084: @cindex invalid block number
14085: @cindex block number invalid
14086: @code{-35 throw} (Invalid block number)
14087:
14088: @item a program directly alters the contents of @code{BLK}:
14089: @cindex @code{BLK}, altering @code{BLK}
14090: The input stream is switched to that other block, at the same
14091: position. If the storing to @code{BLK} happens when interpreting
14092: non-block input, the system will get quite confused when the block ends.
14093:
14094: @item no current block buffer for @code{UPDATE}:
14095: @cindex @code{UPDATE}, no current block buffer
14096: @code{UPDATE} has no effect.
14097:
14098: @end table
14099:
14100: @c ---------------------------------------------------------------------
14101: @node block-other, , block-ambcond, The optional Block word set
14102: @subsection Other system documentation
14103: @c ---------------------------------------------------------------------
14104: @cindex other system documentation, block words
14105: @cindex block words, other system documentation
14106:
14107: @table @i
14108: @item any restrictions a multiprogramming system places on the use of buffer addresses:
14109: No restrictions (yet).
14110:
14111: @item the number of blocks available for source and data:
14112: depends on your disk space.
14113:
14114: @end table
14115:
14116:
14117: @c =====================================================================
14118: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
14119: @section The optional Double Number word set
14120: @c =====================================================================
14121: @cindex system documentation, double words
14122: @cindex double words, system documentation
14123:
14124: @menu
14125: * double-ambcond:: Ambiguous Conditions
14126: @end menu
14127:
14128:
14129: @c ---------------------------------------------------------------------
14130: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
14131: @subsection Ambiguous conditions
14132: @c ---------------------------------------------------------------------
14133: @cindex double words, ambiguous conditions
14134: @cindex ambiguous conditions, double words
14135:
14136: @table @i
14137: @item @i{d} outside of range of @i{n} in @code{D>S}:
14138: @cindex @code{D>S}, @i{d} out of range of @i{n}
14139: The least significant cell of @i{d} is produced.
14140:
14141: @end table
14142:
14143:
14144: @c =====================================================================
14145: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
14146: @section The optional Exception word set
14147: @c =====================================================================
14148: @cindex system documentation, exception words
14149: @cindex exception words, system documentation
14150:
14151: @menu
14152: * exception-idef:: Implementation Defined Options
14153: @end menu
14154:
14155:
14156: @c ---------------------------------------------------------------------
14157: @node exception-idef, , The optional Exception word set, The optional Exception word set
14158: @subsection Implementation Defined Options
14159: @c ---------------------------------------------------------------------
14160: @cindex implementation-defined options, exception words
14161: @cindex exception words, implementation-defined options
14162:
14163: @table @i
14164: @item @code{THROW}-codes used in the system:
14165: @cindex @code{THROW}-codes used in the system
14166: The codes -256@minus{}-511 are used for reporting signals. The mapping
14167: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
14168: codes -512@minus{}-2047 are used for OS errors (for file and memory
14169: allocation operations). The mapping from OS error numbers to throw codes
14170: is -512@minus{}@code{errno}. One side effect of this mapping is that
14171: undefined OS errors produce a message with a strange number; e.g.,
14172: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
14173: @end table
14174:
14175: @c =====================================================================
14176: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
14177: @section The optional Facility word set
14178: @c =====================================================================
14179: @cindex system documentation, facility words
14180: @cindex facility words, system documentation
14181:
14182: @menu
14183: * facility-idef:: Implementation Defined Options
14184: * facility-ambcond:: Ambiguous Conditions
14185: @end menu
14186:
14187:
14188: @c ---------------------------------------------------------------------
14189: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
14190: @subsection Implementation Defined Options
14191: @c ---------------------------------------------------------------------
14192: @cindex implementation-defined options, facility words
14193: @cindex facility words, implementation-defined options
14194:
14195: @table @i
14196: @item encoding of keyboard events (@code{EKEY}):
14197: @cindex keyboard events, encoding in @code{EKEY}
14198: @cindex @code{EKEY}, encoding of keyboard events
14199: Keys corresponding to ASCII characters are encoded as ASCII characters.
14200: Other keys are encoded with the constants @code{k-left}, @code{k-right},
14201: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
14202: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
14203: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
14204:
14205:
14206: @item duration of a system clock tick:
14207: @cindex duration of a system clock tick
14208: @cindex clock tick duration
14209: System dependent. With respect to @code{MS}, the time is specified in
14210: microseconds. How well the OS and the hardware implement this, is
14211: another question.
14212:
14213: @item repeatability to be expected from the execution of @code{MS}:
14214: @cindex repeatability to be expected from the execution of @code{MS}
14215: @cindex @code{MS}, repeatability to be expected
14216: System dependent. On Unix, a lot depends on load. If the system is
14217: lightly loaded, and the delay is short enough that Gforth does not get
14218: swapped out, the performance should be acceptable. Under MS-DOS and
14219: other single-tasking systems, it should be good.
14220:
14221: @end table
14222:
14223:
14224: @c ---------------------------------------------------------------------
14225: @node facility-ambcond, , facility-idef, The optional Facility word set
14226: @subsection Ambiguous conditions
14227: @c ---------------------------------------------------------------------
14228: @cindex facility words, ambiguous conditions
14229: @cindex ambiguous conditions, facility words
14230:
14231: @table @i
14232: @item @code{AT-XY} can't be performed on user output device:
14233: @cindex @code{AT-XY} can't be performed on user output device
14234: Largely terminal dependent. No range checks are done on the arguments.
14235: No errors are reported. You may see some garbage appearing, you may see
14236: simply nothing happen.
14237:
14238: @end table
14239:
14240:
14241: @c =====================================================================
14242: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
14243: @section The optional File-Access word set
14244: @c =====================================================================
14245: @cindex system documentation, file words
14246: @cindex file words, system documentation
14247:
14248: @menu
14249: * file-idef:: Implementation Defined Options
14250: * file-ambcond:: Ambiguous Conditions
14251: @end menu
14252:
14253: @c ---------------------------------------------------------------------
14254: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
14255: @subsection Implementation Defined Options
14256: @c ---------------------------------------------------------------------
14257: @cindex implementation-defined options, file words
14258: @cindex file words, implementation-defined options
14259:
14260: @table @i
14261: @item file access methods used:
14262: @cindex file access methods used
14263: @code{R/O}, @code{R/W} and @code{BIN} work as you would
14264: expect. @code{W/O} translates into the C file opening mode @code{w} (or
14265: @code{wb}): The file is cleared, if it exists, and created, if it does
14266: not (with both @code{open-file} and @code{create-file}). Under Unix
14267: @code{create-file} creates a file with 666 permissions modified by your
14268: umask.
14269:
14270: @item file exceptions:
14271: @cindex file exceptions
14272: The file words do not raise exceptions (except, perhaps, memory access
14273: faults when you pass illegal addresses or file-ids).
14274:
14275: @item file line terminator:
14276: @cindex file line terminator
14277: System-dependent. Gforth uses C's newline character as line
14278: terminator. What the actual character code(s) of this are is
14279: system-dependent.
14280:
14281: @item file name format:
14282: @cindex file name format
14283: System dependent. Gforth just uses the file name format of your OS.
14284:
14285: @item information returned by @code{FILE-STATUS}:
14286: @cindex @code{FILE-STATUS}, returned information
14287: @code{FILE-STATUS} returns the most powerful file access mode allowed
14288: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
14289: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
14290: along with the returned mode.
14291:
14292: @item input file state after an exception when including source:
14293: @cindex exception when including source
14294: All files that are left via the exception are closed.
14295:
14296: @item @i{ior} values and meaning:
14297: @cindex @i{ior} values and meaning
14298: @cindex @i{wior} values and meaning
14299: The @i{ior}s returned by the file and memory allocation words are
14300: intended as throw codes. They typically are in the range
14301: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
14302: @i{ior}s is -512@minus{}@i{errno}.
14303:
14304: @item maximum depth of file input nesting:
14305: @cindex maximum depth of file input nesting
14306: @cindex file input nesting, maximum depth
14307: limited by the amount of return stack, locals/TIB stack, and the number
14308: of open files available. This should not give you troubles.
14309:
14310: @item maximum size of input line:
14311: @cindex maximum size of input line
14312: @cindex input line size, maximum
14313: @code{/line}. Currently 255.
14314:
14315: @item methods of mapping block ranges to files:
14316: @cindex mapping block ranges to files
14317: @cindex files containing blocks
14318: @cindex blocks in files
14319: By default, blocks are accessed in the file @file{blocks.fb} in the
14320: current working directory. The file can be switched with @code{USE}.
14321:
14322: @item number of string buffers provided by @code{S"}:
14323: @cindex @code{S"}, number of string buffers
14324: 1
14325:
14326: @item size of string buffer used by @code{S"}:
14327: @cindex @code{S"}, size of string buffer
14328: @code{/line}. currently 255.
14329:
14330: @end table
14331:
14332: @c ---------------------------------------------------------------------
14333: @node file-ambcond, , file-idef, The optional File-Access word set
14334: @subsection Ambiguous conditions
14335: @c ---------------------------------------------------------------------
14336: @cindex file words, ambiguous conditions
14337: @cindex ambiguous conditions, file words
14338:
14339: @table @i
14340: @item attempting to position a file outside its boundaries:
14341: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
14342: @code{REPOSITION-FILE} is performed as usual: Afterwards,
14343: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
14344:
14345: @item attempting to read from file positions not yet written:
14346: @cindex reading from file positions not yet written
14347: End-of-file, i.e., zero characters are read and no error is reported.
14348:
14349: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
14350: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
14351: An appropriate exception may be thrown, but a memory fault or other
14352: problem is more probable.
14353:
14354: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
14355: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
14356: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
14357: The @i{ior} produced by the operation, that discovered the problem, is
14358: thrown.
14359:
14360: @item named file cannot be opened (@code{INCLUDED}):
14361: @cindex @code{INCLUDED}, named file cannot be opened
14362: The @i{ior} produced by @code{open-file} is thrown.
14363:
14364: @item requesting an unmapped block number:
14365: @cindex unmapped block numbers
14366: There are no unmapped legal block numbers. On some operating systems,
14367: writing a block with a large number may overflow the file system and
14368: have an error message as consequence.
14369:
14370: @item using @code{source-id} when @code{blk} is non-zero:
14371: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
14372: @code{source-id} performs its function. Typically it will give the id of
14373: the source which loaded the block. (Better ideas?)
14374:
14375: @end table
14376:
14377:
14378: @c =====================================================================
14379: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
14380: @section The optional Floating-Point word set
14381: @c =====================================================================
14382: @cindex system documentation, floating-point words
14383: @cindex floating-point words, system documentation
14384:
14385: @menu
14386: * floating-idef:: Implementation Defined Options
14387: * floating-ambcond:: Ambiguous Conditions
14388: @end menu
14389:
14390:
14391: @c ---------------------------------------------------------------------
14392: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
14393: @subsection Implementation Defined Options
14394: @c ---------------------------------------------------------------------
14395: @cindex implementation-defined options, floating-point words
14396: @cindex floating-point words, implementation-defined options
14397:
14398: @table @i
14399: @item format and range of floating point numbers:
14400: @cindex format and range of floating point numbers
14401: @cindex floating point numbers, format and range
14402: System-dependent; the @code{double} type of C.
14403:
14404: @item results of @code{REPRESENT} when @i{float} is out of range:
14405: @cindex @code{REPRESENT}, results when @i{float} is out of range
14406: System dependent; @code{REPRESENT} is implemented using the C library
14407: function @code{ecvt()} and inherits its behaviour in this respect.
14408:
14409: @item rounding or truncation of floating-point numbers:
14410: @cindex rounding of floating-point numbers
14411: @cindex truncation of floating-point numbers
14412: @cindex floating-point numbers, rounding or truncation
14413: System dependent; the rounding behaviour is inherited from the hosting C
14414: compiler. IEEE-FP-based (i.e., most) systems by default round to
14415: nearest, and break ties by rounding to even (i.e., such that the last
14416: bit of the mantissa is 0).
14417:
14418: @item size of floating-point stack:
14419: @cindex floating-point stack size
14420: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
14421: the floating-point stack (in floats). You can specify this on startup
14422: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
14423:
14424: @item width of floating-point stack:
14425: @cindex floating-point stack width
14426: @code{1 floats}.
14427:
14428: @end table
14429:
14430:
14431: @c ---------------------------------------------------------------------
14432: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
14433: @subsection Ambiguous conditions
14434: @c ---------------------------------------------------------------------
14435: @cindex floating-point words, ambiguous conditions
14436: @cindex ambiguous conditions, floating-point words
14437:
14438: @table @i
14439: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
14440: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
14441: System-dependent. Typically results in a @code{-23 THROW} like other
14442: alignment violations.
14443:
14444: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
14445: @cindex @code{f@@} used with an address that is not float aligned
14446: @cindex @code{f!} used with an address that is not float aligned
14447: System-dependent. Typically results in a @code{-23 THROW} like other
14448: alignment violations.
14449:
14450: @item floating-point result out of range:
14451: @cindex floating-point result out of range
14452: System-dependent. Can result in a @code{-43 throw} (floating point
14453: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
14454: (floating point inexact result), @code{-55 THROW} (Floating-point
14455: unidentified fault), or can produce a special value representing, e.g.,
14456: Infinity.
14457:
14458: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
14459: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
14460: System-dependent. Typically results in an alignment fault like other
14461: alignment violations.
14462:
14463: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
14464: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
14465: The floating-point number is converted into decimal nonetheless.
14466:
14467: @item Both arguments are equal to zero (@code{FATAN2}):
14468: @cindex @code{FATAN2}, both arguments are equal to zero
14469: System-dependent. @code{FATAN2} is implemented using the C library
14470: function @code{atan2()}.
14471:
14472: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14473: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14474: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
14475: because of small errors and the tan will be a very large (or very small)
14476: but finite number.
14477:
14478: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14479: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
14480: The result is rounded to the nearest float.
14481:
14482: @item dividing by zero:
14483: @cindex dividing by zero, floating-point
14484: @cindex floating-point dividing by zero
14485: @cindex floating-point unidentified fault, FP divide-by-zero
14486: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14487: (floating point divide by zero) or @code{-55 throw} (Floating-point
14488: unidentified fault).
14489:
14490: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14491: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14492: System dependent. On IEEE-FP based systems the number is converted into
14493: an infinity.
14494:
14495: @item @i{float}<1 (@code{FACOSH}):
14496: @cindex @code{FACOSH}, @i{float}<1
14497: @cindex floating-point unidentified fault, @code{FACOSH}
14498: Platform-dependent; on IEEE-FP systems typically produces a NaN.
14499:
14500: @item @i{float}=<-1 (@code{FLNP1}):
14501: @cindex @code{FLNP1}, @i{float}=<-1
14502: @cindex floating-point unidentified fault, @code{FLNP1}
14503: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14504: negative infinity for @i{float}=-1).
14505:
14506: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14507: @cindex @code{FLN}, @i{float}=<0
14508: @cindex @code{FLOG}, @i{float}=<0
14509: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
14510: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14511: negative infinity for @i{float}=0).
14512:
14513: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14514: @cindex @code{FASINH}, @i{float}<0
14515: @cindex @code{FSQRT}, @i{float}<0
14516: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
14517: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14518: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14519: C library?).
14520:
14521: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14522: @cindex @code{FACOS}, |@i{float}|>1
14523: @cindex @code{FASIN}, |@i{float}|>1
14524: @cindex @code{FATANH}, |@i{float}|>1
14525: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
14526: Platform-dependent; IEEE-FP systems typically produce a NaN.
14527:
14528: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14529: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
14530: @cindex floating-point unidentified fault, @code{F>D}
14531: Platform-dependent; typically, some double number is produced and no
14532: error is reported.
14533:
14534: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14535: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
14536: @code{Precision} characters of the numeric output area are used. If
14537: @code{precision} is too high, these words will smash the data or code
14538: close to @code{here}.
14539: @end table
14540:
14541: @c =====================================================================
14542: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14543: @section The optional Locals word set
14544: @c =====================================================================
14545: @cindex system documentation, locals words
14546: @cindex locals words, system documentation
14547:
14548: @menu
14549: * locals-idef:: Implementation Defined Options
14550: * locals-ambcond:: Ambiguous Conditions
14551: @end menu
14552:
14553:
14554: @c ---------------------------------------------------------------------
14555: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14556: @subsection Implementation Defined Options
14557: @c ---------------------------------------------------------------------
14558: @cindex implementation-defined options, locals words
14559: @cindex locals words, implementation-defined options
14560:
14561: @table @i
14562: @item maximum number of locals in a definition:
14563: @cindex maximum number of locals in a definition
14564: @cindex locals, maximum number in a definition
14565: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14566: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14567: characters. The number of locals in a definition is bounded by the size
14568: of locals-buffer, which contains the names of the locals.
14569:
14570: @end table
14571:
14572:
14573: @c ---------------------------------------------------------------------
14574: @node locals-ambcond, , locals-idef, The optional Locals word set
14575: @subsection Ambiguous conditions
14576: @c ---------------------------------------------------------------------
14577: @cindex locals words, ambiguous conditions
14578: @cindex ambiguous conditions, locals words
14579:
14580: @table @i
14581: @item executing a named local in interpretation state:
14582: @cindex local in interpretation state
14583: @cindex Interpreting a compile-only word, for a local
14584: Locals have no interpretation semantics. If you try to perform the
14585: interpretation semantics, you will get a @code{-14 throw} somewhere
14586: (Interpreting a compile-only word). If you perform the compilation
14587: semantics, the locals access will be compiled (irrespective of state).
14588:
14589: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
14590: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14591: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14592: @cindex Invalid name argument, @code{TO}
14593: @code{-32 throw} (Invalid name argument)
14594:
14595: @end table
14596:
14597:
14598: @c =====================================================================
14599: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14600: @section The optional Memory-Allocation word set
14601: @c =====================================================================
14602: @cindex system documentation, memory-allocation words
14603: @cindex memory-allocation words, system documentation
14604:
14605: @menu
14606: * memory-idef:: Implementation Defined Options
14607: @end menu
14608:
14609:
14610: @c ---------------------------------------------------------------------
14611: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14612: @subsection Implementation Defined Options
14613: @c ---------------------------------------------------------------------
14614: @cindex implementation-defined options, memory-allocation words
14615: @cindex memory-allocation words, implementation-defined options
14616:
14617: @table @i
14618: @item values and meaning of @i{ior}:
14619: @cindex @i{ior} values and meaning
14620: The @i{ior}s returned by the file and memory allocation words are
14621: intended as throw codes. They typically are in the range
14622: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
14623: @i{ior}s is -512@minus{}@i{errno}.
14624:
14625: @end table
14626:
14627: @c =====================================================================
14628: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14629: @section The optional Programming-Tools word set
14630: @c =====================================================================
14631: @cindex system documentation, programming-tools words
14632: @cindex programming-tools words, system documentation
14633:
14634: @menu
14635: * programming-idef:: Implementation Defined Options
14636: * programming-ambcond:: Ambiguous Conditions
14637: @end menu
14638:
14639:
14640: @c ---------------------------------------------------------------------
14641: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14642: @subsection Implementation Defined Options
14643: @c ---------------------------------------------------------------------
14644: @cindex implementation-defined options, programming-tools words
14645: @cindex programming-tools words, implementation-defined options
14646:
14647: @table @i
14648: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14649: @cindex @code{;CODE} ending sequence
14650: @cindex @code{CODE} ending sequence
14651: @code{END-CODE}
14652:
14653: @item manner of processing input following @code{;CODE} and @code{CODE}:
14654: @cindex @code{;CODE}, processing input
14655: @cindex @code{CODE}, processing input
14656: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14657: the input is processed by the text interpreter, (starting) in interpret
14658: state.
14659:
14660: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14661: @cindex @code{ASSEMBLER}, search order capability
14662: The ANS Forth search order word set.
14663:
14664: @item source and format of display by @code{SEE}:
14665: @cindex @code{SEE}, source and format of output
14666: The source for @code{see} is the executable code used by the inner
14667: interpreter. The current @code{see} tries to output Forth source code
14668: (and on some platforms, assembly code for primitives) as well as
14669: possible.
14670:
14671: @end table
14672:
14673: @c ---------------------------------------------------------------------
14674: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
14675: @subsection Ambiguous conditions
14676: @c ---------------------------------------------------------------------
14677: @cindex programming-tools words, ambiguous conditions
14678: @cindex ambiguous conditions, programming-tools words
14679:
14680: @table @i
14681:
14682: @item deleting the compilation word list (@code{FORGET}):
14683: @cindex @code{FORGET}, deleting the compilation word list
14684: Not implemented (yet).
14685:
14686: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14687: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14688: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
14689: @cindex control-flow stack underflow
14690: This typically results in an @code{abort"} with a descriptive error
14691: message (may change into a @code{-22 throw} (Control structure mismatch)
14692: in the future). You may also get a memory access error. If you are
14693: unlucky, this ambiguous condition is not caught.
14694:
14695: @item @i{name} can't be found (@code{FORGET}):
14696: @cindex @code{FORGET}, @i{name} can't be found
14697: Not implemented (yet).
14698:
14699: @item @i{name} not defined via @code{CREATE}:
14700: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
14701: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14702: the execution semantics of the last defined word no matter how it was
14703: defined.
14704:
14705: @item @code{POSTPONE} applied to @code{[IF]}:
14706: @cindex @code{POSTPONE} applied to @code{[IF]}
14707: @cindex @code{[IF]} and @code{POSTPONE}
14708: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14709: equivalent to @code{[IF]}.
14710:
14711: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14712: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14713: Continue in the same state of conditional compilation in the next outer
14714: input source. Currently there is no warning to the user about this.
14715:
14716: @item removing a needed definition (@code{FORGET}):
14717: @cindex @code{FORGET}, removing a needed definition
14718: Not implemented (yet).
14719:
14720: @end table
14721:
14722:
14723: @c =====================================================================
14724: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
14725: @section The optional Search-Order word set
14726: @c =====================================================================
14727: @cindex system documentation, search-order words
14728: @cindex search-order words, system documentation
14729:
14730: @menu
14731: * search-idef:: Implementation Defined Options
14732: * search-ambcond:: Ambiguous Conditions
14733: @end menu
14734:
14735:
14736: @c ---------------------------------------------------------------------
14737: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14738: @subsection Implementation Defined Options
14739: @c ---------------------------------------------------------------------
14740: @cindex implementation-defined options, search-order words
14741: @cindex search-order words, implementation-defined options
14742:
14743: @table @i
14744: @item maximum number of word lists in search order:
14745: @cindex maximum number of word lists in search order
14746: @cindex search order, maximum depth
14747: @code{s" wordlists" environment? drop .}. Currently 16.
14748:
14749: @item minimum search order:
14750: @cindex minimum search order
14751: @cindex search order, minimum
14752: @code{root root}.
14753:
14754: @end table
14755:
14756: @c ---------------------------------------------------------------------
14757: @node search-ambcond, , search-idef, The optional Search-Order word set
14758: @subsection Ambiguous conditions
14759: @c ---------------------------------------------------------------------
14760: @cindex search-order words, ambiguous conditions
14761: @cindex ambiguous conditions, search-order words
14762:
14763: @table @i
14764: @item changing the compilation word list (during compilation):
14765: @cindex changing the compilation word list (during compilation)
14766: @cindex compilation word list, change before definition ends
14767: The word is entered into the word list that was the compilation word list
14768: at the start of the definition. Any changes to the name field (e.g.,
14769: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
14770: are applied to the latest defined word (as reported by @code{latest} or
14771: @code{latestxt}), if possible, irrespective of the compilation word list.
14772:
14773: @item search order empty (@code{previous}):
14774: @cindex @code{previous}, search order empty
14775: @cindex vocstack empty, @code{previous}
14776: @code{abort" Vocstack empty"}.
14777:
14778: @item too many word lists in search order (@code{also}):
14779: @cindex @code{also}, too many word lists in search order
14780: @cindex vocstack full, @code{also}
14781: @code{abort" Vocstack full"}.
14782:
14783: @end table
14784:
14785: @c ***************************************************************
14786: @node Standard vs Extensions, Model, ANS conformance, Top
14787: @chapter Should I use Gforth extensions?
14788: @cindex Gforth extensions
14789:
14790: As you read through the rest of this manual, you will see documentation
14791: for @i{Standard} words, and documentation for some appealing Gforth
14792: @i{extensions}. You might ask yourself the question: @i{``Should I
14793: restrict myself to the standard, or should I use the extensions?''}
14794:
14795: The answer depends on the goals you have for the program you are working
14796: on:
14797:
14798: @itemize @bullet
14799:
14800: @item Is it just for yourself or do you want to share it with others?
14801:
14802: @item
14803: If you want to share it, do the others all use Gforth?
14804:
14805: @item
14806: If it is just for yourself, do you want to restrict yourself to Gforth?
14807:
14808: @end itemize
14809:
14810: If restricting the program to Gforth is ok, then there is no reason not
14811: to use extensions. It is still a good idea to keep to the standard
14812: where it is easy, in case you want to reuse these parts in another
14813: program that you want to be portable.
14814:
14815: If you want to be able to port the program to other Forth systems, there
14816: are the following points to consider:
14817:
14818: @itemize @bullet
14819:
14820: @item
14821: Most Forth systems that are being maintained support the ANS Forth
14822: standard. So if your program complies with the standard, it will be
14823: portable among many systems.
14824:
14825: @item
14826: A number of the Gforth extensions can be implemented in ANS Forth using
14827: public-domain files provided in the @file{compat/} directory. These are
14828: mentioned in the text in passing. There is no reason not to use these
14829: extensions, your program will still be ANS Forth compliant; just include
14830: the appropriate compat files with your program.
14831:
14832: @item
14833: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14834: analyse your program and determine what non-Standard words it relies
14835: upon. However, it does not check whether you use standard words in a
14836: non-standard way.
14837:
14838: @item
14839: Some techniques are not standardized by ANS Forth, and are hard or
14840: impossible to implement in a standard way, but can be implemented in
14841: most Forth systems easily, and usually in similar ways (e.g., accessing
14842: word headers). Forth has a rich historical precedent for programmers
14843: taking advantage of implementation-dependent features of their tools
14844: (for example, relying on a knowledge of the dictionary
14845: structure). Sometimes these techniques are necessary to extract every
14846: last bit of performance from the hardware, sometimes they are just a
14847: programming shorthand.
14848:
14849: @item
14850: Does using a Gforth extension save more work than the porting this part
14851: to other Forth systems (if any) will cost?
14852:
14853: @item
14854: Is the additional functionality worth the reduction in portability and
14855: the additional porting problems?
14856:
14857: @end itemize
14858:
14859: In order to perform these consideratios, you need to know what's
14860: standard and what's not. This manual generally states if something is
14861: non-standard, but the authoritative source is the
14862: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
14863: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14864: into the thought processes of the technical committee.
14865:
14866: Note also that portability between Forth systems is not the only
14867: portability issue; there is also the issue of portability between
14868: different platforms (processor/OS combinations).
14869:
14870: @c ***************************************************************
14871: @node Model, Integrating Gforth, Standard vs Extensions, Top
14872: @chapter Model
14873:
14874: This chapter has yet to be written. It will contain information, on
14875: which internal structures you can rely.
14876:
14877: @c ***************************************************************
14878: @node Integrating Gforth, Emacs and Gforth, Model, Top
14879: @chapter Integrating Gforth into C programs
14880:
14881: This is not yet implemented.
14882:
14883: Several people like to use Forth as scripting language for applications
14884: that are otherwise written in C, C++, or some other language.
14885:
14886: The Forth system ATLAST provides facilities for embedding it into
14887: applications; unfortunately it has several disadvantages: most
14888: importantly, it is not based on ANS Forth, and it is apparently dead
14889: (i.e., not developed further and not supported). The facilities
14890: provided by Gforth in this area are inspired by ATLAST's facilities, so
14891: making the switch should not be hard.
14892:
14893: We also tried to design the interface such that it can easily be
14894: implemented by other Forth systems, so that we may one day arrive at a
14895: standardized interface. Such a standard interface would allow you to
14896: replace the Forth system without having to rewrite C code.
14897:
14898: You embed the Gforth interpreter by linking with the library
14899: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
14900: global symbols in this library that belong to the interface, have the
14901: prefix @code{forth_}. (Global symbols that are used internally have the
14902: prefix @code{gforth_}).
14903:
14904: You can include the declarations of Forth types and the functions and
14905: variables of the interface with @code{#include <forth.h>}.
14906:
14907: Types.
14908:
14909: Variables.
14910:
14911: Data and FP Stack pointer. Area sizes.
14912:
14913: functions.
14914:
14915: forth_init(imagefile)
14916: forth_evaluate(string) exceptions?
14917: forth_goto(address) (or forth_execute(xt)?)
14918: forth_continue() (a corountining mechanism)
14919:
14920: Adding primitives.
14921:
14922: No checking.
14923:
14924: Signals?
14925:
14926: Accessing the Stacks
14927:
14928: @c ******************************************************************
14929: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14930: @chapter Emacs and Gforth
14931: @cindex Emacs and Gforth
14932:
14933: @cindex @file{gforth.el}
14934: @cindex @file{forth.el}
14935: @cindex Rydqvist, Goran
14936: @cindex Kuehling, David
14937: @cindex comment editing commands
14938: @cindex @code{\}, editing with Emacs
14939: @cindex debug tracer editing commands
14940: @cindex @code{~~}, removal with Emacs
14941: @cindex Forth mode in Emacs
14942:
14943: Gforth comes with @file{gforth.el}, an improved version of
14944: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
14945: improvements are:
14946:
14947: @itemize @bullet
14948: @item
14949: A better handling of indentation.
14950: @item
14951: A custom hilighting engine for Forth-code.
14952: @item
14953: Comment paragraph filling (@kbd{M-q})
14954: @item
14955: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14956: @item
14957: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
14958: @item
14959: Support of the @code{info-lookup} feature for looking up the
14960: documentation of a word.
14961: @item
14962: Support for reading and writing blocks files.
14963: @end itemize
14964:
14965: To get a basic description of these features, enter Forth mode and
14966: type @kbd{C-h m}.
14967:
14968: @cindex source location of error or debugging output in Emacs
14969: @cindex error output, finding the source location in Emacs
14970: @cindex debugging output, finding the source location in Emacs
14971: In addition, Gforth supports Emacs quite well: The source code locations
14972: given in error messages, debugging output (from @code{~~}) and failed
14973: assertion messages are in the right format for Emacs' compilation mode
14974: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14975: Manual}) so the source location corresponding to an error or other
14976: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14977: @kbd{C-c C-c} for the error under the cursor).
14978:
14979: @cindex viewing the documentation of a word in Emacs
14980: @cindex context-sensitive help
14981: Moreover, for words documented in this manual, you can look up the
14982: glossary entry quickly by using @kbd{C-h TAB}
14983: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14984: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14985: later and does not work for words containing @code{:}.
14986:
14987: @menu
14988: * Installing gforth.el:: Making Emacs aware of Forth.
14989: * Emacs Tags:: Viewing the source of a word in Emacs.
14990: * Hilighting:: Making Forth code look prettier.
14991: * Auto-Indentation:: Customizing auto-indentation.
14992: * Blocks Files:: Reading and writing blocks files.
14993: @end menu
14994:
14995: @c ----------------------------------
14996: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
14997: @section Installing gforth.el
14998: @cindex @file{.emacs}
14999: @cindex @file{gforth.el}, installation
15000: To make the features from @file{gforth.el} available in Emacs, add
15001: the following lines to your @file{.emacs} file:
15002:
15003: @example
15004: (autoload 'forth-mode "gforth.el")
15005: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
15006: auto-mode-alist))
15007: (autoload 'forth-block-mode "gforth.el")
15008: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
15009: auto-mode-alist))
15010: (add-hook 'forth-mode-hook (function (lambda ()
15011: ;; customize variables here:
15012: (setq forth-indent-level 4)
15013: (setq forth-minor-indent-level 2)
15014: (setq forth-hilight-level 3)
15015: ;;; ...
15016: )))
15017: @end example
15018:
15019: @c ----------------------------------
15020: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
15021: @section Emacs Tags
15022: @cindex @file{TAGS} file
15023: @cindex @file{etags.fs}
15024: @cindex viewing the source of a word in Emacs
15025: @cindex @code{require}, placement in files
15026: @cindex @code{include}, placement in files
15027: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
15028: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
15029: contains the definitions of all words defined afterwards. You can then
15030: find the source for a word using @kbd{M-.}. Note that Emacs can use
15031: several tags files at the same time (e.g., one for the Gforth sources
15032: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
15033: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
15034: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
15035: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
15036: with @file{etags.fs}, you should avoid putting definitions both before
15037: and after @code{require} etc., otherwise you will see the same file
15038: visited several times by commands like @code{tags-search}.
15039:
15040: @c ----------------------------------
15041: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
15042: @section Hilighting
15043: @cindex hilighting Forth code in Emacs
15044: @cindex highlighting Forth code in Emacs
15045: @file{gforth.el} comes with a custom source hilighting engine. When
15046: you open a file in @code{forth-mode}, it will be completely parsed,
15047: assigning faces to keywords, comments, strings etc. While you edit
15048: the file, modified regions get parsed and updated on-the-fly.
15049:
15050: Use the variable `forth-hilight-level' to change the level of
15051: decoration from 0 (no hilighting at all) to 3 (the default). Even if
15052: you set the hilighting level to 0, the parser will still work in the
15053: background, collecting information about whether regions of text are
15054: ``compiled'' or ``interpreted''. Those information are required for
15055: auto-indentation to work properly. Set `forth-disable-parser' to
15056: non-nil if your computer is too slow to handle parsing. This will
15057: have an impact on the smartness of the auto-indentation engine,
15058: though.
15059:
15060: Sometimes Forth sources define new features that should be hilighted,
15061: new control structures, defining-words etc. You can use the variable
15062: `forth-custom-words' to make @code{forth-mode} hilight additional
15063: words and constructs. See the docstring of `forth-words' for details
15064: (in Emacs, type @kbd{C-h v forth-words}).
15065:
15066: `forth-custom-words' is meant to be customized in your
15067: @file{.emacs} file. To customize hilighing in a file-specific manner,
15068: set `forth-local-words' in a local-variables section at the end of
15069: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
15070:
15071: Example:
15072: @example
15073: 0 [IF]
15074: Local Variables:
15075: forth-local-words:
15076: ((("t:") definition-starter (font-lock-keyword-face . 1)
15077: "[ \t\n]" t name (font-lock-function-name-face . 3))
15078: ((";t") definition-ender (font-lock-keyword-face . 1)))
15079: End:
15080: [THEN]
15081: @end example
15082:
15083: @c ----------------------------------
15084: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
15085: @section Auto-Indentation
15086: @cindex auto-indentation of Forth code in Emacs
15087: @cindex indentation of Forth code in Emacs
15088: @code{forth-mode} automatically tries to indent lines in a smart way,
15089: whenever you type @key{TAB} or break a line with @kbd{C-m}.
15090:
15091: Simple customization can be achieved by setting
15092: `forth-indent-level' and `forth-minor-indent-level' in your
15093: @file{.emacs} file. For historical reasons @file{gforth.el} indents
15094: per default by multiples of 4 columns. To use the more traditional
15095: 3-column indentation, add the following lines to your @file{.emacs}:
15096:
15097: @example
15098: (add-hook 'forth-mode-hook (function (lambda ()
15099: ;; customize variables here:
15100: (setq forth-indent-level 3)
15101: (setq forth-minor-indent-level 1)
15102: )))
15103: @end example
15104:
15105: If you want indentation to recognize non-default words, customize it
15106: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
15107: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
15108: v forth-indent-words}).
15109:
15110: To customize indentation in a file-specific manner, set
15111: `forth-local-indent-words' in a local-variables section at the end of
15112: your source file (@pxref{Local Variables in Files, Variables,,emacs,
15113: Emacs Manual}).
15114:
15115: Example:
15116: @example
15117: 0 [IF]
15118: Local Variables:
15119: forth-local-indent-words:
15120: ((("t:") (0 . 2) (0 . 2))
15121: ((";t") (-2 . 0) (0 . -2)))
15122: End:
15123: [THEN]
15124: @end example
15125:
15126: @c ----------------------------------
15127: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
15128: @section Blocks Files
15129: @cindex blocks files, use with Emacs
15130: @code{forth-mode} Autodetects blocks files by checking whether the
15131: length of the first line exceeds 1023 characters. It then tries to
15132: convert the file into normal text format. When you save the file, it
15133: will be written to disk as normal stream-source file.
15134:
15135: If you want to write blocks files, use @code{forth-blocks-mode}. It
15136: inherits all the features from @code{forth-mode}, plus some additions:
15137:
15138: @itemize @bullet
15139: @item
15140: Files are written to disk in blocks file format.
15141: @item
15142: Screen numbers are displayed in the mode line (enumerated beginning
15143: with the value of `forth-block-base')
15144: @item
15145: Warnings are displayed when lines exceed 64 characters.
15146: @item
15147: The beginning of the currently edited block is marked with an
15148: overlay-arrow.
15149: @end itemize
15150:
15151: There are some restrictions you should be aware of. When you open a
15152: blocks file that contains tabulator or newline characters, these
15153: characters will be translated into spaces when the file is written
15154: back to disk. If tabs or newlines are encountered during blocks file
15155: reading, an error is output to the echo area. So have a look at the
15156: `*Messages*' buffer, when Emacs' bell rings during reading.
15157:
15158: Please consult the docstring of @code{forth-blocks-mode} for more
15159: information by typing @kbd{C-h v forth-blocks-mode}).
15160:
15161: @c ******************************************************************
15162: @node Image Files, Engine, Emacs and Gforth, Top
15163: @chapter Image Files
15164: @cindex image file
15165: @cindex @file{.fi} files
15166: @cindex precompiled Forth code
15167: @cindex dictionary in persistent form
15168: @cindex persistent form of dictionary
15169:
15170: An image file is a file containing an image of the Forth dictionary,
15171: i.e., compiled Forth code and data residing in the dictionary. By
15172: convention, we use the extension @code{.fi} for image files.
15173:
15174: @menu
15175: * Image Licensing Issues:: Distribution terms for images.
15176: * Image File Background:: Why have image files?
15177: * Non-Relocatable Image Files:: don't always work.
15178: * Data-Relocatable Image Files:: are better.
15179: * Fully Relocatable Image Files:: better yet.
15180: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
15181: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
15182: * Modifying the Startup Sequence:: and turnkey applications.
15183: @end menu
15184:
15185: @node Image Licensing Issues, Image File Background, Image Files, Image Files
15186: @section Image Licensing Issues
15187: @cindex license for images
15188: @cindex image license
15189:
15190: An image created with @code{gforthmi} (@pxref{gforthmi}) or
15191: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
15192: original image; i.e., according to copyright law it is a derived work of
15193: the original image.
15194:
15195: Since Gforth is distributed under the GNU GPL, the newly created image
15196: falls under the GNU GPL, too. In particular, this means that if you
15197: distribute the image, you have to make all of the sources for the image
15198: available, including those you wrote. For details see @ref{Copying, ,
15199: GNU General Public License (Section 3)}.
15200:
15201: If you create an image with @code{cross} (@pxref{cross.fs}), the image
15202: contains only code compiled from the sources you gave it; if none of
15203: these sources is under the GPL, the terms discussed above do not apply
15204: to the image. However, if your image needs an engine (a gforth binary)
15205: that is under the GPL, you should make sure that you distribute both in
15206: a way that is at most a @emph{mere aggregation}, if you don't want the
15207: terms of the GPL to apply to the image.
15208:
15209: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
15210: @section Image File Background
15211: @cindex image file background
15212:
15213: Gforth consists not only of primitives (in the engine), but also of
15214: definitions written in Forth. Since the Forth compiler itself belongs to
15215: those definitions, it is not possible to start the system with the
15216: engine and the Forth source alone. Therefore we provide the Forth
15217: code as an image file in nearly executable form. When Gforth starts up,
15218: a C routine loads the image file into memory, optionally relocates the
15219: addresses, then sets up the memory (stacks etc.) according to
15220: information in the image file, and (finally) starts executing Forth
15221: code.
15222:
15223: The default image file is @file{gforth.fi} (in the @code{GFORTHPATH}).
15224: You can use a different image by using the @code{-i},
15225: @code{--image-file} or @code{--appl-image} options (@pxref{Invoking
15226: Gforth}), e.g.:
15227:
15228: @example
15229: gforth-fast -i myimage.fi
15230: @end example
15231:
15232: There are different variants of image files, and they represent
15233: different compromises between the goals of making it easy to generate
15234: image files and making them portable.
15235:
15236: @cindex relocation at run-time
15237: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
15238: run-time. This avoids many of the complications discussed below (image
15239: files are data relocatable without further ado), but costs performance
15240: (one addition per memory access) and makes it difficult to pass
15241: addresses between Forth and library calls or other programs.
15242:
15243: @cindex relocation at load-time
15244: By contrast, the Gforth loader performs relocation at image load time. The
15245: loader also has to replace tokens that represent primitive calls with the
15246: appropriate code-field addresses (or code addresses in the case of
15247: direct threading).
15248:
15249: There are three kinds of image files, with different degrees of
15250: relocatability: non-relocatable, data-relocatable, and fully relocatable
15251: image files.
15252:
15253: @cindex image file loader
15254: @cindex relocating loader
15255: @cindex loader for image files
15256: These image file variants have several restrictions in common; they are
15257: caused by the design of the image file loader:
15258:
15259: @itemize @bullet
15260: @item
15261: There is only one segment; in particular, this means, that an image file
15262: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
15263: them). The contents of the stacks are not represented, either.
15264:
15265: @item
15266: The only kinds of relocation supported are: adding the same offset to
15267: all cells that represent data addresses; and replacing special tokens
15268: with code addresses or with pieces of machine code.
15269:
15270: If any complex computations involving addresses are performed, the
15271: results cannot be represented in the image file. Several applications that
15272: use such computations come to mind:
15273:
15274: @itemize @minus
15275: @item
15276: Hashing addresses (or data structures which contain addresses) for table
15277: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
15278: purpose, you will have no problem, because the hash tables are
15279: recomputed automatically when the system is started. If you use your own
15280: hash tables, you will have to do something similar.
15281:
15282: @item
15283: There's a cute implementation of doubly-linked lists that uses
15284: @code{XOR}ed addresses. You could represent such lists as singly-linked
15285: in the image file, and restore the doubly-linked representation on
15286: startup.@footnote{In my opinion, though, you should think thrice before
15287: using a doubly-linked list (whatever implementation).}
15288:
15289: @item
15290: The code addresses of run-time routines like @code{docol:} cannot be
15291: represented in the image file (because their tokens would be replaced by
15292: machine code in direct threaded implementations). As a workaround,
15293: compute these addresses at run-time with @code{>code-address} from the
15294: executions tokens of appropriate words (see the definitions of
15295: @code{docol:} and friends in @file{kernel/getdoers.fs}).
15296:
15297: @item
15298: On many architectures addresses are represented in machine code in some
15299: shifted or mangled form. You cannot put @code{CODE} words that contain
15300: absolute addresses in this form in a relocatable image file. Workarounds
15301: are representing the address in some relative form (e.g., relative to
15302: the CFA, which is present in some register), or loading the address from
15303: a place where it is stored in a non-mangled form.
15304: @end itemize
15305: @end itemize
15306:
15307: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
15308: @section Non-Relocatable Image Files
15309: @cindex non-relocatable image files
15310: @cindex image file, non-relocatable
15311:
15312: These files are simple memory dumps of the dictionary. They are
15313: specific to the executable (i.e., @file{gforth} file) they were
15314: created with. What's worse, they are specific to the place on which
15315: the dictionary resided when the image was created. Now, there is no
15316: guarantee that the dictionary will reside at the same place the next
15317: time you start Gforth, so there's no guarantee that a non-relocatable
15318: image will work the next time (Gforth will complain instead of
15319: crashing, though). Indeed, on OSs with (enabled) address-space
15320: randomization non-relocatable images are unlikely to work.
15321:
15322: You can create a non-relocatable image file with @code{savesystem}, e.g.:
15323:
15324: @example
15325: gforth app.fs -e "savesystem app.fi bye"
15326: @end example
15327:
15328: doc-savesystem
15329:
15330:
15331: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
15332: @section Data-Relocatable Image Files
15333: @cindex data-relocatable image files
15334: @cindex image file, data-relocatable
15335:
15336: These files contain relocatable data addresses, but fixed code
15337: addresses (instead of tokens). They are specific to the executable
15338: (i.e., @file{gforth} file) they were created with. Also, they disable
15339: dynamic native code generation (typically a factor of 2 in speed).
15340: You get a data-relocatable image, if you pass the engine you want to
15341: use through the @code{GFORTHD} environment variable to @file{gforthmi}
15342: (@pxref{gforthmi}), e.g.
15343:
15344: @example
15345: GFORTHD="/usr/bin/gforth-fast --no-dynamic" gforthmi myimage.fi source.fs
15346: @end example
15347:
15348: Note that the @code{--no-dynamic} is required here for the image to
15349: work (otherwise it will contain references to dynamically generated
15350: code that is not saved in the image).
15351:
15352:
15353: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
15354: @section Fully Relocatable Image Files
15355: @cindex fully relocatable image files
15356: @cindex image file, fully relocatable
15357:
15358: @cindex @file{kern*.fi}, relocatability
15359: @cindex @file{gforth.fi}, relocatability
15360: These image files have relocatable data addresses, and tokens for code
15361: addresses. They can be used with different binaries (e.g., with and
15362: without debugging) on the same machine, and even across machines with
15363: the same data formats (byte order, cell size, floating point format),
15364: and they work with dynamic native code generation. However, they are
15365: usually specific to the version of Gforth they were created with. The
15366: files @file{gforth.fi} and @file{kernl*.fi} are fully relocatable.
15367:
15368: There are two ways to create a fully relocatable image file:
15369:
15370: @menu
15371: * gforthmi:: The normal way
15372: * cross.fs:: The hard way
15373: @end menu
15374:
15375: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
15376: @subsection @file{gforthmi}
15377: @cindex @file{comp-i.fs}
15378: @cindex @file{gforthmi}
15379:
15380: You will usually use @file{gforthmi}. If you want to create an
15381: image @i{file} that contains everything you would load by invoking
15382: Gforth with @code{gforth @i{options}}, you simply say:
15383: @example
15384: gforthmi @i{file} @i{options}
15385: @end example
15386:
15387: E.g., if you want to create an image @file{asm.fi} that has the file
15388: @file{asm.fs} loaded in addition to the usual stuff, you could do it
15389: like this:
15390:
15391: @example
15392: gforthmi asm.fi asm.fs
15393: @end example
15394:
15395: @file{gforthmi} is implemented as a sh script and works like this: It
15396: produces two non-relocatable images for different addresses and then
15397: compares them. Its output reflects this: first you see the output (if
15398: any) of the two Gforth invocations that produce the non-relocatable image
15399: files, then you see the output of the comparing program: It displays the
15400: offset used for data addresses and the offset used for code addresses;
15401: moreover, for each cell that cannot be represented correctly in the
15402: image files, it displays a line like this:
15403:
15404: @example
15405: 78DC BFFFFA50 BFFFFA40
15406: @end example
15407:
15408: This means that at offset $78dc from @code{forthstart}, one input image
15409: contains $bffffa50, and the other contains $bffffa40. Since these cells
15410: cannot be represented correctly in the output image, you should examine
15411: these places in the dictionary and verify that these cells are dead
15412: (i.e., not read before they are written).
15413:
15414: @cindex --application, @code{gforthmi} option
15415: If you insert the option @code{--application} in front of the image file
15416: name, you will get an image that uses the @code{--appl-image} option
15417: instead of the @code{--image-file} option (@pxref{Invoking
15418: Gforth}). When you execute such an image on Unix (by typing the image
15419: name as command), the Gforth engine will pass all options to the image
15420: instead of trying to interpret them as engine options.
15421:
15422: If you type @file{gforthmi} with no arguments, it prints some usage
15423: instructions.
15424:
15425: @cindex @code{savesystem} during @file{gforthmi}
15426: @cindex @code{bye} during @file{gforthmi}
15427: @cindex doubly indirect threaded code
15428: @cindex environment variables
15429: @cindex @code{GFORTHD} -- environment variable
15430: @cindex @code{GFORTH} -- environment variable
15431: @cindex @code{gforth-ditc}
15432: There are a few wrinkles: After processing the passed @i{options}, the
15433: words @code{savesystem} and @code{bye} must be visible. A special
15434: doubly indirect threaded version of the @file{gforth} executable is
15435: used for creating the non-relocatable images; you can pass the exact
15436: filename of this executable through the environment variable
15437: @code{GFORTHD} (default: @file{gforth-ditc}); if you pass a version
15438: that is not doubly indirect threaded, you will not get a fully
15439: relocatable image, but a data-relocatable image
15440: (@pxref{Data-Relocatable Image Files}), because there is no code
15441: address offset). The normal @file{gforth} executable is used for
15442: creating the relocatable image; you can pass the exact filename of
15443: this executable through the environment variable @code{GFORTH}.
15444:
15445: @node cross.fs, , gforthmi, Fully Relocatable Image Files
15446: @subsection @file{cross.fs}
15447: @cindex @file{cross.fs}
15448: @cindex cross-compiler
15449: @cindex metacompiler
15450: @cindex target compiler
15451:
15452: You can also use @code{cross}, a batch compiler that accepts a Forth-like
15453: programming language (@pxref{Cross Compiler}).
15454:
15455: @code{cross} allows you to create image files for machines with
15456: different data sizes and data formats than the one used for generating
15457: the image file. You can also use it to create an application image that
15458: does not contain a Forth compiler. These features are bought with
15459: restrictions and inconveniences in programming. E.g., addresses have to
15460: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
15461: order to make the code relocatable.
15462:
15463:
15464: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
15465: @section Stack and Dictionary Sizes
15466: @cindex image file, stack and dictionary sizes
15467: @cindex dictionary size default
15468: @cindex stack size default
15469:
15470: If you invoke Gforth with a command line flag for the size
15471: (@pxref{Invoking Gforth}), the size you specify is stored in the
15472: dictionary. If you save the dictionary with @code{savesystem} or create
15473: an image with @file{gforthmi}, this size will become the default
15474: for the resulting image file. E.g., the following will create a
15475: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
15476:
15477: @example
15478: gforthmi gforth.fi -m 1M
15479: @end example
15480:
15481: In other words, if you want to set the default size for the dictionary
15482: and the stacks of an image, just invoke @file{gforthmi} with the
15483: appropriate options when creating the image.
15484:
15485: @cindex stack size, cache-friendly
15486: Note: For cache-friendly behaviour (i.e., good performance), you should
15487: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
15488: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
15489: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
15490:
15491: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
15492: @section Running Image Files
15493: @cindex running image files
15494: @cindex invoking image files
15495: @cindex image file invocation
15496:
15497: @cindex -i, invoke image file
15498: @cindex --image file, invoke image file
15499: You can invoke Gforth with an image file @i{image} instead of the
15500: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
15501: @example
15502: gforth -i @i{image}
15503: @end example
15504:
15505: @cindex executable image file
15506: @cindex image file, executable
15507: If your operating system supports starting scripts with a line of the
15508: form @code{#! ...}, you just have to type the image file name to start
15509: Gforth with this image file (note that the file extension @code{.fi} is
15510: just a convention). I.e., to run Gforth with the image file @i{image},
15511: you can just type @i{image} instead of @code{gforth -i @i{image}}.
15512: This works because every @code{.fi} file starts with a line of this
15513: format:
15514:
15515: @example
15516: #! /usr/local/bin/gforth-0.4.0 -i
15517: @end example
15518:
15519: The file and pathname for the Gforth engine specified on this line is
15520: the specific Gforth executable that it was built against; i.e. the value
15521: of the environment variable @code{GFORTH} at the time that
15522: @file{gforthmi} was executed.
15523:
15524: You can make use of the same shell capability to make a Forth source
15525: file into an executable. For example, if you place this text in a file:
15526:
15527: @example
15528: #! /usr/local/bin/gforth
15529:
15530: ." Hello, world" CR
15531: bye
15532: @end example
15533:
15534: @noindent
15535: and then make the file executable (chmod +x in Unix), you can run it
15536: directly from the command line. The sequence @code{#!} is used in two
15537: ways; firstly, it is recognised as a ``magic sequence'' by the operating
15538: system@footnote{The Unix kernel actually recognises two types of files:
15539: executable files and files of data, where the data is processed by an
15540: interpreter that is specified on the ``interpreter line'' -- the first
15541: line of the file, starting with the sequence #!. There may be a small
15542: limit (e.g., 32) on the number of characters that may be specified on
15543: the interpreter line.} secondly it is treated as a comment character by
15544: Gforth. Because of the second usage, a space is required between
15545: @code{#!} and the path to the executable (moreover, some Unixes
15546: require the sequence @code{#! /}).
15547:
15548: The disadvantage of this latter technique, compared with using
15549: @file{gforthmi}, is that it is slightly slower; the Forth source code is
15550: compiled on-the-fly, each time the program is invoked.
15551:
15552: doc-#!
15553:
15554:
15555: @node Modifying the Startup Sequence, , Running Image Files, Image Files
15556: @section Modifying the Startup Sequence
15557: @cindex startup sequence for image file
15558: @cindex image file initialization sequence
15559: @cindex initialization sequence of image file
15560:
15561: You can add your own initialization to the startup sequence of an image
15562: through the deferred word @code{'cold}. @code{'cold} is invoked just
15563: before the image-specific command line processing (i.e., loading files
15564: and evaluating (@code{-e}) strings) starts.
15565:
15566: A sequence for adding your initialization usually looks like this:
15567:
15568: @example
15569: :noname
15570: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
15571: ... \ your stuff
15572: ; IS 'cold
15573: @end example
15574:
15575: After @code{'cold}, Gforth processes the image options
15576: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
15577: another deferred word. This normally prints Gforth's startup message
15578: and does nothing else.
15579:
15580: @cindex turnkey image files
15581: @cindex image file, turnkey applications
15582: So, if you want to make a turnkey image (i.e., an image for an
15583: application instead of an extended Forth system), you can do this in
15584: two ways:
15585:
15586: @itemize @bullet
15587:
15588: @item
15589: If you want to do your interpretation of the OS command-line
15590: arguments, hook into @code{'cold}. In that case you probably also
15591: want to build the image with @code{gforthmi --application}
15592: (@pxref{gforthmi}) to keep the engine from processing OS command line
15593: options. You can then do your own command-line processing with
15594: @code{next-arg}
15595:
15596: @item
15597: If you want to have the normal Gforth processing of OS command-line
15598: arguments, hook into @code{bootmessage}.
15599:
15600: @end itemize
15601:
15602: In either case, you probably do not want the word that you execute in
15603: these hooks to exit normally, but use @code{bye} or @code{throw}.
15604: Otherwise the Gforth startup process would continue and eventually
15605: present the Forth command line to the user.
15606:
15607: doc-'cold
15608: doc-bootmessage
15609:
15610: @c ******************************************************************
15611: @node Engine, Cross Compiler, Image Files, Top
15612: @chapter Engine
15613: @cindex engine
15614: @cindex virtual machine
15615:
15616: Reading this chapter is not necessary for programming with Gforth. It
15617: may be helpful for finding your way in the Gforth sources.
15618:
15619: The ideas in this section have also been published in the following
15620: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15621: Forth-Tagung '93; M. Anton Ertl,
15622: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15623: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15624: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15625: Threaded code variations and optimizations (extended version)}},
15626: Forth-Tagung '02.
15627:
15628: @menu
15629: * Portability::
15630: * Threading::
15631: * Primitives::
15632: * Performance::
15633: @end menu
15634:
15635: @node Portability, Threading, Engine, Engine
15636: @section Portability
15637: @cindex engine portability
15638:
15639: An important goal of the Gforth Project is availability across a wide
15640: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15641: achieved this goal by manually coding the engine in assembly language
15642: for several then-popular processors. This approach is very
15643: labor-intensive and the results are short-lived due to progress in
15644: computer architecture.
15645:
15646: @cindex C, using C for the engine
15647: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15648: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15649: particularly popular for UNIX-based Forths due to the large variety of
15650: architectures of UNIX machines. Unfortunately an implementation in C
15651: does not mix well with the goals of efficiency and with using
15652: traditional techniques: Indirect or direct threading cannot be expressed
15653: in C, and switch threading, the fastest technique available in C, is
15654: significantly slower. Another problem with C is that it is very
15655: cumbersome to express double integer arithmetic.
15656:
15657: @cindex GNU C for the engine
15658: @cindex long long
15659: Fortunately, there is a portable language that does not have these
15660: limitations: GNU C, the version of C processed by the GNU C compiler
15661: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15662: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15663: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15664: threading possible, its @code{long long} type (@pxref{Long Long, ,
15665: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
15666: double numbers on many systems. GNU C is freely available on all
15667: important (and many unimportant) UNIX machines, VMS, 80386s running
15668: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15669: on all these machines.
15670:
15671: Writing in a portable language has the reputation of producing code that
15672: is slower than assembly. For our Forth engine we repeatedly looked at
15673: the code produced by the compiler and eliminated most compiler-induced
15674: inefficiencies by appropriate changes in the source code.
15675:
15676: @cindex explicit register declarations
15677: @cindex --enable-force-reg, configuration flag
15678: @cindex -DFORCE_REG
15679: However, register allocation cannot be portably influenced by the
15680: programmer, leading to some inefficiencies on register-starved
15681: machines. We use explicit register declarations (@pxref{Explicit Reg
15682: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15683: improve the speed on some machines. They are turned on by using the
15684: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15685: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15686: machine, but also on the compiler version: On some machines some
15687: compiler versions produce incorrect code when certain explicit register
15688: declarations are used. So by default @code{-DFORCE_REG} is not used.
15689:
15690: @node Threading, Primitives, Portability, Engine
15691: @section Threading
15692: @cindex inner interpreter implementation
15693: @cindex threaded code implementation
15694:
15695: @cindex labels as values
15696: GNU C's labels as values extension (available since @code{gcc-2.0},
15697: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
15698: makes it possible to take the address of @i{label} by writing
15699: @code{&&@i{label}}. This address can then be used in a statement like
15700: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
15701: @code{goto x}.
15702:
15703: @cindex @code{NEXT}, indirect threaded
15704: @cindex indirect threaded inner interpreter
15705: @cindex inner interpreter, indirect threaded
15706: With this feature an indirect threaded @code{NEXT} looks like:
15707: @example
15708: cfa = *ip++;
15709: ca = *cfa;
15710: goto *ca;
15711: @end example
15712: @cindex instruction pointer
15713: For those unfamiliar with the names: @code{ip} is the Forth instruction
15714: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15715: execution token and points to the code field of the next word to be
15716: executed; The @code{ca} (code address) fetched from there points to some
15717: executable code, e.g., a primitive or the colon definition handler
15718: @code{docol}.
15719:
15720: @cindex @code{NEXT}, direct threaded
15721: @cindex direct threaded inner interpreter
15722: @cindex inner interpreter, direct threaded
15723: Direct threading is even simpler:
15724: @example
15725: ca = *ip++;
15726: goto *ca;
15727: @end example
15728:
15729: Of course we have packaged the whole thing neatly in macros called
15730: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
15731:
15732: @menu
15733: * Scheduling::
15734: * Direct or Indirect Threaded?::
15735: * Dynamic Superinstructions::
15736: * DOES>::
15737: @end menu
15738:
15739: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15740: @subsection Scheduling
15741: @cindex inner interpreter optimization
15742:
15743: There is a little complication: Pipelined and superscalar processors,
15744: i.e., RISC and some modern CISC machines can process independent
15745: instructions while waiting for the results of an instruction. The
15746: compiler usually reorders (schedules) the instructions in a way that
15747: achieves good usage of these delay slots. However, on our first tries
15748: the compiler did not do well on scheduling primitives. E.g., for
15749: @code{+} implemented as
15750: @example
15751: n=sp[0]+sp[1];
15752: sp++;
15753: sp[0]=n;
15754: NEXT;
15755: @end example
15756: the @code{NEXT} comes strictly after the other code, i.e., there is
15757: nearly no scheduling. After a little thought the problem becomes clear:
15758: The compiler cannot know that @code{sp} and @code{ip} point to different
15759: addresses (and the version of @code{gcc} we used would not know it even
15760: if it was possible), so it could not move the load of the cfa above the
15761: store to the TOS. Indeed the pointers could be the same, if code on or
15762: very near the top of stack were executed. In the interest of speed we
15763: chose to forbid this probably unused ``feature'' and helped the compiler
15764: in scheduling: @code{NEXT} is divided into several parts:
15765: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15766: like:
15767: @example
15768: NEXT_P0;
15769: n=sp[0]+sp[1];
15770: sp++;
15771: NEXT_P1;
15772: sp[0]=n;
15773: NEXT_P2;
15774: @end example
15775:
15776: There are various schemes that distribute the different operations of
15777: NEXT between these parts in several ways; in general, different schemes
15778: perform best on different processors. We use a scheme for most
15779: architectures that performs well for most processors of this
15780: architecture; in the future we may switch to benchmarking and chosing
15781: the scheme on installation time.
15782:
15783:
15784: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
15785: @subsection Direct or Indirect Threaded?
15786: @cindex threading, direct or indirect?
15787:
15788: Threaded forth code consists of references to primitives (simple machine
15789: code routines like @code{+}) and to non-primitives (e.g., colon
15790: definitions, variables, constants); for a specific class of
15791: non-primitives (e.g., variables) there is one code routine (e.g.,
15792: @code{dovar}), but each variable needs a separate reference to its data.
15793:
15794: Traditionally Forth has been implemented as indirect threaded code,
15795: because this allows to use only one cell to reference a non-primitive
15796: (basically you point to the data, and find the code address there).
15797:
15798: @cindex primitive-centric threaded code
15799: However, threaded code in Gforth (since 0.6.0) uses two cells for
15800: non-primitives, one for the code address, and one for the data address;
15801: the data pointer is an immediate argument for the virtual machine
15802: instruction represented by the code address. We call this
15803: @emph{primitive-centric} threaded code, because all code addresses point
15804: to simple primitives. E.g., for a variable, the code address is for
15805: @code{lit} (also used for integer literals like @code{99}).
15806:
15807: Primitive-centric threaded code allows us to use (faster) direct
15808: threading as dispatch method, completely portably (direct threaded code
15809: in Gforth before 0.6.0 required architecture-specific code). It also
15810: eliminates the performance problems related to I-cache consistency that
15811: 386 implementations have with direct threaded code, and allows
15812: additional optimizations.
15813:
15814: @cindex hybrid direct/indirect threaded code
15815: There is a catch, however: the @var{xt} parameter of @code{execute} can
15816: occupy only one cell, so how do we pass non-primitives with their code
15817: @emph{and} data addresses to them? Our answer is to use indirect
15818: threaded dispatch for @code{execute} and other words that use a
15819: single-cell xt. So, normal threaded code in colon definitions uses
15820: direct threading, and @code{execute} and similar words, which dispatch
15821: to xts on the data stack, use indirect threaded code. We call this
15822: @emph{hybrid direct/indirect} threaded code.
15823:
15824: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15825: @cindex gforth engine
15826: @cindex gforth-fast engine
15827: The engines @command{gforth} and @command{gforth-fast} use hybrid
15828: direct/indirect threaded code. This means that with these engines you
15829: cannot use @code{,} to compile an xt. Instead, you have to use
15830: @code{compile,}.
15831:
15832: @cindex gforth-itc engine
15833: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15834: This engine uses plain old indirect threaded code. It still compiles in
15835: a primitive-centric style, so you cannot use @code{compile,} instead of
15836: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
15837: ... [}). If you want to do that, you have to use @command{gforth-itc}
15838: and execute @code{' , is compile,}. Your program can check if it is
15839: running on a hybrid direct/indirect threaded engine or a pure indirect
15840: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15841:
15842:
15843: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15844: @subsection Dynamic Superinstructions
15845: @cindex Dynamic superinstructions with replication
15846: @cindex Superinstructions
15847: @cindex Replication
15848:
15849: The engines @command{gforth} and @command{gforth-fast} use another
15850: optimization: Dynamic superinstructions with replication. As an
15851: example, consider the following colon definition:
15852:
15853: @example
15854: : squared ( n1 -- n2 )
15855: dup * ;
15856: @end example
15857:
15858: Gforth compiles this into the threaded code sequence
15859:
15860: @example
15861: dup
15862: *
15863: ;s
15864: @end example
15865:
15866: In normal direct threaded code there is a code address occupying one
15867: cell for each of these primitives. Each code address points to a
15868: machine code routine, and the interpreter jumps to this machine code in
15869: order to execute the primitive. The routines for these three
15870: primitives are (in @command{gforth-fast} on the 386):
15871:
15872: @example
15873: Code dup
15874: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
15875: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
15876: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15877: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15878: end-code
15879: Code *
15880: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15881: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
15882: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
15883: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
15884: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15885: end-code
15886: Code ;s
15887: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
15888: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
15889: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15890: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15891: end-code
15892: @end example
15893:
15894: With dynamic superinstructions and replication the compiler does not
15895: just lay down the threaded code, but also copies the machine code
15896: fragments, usually without the jump at the end.
15897:
15898: @example
15899: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
15900: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
15901: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15902: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15903: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
15904: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
15905: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
15906: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
15907: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
15908: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15909: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15910: @end example
15911:
15912: Only when a threaded-code control-flow change happens (e.g., in
15913: @code{;s}), the jump is appended. This optimization eliminates many of
15914: these jumps and makes the rest much more predictable. The speedup
15915: depends on the processor and the application; on the Athlon and Pentium
15916: III this optimization typically produces a speedup by a factor of 2.
15917:
15918: The code addresses in the direct-threaded code are set to point to the
15919: appropriate points in the copied machine code, in this example like
15920: this:
15921:
15922: @example
15923: primitive code address
15924: dup $4057D27D
15925: * $4057D286
15926: ;s $4057D292
15927: @end example
15928:
15929: Thus there can be threaded-code jumps to any place in this piece of
15930: code. This also simplifies decompilation quite a bit.
15931:
15932: @cindex --no-dynamic command-line option
15933: @cindex --no-super command-line option
15934: You can disable this optimization with @option{--no-dynamic}. You can
15935: use the copying without eliminating the jumps (i.e., dynamic
15936: replication, but without superinstructions) with @option{--no-super};
15937: this gives the branch prediction benefit alone; the effect on
15938: performance depends on the CPU; on the Athlon and Pentium III the
15939: speedup is a little less than for dynamic superinstructions with
15940: replication.
15941:
15942: @cindex patching threaded code
15943: One use of these options is if you want to patch the threaded code.
15944: With superinstructions, many of the dispatch jumps are eliminated, so
15945: patching often has no effect. These options preserve all the dispatch
15946: jumps.
15947:
15948: @cindex --dynamic command-line option
15949: On some machines dynamic superinstructions are disabled by default,
15950: because it is unsafe on these machines. However, if you feel
15951: adventurous, you can enable it with @option{--dynamic}.
15952:
15953: @node DOES>, , Dynamic Superinstructions, Threading
15954: @subsection DOES>
15955: @cindex @code{DOES>} implementation
15956:
15957: @cindex @code{dodoes} routine
15958: @cindex @code{DOES>}-code
15959: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15960: the chunk of code executed by every word defined by a
15961: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15962: this is only needed if the xt of the word is @code{execute}d. The main
15963: problem here is: How to find the Forth code to be executed, i.e. the
15964: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15965: solutions:
15966:
15967: In fig-Forth the code field points directly to the @code{dodoes} and the
15968: @code{DOES>}-code address is stored in the cell after the code address
15969: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15970: illegal in the Forth-79 and all later standards, because in fig-Forth
15971: this address lies in the body (which is illegal in these
15972: standards). However, by making the code field larger for all words this
15973: solution becomes legal again. We use this approach. Leaving a cell
15974: unused in most words is a bit wasteful, but on the machines we are
15975: targeting this is hardly a problem.
15976:
15977:
15978: @node Primitives, Performance, Threading, Engine
15979: @section Primitives
15980: @cindex primitives, implementation
15981: @cindex virtual machine instructions, implementation
15982:
15983: @menu
15984: * Automatic Generation::
15985: * TOS Optimization::
15986: * Produced code::
15987: @end menu
15988:
15989: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15990: @subsection Automatic Generation
15991: @cindex primitives, automatic generation
15992:
15993: @cindex @file{prims2x.fs}
15994:
15995: Since the primitives are implemented in a portable language, there is no
15996: longer any need to minimize the number of primitives. On the contrary,
15997: having many primitives has an advantage: speed. In order to reduce the
15998: number of errors in primitives and to make programming them easier, we
15999: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
16000: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
16001: generates most (and sometimes all) of the C code for a primitive from
16002: the stack effect notation. The source for a primitive has the following
16003: form:
16004:
16005: @cindex primitive source format
16006: @format
16007: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
16008: [@code{""}@i{glossary entry}@code{""}]
16009: @i{C code}
16010: [@code{:}
16011: @i{Forth code}]
16012: @end format
16013:
16014: The items in brackets are optional. The category and glossary fields
16015: are there for generating the documentation, the Forth code is there
16016: for manual implementations on machines without GNU C. E.g., the source
16017: for the primitive @code{+} is:
16018: @example
16019: + ( n1 n2 -- n ) core plus
16020: n = n1+n2;
16021: @end example
16022:
16023: This looks like a specification, but in fact @code{n = n1+n2} is C
16024: code. Our primitive generation tool extracts a lot of information from
16025: the stack effect notations@footnote{We use a one-stack notation, even
16026: though we have separate data and floating-point stacks; The separate
16027: notation can be generated easily from the unified notation.}: The number
16028: of items popped from and pushed on the stack, their type, and by what
16029: name they are referred to in the C code. It then generates a C code
16030: prelude and postlude for each primitive. The final C code for @code{+}
16031: looks like this:
16032:
16033: @example
16034: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
16035: /* */ /* documentation */
16036: NAME("+") /* debugging output (with -DDEBUG) */
16037: @{
16038: DEF_CA /* definition of variable ca (indirect threading) */
16039: Cell n1; /* definitions of variables */
16040: Cell n2;
16041: Cell n;
16042: NEXT_P0; /* NEXT part 0 */
16043: n1 = (Cell) sp[1]; /* input */
16044: n2 = (Cell) TOS;
16045: sp += 1; /* stack adjustment */
16046: @{
16047: n = n1+n2; /* C code taken from the source */
16048: @}
16049: NEXT_P1; /* NEXT part 1 */
16050: TOS = (Cell)n; /* output */
16051: NEXT_P2; /* NEXT part 2 */
16052: @}
16053: @end example
16054:
16055: This looks long and inefficient, but the GNU C compiler optimizes quite
16056: well and produces optimal code for @code{+} on, e.g., the R3000 and the
16057: HP RISC machines: Defining the @code{n}s does not produce any code, and
16058: using them as intermediate storage also adds no cost.
16059:
16060: There are also other optimizations that are not illustrated by this
16061: example: assignments between simple variables are usually for free (copy
16062: propagation). If one of the stack items is not used by the primitive
16063: (e.g. in @code{drop}), the compiler eliminates the load from the stack
16064: (dead code elimination). On the other hand, there are some things that
16065: the compiler does not do, therefore they are performed by
16066: @file{prims2x.fs}: The compiler does not optimize code away that stores
16067: a stack item to the place where it just came from (e.g., @code{over}).
16068:
16069: While programming a primitive is usually easy, there are a few cases
16070: where the programmer has to take the actions of the generator into
16071: account, most notably @code{?dup}, but also words that do not (always)
16072: fall through to @code{NEXT}.
16073:
16074: For more information
16075:
16076: @node TOS Optimization, Produced code, Automatic Generation, Primitives
16077: @subsection TOS Optimization
16078: @cindex TOS optimization for primitives
16079: @cindex primitives, keeping the TOS in a register
16080:
16081: An important optimization for stack machine emulators, e.g., Forth
16082: engines, is keeping one or more of the top stack items in
16083: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
16084: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
16085: @itemize @bullet
16086: @item
16087: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
16088: due to fewer loads from and stores to the stack.
16089: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
16090: @i{y<n}, due to additional moves between registers.
16091: @end itemize
16092:
16093: @cindex -DUSE_TOS
16094: @cindex -DUSE_NO_TOS
16095: In particular, keeping one item in a register is never a disadvantage,
16096: if there are enough registers. Keeping two items in registers is a
16097: disadvantage for frequent words like @code{?branch}, constants,
16098: variables, literals and @code{i}. Therefore our generator only produces
16099: code that keeps zero or one items in registers. The generated C code
16100: covers both cases; the selection between these alternatives is made at
16101: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
16102: code for @code{+} is just a simple variable name in the one-item case,
16103: otherwise it is a macro that expands into @code{sp[0]}. Note that the
16104: GNU C compiler tries to keep simple variables like @code{TOS} in
16105: registers, and it usually succeeds, if there are enough registers.
16106:
16107: @cindex -DUSE_FTOS
16108: @cindex -DUSE_NO_FTOS
16109: The primitive generator performs the TOS optimization for the
16110: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
16111: operations the benefit of this optimization is even larger:
16112: floating-point operations take quite long on most processors, but can be
16113: performed in parallel with other operations as long as their results are
16114: not used. If the FP-TOS is kept in a register, this works. If
16115: it is kept on the stack, i.e., in memory, the store into memory has to
16116: wait for the result of the floating-point operation, lengthening the
16117: execution time of the primitive considerably.
16118:
16119: The TOS optimization makes the automatic generation of primitives a
16120: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
16121: @code{TOS} is not sufficient. There are some special cases to
16122: consider:
16123: @itemize @bullet
16124: @item In the case of @code{dup ( w -- w w )} the generator must not
16125: eliminate the store to the original location of the item on the stack,
16126: if the TOS optimization is turned on.
16127: @item Primitives with stack effects of the form @code{--}
16128: @i{out1}...@i{outy} must store the TOS to the stack at the start.
16129: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
16130: must load the TOS from the stack at the end. But for the null stack
16131: effect @code{--} no stores or loads should be generated.
16132: @end itemize
16133:
16134: @node Produced code, , TOS Optimization, Primitives
16135: @subsection Produced code
16136: @cindex primitives, assembly code listing
16137:
16138: @cindex @file{engine.s}
16139: To see what assembly code is produced for the primitives on your machine
16140: with your compiler and your flag settings, type @code{make engine.s} and
16141: look at the resulting file @file{engine.s}. Alternatively, you can also
16142: disassemble the code of primitives with @code{see} on some architectures.
16143:
16144: @node Performance, , Primitives, Engine
16145: @section Performance
16146: @cindex performance of some Forth interpreters
16147: @cindex engine performance
16148: @cindex benchmarking Forth systems
16149: @cindex Gforth performance
16150:
16151: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
16152: impossible to write a significantly faster threaded-code engine.
16153:
16154: On register-starved machines like the 386 architecture processors
16155: improvements are possible, because @code{gcc} does not utilize the
16156: registers as well as a human, even with explicit register declarations;
16157: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
16158: and hand-tuned it for the 486; this system is 1.19 times faster on the
16159: Sieve benchmark on a 486DX2/66 than Gforth compiled with
16160: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
16161: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
16162: registers fit in real registers (and we can even afford to use the TOS
16163: optimization), resulting in a speedup of 1.14 on the sieve over the
16164: earlier results. And dynamic superinstructions provide another speedup
16165: (but only around a factor 1.2 on the 486).
16166:
16167: @cindex Win32Forth performance
16168: @cindex NT Forth performance
16169: @cindex eforth performance
16170: @cindex ThisForth performance
16171: @cindex PFE performance
16172: @cindex TILE performance
16173: The potential advantage of assembly language implementations is not
16174: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
16175: (direct threaded, compiled with @code{gcc-2.95.1} and
16176: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
16177: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
16178: (with and without peephole (aka pinhole) optimization of the threaded
16179: code); all these systems were written in assembly language. We also
16180: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
16181: with @code{gcc-2.6.3} with the default configuration for Linux:
16182: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
16183: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
16184: employs peephole optimization of the threaded code) and TILE (compiled
16185: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
16186: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
16187: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
16188: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
16189: then extended it to run the benchmarks, added the peephole optimizer,
16190: ran the benchmarks and reported the results.
16191:
16192: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
16193: matrix multiplication come from the Stanford integer benchmarks and have
16194: been translated into Forth by Martin Fraeman; we used the versions
16195: included in the TILE Forth package, but with bigger data set sizes; and
16196: a recursive Fibonacci number computation for benchmarking calling
16197: performance. The following table shows the time taken for the benchmarks
16198: scaled by the time taken by Gforth (in other words, it shows the speedup
16199: factor that Gforth achieved over the other systems).
16200:
16201: @example
16202: relative Win32- NT eforth This-
16203: time Gforth Forth Forth eforth +opt PFE Forth TILE
16204: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
16205: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
16206: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
16207: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
16208: @end example
16209:
16210: You may be quite surprised by the good performance of Gforth when
16211: compared with systems written in assembly language. One important reason
16212: for the disappointing performance of these other systems is probably
16213: that they are not written optimally for the 486 (e.g., they use the
16214: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
16215: but costly method for relocating the Forth image: like @code{cforth}, it
16216: computes the actual addresses at run time, resulting in two address
16217: computations per @code{NEXT} (@pxref{Image File Background}).
16218:
16219: The speedup of Gforth over PFE, ThisForth and TILE can be easily
16220: explained with the self-imposed restriction of the latter systems to
16221: standard C, which makes efficient threading impossible (however, the
16222: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
16223: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
16224: Moreover, current C compilers have a hard time optimizing other aspects
16225: of the ThisForth and the TILE source.
16226:
16227: The performance of Gforth on 386 architecture processors varies widely
16228: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
16229: allocate any of the virtual machine registers into real machine
16230: registers by itself and would not work correctly with explicit register
16231: declarations, giving a significantly slower engine (on a 486DX2/66
16232: running the Sieve) than the one measured above.
16233:
16234: Note that there have been several releases of Win32Forth since the
16235: release presented here, so the results presented above may have little
16236: predictive value for the performance of Win32Forth today (results for
16237: the current release on an i486DX2/66 are welcome).
16238:
16239: @cindex @file{Benchres}
16240: In
16241: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
16242: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
16243: Maierhofer (presented at EuroForth '95), an indirect threaded version of
16244: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
16245: several native code systems; that version of Gforth is slower on a 486
16246: than the version used here. You can find a newer version of these
16247: measurements at
16248: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
16249: find numbers for Gforth on various machines in @file{Benchres}.
16250:
16251: @c ******************************************************************
16252: @c @node Binding to System Library, Cross Compiler, Engine, Top
16253: @c @chapter Binding to System Library
16254:
16255: @c ****************************************************************
16256: @node Cross Compiler, Bugs, Engine, Top
16257: @chapter Cross Compiler
16258: @cindex @file{cross.fs}
16259: @cindex cross-compiler
16260: @cindex metacompiler
16261: @cindex target compiler
16262:
16263: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
16264: mostly written in Forth, including crucial parts like the outer
16265: interpreter and compiler, it needs compiled Forth code to get
16266: started. The cross compiler allows to create new images for other
16267: architectures, even running under another Forth system.
16268:
16269: @menu
16270: * Using the Cross Compiler::
16271: * How the Cross Compiler Works::
16272: @end menu
16273:
16274: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
16275: @section Using the Cross Compiler
16276:
16277: The cross compiler uses a language that resembles Forth, but isn't. The
16278: main difference is that you can execute Forth code after definition,
16279: while you usually can't execute the code compiled by cross, because the
16280: code you are compiling is typically for a different computer than the
16281: one you are compiling on.
16282:
16283: @c anton: This chapter is somewhat different from waht I would expect: I
16284: @c would expect an explanation of the cross language and how to create an
16285: @c application image with it. The section explains some aspects of
16286: @c creating a Gforth kernel.
16287:
16288: The Makefile is already set up to allow you to create kernels for new
16289: architectures with a simple make command. The generic kernels using the
16290: GCC compiled virtual machine are created in the normal build process
16291: with @code{make}. To create a embedded Gforth executable for e.g. the
16292: 8086 processor (running on a DOS machine), type
16293:
16294: @example
16295: make kernl-8086.fi
16296: @end example
16297:
16298: This will use the machine description from the @file{arch/8086}
16299: directory to create a new kernel. A machine file may look like that:
16300:
16301: @example
16302: \ Parameter for target systems 06oct92py
16303:
16304: 4 Constant cell \ cell size in bytes
16305: 2 Constant cell<< \ cell shift to bytes
16306: 5 Constant cell>bit \ cell shift to bits
16307: 8 Constant bits/char \ bits per character
16308: 8 Constant bits/byte \ bits per byte [default: 8]
16309: 8 Constant float \ bytes per float
16310: 8 Constant /maxalign \ maximum alignment in bytes
16311: false Constant bigendian \ byte order
16312: ( true=big, false=little )
16313:
16314: include machpc.fs \ feature list
16315: @end example
16316:
16317: This part is obligatory for the cross compiler itself, the feature list
16318: is used by the kernel to conditionally compile some features in and out,
16319: depending on whether the target supports these features.
16320:
16321: There are some optional features, if you define your own primitives,
16322: have an assembler, or need special, nonstandard preparation to make the
16323: boot process work. @code{asm-include} includes an assembler,
16324: @code{prims-include} includes primitives, and @code{>boot} prepares for
16325: booting.
16326:
16327: @example
16328: : asm-include ." Include assembler" cr
16329: s" arch/8086/asm.fs" included ;
16330:
16331: : prims-include ." Include primitives" cr
16332: s" arch/8086/prim.fs" included ;
16333:
16334: : >boot ." Prepare booting" cr
16335: s" ' boot >body into-forth 1+ !" evaluate ;
16336: @end example
16337:
16338: These words are used as sort of macro during the cross compilation in
16339: the file @file{kernel/main.fs}. Instead of using these macros, it would
16340: be possible --- but more complicated --- to write a new kernel project
16341: file, too.
16342:
16343: @file{kernel/main.fs} expects the machine description file name on the
16344: stack; the cross compiler itself (@file{cross.fs}) assumes that either
16345: @code{mach-file} leaves a counted string on the stack, or
16346: @code{machine-file} leaves an address, count pair of the filename on the
16347: stack.
16348:
16349: The feature list is typically controlled using @code{SetValue}, generic
16350: files that are used by several projects can use @code{DefaultValue}
16351: instead. Both functions work like @code{Value}, when the value isn't
16352: defined, but @code{SetValue} works like @code{to} if the value is
16353: defined, and @code{DefaultValue} doesn't set anything, if the value is
16354: defined.
16355:
16356: @example
16357: \ generic mach file for pc gforth 03sep97jaw
16358:
16359: true DefaultValue NIL \ relocating
16360:
16361: >ENVIRON
16362:
16363: true DefaultValue file \ controls the presence of the
16364: \ file access wordset
16365: true DefaultValue OS \ flag to indicate a operating system
16366:
16367: true DefaultValue prims \ true: primitives are c-code
16368:
16369: true DefaultValue floating \ floating point wordset is present
16370:
16371: true DefaultValue glocals \ gforth locals are present
16372: \ will be loaded
16373: true DefaultValue dcomps \ double number comparisons
16374:
16375: true DefaultValue hash \ hashing primitives are loaded/present
16376:
16377: true DefaultValue xconds \ used together with glocals,
16378: \ special conditionals supporting gforths'
16379: \ local variables
16380: true DefaultValue header \ save a header information
16381:
16382: true DefaultValue backtrace \ enables backtrace code
16383:
16384: false DefaultValue ec
16385: false DefaultValue crlf
16386:
16387: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
16388:
16389: &16 KB DefaultValue stack-size
16390: &15 KB &512 + DefaultValue fstack-size
16391: &15 KB DefaultValue rstack-size
16392: &14 KB &512 + DefaultValue lstack-size
16393: @end example
16394:
16395: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
16396: @section How the Cross Compiler Works
16397:
16398: @node Bugs, Origin, Cross Compiler, Top
16399: @appendix Bugs
16400: @cindex bug reporting
16401:
16402: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
16403:
16404: If you find a bug, please submit a bug report through
16405: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
16406:
16407: @itemize @bullet
16408: @item
16409: A program (or a sequence of keyboard commands) that reproduces the bug.
16410: @item
16411: A description of what you think constitutes the buggy behaviour.
16412: @item
16413: The Gforth version used (it is announced at the start of an
16414: interactive Gforth session).
16415: @item
16416: The machine and operating system (on Unix
16417: systems @code{uname -a} will report this information).
16418: @item
16419: The installation options (you can find the configure options at the
16420: start of @file{config.status}) and configuration (@code{configure}
16421: output or @file{config.cache}).
16422: @item
16423: A complete list of changes (if any) you (or your installer) have made to the
16424: Gforth sources.
16425: @end itemize
16426:
16427: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
16428: to Report Bugs, gcc.info, GNU C Manual}.
16429:
16430:
16431: @node Origin, Forth-related information, Bugs, Top
16432: @appendix Authors and Ancestors of Gforth
16433:
16434: @section Authors and Contributors
16435: @cindex authors of Gforth
16436: @cindex contributors to Gforth
16437:
16438: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
16439: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
16440: lot to the manual. Assemblers and disassemblers were contributed by
16441: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
16442: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
16443: and Stuart Ramsden inspired us with their continuous feedback. Lennart
16444: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
16445: working on automatic support for calling C libraries. Helpful comments
16446: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
16447: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
16448: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
16449: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
16450: comments from many others; thank you all, sorry for not listing you
16451: here (but digging through my mailbox to extract your names is on my
16452: to-do list).
16453:
16454: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
16455: and autoconf, among others), and to the creators of the Internet: Gforth
16456: was developed across the Internet, and its authors did not meet
16457: physically for the first 4 years of development.
16458:
16459: @section Pedigree
16460: @cindex pedigree of Gforth
16461:
16462: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
16463: significant part of the design of Gforth was prescribed by ANS Forth.
16464:
16465: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
16466: 32 bit native code version of VolksForth for the Atari ST, written
16467: mostly by Dietrich Weineck.
16468:
16469: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
16470: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
16471: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
16472:
16473: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
16474: @c Forth-83 standard. !! Pedigree? When?
16475:
16476: A team led by Bill Ragsdale implemented fig-Forth on many processors in
16477: 1979. Robert Selzer and Bill Ragsdale developed the original
16478: implementation of fig-Forth for the 6502 based on microForth.
16479:
16480: The principal architect of microForth was Dean Sanderson. microForth was
16481: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
16482: the 1802, and subsequently implemented on the 8080, the 6800 and the
16483: Z80.
16484:
16485: All earlier Forth systems were custom-made, usually by Charles Moore,
16486: who discovered (as he puts it) Forth during the late 60s. The first full
16487: Forth existed in 1971.
16488:
16489: A part of the information in this section comes from
16490: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
16491: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
16492: Charles H. Moore, presented at the HOPL-II conference and preprinted
16493: in SIGPLAN Notices 28(3), 1993. You can find more historical and
16494: genealogical information about Forth there. For a more general (and
16495: graphical) Forth family tree look see
16496: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
16497: Forth Family Tree and Timeline}.
16498:
16499: @c ------------------------------------------------------------------
16500: @node Forth-related information, Licenses, Origin, Top
16501: @appendix Other Forth-related information
16502: @cindex Forth-related information
16503:
16504: @c anton: I threw most of this stuff out, because it can be found through
16505: @c the FAQ and the FAQ is more likely to be up-to-date.
16506:
16507: @cindex comp.lang.forth
16508: @cindex frequently asked questions
16509: There is an active news group (comp.lang.forth) discussing Forth
16510: (including Gforth) and Forth-related issues. Its
16511: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
16512: (frequently asked questions and their answers) contains a lot of
16513: information on Forth. You should read it before posting to
16514: comp.lang.forth.
16515:
16516: The ANS Forth standard is most usable in its
16517: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
16518:
16519: @c ---------------------------------------------------
16520: @node Licenses, Word Index, Forth-related information, Top
16521: @appendix Licenses
16522:
16523: @menu
16524: * GNU Free Documentation License:: License for copying this manual.
16525: * Copying:: GPL (for copying this software).
16526: @end menu
16527:
16528: @node GNU Free Documentation License, Copying, Licenses, Licenses
16529: @appendixsec GNU Free Documentation License
16530: @include fdl.texi
16531:
16532: @node Copying, , GNU Free Documentation License, Licenses
16533: @appendixsec GNU GENERAL PUBLIC LICENSE
16534: @include gpl.texi
16535:
16536:
16537:
16538: @c ------------------------------------------------------------------
16539: @node Word Index, Concept Index, Licenses, Top
16540: @unnumbered Word Index
16541:
16542: This index is a list of Forth words that have ``glossary'' entries
16543: within this manual. Each word is listed with its stack effect and
16544: wordset.
16545:
16546: @printindex fn
16547:
16548: @c anton: the name index seems superfluous given the word and concept indices.
16549:
16550: @c @node Name Index, Concept Index, Word Index, Top
16551: @c @unnumbered Name Index
16552:
16553: @c This index is a list of Forth words that have ``glossary'' entries
16554: @c within this manual.
16555:
16556: @c @printindex ky
16557:
16558: @c -------------------------------------------------------
16559: @node Concept Index, , Word Index, Top
16560: @unnumbered Concept and Word Index
16561:
16562: Not all entries listed in this index are present verbatim in the
16563: text. This index also duplicates, in abbreviated form, all of the words
16564: listed in the Word Index (only the names are listed for the words here).
16565:
16566: @printindex cp
16567:
16568: @bye
16569:
16570:
16571:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>