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: * Assembler Definitions:: Definitions in assembly language
422: * Common Assembler:: Assembler Syntax
423: * Common Disassembler::
424: * 386 Assembler:: Deviations and special cases
425: * AMD64 Assembler::
426: * Alpha Assembler:: Deviations and special cases
427: * MIPS assembler:: Deviations and special cases
428: * PowerPC assembler:: Deviations and special cases
429: * ARM Assembler:: Deviations and special cases
430: * Other assemblers:: How to write them
431:
432: Tools
433:
434: * ANS Report:: Report the words used, sorted by wordset.
435: * Stack depth changes:: Where does this stack item come from?
436:
437: ANS conformance
438:
439: * The Core Words::
440: * The optional Block word set::
441: * The optional Double Number word set::
442: * The optional Exception word set::
443: * The optional Facility word set::
444: * The optional File-Access word set::
445: * The optional Floating-Point word set::
446: * The optional Locals word set::
447: * The optional Memory-Allocation word set::
448: * The optional Programming-Tools word set::
449: * The optional Search-Order word set::
450:
451: The Core Words
452:
453: * core-idef:: Implementation Defined Options
454: * core-ambcond:: Ambiguous Conditions
455: * core-other:: Other System Documentation
456:
457: The optional Block word set
458:
459: * block-idef:: Implementation Defined Options
460: * block-ambcond:: Ambiguous Conditions
461: * block-other:: Other System Documentation
462:
463: The optional Double Number word set
464:
465: * double-ambcond:: Ambiguous Conditions
466:
467: The optional Exception word set
468:
469: * exception-idef:: Implementation Defined Options
470:
471: The optional Facility word set
472:
473: * facility-idef:: Implementation Defined Options
474: * facility-ambcond:: Ambiguous Conditions
475:
476: The optional File-Access word set
477:
478: * file-idef:: Implementation Defined Options
479: * file-ambcond:: Ambiguous Conditions
480:
481: The optional Floating-Point word set
482:
483: * floating-idef:: Implementation Defined Options
484: * floating-ambcond:: Ambiguous Conditions
485:
486: The optional Locals word set
487:
488: * locals-idef:: Implementation Defined Options
489: * locals-ambcond:: Ambiguous Conditions
490:
491: The optional Memory-Allocation word set
492:
493: * memory-idef:: Implementation Defined Options
494:
495: The optional Programming-Tools word set
496:
497: * programming-idef:: Implementation Defined Options
498: * programming-ambcond:: Ambiguous Conditions
499:
500: The optional Search-Order word set
501:
502: * search-idef:: Implementation Defined Options
503: * search-ambcond:: Ambiguous Conditions
504:
505: Emacs and Gforth
506:
507: * Installing gforth.el:: Making Emacs aware of Forth.
508: * Emacs Tags:: Viewing the source of a word in Emacs.
509: * Hilighting:: Making Forth code look prettier.
510: * Auto-Indentation:: Customizing auto-indentation.
511: * Blocks Files:: Reading and writing blocks files.
512:
513: Image Files
514:
515: * Image Licensing Issues:: Distribution terms for images.
516: * Image File Background:: Why have image files?
517: * Non-Relocatable Image Files:: don't always work.
518: * Data-Relocatable Image Files:: are better.
519: * Fully Relocatable Image Files:: better yet.
520: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
521: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
522: * Modifying the Startup Sequence:: and turnkey applications.
523:
524: Fully Relocatable Image Files
525:
526: * gforthmi:: The normal way
527: * cross.fs:: The hard way
528:
529: Engine
530:
531: * Portability::
532: * Threading::
533: * Primitives::
534: * Performance::
535:
536: Threading
537:
538: * Scheduling::
539: * Direct or Indirect Threaded?::
540: * Dynamic Superinstructions::
541: * DOES>::
542:
543: Primitives
544:
545: * Automatic Generation::
546: * TOS Optimization::
547: * Produced code::
548:
549: Cross Compiler
550:
551: * Using the Cross Compiler::
552: * How the Cross Compiler Works::
553:
554: Licenses
555:
556: * GNU Free Documentation License:: License for copying this manual.
557: * Copying:: GPL (for copying this software).
558:
559: @end detailmenu
560: @end menu
561:
562: @c ----------------------------------------------------------
563: @iftex
564: @unnumbered Preface
565: @cindex Preface
566: This manual documents Gforth. Some introductory material is provided for
567: readers who are unfamiliar with Forth or who are migrating to Gforth
568: from other Forth compilers. However, this manual is primarily a
569: reference manual.
570: @end iftex
571:
572: @comment TODO much more blurb here.
573:
574: @c ******************************************************************
575: @node Goals, Gforth Environment, Top, Top
576: @comment node-name, next, previous, up
577: @chapter Goals of Gforth
578: @cindex goals of the Gforth project
579: The goal of the Gforth Project is to develop a standard model for
580: ANS Forth. This can be split into several subgoals:
581:
582: @itemize @bullet
583: @item
584: Gforth should conform to the ANS Forth Standard.
585: @item
586: It should be a model, i.e. it should define all the
587: implementation-dependent things.
588: @item
589: It should become standard, i.e. widely accepted and used. This goal
590: is the most difficult one.
591: @end itemize
592:
593: To achieve these goals Gforth should be
594: @itemize @bullet
595: @item
596: Similar to previous models (fig-Forth, F83)
597: @item
598: Powerful. It should provide for all the things that are considered
599: necessary today and even some that are not yet considered necessary.
600: @item
601: Efficient. It should not get the reputation of being exceptionally
602: slow.
603: @item
604: Free.
605: @item
606: Available on many machines/easy to port.
607: @end itemize
608:
609: Have we achieved these goals? Gforth conforms to the ANS Forth
610: standard. It may be considered a model, but we have not yet documented
611: which parts of the model are stable and which parts we are likely to
612: change. It certainly has not yet become a de facto standard, but it
613: appears to be quite popular. It has some similarities to and some
614: differences from previous models. It has some powerful features, but not
615: yet everything that we envisioned. We certainly have achieved our
616: execution speed goals (@pxref{Performance})@footnote{However, in 1998
617: the bar was raised when the major commercial Forth vendors switched to
618: native code compilers.}. It is free and available on many machines.
619:
620: @c ******************************************************************
621: @node Gforth Environment, Tutorial, Goals, Top
622: @chapter Gforth Environment
623: @cindex Gforth environment
624:
625: Note: ultimately, the Gforth man page will be auto-generated from the
626: material in this chapter.
627:
628: @menu
629: * Invoking Gforth:: Getting in
630: * Leaving Gforth:: Getting out
631: * Command-line editing::
632: * Environment variables:: that affect how Gforth starts up
633: * Gforth Files:: What gets installed and where
634: * Gforth in pipes::
635: * Startup speed:: When 14ms is not fast enough ...
636: @end menu
637:
638: For related information about the creation of images see @ref{Image Files}.
639:
640: @comment ----------------------------------------------
641: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
642: @section Invoking Gforth
643: @cindex invoking Gforth
644: @cindex running Gforth
645: @cindex command-line options
646: @cindex options on the command line
647: @cindex flags on the command line
648:
649: Gforth is made up of two parts; an executable ``engine'' (named
650: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
651: will usually just say @code{gforth} -- this automatically loads the
652: default image file @file{gforth.fi}. In many other cases the default
653: Gforth image will be invoked like this:
654: @example
655: gforth [file | -e forth-code] ...
656: @end example
657: @noindent
658: This interprets the contents of the files and the Forth code in the order they
659: are given.
660:
661: In addition to the @command{gforth} engine, there is also an engine
662: called @command{gforth-fast}, which is faster, but gives less
663: informative error messages (@pxref{Error messages}) and may catch some
664: errors (in particular, stack underflows and integer division errors)
665: later or not at all. You should use it for debugged,
666: performance-critical programs.
667:
668: Moreover, there is an engine called @command{gforth-itc}, which is
669: useful in some backwards-compatibility situations (@pxref{Direct or
670: Indirect Threaded?}).
671:
672: In general, the command line looks like this:
673:
674: @example
675: gforth[-fast] [engine options] [image options]
676: @end example
677:
678: The engine options must come before the rest of the command
679: line. They are:
680:
681: @table @code
682: @cindex -i, command-line option
683: @cindex --image-file, command-line option
684: @item --image-file @i{file}
685: @itemx -i @i{file}
686: Loads the Forth image @i{file} instead of the default
687: @file{gforth.fi} (@pxref{Image Files}).
688:
689: @cindex --appl-image, command-line option
690: @item --appl-image @i{file}
691: Loads the image @i{file} and leaves all further command-line arguments
692: to the image (instead of processing them as engine options). This is
693: useful for building executable application images on Unix, built with
694: @code{gforthmi --application ...}.
695:
696: @cindex --path, command-line option
697: @cindex -p, command-line option
698: @item --path @i{path}
699: @itemx -p @i{path}
700: Uses @i{path} for searching the image file and Forth source code files
701: instead of the default in the environment variable @code{GFORTHPATH} or
702: the path specified at installation time (e.g.,
703: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
704: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
705:
706: @cindex --dictionary-size, command-line option
707: @cindex -m, command-line option
708: @cindex @i{size} parameters for command-line options
709: @cindex size of the dictionary and the stacks
710: @item --dictionary-size @i{size}
711: @itemx -m @i{size}
712: Allocate @i{size} space for the Forth dictionary space instead of
713: using the default specified in the image (typically 256K). The
714: @i{size} specification for this and subsequent options consists of
715: an integer and a unit (e.g.,
716: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
717: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
718: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
719: @code{e} is used.
720:
721: @cindex --data-stack-size, command-line option
722: @cindex -d, command-line option
723: @item --data-stack-size @i{size}
724: @itemx -d @i{size}
725: Allocate @i{size} space for the data stack instead of using the
726: default specified in the image (typically 16K).
727:
728: @cindex --return-stack-size, command-line option
729: @cindex -r, command-line option
730: @item --return-stack-size @i{size}
731: @itemx -r @i{size}
732: Allocate @i{size} space for the return stack instead of using the
733: default specified in the image (typically 15K).
734:
735: @cindex --fp-stack-size, command-line option
736: @cindex -f, command-line option
737: @item --fp-stack-size @i{size}
738: @itemx -f @i{size}
739: Allocate @i{size} space for the floating point stack instead of
740: using the default specified in the image (typically 15.5K). In this case
741: the unit specifier @code{e} refers to floating point numbers.
742:
743: @cindex --locals-stack-size, command-line option
744: @cindex -l, command-line option
745: @item --locals-stack-size @i{size}
746: @itemx -l @i{size}
747: Allocate @i{size} space for the locals stack instead of using the
748: default specified in the image (typically 14.5K).
749:
750: @cindex --vm-commit, command-line option
751: @cindex overcommit memory for dictionary and stacks
752: @cindex memory overcommit for dictionary and stacks
753: @item --vm-commit
754: Normally, Gforth tries to start up even if there is not enough virtual
755: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
756: on OSs that support it); so you can ask for a really big dictionary
757: and/or stacks, and as long as you don't use more virtual memory than
758: is available, everything will be fine (but if you use more, processes
759: get killed). With this option you just use the default allocation
760: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
761: means that you cannot and should not ask for as big dictionary and
762: stacks, but once Gforth successfully starts up, out-of-memory won't
763: kill it.
764:
765: @cindex -h, command-line option
766: @cindex --help, command-line option
767: @item --help
768: @itemx -h
769: Print a message about the command-line options
770:
771: @cindex -v, command-line option
772: @cindex --version, command-line option
773: @item --version
774: @itemx -v
775: Print version and exit
776:
777: @cindex --debug, command-line option
778: @item --debug
779: Print some information useful for debugging on startup.
780:
781: @cindex --offset-image, command-line option
782: @item --offset-image
783: Start the dictionary at a slightly different position than would be used
784: otherwise (useful for creating data-relocatable images,
785: @pxref{Data-Relocatable Image Files}).
786:
787: @cindex --no-offset-im, command-line option
788: @item --no-offset-im
789: Start the dictionary at the normal position.
790:
791: @cindex --clear-dictionary, command-line option
792: @item --clear-dictionary
793: Initialize all bytes in the dictionary to 0 before loading the image
794: (@pxref{Data-Relocatable Image Files}).
795:
796: @cindex --die-on-signal, command-line-option
797: @item --die-on-signal
798: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
799: or the segmentation violation SIGSEGV) by translating it into a Forth
800: @code{THROW}. With this option, Gforth exits if it receives such a
801: signal. This option is useful when the engine and/or the image might be
802: severely broken (such that it causes another signal before recovering
803: from the first); this option avoids endless loops in such cases.
804:
805: @cindex --no-dynamic, command-line option
806: @cindex --dynamic, command-line option
807: @item --no-dynamic
808: @item --dynamic
809: Disable or enable dynamic superinstructions with replication
810: (@pxref{Dynamic Superinstructions}).
811:
812: @cindex --no-super, command-line option
813: @item --no-super
814: Disable dynamic superinstructions, use just dynamic replication; this is
815: useful if you want to patch threaded code (@pxref{Dynamic
816: Superinstructions}).
817:
818: @cindex --ss-number, command-line option
819: @item --ss-number=@var{N}
820: Use only the first @var{N} static superinstructions compiled into the
821: engine (default: use them all; note that only @code{gforth-fast} has
822: any). This option is useful for measuring the performance impact of
823: static superinstructions.
824:
825: @cindex --ss-min-..., command-line options
826: @item --ss-min-codesize
827: @item --ss-min-ls
828: @item --ss-min-lsu
829: @item --ss-min-nexts
830: Use specified metric for determining the cost of a primitive or static
831: superinstruction for static superinstruction selection. @code{Codesize}
832: is the native code size of the primive or static superinstruction,
833: @code{ls} is the number of loads and stores, @code{lsu} is the number of
834: loads, stores, and updates, and @code{nexts} is the number of dispatches
835: (not taking dynamic superinstructions into account), i.e. every
836: primitive or static superinstruction has cost 1. Default:
837: @code{codesize} if you use dynamic code generation, otherwise
838: @code{nexts}.
839:
840: @cindex --ss-greedy, command-line option
841: @item --ss-greedy
842: This option is useful for measuring the performance impact of static
843: superinstructions. By default, an optimal shortest-path algorithm is
844: used for selecting static superinstructions. With @option{--ss-greedy}
845: this algorithm is modified to assume that anything after the static
846: superinstruction currently under consideration is not combined into
847: static superinstructions. With @option{--ss-min-nexts} this produces
848: the same result as a greedy algorithm that always selects the longest
849: superinstruction available at the moment. E.g., if there are
850: superinstructions AB and BCD, then for the sequence A B C D the optimal
851: algorithm will select A BCD and the greedy algorithm will select AB C D.
852:
853: @cindex --print-metrics, command-line option
854: @item --print-metrics
855: Prints some metrics used during static superinstruction selection:
856: @code{code size} is the actual size of the dynamically generated code.
857: @code{Metric codesize} is the sum of the codesize metrics as seen by
858: static superinstruction selection; there is a difference from @code{code
859: size}, because not all primitives and static superinstructions are
860: compiled into dynamically generated code, and because of markers. The
861: other metrics correspond to the @option{ss-min-...} options. This
862: option is useful for evaluating the effects of the @option{--ss-...}
863: options.
864:
865: @end table
866:
867: @cindex loading files at startup
868: @cindex executing code on startup
869: @cindex batch processing with Gforth
870: As explained above, the image-specific command-line arguments for the
871: default image @file{gforth.fi} consist of a sequence of filenames and
872: @code{-e @var{forth-code}} options that are interpreted in the sequence
873: in which they are given. The @code{-e @var{forth-code}} or
874: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
875: option takes only one argument; if you want to evaluate more Forth
876: words, you have to quote them or use @code{-e} several times. To exit
877: after processing the command line (instead of entering interactive mode)
878: append @code{-e bye} to the command line. You can also process the
879: command-line arguments with a Forth program (@pxref{OS command line
880: arguments}).
881:
882: @cindex versions, invoking other versions of Gforth
883: If you have several versions of Gforth installed, @code{gforth} will
884: invoke the version that was installed last. @code{gforth-@i{version}}
885: invokes a specific version. If your environment contains the variable
886: @code{GFORTHPATH}, you may want to override it by using the
887: @code{--path} option.
888:
889: Not yet implemented:
890: On startup the system first executes the system initialization file
891: (unless the option @code{--no-init-file} is given; note that the system
892: resulting from using this option may not be ANS Forth conformant). Then
893: the user initialization file @file{.gforth.fs} is executed, unless the
894: option @code{--no-rc} is given; this file is searched for in @file{.},
895: then in @file{~}, then in the normal path (see above).
896:
897:
898:
899: @comment ----------------------------------------------
900: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
901: @section Leaving Gforth
902: @cindex Gforth - leaving
903: @cindex leaving Gforth
904:
905: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
906: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
907: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
908: data are discarded. For ways of saving the state of the system before
909: leaving Gforth see @ref{Image Files}.
910:
911: doc-bye
912:
913:
914: @comment ----------------------------------------------
915: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
916: @section Command-line editing
917: @cindex command-line editing
918:
919: Gforth maintains a history file that records every line that you type to
920: the text interpreter. This file is preserved between sessions, and is
921: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
922: repeatedly you can recall successively older commands from this (or
923: previous) session(s). The full list of command-line editing facilities is:
924:
925: @itemize @bullet
926: @item
927: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
928: commands from the history buffer.
929: @item
930: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
931: from the history buffer.
932: @item
933: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
934: @item
935: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
936: @item
937: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
938: closing up the line.
939: @item
940: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
941: @item
942: @kbd{Ctrl-a} to move the cursor to the start of the line.
943: @item
944: @kbd{Ctrl-e} to move the cursor to the end of the line.
945: @item
946: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
947: line.
948: @item
949: @key{TAB} to step through all possible full-word completions of the word
950: currently being typed.
951: @item
952: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
953: using @code{bye}).
954: @item
955: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
956: character under the cursor.
957: @end itemize
958:
959: When editing, displayable characters are inserted to the left of the
960: cursor position; the line is always in ``insert'' (as opposed to
961: ``overstrike'') mode.
962:
963: @cindex history file
964: @cindex @file{.gforth-history}
965: On Unix systems, the history file is @file{~/.gforth-history} by
966: default@footnote{i.e. it is stored in the user's home directory.}. You
967: can find out the name and location of your history file using:
968:
969: @example
970: history-file type \ Unix-class systems
971:
972: history-file type \ Other systems
973: history-dir type
974: @end example
975:
976: If you enter long definitions by hand, you can use a text editor to
977: paste them out of the history file into a Forth source file for reuse at
978: a later time.
979:
980: Gforth never trims the size of the history file, so you should do this
981: periodically, if necessary.
982:
983: @comment this is all defined in history.fs
984: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
985: @comment chosen?
986:
987:
988: @comment ----------------------------------------------
989: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
990: @section Environment variables
991: @cindex environment variables
992:
993: Gforth uses these environment variables:
994:
995: @itemize @bullet
996: @item
997: @cindex @code{GFORTHHIST} -- environment variable
998: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
999: open/create the history file, @file{.gforth-history}. Default:
1000: @code{$HOME}.
1001:
1002: @item
1003: @cindex @code{GFORTHPATH} -- environment variable
1004: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
1005: for Forth source-code files.
1006:
1007: @item
1008: @cindex @code{LANG} -- environment variable
1009: @code{LANG} -- see @code{LC_CTYPE}
1010:
1011: @item
1012: @cindex @code{LC_ALL} -- environment variable
1013: @code{LC_ALL} -- see @code{LC_CTYPE}
1014:
1015: @item
1016: @cindex @code{LC_CTYPE} -- environment variable
1017: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
1018: startup, Gforth uses the UTF-8 encoding for strings internally and
1019: expects its input and produces its output in UTF-8 encoding, otherwise
1020: the encoding is 8bit (see @pxref{Xchars and Unicode}). If this
1021: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
1022: that is unset, in @code{LANG}.
1023:
1024: @item
1025: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
1026:
1027: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
1028: of @code{system} before passing it to C's @code{system()}. Default:
1029: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1030: and the command are directly concatenated, so if a space between them is
1031: necessary, append it to the prefix.
1032:
1033: @item
1034: @cindex @code{GFORTH} -- environment variable
1035: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1036:
1037: @item
1038: @cindex @code{GFORTHD} -- environment variable
1039: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1040:
1041: @item
1042: @cindex @code{TMP}, @code{TEMP} - environment variable
1043: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1044: location for the history file.
1045: @end itemize
1046:
1047: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1048: @comment mentioning these.
1049:
1050: All the Gforth environment variables default to sensible values if they
1051: are not set.
1052:
1053:
1054: @comment ----------------------------------------------
1055: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1056: @section Gforth files
1057: @cindex Gforth files
1058:
1059: When you install Gforth on a Unix system, it installs files in these
1060: locations by default:
1061:
1062: @itemize @bullet
1063: @item
1064: @file{/usr/local/bin/gforth}
1065: @item
1066: @file{/usr/local/bin/gforthmi}
1067: @item
1068: @file{/usr/local/man/man1/gforth.1} - man page.
1069: @item
1070: @file{/usr/local/info} - the Info version of this manual.
1071: @item
1072: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1073: @item
1074: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1075: @item
1076: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1077: @item
1078: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1079: @end itemize
1080:
1081: You can select different places for installation by using
1082: @code{configure} options (listed with @code{configure --help}).
1083:
1084: @comment ----------------------------------------------
1085: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1086: @section Gforth in pipes
1087: @cindex pipes, Gforth as part of
1088:
1089: Gforth can be used in pipes created elsewhere (described here). It can
1090: also create pipes on its own (@pxref{Pipes}).
1091:
1092: @cindex input from pipes
1093: If you pipe into Gforth, your program should read with @code{read-file}
1094: or @code{read-line} from @code{stdin} (@pxref{General files}).
1095: @code{Key} does not recognize the end of input. Words like
1096: @code{accept} echo the input and are therefore usually not useful for
1097: reading from a pipe. You have to invoke the Forth program with an OS
1098: command-line option, as you have no chance to use the Forth command line
1099: (the text interpreter would try to interpret the pipe input).
1100:
1101: @cindex output in pipes
1102: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1103:
1104: @cindex silent exiting from Gforth
1105: When you write to a pipe that has been closed at the other end, Gforth
1106: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1107: into the exception @code{broken-pipe-error}. If your application does
1108: not catch that exception, the system catches it and exits, usually
1109: silently (unless you were working on the Forth command line; then it
1110: prints an error message and exits). This is usually the desired
1111: behaviour.
1112:
1113: If you do not like this behaviour, you have to catch the exception
1114: yourself, and react to it.
1115:
1116: Here's an example of an invocation of Gforth that is usable in a pipe:
1117:
1118: @example
1119: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1120: type repeat ; foo bye"
1121: @end example
1122:
1123: This example just copies the input verbatim to the output. A very
1124: simple pipe containing this example looks like this:
1125:
1126: @example
1127: cat startup.fs |
1128: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1129: type repeat ; foo bye"|
1130: head
1131: @end example
1132:
1133: @cindex stderr and pipes
1134: Pipes involving Gforth's @code{stderr} output do not work.
1135:
1136: @comment ----------------------------------------------
1137: @node Startup speed, , Gforth in pipes, Gforth Environment
1138: @section Startup speed
1139: @cindex Startup speed
1140: @cindex speed, startup
1141:
1142: If Gforth is used for CGI scripts or in shell scripts, its startup
1143: speed may become a problem. On a 3GHz Core 2 Duo E8400 under 64-bit
1144: Linux 2.6.27.8 with libc-2.7, @code{gforth-fast -e bye} takes 13.1ms
1145: user and 1.2ms system time (@code{gforth -e bye} is faster on startup
1146: with about 3.4ms user time and 1.2ms system time, because it subsumes
1147: some of the options discussed below).
1148:
1149: If startup speed is a problem, you may consider the following ways to
1150: improve it; or you may consider ways to reduce the number of startups
1151: (for example, by using Fast-CGI). Note that the first steps below
1152: improve the startup time at the cost of run-time (including
1153: compile-time), so whether they are profitable depends on the balance
1154: of these times in your application.
1155:
1156: An easy step that influences Gforth startup speed is the use of a
1157: number of options that increase run-time, but decrease image-loading
1158: time.
1159:
1160: The first of these that you should try is @code{--ss-number=0
1161: --ss-states=1} because this option buys relatively little run-time
1162: speedup and costs quite a bit of time at startup. @code{gforth-fast
1163: --ss-number=0 --ss-states=1 -e bye} takes about 2.8ms user and 1.5ms
1164: system time.
1165:
1166: The next option is @code{--no-dynamic} which has a substantial impact
1167: on run-time (about a factor of 2 on several platforms), but still
1168: makes startup speed a little faster: @code{gforth-fast --ss-number=0
1169: --ss-states=1 --no-dynamic -e bye} consumes about 2.6ms user and 1.2ms
1170: system time.
1171:
1172: The next step to improve startup speed is to use a data-relocatable
1173: image (@pxref{Data-Relocatable Image Files}). This avoids the
1174: relocation cost for the code in the image (but not for the data).
1175: Note that the image is then specific to the particular binary you are
1176: using (i.e., whether it is @code{gforth}, @code{gforth-fast}, and even
1177: the particular build). You create the data-relocatable image that
1178: works with @code{./gforth-fast} with @code{GFORTHD="./gforth-fast
1179: --no-dynamic" gforthmi gforthdr.fi} (the @code{--no-dynamic} is
1180: required here or the image will not work). And you run it with
1181: @code{gforth-fast -i gforthdr.fi ... -e bye} (the flags discussed
1182: above don't matter here, because they only come into play on
1183: relocatable code). @code{gforth-fast -i gforthdr.fi -e bye} takes
1184: about 1.1ms user and 1.2ms system time.
1185:
1186: One step further is to avoid all relocation cost and part of the
1187: copy-on-write cost through using a non-relocatable image
1188: (@pxref{Non-Relocatable Image Files}). However, this has the
1189: disadvantage that it does not work on operating systems with address
1190: space randomization (the default in, e.g., Linux nowadays), or if the
1191: dictionary moves for any other reason (e.g., because of a change of
1192: the OS kernel or an updated library), so we cannot really recommend
1193: it. You create a non-relocatable image with @code{gforth-fast
1194: --no-dynamic -e "savesystem gforthnr.fi bye"} (the @code{--no-dynamic}
1195: is required here, too). And you run it with @code{gforth-fast -i
1196: gforthnr.fi ... -e bye} (again the flags discussed above don't
1197: matter). @code{gforth-fast -i gforthdr.fi -e bye} takes
1198: about 0.9ms user and 0.9ms system time.
1199:
1200: If the script you want to execute contains a significant amount of
1201: code, it may be profitable to compile it into the image to avoid the
1202: cost of compiling it at startup time.
1203:
1204: @c ******************************************************************
1205: @node Tutorial, Introduction, Gforth Environment, Top
1206: @chapter Forth Tutorial
1207: @cindex Tutorial
1208: @cindex Forth Tutorial
1209:
1210: @c Topics from nac's Introduction that could be mentioned:
1211: @c press <ret> after each line
1212: @c Prompt
1213: @c numbers vs. words in dictionary on text interpretation
1214: @c what happens on redefinition
1215: @c parsing words (in particular, defining words)
1216:
1217: The difference of this chapter from the Introduction
1218: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1219: be used while sitting in front of a computer, and covers much more
1220: material, but does not explain how the Forth system works.
1221:
1222: This tutorial can be used with any ANS-compliant Forth; any
1223: Gforth-specific features are marked as such and you can skip them if
1224: you work with another Forth. This tutorial does not explain all
1225: features of Forth, just enough to get you started and give you some
1226: ideas about the facilities available in Forth. Read the rest of the
1227: manual when you are through this.
1228:
1229: The intended way to use this tutorial is that you work through it while
1230: sitting in front of the console, take a look at the examples and predict
1231: what they will do, then try them out; if the outcome is not as expected,
1232: find out why (e.g., by trying out variations of the example), so you
1233: understand what's going on. There are also some assignments that you
1234: should solve.
1235:
1236: This tutorial assumes that you have programmed before and know what,
1237: e.g., a loop is.
1238:
1239: @c !! explain compat library
1240:
1241: @menu
1242: * Starting Gforth Tutorial::
1243: * Syntax Tutorial::
1244: * Crash Course Tutorial::
1245: * Stack Tutorial::
1246: * Arithmetics Tutorial::
1247: * Stack Manipulation Tutorial::
1248: * Using files for Forth code Tutorial::
1249: * Comments Tutorial::
1250: * Colon Definitions Tutorial::
1251: * Decompilation Tutorial::
1252: * Stack-Effect Comments Tutorial::
1253: * Types Tutorial::
1254: * Factoring Tutorial::
1255: * Designing the stack effect Tutorial::
1256: * Local Variables Tutorial::
1257: * Conditional execution Tutorial::
1258: * Flags and Comparisons Tutorial::
1259: * General Loops Tutorial::
1260: * Counted loops Tutorial::
1261: * Recursion Tutorial::
1262: * Leaving definitions or loops Tutorial::
1263: * Return Stack Tutorial::
1264: * Memory Tutorial::
1265: * Characters and Strings Tutorial::
1266: * Alignment Tutorial::
1267: * Floating Point Tutorial::
1268: * Files Tutorial::
1269: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1270: * Execution Tokens Tutorial::
1271: * Exceptions Tutorial::
1272: * Defining Words Tutorial::
1273: * Arrays and Records Tutorial::
1274: * POSTPONE Tutorial::
1275: * Literal Tutorial::
1276: * Advanced macros Tutorial::
1277: * Compilation Tokens Tutorial::
1278: * Wordlists and Search Order Tutorial::
1279: @end menu
1280:
1281: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1282: @section Starting Gforth
1283: @cindex starting Gforth tutorial
1284: You can start Gforth by typing its name:
1285:
1286: @example
1287: gforth
1288: @end example
1289:
1290: That puts you into interactive mode; you can leave Gforth by typing
1291: @code{bye}. While in Gforth, you can edit the command line and access
1292: the command line history with cursor keys, similar to bash.
1293:
1294:
1295: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1296: @section Syntax
1297: @cindex syntax tutorial
1298:
1299: A @dfn{word} is a sequence of arbitrary characters (except white
1300: space). Words are separated by white space. E.g., each of the
1301: following lines contains exactly one word:
1302:
1303: @example
1304: word
1305: !@@#$%^&*()
1306: 1234567890
1307: 5!a
1308: @end example
1309:
1310: A frequent beginner's error is to leave out necessary white space,
1311: resulting in an error like @samp{Undefined word}; so if you see such an
1312: error, check if you have put spaces wherever necessary.
1313:
1314: @example
1315: ." hello, world" \ correct
1316: ."hello, world" \ gives an "Undefined word" error
1317: @end example
1318:
1319: Gforth and most other Forth systems ignore differences in case (they are
1320: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1321: your system is case-sensitive, you may have to type all the examples
1322: given here in upper case.
1323:
1324:
1325: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1326: @section Crash Course
1327:
1328: Forth does not prevent you from shooting yourself in the foot. Let's
1329: try a few ways to crash Gforth:
1330:
1331: @example
1332: 0 0 !
1333: here execute
1334: ' catch >body 20 erase abort
1335: ' (quit) >body 20 erase
1336: @end example
1337:
1338: The last two examples are guaranteed to destroy important parts of
1339: Gforth (and most other systems), so you better leave Gforth afterwards
1340: (if it has not finished by itself). On some systems you may have to
1341: kill gforth from outside (e.g., in Unix with @code{kill}).
1342:
1343: You will find out later what these lines do and then you will get an
1344: idea why they produce crashes.
1345:
1346: Now that you know how to produce crashes (and that there's not much to
1347: them), let's learn how to produce meaningful programs.
1348:
1349:
1350: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1351: @section Stack
1352: @cindex stack tutorial
1353:
1354: The most obvious feature of Forth is the stack. When you type in a
1355: number, it is pushed on the stack. You can display the contents of the
1356: stack with @code{.s}.
1357:
1358: @example
1359: 1 2 .s
1360: 3 .s
1361: @end example
1362:
1363: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1364: appear in @code{.s} output as they appeared in the input.
1365:
1366: You can print the top element of the stack with @code{.}.
1367:
1368: @example
1369: 1 2 3 . . .
1370: @end example
1371:
1372: In general, words consume their stack arguments (@code{.s} is an
1373: exception).
1374:
1375: @quotation Assignment
1376: What does the stack contain after @code{5 6 7 .}?
1377: @end quotation
1378:
1379:
1380: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1381: @section Arithmetics
1382: @cindex arithmetics tutorial
1383:
1384: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1385: operate on the top two stack items:
1386:
1387: @example
1388: 2 2 .s
1389: + .s
1390: .
1391: 2 1 - .
1392: 7 3 mod .
1393: @end example
1394:
1395: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1396: as in the corresponding infix expression (this is generally the case in
1397: Forth).
1398:
1399: Parentheses are superfluous (and not available), because the order of
1400: the words unambiguously determines the order of evaluation and the
1401: operands:
1402:
1403: @example
1404: 3 4 + 5 * .
1405: 3 4 5 * + .
1406: @end example
1407:
1408: @quotation Assignment
1409: What are the infix expressions corresponding to the Forth code above?
1410: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1411: known as Postfix or RPN (Reverse Polish Notation).}.
1412: @end quotation
1413:
1414: To change the sign, use @code{negate}:
1415:
1416: @example
1417: 2 negate .
1418: @end example
1419:
1420: @quotation Assignment
1421: Convert -(-3)*4-5 to Forth.
1422: @end quotation
1423:
1424: @code{/mod} performs both @code{/} and @code{mod}.
1425:
1426: @example
1427: 7 3 /mod . .
1428: @end example
1429:
1430: Reference: @ref{Arithmetic}.
1431:
1432:
1433: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1434: @section Stack Manipulation
1435: @cindex stack manipulation tutorial
1436:
1437: Stack manipulation words rearrange the data on the stack.
1438:
1439: @example
1440: 1 .s drop .s
1441: 1 .s dup .s drop drop .s
1442: 1 2 .s over .s drop drop drop
1443: 1 2 .s swap .s drop drop
1444: 1 2 3 .s rot .s drop drop drop
1445: @end example
1446:
1447: These are the most important stack manipulation words. There are also
1448: variants that manipulate twice as many stack items:
1449:
1450: @example
1451: 1 2 3 4 .s 2swap .s 2drop 2drop
1452: @end example
1453:
1454: Two more stack manipulation words are:
1455:
1456: @example
1457: 1 2 .s nip .s drop
1458: 1 2 .s tuck .s 2drop drop
1459: @end example
1460:
1461: @quotation Assignment
1462: Replace @code{nip} and @code{tuck} with combinations of other stack
1463: manipulation words.
1464:
1465: @example
1466: Given: How do you get:
1467: 1 2 3 3 2 1
1468: 1 2 3 1 2 3 2
1469: 1 2 3 1 2 3 3
1470: 1 2 3 1 3 3
1471: 1 2 3 2 1 3
1472: 1 2 3 4 4 3 2 1
1473: 1 2 3 1 2 3 1 2 3
1474: 1 2 3 4 1 2 3 4 1 2
1475: 1 2 3
1476: 1 2 3 1 2 3 4
1477: 1 2 3 1 3
1478: @end example
1479: @end quotation
1480:
1481: @example
1482: 5 dup * .
1483: @end example
1484:
1485: @quotation Assignment
1486: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1487: Write a piece of Forth code that expects two numbers on the stack
1488: (@var{a} and @var{b}, with @var{b} on top) and computes
1489: @code{(a-b)(a+1)}.
1490: @end quotation
1491:
1492: Reference: @ref{Stack Manipulation}.
1493:
1494:
1495: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1496: @section Using files for Forth code
1497: @cindex loading Forth code, tutorial
1498: @cindex files containing Forth code, tutorial
1499:
1500: While working at the Forth command line is convenient for one-line
1501: examples and short one-off code, you probably want to store your source
1502: code in files for convenient editing and persistence. You can use your
1503: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1504: Gforth}) to create @var{file.fs} and use
1505:
1506: @example
1507: s" @var{file.fs}" included
1508: @end example
1509:
1510: to load it into your Forth system. The file name extension I use for
1511: Forth files is @samp{.fs}.
1512:
1513: You can easily start Gforth with some files loaded like this:
1514:
1515: @example
1516: gforth @var{file1.fs} @var{file2.fs}
1517: @end example
1518:
1519: If an error occurs during loading these files, Gforth terminates,
1520: whereas an error during @code{INCLUDED} within Gforth usually gives you
1521: a Gforth command line. Starting the Forth system every time gives you a
1522: clean start every time, without interference from the results of earlier
1523: tries.
1524:
1525: I often put all the tests in a file, then load the code and run the
1526: tests with
1527:
1528: @example
1529: gforth @var{code.fs} @var{tests.fs} -e bye
1530: @end example
1531:
1532: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1533: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1534: restart this command without ado.
1535:
1536: The advantage of this approach is that the tests can be repeated easily
1537: every time the program ist changed, making it easy to catch bugs
1538: introduced by the change.
1539:
1540: Reference: @ref{Forth source files}.
1541:
1542:
1543: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1544: @section Comments
1545: @cindex comments tutorial
1546:
1547: @example
1548: \ That's a comment; it ends at the end of the line
1549: ( Another comment; it ends here: ) .s
1550: @end example
1551:
1552: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1553: separated with white space from the following text.
1554:
1555: @example
1556: \This gives an "Undefined word" error
1557: @end example
1558:
1559: The first @code{)} ends a comment started with @code{(}, so you cannot
1560: nest @code{(}-comments; and you cannot comment out text containing a
1561: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1562: avoid @code{)} in word names.}.
1563:
1564: I use @code{\}-comments for descriptive text and for commenting out code
1565: of one or more line; I use @code{(}-comments for describing the stack
1566: effect, the stack contents, or for commenting out sub-line pieces of
1567: code.
1568:
1569: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1570: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1571: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1572: with @kbd{M-q}.
1573:
1574: Reference: @ref{Comments}.
1575:
1576:
1577: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1578: @section Colon Definitions
1579: @cindex colon definitions, tutorial
1580: @cindex definitions, tutorial
1581: @cindex procedures, tutorial
1582: @cindex functions, tutorial
1583:
1584: are similar to procedures and functions in other programming languages.
1585:
1586: @example
1587: : squared ( n -- n^2 )
1588: dup * ;
1589: 5 squared .
1590: 7 squared .
1591: @end example
1592:
1593: @code{:} starts the colon definition; its name is @code{squared}. The
1594: following comment describes its stack effect. The words @code{dup *}
1595: are not executed, but compiled into the definition. @code{;} ends the
1596: colon definition.
1597:
1598: The newly-defined word can be used like any other word, including using
1599: it in other definitions:
1600:
1601: @example
1602: : cubed ( n -- n^3 )
1603: dup squared * ;
1604: -5 cubed .
1605: : fourth-power ( n -- n^4 )
1606: squared squared ;
1607: 3 fourth-power .
1608: @end example
1609:
1610: @quotation Assignment
1611: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1612: @code{/mod} in terms of other Forth words, and check if they work (hint:
1613: test your tests on the originals first). Don't let the
1614: @samp{redefined}-Messages spook you, they are just warnings.
1615: @end quotation
1616:
1617: Reference: @ref{Colon Definitions}.
1618:
1619:
1620: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1621: @section Decompilation
1622: @cindex decompilation tutorial
1623: @cindex see tutorial
1624:
1625: You can decompile colon definitions with @code{see}:
1626:
1627: @example
1628: see squared
1629: see cubed
1630: @end example
1631:
1632: In Gforth @code{see} shows you a reconstruction of the source code from
1633: the executable code. Informations that were present in the source, but
1634: not in the executable code, are lost (e.g., comments).
1635:
1636: You can also decompile the predefined words:
1637:
1638: @example
1639: see .
1640: see +
1641: @end example
1642:
1643:
1644: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1645: @section Stack-Effect Comments
1646: @cindex stack-effect comments, tutorial
1647: @cindex --, tutorial
1648: By convention the comment after the name of a definition describes the
1649: stack effect: The part in front of the @samp{--} describes the state of
1650: the stack before the execution of the definition, i.e., the parameters
1651: that are passed into the colon definition; the part behind the @samp{--}
1652: is the state of the stack after the execution of the definition, i.e.,
1653: the results of the definition. The stack comment only shows the top
1654: stack items that the definition accesses and/or changes.
1655:
1656: You should put a correct stack effect on every definition, even if it is
1657: just @code{( -- )}. You should also add some descriptive comment to
1658: more complicated words (I usually do this in the lines following
1659: @code{:}). If you don't do this, your code becomes unreadable (because
1660: you have to work through every definition before you can understand
1661: any).
1662:
1663: @quotation Assignment
1664: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1665: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1666: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1667: are done, you can compare your stack effects to those in this manual
1668: (@pxref{Word Index}).
1669: @end quotation
1670:
1671: Sometimes programmers put comments at various places in colon
1672: definitions that describe the contents of the stack at that place (stack
1673: comments); i.e., they are like the first part of a stack-effect
1674: comment. E.g.,
1675:
1676: @example
1677: : cubed ( n -- n^3 )
1678: dup squared ( n n^2 ) * ;
1679: @end example
1680:
1681: In this case the stack comment is pretty superfluous, because the word
1682: is simple enough. If you think it would be a good idea to add such a
1683: comment to increase readability, you should also consider factoring the
1684: word into several simpler words (@pxref{Factoring Tutorial,,
1685: Factoring}), which typically eliminates the need for the stack comment;
1686: however, if you decide not to refactor it, then having such a comment is
1687: better than not having it.
1688:
1689: The names of the stack items in stack-effect and stack comments in the
1690: standard, in this manual, and in many programs specify the type through
1691: a type prefix, similar to Fortran and Hungarian notation. The most
1692: frequent prefixes are:
1693:
1694: @table @code
1695: @item n
1696: signed integer
1697: @item u
1698: unsigned integer
1699: @item c
1700: character
1701: @item f
1702: Boolean flags, i.e. @code{false} or @code{true}.
1703: @item a-addr,a-
1704: Cell-aligned address
1705: @item c-addr,c-
1706: Char-aligned address (note that a Char may have two bytes in Windows NT)
1707: @item xt
1708: Execution token, same size as Cell
1709: @item w,x
1710: Cell, can contain an integer or an address. It usually takes 32, 64 or
1711: 16 bits (depending on your platform and Forth system). A cell is more
1712: commonly known as machine word, but the term @emph{word} already means
1713: something different in Forth.
1714: @item d
1715: signed double-cell integer
1716: @item ud
1717: unsigned double-cell integer
1718: @item r
1719: Float (on the FP stack)
1720: @end table
1721:
1722: You can find a more complete list in @ref{Notation}.
1723:
1724: @quotation Assignment
1725: Write stack-effect comments for all definitions you have written up to
1726: now.
1727: @end quotation
1728:
1729:
1730: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1731: @section Types
1732: @cindex types tutorial
1733:
1734: In Forth the names of the operations are not overloaded; so similar
1735: operations on different types need different names; e.g., @code{+} adds
1736: integers, and you have to use @code{f+} to add floating-point numbers.
1737: The following prefixes are often used for related operations on
1738: different types:
1739:
1740: @table @code
1741: @item (none)
1742: signed integer
1743: @item u
1744: unsigned integer
1745: @item c
1746: character
1747: @item d
1748: signed double-cell integer
1749: @item ud, du
1750: unsigned double-cell integer
1751: @item 2
1752: two cells (not-necessarily double-cell numbers)
1753: @item m, um
1754: mixed single-cell and double-cell operations
1755: @item f
1756: floating-point (note that in stack comments @samp{f} represents flags,
1757: and @samp{r} represents FP numbers; also, you need to include the
1758: exponent part in literal FP numbers, @pxref{Floating Point Tutorial}).
1759: @end table
1760:
1761: If there are no differences between the signed and the unsigned variant
1762: (e.g., for @code{+}), there is only the prefix-less variant.
1763:
1764: Forth does not perform type checking, neither at compile time, nor at
1765: run time. If you use the wrong operation, the data are interpreted
1766: incorrectly:
1767:
1768: @example
1769: -1 u.
1770: @end example
1771:
1772: If you have only experience with type-checked languages until now, and
1773: have heard how important type-checking is, don't panic! In my
1774: experience (and that of other Forthers), type errors in Forth code are
1775: usually easy to find (once you get used to it), the increased vigilance
1776: of the programmer tends to catch some harder errors in addition to most
1777: type errors, and you never have to work around the type system, so in
1778: most situations the lack of type-checking seems to be a win (projects to
1779: add type checking to Forth have not caught on).
1780:
1781:
1782: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1783: @section Factoring
1784: @cindex factoring tutorial
1785:
1786: If you try to write longer definitions, you will soon find it hard to
1787: keep track of the stack contents. Therefore, good Forth programmers
1788: tend to write only short definitions (e.g., three lines). The art of
1789: finding meaningful short definitions is known as factoring (as in
1790: factoring polynomials).
1791:
1792: Well-factored programs offer additional advantages: smaller, more
1793: general words, are easier to test and debug and can be reused more and
1794: better than larger, specialized words.
1795:
1796: So, if you run into difficulties with stack management, when writing
1797: code, try to define meaningful factors for the word, and define the word
1798: in terms of those. Even if a factor contains only two words, it is
1799: often helpful.
1800:
1801: Good factoring is not easy, and it takes some practice to get the knack
1802: for it; but even experienced Forth programmers often don't find the
1803: right solution right away, but only when rewriting the program. So, if
1804: you don't come up with a good solution immediately, keep trying, don't
1805: despair.
1806:
1807: @c example !!
1808:
1809:
1810: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1811: @section Designing the stack effect
1812: @cindex Stack effect design, tutorial
1813: @cindex design of stack effects, tutorial
1814:
1815: In other languages you can use an arbitrary order of parameters for a
1816: function; and since there is only one result, you don't have to deal with
1817: the order of results, either.
1818:
1819: In Forth (and other stack-based languages, e.g., PostScript) the
1820: parameter and result order of a definition is important and should be
1821: designed well. The general guideline is to design the stack effect such
1822: that the word is simple to use in most cases, even if that complicates
1823: the implementation of the word. Some concrete rules are:
1824:
1825: @itemize @bullet
1826:
1827: @item
1828: Words consume all of their parameters (e.g., @code{.}).
1829:
1830: @item
1831: If there is a convention on the order of parameters (e.g., from
1832: mathematics or another programming language), stick with it (e.g.,
1833: @code{-}).
1834:
1835: @item
1836: If one parameter usually requires only a short computation (e.g., it is
1837: a constant), pass it on the top of the stack. Conversely, parameters
1838: that usually require a long sequence of code to compute should be passed
1839: as the bottom (i.e., first) parameter. This makes the code easier to
1840: read, because the reader does not need to keep track of the bottom item
1841: through a long sequence of code (or, alternatively, through stack
1842: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1843: address on top of the stack because it is usually simpler to compute
1844: than the stored value (often the address is just a variable).
1845:
1846: @item
1847: Similarly, results that are usually consumed quickly should be returned
1848: on the top of stack, whereas a result that is often used in long
1849: computations should be passed as bottom result. E.g., the file words
1850: like @code{open-file} return the error code on the top of stack, because
1851: it is usually consumed quickly by @code{throw}; moreover, the error code
1852: has to be checked before doing anything with the other results.
1853:
1854: @end itemize
1855:
1856: These rules are just general guidelines, don't lose sight of the overall
1857: goal to make the words easy to use. E.g., if the convention rule
1858: conflicts with the computation-length rule, you might decide in favour
1859: of the convention if the word will be used rarely, and in favour of the
1860: computation-length rule if the word will be used frequently (because
1861: with frequent use the cost of breaking the computation-length rule would
1862: be quite high, and frequent use makes it easier to remember an
1863: unconventional order).
1864:
1865: @c example !! structure package
1866:
1867:
1868: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1869: @section Local Variables
1870: @cindex local variables, tutorial
1871:
1872: You can define local variables (@emph{locals}) in a colon definition:
1873:
1874: @example
1875: : swap @{ a b -- b a @}
1876: b a ;
1877: 1 2 swap .s 2drop
1878: @end example
1879:
1880: (If your Forth system does not support this syntax, include
1881: @file{compat/anslocal.fs} first).
1882:
1883: In this example @code{@{ a b -- b a @}} is the locals definition; it
1884: takes two cells from the stack, puts the top of stack in @code{b} and
1885: the next stack element in @code{a}. @code{--} starts a comment ending
1886: with @code{@}}. After the locals definition, using the name of the
1887: local will push its value on the stack. You can leave the comment
1888: part (@code{-- b a}) away:
1889:
1890: @example
1891: : swap ( x1 x2 -- x2 x1 )
1892: @{ a b @} b a ;
1893: @end example
1894:
1895: In Gforth you can have several locals definitions, anywhere in a colon
1896: definition; in contrast, in a standard program you can have only one
1897: locals definition per colon definition, and that locals definition must
1898: be outside any control structure.
1899:
1900: With locals you can write slightly longer definitions without running
1901: into stack trouble. However, I recommend trying to write colon
1902: definitions without locals for exercise purposes to help you gain the
1903: essential factoring skills.
1904:
1905: @quotation Assignment
1906: Rewrite your definitions until now with locals
1907: @end quotation
1908:
1909: Reference: @ref{Locals}.
1910:
1911:
1912: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1913: @section Conditional execution
1914: @cindex conditionals, tutorial
1915: @cindex if, tutorial
1916:
1917: In Forth you can use control structures only inside colon definitions.
1918: An @code{if}-structure looks like this:
1919:
1920: @example
1921: : abs ( n1 -- +n2 )
1922: dup 0 < if
1923: negate
1924: endif ;
1925: 5 abs .
1926: -5 abs .
1927: @end example
1928:
1929: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1930: the following code is performed, otherwise execution continues after the
1931: @code{endif} (or @code{else}). @code{<} compares the top two stack
1932: elements and produces a flag:
1933:
1934: @example
1935: 1 2 < .
1936: 2 1 < .
1937: 1 1 < .
1938: @end example
1939:
1940: Actually the standard name for @code{endif} is @code{then}. This
1941: tutorial presents the examples using @code{endif}, because this is often
1942: less confusing for people familiar with other programming languages
1943: where @code{then} has a different meaning. If your system does not have
1944: @code{endif}, define it with
1945:
1946: @example
1947: : endif postpone then ; immediate
1948: @end example
1949:
1950: You can optionally use an @code{else}-part:
1951:
1952: @example
1953: : min ( n1 n2 -- n )
1954: 2dup < if
1955: drop
1956: else
1957: nip
1958: endif ;
1959: 2 3 min .
1960: 3 2 min .
1961: @end example
1962:
1963: @quotation Assignment
1964: Write @code{min} without @code{else}-part (hint: what's the definition
1965: of @code{nip}?).
1966: @end quotation
1967:
1968: Reference: @ref{Selection}.
1969:
1970:
1971: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1972: @section Flags and Comparisons
1973: @cindex flags tutorial
1974: @cindex comparison tutorial
1975:
1976: In a false-flag all bits are clear (0 when interpreted as integer). In
1977: a canonical true-flag all bits are set (-1 as a twos-complement signed
1978: integer); in many contexts (e.g., @code{if}) any non-zero value is
1979: treated as true flag.
1980:
1981: @example
1982: false .
1983: true .
1984: true hex u. decimal
1985: @end example
1986:
1987: Comparison words produce canonical flags:
1988:
1989: @example
1990: 1 1 = .
1991: 1 0= .
1992: 0 1 < .
1993: 0 0 < .
1994: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1995: -1 1 < .
1996: @end example
1997:
1998: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1999: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
2000: these combinations are standard (for details see the standard,
2001: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
2002:
2003: You can use @code{and or xor invert} as operations on canonical flags.
2004: Actually they are bitwise operations:
2005:
2006: @example
2007: 1 2 and .
2008: 1 2 or .
2009: 1 3 xor .
2010: 1 invert .
2011: @end example
2012:
2013: You can convert a zero/non-zero flag into a canonical flag with
2014: @code{0<>} (and complement it on the way with @code{0=}).
2015:
2016: @example
2017: 1 0= .
2018: 1 0<> .
2019: @end example
2020:
2021: You can use the all-bits-set feature of canonical flags and the bitwise
2022: operation of the Boolean operations to avoid @code{if}s:
2023:
2024: @example
2025: : foo ( n1 -- n2 )
2026: 0= if
2027: 14
2028: else
2029: 0
2030: endif ;
2031: 0 foo .
2032: 1 foo .
2033:
2034: : foo ( n1 -- n2 )
2035: 0= 14 and ;
2036: 0 foo .
2037: 1 foo .
2038: @end example
2039:
2040: @quotation Assignment
2041: Write @code{min} without @code{if}.
2042: @end quotation
2043:
2044: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2045: @ref{Bitwise operations}.
2046:
2047:
2048: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2049: @section General Loops
2050: @cindex loops, indefinite, tutorial
2051:
2052: The endless loop is the most simple one:
2053:
2054: @example
2055: : endless ( -- )
2056: 0 begin
2057: dup . 1+
2058: again ;
2059: endless
2060: @end example
2061:
2062: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2063: does nothing at run-time, @code{again} jumps back to @code{begin}.
2064:
2065: A loop with one exit at any place looks like this:
2066:
2067: @example
2068: : log2 ( +n1 -- n2 )
2069: \ logarithmus dualis of n1>0, rounded down to the next integer
2070: assert( dup 0> )
2071: 2/ 0 begin
2072: over 0> while
2073: 1+ swap 2/ swap
2074: repeat
2075: nip ;
2076: 7 log2 .
2077: 8 log2 .
2078: @end example
2079:
2080: At run-time @code{while} consumes a flag; if it is 0, execution
2081: continues behind the @code{repeat}; if the flag is non-zero, execution
2082: continues behind the @code{while}. @code{Repeat} jumps back to
2083: @code{begin}, just like @code{again}.
2084:
2085: In Forth there are a number of combinations/abbreviations, like
2086: @code{1+}. However, @code{2/} is not one of them; it shifts its
2087: argument right by one bit (arithmetic shift right), and viewed as
2088: division that always rounds towards negative infinity (floored
2089: division). In contrast, @code{/} rounds towards zero on some systems
2090: (not on default installations of gforth (>=0.7.0), however).
2091:
2092: @example
2093: -5 2 / . \ -2 or -3
2094: -5 2/ . \ -3
2095: @end example
2096:
2097: @code{assert(} is no standard word, but you can get it on systems other
2098: than Gforth by including @file{compat/assert.fs}. You can see what it
2099: does by trying
2100:
2101: @example
2102: 0 log2 .
2103: @end example
2104:
2105: Here's a loop with an exit at the end:
2106:
2107: @example
2108: : log2 ( +n1 -- n2 )
2109: \ logarithmus dualis of n1>0, rounded down to the next integer
2110: assert( dup 0 > )
2111: -1 begin
2112: 1+ swap 2/ swap
2113: over 0 <=
2114: until
2115: nip ;
2116: @end example
2117:
2118: @code{Until} consumes a flag; if it is non-zero, execution continues at
2119: the @code{begin}, otherwise after the @code{until}.
2120:
2121: @quotation Assignment
2122: Write a definition for computing the greatest common divisor.
2123: @end quotation
2124:
2125: Reference: @ref{Simple Loops}.
2126:
2127:
2128: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2129: @section Counted loops
2130: @cindex loops, counted, tutorial
2131:
2132: @example
2133: : ^ ( n1 u -- n )
2134: \ n = the uth power of n1
2135: 1 swap 0 u+do
2136: over *
2137: loop
2138: nip ;
2139: 3 2 ^ .
2140: 4 3 ^ .
2141: @end example
2142:
2143: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2144: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2145: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2146: times (or not at all, if @code{u3-u4<0}).
2147:
2148: You can see the stack effect design rules at work in the stack effect of
2149: the loop start words: Since the start value of the loop is more
2150: frequently constant than the end value, the start value is passed on
2151: the top-of-stack.
2152:
2153: You can access the counter of a counted loop with @code{i}:
2154:
2155: @example
2156: : fac ( u -- u! )
2157: 1 swap 1+ 1 u+do
2158: i *
2159: loop ;
2160: 5 fac .
2161: 7 fac .
2162: @end example
2163:
2164: There is also @code{+do}, which expects signed numbers (important for
2165: deciding whether to enter the loop).
2166:
2167: @quotation Assignment
2168: Write a definition for computing the nth Fibonacci number.
2169: @end quotation
2170:
2171: You can also use increments other than 1:
2172:
2173: @example
2174: : up2 ( n1 n2 -- )
2175: +do
2176: i .
2177: 2 +loop ;
2178: 10 0 up2
2179:
2180: : down2 ( n1 n2 -- )
2181: -do
2182: i .
2183: 2 -loop ;
2184: 0 10 down2
2185: @end example
2186:
2187: Reference: @ref{Counted Loops}.
2188:
2189:
2190: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2191: @section Recursion
2192: @cindex recursion tutorial
2193:
2194: Usually the name of a definition is not visible in the definition; but
2195: earlier definitions are usually visible:
2196:
2197: @example
2198: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
2199: : / ( n1 n2 -- n )
2200: dup 0= if
2201: -10 throw \ report division by zero
2202: endif
2203: / \ old version
2204: ;
2205: 1 0 /
2206: @end example
2207:
2208: For recursive definitions you can use @code{recursive} (non-standard) or
2209: @code{recurse}:
2210:
2211: @example
2212: : fac1 ( n -- n! ) recursive
2213: dup 0> if
2214: dup 1- fac1 *
2215: else
2216: drop 1
2217: endif ;
2218: 7 fac1 .
2219:
2220: : fac2 ( n -- n! )
2221: dup 0> if
2222: dup 1- recurse *
2223: else
2224: drop 1
2225: endif ;
2226: 8 fac2 .
2227: @end example
2228:
2229: @quotation Assignment
2230: Write a recursive definition for computing the nth Fibonacci number.
2231: @end quotation
2232:
2233: Reference (including indirect recursion): @xref{Calls and returns}.
2234:
2235:
2236: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2237: @section Leaving definitions or loops
2238: @cindex leaving definitions, tutorial
2239: @cindex leaving loops, tutorial
2240:
2241: @code{EXIT} exits the current definition right away. For every counted
2242: loop that is left in this way, an @code{UNLOOP} has to be performed
2243: before the @code{EXIT}:
2244:
2245: @c !! real examples
2246: @example
2247: : ...
2248: ... u+do
2249: ... if
2250: ... unloop exit
2251: endif
2252: ...
2253: loop
2254: ... ;
2255: @end example
2256:
2257: @code{LEAVE} leaves the innermost counted loop right away:
2258:
2259: @example
2260: : ...
2261: ... u+do
2262: ... if
2263: ... leave
2264: endif
2265: ...
2266: loop
2267: ... ;
2268: @end example
2269:
2270: @c !! example
2271:
2272: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2273:
2274:
2275: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2276: @section Return Stack
2277: @cindex return stack tutorial
2278:
2279: In addition to the data stack Forth also has a second stack, the return
2280: stack; most Forth systems store the return addresses of procedure calls
2281: there (thus its name). Programmers can also use this stack:
2282:
2283: @example
2284: : foo ( n1 n2 -- )
2285: .s
2286: >r .s
2287: r@@ .
2288: >r .s
2289: r@@ .
2290: r> .
2291: r@@ .
2292: r> . ;
2293: 1 2 foo
2294: @end example
2295:
2296: @code{>r} takes an element from the data stack and pushes it onto the
2297: return stack; conversely, @code{r>} moves an elementm from the return to
2298: the data stack; @code{r@@} pushes a copy of the top of the return stack
2299: on the data stack.
2300:
2301: Forth programmers usually use the return stack for storing data
2302: temporarily, if using the data stack alone would be too complex, and
2303: factoring and locals are not an option:
2304:
2305: @example
2306: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2307: rot >r rot r> ;
2308: @end example
2309:
2310: The return address of the definition and the loop control parameters of
2311: counted loops usually reside on the return stack, so you have to take
2312: all items, that you have pushed on the return stack in a colon
2313: definition or counted loop, from the return stack before the definition
2314: or loop ends. You cannot access items that you pushed on the return
2315: stack outside some definition or loop within the definition of loop.
2316:
2317: If you miscount the return stack items, this usually ends in a crash:
2318:
2319: @example
2320: : crash ( n -- )
2321: >r ;
2322: 5 crash
2323: @end example
2324:
2325: You cannot mix using locals and using the return stack (according to the
2326: standard; Gforth has no problem). However, they solve the same
2327: problems, so this shouldn't be an issue.
2328:
2329: @quotation Assignment
2330: Can you rewrite any of the definitions you wrote until now in a better
2331: way using the return stack?
2332: @end quotation
2333:
2334: Reference: @ref{Return stack}.
2335:
2336:
2337: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2338: @section Memory
2339: @cindex memory access/allocation tutorial
2340:
2341: You can create a global variable @code{v} with
2342:
2343: @example
2344: variable v ( -- addr )
2345: @end example
2346:
2347: @code{v} pushes the address of a cell in memory on the stack. This cell
2348: was reserved by @code{variable}. You can use @code{!} (store) to store
2349: values into this cell and @code{@@} (fetch) to load the value from the
2350: stack into memory:
2351:
2352: @example
2353: v .
2354: 5 v ! .s
2355: v @@ .
2356: @end example
2357:
2358: You can see a raw dump of memory with @code{dump}:
2359:
2360: @example
2361: v 1 cells .s dump
2362: @end example
2363:
2364: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2365: generally, address units (aus)) that @code{n1 cells} occupy. You can
2366: also reserve more memory:
2367:
2368: @example
2369: create v2 20 cells allot
2370: v2 20 cells dump
2371: @end example
2372:
2373: creates a variable-like word @code{v2} and reserves 20 uninitialized
2374: cells; the address pushed by @code{v2} points to the start of these 20
2375: cells (@pxref{CREATE}). You can use address arithmetic to access
2376: these cells:
2377:
2378: @example
2379: 3 v2 5 cells + !
2380: v2 20 cells dump
2381: @end example
2382:
2383: You can reserve and initialize memory with @code{,}:
2384:
2385: @example
2386: create v3
2387: 5 , 4 , 3 , 2 , 1 ,
2388: v3 @@ .
2389: v3 cell+ @@ .
2390: v3 2 cells + @@ .
2391: v3 5 cells dump
2392: @end example
2393:
2394: @quotation Assignment
2395: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2396: @code{u} cells, with the first of these cells at @code{addr}, the next
2397: one at @code{addr cell+} etc.
2398: @end quotation
2399:
2400: The difference between @code{variable} and @code{create} is that
2401: @code{variable} allots a cell, and that you cannot allot additional
2402: memory to a variable in standard Forth.
2403:
2404: You can also reserve memory without creating a new word:
2405:
2406: @example
2407: here 10 cells allot .
2408: here .
2409: @end example
2410:
2411: The first @code{here} pushes the start address of the memory area, the
2412: second @code{here} the address after the dictionary area. You should
2413: store the start address somewhere, or you will have a hard time
2414: finding the memory area again.
2415:
2416: @code{Allot} manages dictionary memory. The dictionary memory contains
2417: the system's data structures for words etc. on Gforth and most other
2418: Forth systems. It is managed like a stack: You can free the memory that
2419: you have just @code{allot}ed with
2420:
2421: @example
2422: -10 cells allot
2423: here .
2424: @end example
2425:
2426: Note that you cannot do this if you have created a new word in the
2427: meantime (because then your @code{allot}ed memory is no longer on the
2428: top of the dictionary ``stack'').
2429:
2430: Alternatively, you can use @code{allocate} and @code{free} which allow
2431: freeing memory in any order:
2432:
2433: @example
2434: 10 cells allocate throw .s
2435: 20 cells allocate throw .s
2436: swap
2437: free throw
2438: free throw
2439: @end example
2440:
2441: The @code{throw}s deal with errors (e.g., out of memory).
2442:
2443: And there is also a
2444: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2445: garbage collector}, which eliminates the need to @code{free} memory
2446: explicitly.
2447:
2448: Reference: @ref{Memory}.
2449:
2450:
2451: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2452: @section Characters and Strings
2453: @cindex strings tutorial
2454: @cindex characters tutorial
2455:
2456: On the stack characters take up a cell, like numbers. In memory they
2457: have their own size (one 8-bit byte on most systems), and therefore
2458: require their own words for memory access:
2459:
2460: @example
2461: create v4
2462: 104 c, 97 c, 108 c, 108 c, 111 c,
2463: v4 4 chars + c@@ .
2464: v4 5 chars dump
2465: @end example
2466:
2467: The preferred representation of strings on the stack is @code{addr
2468: u-count}, where @code{addr} is the address of the first character and
2469: @code{u-count} is the number of characters in the string.
2470:
2471: @example
2472: v4 5 type
2473: @end example
2474:
2475: You get a string constant with
2476:
2477: @example
2478: s" hello, world" .s
2479: type
2480: @end example
2481:
2482: Make sure you have a space between @code{s"} and the string; @code{s"}
2483: is a normal Forth word and must be delimited with white space (try what
2484: happens when you remove the space).
2485:
2486: However, this interpretive use of @code{s"} is quite restricted: the
2487: string exists only until the next call of @code{s"} (some Forth systems
2488: keep more than one of these strings, but usually they still have a
2489: limited lifetime).
2490:
2491: @example
2492: s" hello," s" world" .s
2493: type
2494: type
2495: @end example
2496:
2497: You can also use @code{s"} in a definition, and the resulting
2498: strings then live forever (well, for as long as the definition):
2499:
2500: @example
2501: : foo s" hello," s" world" ;
2502: foo .s
2503: type
2504: type
2505: @end example
2506:
2507: @quotation Assignment
2508: @code{Emit ( c -- )} types @code{c} as character (not a number).
2509: Implement @code{type ( addr u -- )}.
2510: @end quotation
2511:
2512: Reference: @ref{Memory Blocks}.
2513:
2514:
2515: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
2516: @section Alignment
2517: @cindex alignment tutorial
2518: @cindex memory alignment tutorial
2519:
2520: On many processors cells have to be aligned in memory, if you want to
2521: access them with @code{@@} and @code{!} (and even if the processor does
2522: not require alignment, access to aligned cells is faster).
2523:
2524: @code{Create} aligns @code{here} (i.e., the place where the next
2525: allocation will occur, and that the @code{create}d word points to).
2526: Likewise, the memory produced by @code{allocate} starts at an aligned
2527: address. Adding a number of @code{cells} to an aligned address produces
2528: another aligned address.
2529:
2530: However, address arithmetic involving @code{char+} and @code{chars} can
2531: create an address that is not cell-aligned. @code{Aligned ( addr --
2532: a-addr )} produces the next aligned address:
2533:
2534: @example
2535: v3 char+ aligned .s @@ .
2536: v3 char+ .s @@ .
2537: @end example
2538:
2539: Similarly, @code{align} advances @code{here} to the next aligned
2540: address:
2541:
2542: @example
2543: create v5 97 c,
2544: here .
2545: align here .
2546: 1000 ,
2547: @end example
2548:
2549: Note that you should use aligned addresses even if your processor does
2550: not require them, if you want your program to be portable.
2551:
2552: Reference: @ref{Address arithmetic}.
2553:
2554: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
2555: @section Floating Point
2556: @cindex floating point tutorial
2557: @cindex FP tutorial
2558:
2559: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
2560: might expect, but there are a few things worth noting:
2561:
2562: The first point is not specific to Forth, but so important and yet not
2563: universally known that I mention it here: FP numbers are not reals.
2564: Many properties (e.g., arithmetic laws) that reals have and that one
2565: expects of all kinds of numbers do not hold for FP numbers. If you
2566: want to use FP computations, you should learn about their problems and
2567: how to avoid them; a good starting point is @cite{David Goldberg,
2568: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
2569: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
2570: Computing Surveys 23(1):5@minus{}48, March 1991}.
2571:
2572: In Forth source code literal FP numbers need an exponent, e.g.,
2573: @code{1e0}; this can also be written shorter as @code{1e}, longer as
2574: @code{+1.0e+0}, and many variations in between. The reason for this is
2575: that, for historical reasons, Forth interprets a decimal point alone
2576: (e.g., @code{1.}) as indicating a double-cell integer. Examples:
2577:
2578: @example
2579: 2e 2e f+ f.
2580: @end example
2581:
2582: Another requirement for literal FP numbers is that the current base is
2583: decimal; with a hex base @code{1e} is interpreted as an integer.
2584:
2585: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
2586: ANS Forth system may implement the FP stack on the data stack, but
2587: virtually all systems implement a separate FP stack; and programming
2588: in a way that accommodates all models is so cumbersome that nobody
2589: does it.} One advantage of this model is that cells are not in the
2590: way when accessing FP values, and vice versa. Forth has a set of
2591: words for manipulating the FP stack: @code{fdup fswap fdrop fover
2592: frot} and (non-standard) @code{fnip ftuck fpick}.
2593:
2594: FP arithmetic words are prefixed with @code{F}. There is the usual
2595: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
2596: other functions, e.g., @code{fsqrt fsin fln fmin}. One word that you
2597: might expect is @code{f=}; but @code{f=} is non-standard, because FP
2598: computation results are usually inaccurate, so exact comparison is
2599: usually a mistake, and one should use approximate comparison.
2600: Unfortunately, @code{f~}, the standard word for that purpose, is not
2601: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
2602: well.
2603:
2604: And of course there are words for accessing FP numbers in memory
2605: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
2606: faligned}). There are also variants of these words with an @code{sf}
2607: and @code{df} prefix for accessing IEEE format single-precision and
2608: double-precision numbers in memory; their main purpose is for
2609: accessing external FP data (e.g., that has been read from or will be
2610: written to a file).
2611:
2612: Here is an example of a dot-product word and its use:
2613:
2614: @example
2615: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
2616: >r swap 2swap swap 0e r> 0 ?DO
2617: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
2618: LOOP
2619: 2drop 2drop ;
2620:
2621: create v 1.23e f, 4.56e f, 7.89e f,
2622:
2623: v 1 floats v 1 floats 3 v* f.
2624: @end example
2625:
2626: @quotation Assignment
2627: Write a program to solve a quadratic equation. Then read @cite{Henry
2628: G. Baker,
2629: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
2630: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
2631: 33(1):30@minus{}39, January 1998}, and see if you can improve your
2632: program. Finally, find a test case where the original and the
2633: improved version produce different results.
2634: @end quotation
2635:
2636: Reference: @ref{Floating Point}; @ref{Floating point stack};
2637: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
2638: arithmetic}.
2639:
2640: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
2641: @section Files
2642: @cindex files tutorial
2643:
2644: This section gives a short introduction into how to use files inside
2645: Forth. It's broken up into five easy steps:
2646:
2647: @enumerate 1
2648: @item Opened an ASCII text file for input
2649: @item Opened a file for output
2650: @item Read input file until string matched (or some other condition matched)
2651: @item Wrote some lines from input ( modified or not) to output
2652: @item Closed the files.
2653: @end enumerate
2654:
2655: Reference: @ref{General files}.
2656:
2657: @subsection Open file for input
2658:
2659: @example
2660: s" foo.in" r/o open-file throw Value fd-in
2661: @end example
2662:
2663: @subsection Create file for output
2664:
2665: @example
2666: s" foo.out" w/o create-file throw Value fd-out
2667: @end example
2668:
2669: The available file modes are r/o for read-only access, r/w for
2670: read-write access, and w/o for write-only access. You could open both
2671: files with r/w, too, if you like. All file words return error codes; for
2672: most applications, it's best to pass there error codes with @code{throw}
2673: to the outer error handler.
2674:
2675: If you want words for opening and assigning, define them as follows:
2676:
2677: @example
2678: 0 Value fd-in
2679: 0 Value fd-out
2680: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2681: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2682: @end example
2683:
2684: Usage example:
2685:
2686: @example
2687: s" foo.in" open-input
2688: s" foo.out" open-output
2689: @end example
2690:
2691: @subsection Scan file for a particular line
2692:
2693: @example
2694: 256 Constant max-line
2695: Create line-buffer max-line 2 + allot
2696:
2697: : scan-file ( addr u -- )
2698: begin
2699: line-buffer max-line fd-in read-line throw
2700: while
2701: >r 2dup line-buffer r> compare 0=
2702: until
2703: else
2704: drop
2705: then
2706: 2drop ;
2707: @end example
2708:
2709: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
2710: the buffer at addr, and returns the number of bytes read, a flag that is
2711: false when the end of file is reached, and an error code.
2712:
2713: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2714: returns zero if both strings are equal. It returns a positive number if
2715: the first string is lexically greater, a negative if the second string
2716: is lexically greater.
2717:
2718: We haven't seen this loop here; it has two exits. Since the @code{while}
2719: exits with the number of bytes read on the stack, we have to clean up
2720: that separately; that's after the @code{else}.
2721:
2722: Usage example:
2723:
2724: @example
2725: s" The text I search is here" scan-file
2726: @end example
2727:
2728: @subsection Copy input to output
2729:
2730: @example
2731: : copy-file ( -- )
2732: begin
2733: line-buffer max-line fd-in read-line throw
2734: while
2735: line-buffer swap fd-out write-line throw
2736: repeat ;
2737: @end example
2738: @c !! does not handle long lines, no newline at end of file
2739:
2740: @subsection Close files
2741:
2742: @example
2743: fd-in close-file throw
2744: fd-out close-file throw
2745: @end example
2746:
2747: Likewise, you can put that into definitions, too:
2748:
2749: @example
2750: : close-input ( -- ) fd-in close-file throw ;
2751: : close-output ( -- ) fd-out close-file throw ;
2752: @end example
2753:
2754: @quotation Assignment
2755: How could you modify @code{copy-file} so that it copies until a second line is
2756: matched? Can you write a program that extracts a section of a text file,
2757: given the line that starts and the line that terminates that section?
2758: @end quotation
2759:
2760: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
2761: @section Interpretation and Compilation Semantics and Immediacy
2762: @cindex semantics tutorial
2763: @cindex interpretation semantics tutorial
2764: @cindex compilation semantics tutorial
2765: @cindex immediate, tutorial
2766:
2767: When a word is compiled, it behaves differently from being interpreted.
2768: E.g., consider @code{+}:
2769:
2770: @example
2771: 1 2 + .
2772: : foo + ;
2773: @end example
2774:
2775: These two behaviours are known as compilation and interpretation
2776: semantics. For normal words (e.g., @code{+}), the compilation semantics
2777: is to append the interpretation semantics to the currently defined word
2778: (@code{foo} in the example above). I.e., when @code{foo} is executed
2779: later, the interpretation semantics of @code{+} (i.e., adding two
2780: numbers) will be performed.
2781:
2782: However, there are words with non-default compilation semantics, e.g.,
2783: the control-flow words like @code{if}. You can use @code{immediate} to
2784: change the compilation semantics of the last defined word to be equal to
2785: the interpretation semantics:
2786:
2787: @example
2788: : [FOO] ( -- )
2789: 5 . ; immediate
2790:
2791: [FOO]
2792: : bar ( -- )
2793: [FOO] ;
2794: bar
2795: see bar
2796: @end example
2797:
2798: Two conventions to mark words with non-default compilation semantics are
2799: names with brackets (more frequently used) and to write them all in
2800: upper case (less frequently used).
2801:
2802: In Gforth (and many other systems) you can also remove the
2803: interpretation semantics with @code{compile-only} (the compilation
2804: semantics is derived from the original interpretation semantics):
2805:
2806: @example
2807: : flip ( -- )
2808: 6 . ; compile-only \ but not immediate
2809: flip
2810:
2811: : flop ( -- )
2812: flip ;
2813: flop
2814: @end example
2815:
2816: In this example the interpretation semantics of @code{flop} is equal to
2817: the original interpretation semantics of @code{flip}.
2818:
2819: The text interpreter has two states: in interpret state, it performs the
2820: interpretation semantics of words it encounters; in compile state, it
2821: performs the compilation semantics of these words.
2822:
2823: Among other things, @code{:} switches into compile state, and @code{;}
2824: switches back to interpret state. They contain the factors @code{]}
2825: (switch to compile state) and @code{[} (switch to interpret state), that
2826: do nothing but switch the state.
2827:
2828: @example
2829: : xxx ( -- )
2830: [ 5 . ]
2831: ;
2832:
2833: xxx
2834: see xxx
2835: @end example
2836:
2837: These brackets are also the source of the naming convention mentioned
2838: above.
2839:
2840: Reference: @ref{Interpretation and Compilation Semantics}.
2841:
2842:
2843: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2844: @section Execution Tokens
2845: @cindex execution tokens tutorial
2846: @cindex XT tutorial
2847:
2848: @code{' word} gives you the execution token (XT) of a word. The XT is a
2849: cell representing the interpretation semantics of a word. You can
2850: execute this semantics with @code{execute}:
2851:
2852: @example
2853: ' + .s
2854: 1 2 rot execute .
2855: @end example
2856:
2857: The XT is similar to a function pointer in C. However, parameter
2858: passing through the stack makes it a little more flexible:
2859:
2860: @example
2861: : map-array ( ... addr u xt -- ... )
2862: \ executes xt ( ... x -- ... ) for every element of the array starting
2863: \ at addr and containing u elements
2864: @{ xt @}
2865: cells over + swap ?do
2866: i @@ xt execute
2867: 1 cells +loop ;
2868:
2869: create a 3 , 4 , 2 , -1 , 4 ,
2870: a 5 ' . map-array .s
2871: 0 a 5 ' + map-array .
2872: s" max-n" environment? drop .s
2873: a 5 ' min map-array .
2874: @end example
2875:
2876: You can use map-array with the XTs of words that consume one element
2877: more than they produce. In theory you can also use it with other XTs,
2878: but the stack effect then depends on the size of the array, which is
2879: hard to understand.
2880:
2881: Since XTs are cell-sized, you can store them in memory and manipulate
2882: them on the stack like other cells. You can also compile the XT into a
2883: word with @code{compile,}:
2884:
2885: @example
2886: : foo1 ( n1 n2 -- n )
2887: [ ' + compile, ] ;
2888: see foo
2889: @end example
2890:
2891: This is non-standard, because @code{compile,} has no compilation
2892: semantics in the standard, but it works in good Forth systems. For the
2893: broken ones, use
2894:
2895: @example
2896: : [compile,] compile, ; immediate
2897:
2898: : foo1 ( n1 n2 -- n )
2899: [ ' + ] [compile,] ;
2900: see foo
2901: @end example
2902:
2903: @code{'} is a word with default compilation semantics; it parses the
2904: next word when its interpretation semantics are executed, not during
2905: compilation:
2906:
2907: @example
2908: : foo ( -- xt )
2909: ' ;
2910: see foo
2911: : bar ( ... "word" -- ... )
2912: ' execute ;
2913: see bar
2914: 1 2 bar + .
2915: @end example
2916:
2917: You often want to parse a word during compilation and compile its XT so
2918: it will be pushed on the stack at run-time. @code{[']} does this:
2919:
2920: @example
2921: : xt-+ ( -- xt )
2922: ['] + ;
2923: see xt-+
2924: 1 2 xt-+ execute .
2925: @end example
2926:
2927: Many programmers tend to see @code{'} and the word it parses as one
2928: unit, and expect it to behave like @code{[']} when compiled, and are
2929: confused by the actual behaviour. If you are, just remember that the
2930: Forth system just takes @code{'} as one unit and has no idea that it is
2931: a parsing word (attempts to convenience programmers in this issue have
2932: usually resulted in even worse pitfalls, see
2933: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2934: @code{State}-smartness---Why it is evil and How to Exorcise it}).
2935:
2936: Note that the state of the interpreter does not come into play when
2937: creating and executing XTs. I.e., even when you execute @code{'} in
2938: compile state, it still gives you the interpretation semantics. And
2939: whatever that state is, @code{execute} performs the semantics
2940: represented by the XT (i.e., for XTs produced with @code{'} the
2941: interpretation semantics).
2942:
2943: Reference: @ref{Tokens for Words}.
2944:
2945:
2946: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2947: @section Exceptions
2948: @cindex exceptions tutorial
2949:
2950: @code{throw ( n -- )} causes an exception unless n is zero.
2951:
2952: @example
2953: 100 throw .s
2954: 0 throw .s
2955: @end example
2956:
2957: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2958: it catches exceptions and pushes the number of the exception on the
2959: stack (or 0, if the xt executed without exception). If there was an
2960: exception, the stacks have the same depth as when entering @code{catch}:
2961:
2962: @example
2963: .s
2964: 3 0 ' / catch .s
2965: 3 2 ' / catch .s
2966: @end example
2967:
2968: @quotation Assignment
2969: Try the same with @code{execute} instead of @code{catch}.
2970: @end quotation
2971:
2972: @code{Throw} always jumps to the dynamically next enclosing
2973: @code{catch}, even if it has to leave several call levels to achieve
2974: this:
2975:
2976: @example
2977: : foo 100 throw ;
2978: : foo1 foo ." after foo" ;
2979: : bar ['] foo1 catch ;
2980: bar .
2981: @end example
2982:
2983: It is often important to restore a value upon leaving a definition, even
2984: if the definition is left through an exception. You can ensure this
2985: like this:
2986:
2987: @example
2988: : ...
2989: save-x
2990: ['] word-changing-x catch ( ... n )
2991: restore-x
2992: ( ... n ) throw ;
2993: @end example
2994:
2995: However, this is still not safe against, e.g., the user pressing
2996: @kbd{Ctrl-C} when execution is between the @code{catch} and
2997: @code{restore-x}.
2998:
2999: Gforth provides an alternative exception handling syntax that is safe
3000: against such cases: @code{try ... restore ... endtry}. If the code
3001: between @code{try} and @code{endtry} has an exception, the stack
3002: depths are restored, the exception number is pushed on the stack, and
3003: the execution continues right after @code{restore}.
3004:
3005: The safer equivalent to the restoration code above is
3006:
3007: @example
3008: : ...
3009: save-x
3010: try
3011: word-changing-x 0
3012: restore
3013: restore-x
3014: endtry
3015: throw ;
3016: @end example
3017:
3018: Reference: @ref{Exception Handling}.
3019:
3020:
3021: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
3022: @section Defining Words
3023: @cindex defining words tutorial
3024: @cindex does> tutorial
3025: @cindex create...does> tutorial
3026:
3027: @c before semantics?
3028:
3029: @code{:}, @code{create}, and @code{variable} are definition words: They
3030: define other words. @code{Constant} is another definition word:
3031:
3032: @example
3033: 5 constant foo
3034: foo .
3035: @end example
3036:
3037: You can also use the prefixes @code{2} (double-cell) and @code{f}
3038: (floating point) with @code{variable} and @code{constant}.
3039:
3040: You can also define your own defining words. E.g.:
3041:
3042: @example
3043: : variable ( "name" -- )
3044: create 0 , ;
3045: @end example
3046:
3047: You can also define defining words that create words that do something
3048: other than just producing their address:
3049:
3050: @example
3051: : constant ( n "name" -- )
3052: create ,
3053: does> ( -- n )
3054: ( addr ) @@ ;
3055:
3056: 5 constant foo
3057: foo .
3058: @end example
3059:
3060: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3061: @code{does>} replaces @code{;}, but it also does something else: It
3062: changes the last defined word such that it pushes the address of the
3063: body of the word and then performs the code after the @code{does>}
3064: whenever it is called.
3065:
3066: In the example above, @code{constant} uses @code{,} to store 5 into the
3067: body of @code{foo}. When @code{foo} executes, it pushes the address of
3068: the body onto the stack, then (in the code after the @code{does>})
3069: fetches the 5 from there.
3070:
3071: The stack comment near the @code{does>} reflects the stack effect of the
3072: defined word, not the stack effect of the code after the @code{does>}
3073: (the difference is that the code expects the address of the body that
3074: the stack comment does not show).
3075:
3076: You can use these definition words to do factoring in cases that involve
3077: (other) definition words. E.g., a field offset is always added to an
3078: address. Instead of defining
3079:
3080: @example
3081: 2 cells constant offset-field1
3082: @end example
3083:
3084: and using this like
3085:
3086: @example
3087: ( addr ) offset-field1 +
3088: @end example
3089:
3090: you can define a definition word
3091:
3092: @example
3093: : simple-field ( n "name" -- )
3094: create ,
3095: does> ( n1 -- n1+n )
3096: ( addr ) @@ + ;
3097: @end example
3098:
3099: Definition and use of field offsets now look like this:
3100:
3101: @example
3102: 2 cells simple-field field1
3103: create mystruct 4 cells allot
3104: mystruct .s field1 .s drop
3105: @end example
3106:
3107: If you want to do something with the word without performing the code
3108: after the @code{does>}, you can access the body of a @code{create}d word
3109: with @code{>body ( xt -- addr )}:
3110:
3111: @example
3112: : value ( n "name" -- )
3113: create ,
3114: does> ( -- n1 )
3115: @@ ;
3116: : to ( n "name" -- )
3117: ' >body ! ;
3118:
3119: 5 value foo
3120: foo .
3121: 7 to foo
3122: foo .
3123: @end example
3124:
3125: @quotation Assignment
3126: Define @code{defer ( "name" -- )}, which creates a word that stores an
3127: XT (at the start the XT of @code{abort}), and upon execution
3128: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3129: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3130: recursion is one application of @code{defer}.
3131: @end quotation
3132:
3133: Reference: @ref{User-defined Defining Words}.
3134:
3135:
3136: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3137: @section Arrays and Records
3138: @cindex arrays tutorial
3139: @cindex records tutorial
3140: @cindex structs tutorial
3141:
3142: Forth has no standard words for defining data structures such as arrays
3143: and records (structs in C terminology), but you can build them yourself
3144: based on address arithmetic. You can also define words for defining
3145: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
3146:
3147: One of the first projects a Forth newcomer sets out upon when learning
3148: about defining words is an array defining word (possibly for
3149: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3150: learn something from it. However, don't be disappointed when you later
3151: learn that you have little use for these words (inappropriate use would
3152: be even worse). I have not found a set of useful array words yet;
3153: the needs are just too diverse, and named, global arrays (the result of
3154: naive use of defining words) are often not flexible enough (e.g.,
3155: consider how to pass them as parameters). Another such project is a set
3156: of words to help dealing with strings.
3157:
3158: On the other hand, there is a useful set of record words, and it has
3159: been defined in @file{compat/struct.fs}; these words are predefined in
3160: Gforth. They are explained in depth elsewhere in this manual (see
3161: @pxref{Structures}). The @code{simple-field} example above is
3162: simplified variant of fields in this package.
3163:
3164:
3165: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3166: @section @code{POSTPONE}
3167: @cindex postpone tutorial
3168:
3169: You can compile the compilation semantics (instead of compiling the
3170: interpretation semantics) of a word with @code{POSTPONE}:
3171:
3172: @example
3173: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3174: POSTPONE + ; immediate
3175: : foo ( n1 n2 -- n )
3176: MY-+ ;
3177: 1 2 foo .
3178: see foo
3179: @end example
3180:
3181: During the definition of @code{foo} the text interpreter performs the
3182: compilation semantics of @code{MY-+}, which performs the compilation
3183: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3184:
3185: This example also displays separate stack comments for the compilation
3186: semantics and for the stack effect of the compiled code. For words with
3187: default compilation semantics these stack effects are usually not
3188: displayed; the stack effect of the compilation semantics is always
3189: @code{( -- )} for these words, the stack effect for the compiled code is
3190: the stack effect of the interpretation semantics.
3191:
3192: Note that the state of the interpreter does not come into play when
3193: performing the compilation semantics in this way. You can also perform
3194: it interpretively, e.g.:
3195:
3196: @example
3197: : foo2 ( n1 n2 -- n )
3198: [ MY-+ ] ;
3199: 1 2 foo .
3200: see foo
3201: @end example
3202:
3203: However, there are some broken Forth systems where this does not always
3204: work, and therefore this practice was been declared non-standard in
3205: 1999.
3206: @c !! repair.fs
3207:
3208: Here is another example for using @code{POSTPONE}:
3209:
3210: @example
3211: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3212: POSTPONE negate POSTPONE + ; immediate compile-only
3213: : bar ( n1 n2 -- n )
3214: MY-- ;
3215: 2 1 bar .
3216: see bar
3217: @end example
3218:
3219: You can define @code{ENDIF} in this way:
3220:
3221: @example
3222: : ENDIF ( Compilation: orig -- )
3223: POSTPONE then ; immediate
3224: @end example
3225:
3226: @quotation Assignment
3227: Write @code{MY-2DUP} that has compilation semantics equivalent to
3228: @code{2dup}, but compiles @code{over over}.
3229: @end quotation
3230:
3231: @c !! @xref{Macros} for reference
3232:
3233:
3234: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3235: @section @code{Literal}
3236: @cindex literal tutorial
3237:
3238: You cannot @code{POSTPONE} numbers:
3239:
3240: @example
3241: : [FOO] POSTPONE 500 ; immediate
3242: @end example
3243:
3244: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
3245:
3246: @example
3247: : [FOO] ( compilation: --; run-time: -- n )
3248: 500 POSTPONE literal ; immediate
3249:
3250: : flip [FOO] ;
3251: flip .
3252: see flip
3253: @end example
3254:
3255: @code{LITERAL} consumes a number at compile-time (when it's compilation
3256: semantics are executed) and pushes it at run-time (when the code it
3257: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3258: number computed at compile time into the current word:
3259:
3260: @example
3261: : bar ( -- n )
3262: [ 2 2 + ] literal ;
3263: see bar
3264: @end example
3265:
3266: @quotation Assignment
3267: Write @code{]L} which allows writing the example above as @code{: bar (
3268: -- n ) [ 2 2 + ]L ;}
3269: @end quotation
3270:
3271: @c !! @xref{Macros} for reference
3272:
3273:
3274: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3275: @section Advanced macros
3276: @cindex macros, advanced tutorial
3277: @cindex run-time code generation, tutorial
3278:
3279: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3280: Execution Tokens}. It frequently performs @code{execute}, a relatively
3281: expensive operation in some Forth implementations. You can use
3282: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3283: and produce a word that contains the word to be performed directly:
3284:
3285: @c use ]] ... [[
3286: @example
3287: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3288: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3289: \ array beginning at addr and containing u elements
3290: @{ xt @}
3291: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
3292: POSTPONE i POSTPONE @@ xt compile,
3293: 1 cells POSTPONE literal POSTPONE +loop ;
3294:
3295: : sum-array ( addr u -- n )
3296: 0 rot rot [ ' + compile-map-array ] ;
3297: see sum-array
3298: a 5 sum-array .
3299: @end example
3300:
3301: You can use the full power of Forth for generating the code; here's an
3302: example where the code is generated in a loop:
3303:
3304: @example
3305: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3306: \ n2=n1+(addr1)*n, addr2=addr1+cell
3307: POSTPONE tuck POSTPONE @@
3308: POSTPONE literal POSTPONE * POSTPONE +
3309: POSTPONE swap POSTPONE cell+ ;
3310:
3311: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
3312: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
3313: 0 postpone literal postpone swap
3314: [ ' compile-vmul-step compile-map-array ]
3315: postpone drop ;
3316: see compile-vmul
3317:
3318: : a-vmul ( addr -- n )
3319: \ n=a*v, where v is a vector that's as long as a and starts at addr
3320: [ a 5 compile-vmul ] ;
3321: see a-vmul
3322: a a-vmul .
3323: @end example
3324:
3325: This example uses @code{compile-map-array} to show off, but you could
3326: also use @code{map-array} instead (try it now!).
3327:
3328: You can use this technique for efficient multiplication of large
3329: matrices. In matrix multiplication, you multiply every line of one
3330: matrix with every column of the other matrix. You can generate the code
3331: for one line once, and use it for every column. The only downside of
3332: this technique is that it is cumbersome to recover the memory consumed
3333: by the generated code when you are done (and in more complicated cases
3334: it is not possible portably).
3335:
3336: @c !! @xref{Macros} for reference
3337:
3338:
3339: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3340: @section Compilation Tokens
3341: @cindex compilation tokens, tutorial
3342: @cindex CT, tutorial
3343:
3344: This section is Gforth-specific. You can skip it.
3345:
3346: @code{' word compile,} compiles the interpretation semantics. For words
3347: with default compilation semantics this is the same as performing the
3348: compilation semantics. To represent the compilation semantics of other
3349: words (e.g., words like @code{if} that have no interpretation
3350: semantics), Gforth has the concept of a compilation token (CT,
3351: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3352: You can perform the compilation semantics represented by a CT with
3353: @code{execute}:
3354:
3355: @example
3356: : foo2 ( n1 n2 -- n )
3357: [ comp' + execute ] ;
3358: see foo
3359: @end example
3360:
3361: You can compile the compilation semantics represented by a CT with
3362: @code{postpone,}:
3363:
3364: @example
3365: : foo3 ( -- )
3366: [ comp' + postpone, ] ;
3367: see foo3
3368: @end example
3369:
3370: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
3371: @code{comp'} is particularly useful for words that have no
3372: interpretation semantics:
3373:
3374: @example
3375: ' if
3376: comp' if .s 2drop
3377: @end example
3378:
3379: Reference: @ref{Tokens for Words}.
3380:
3381:
3382: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3383: @section Wordlists and Search Order
3384: @cindex wordlists tutorial
3385: @cindex search order, tutorial
3386:
3387: The dictionary is not just a memory area that allows you to allocate
3388: memory with @code{allot}, it also contains the Forth words, arranged in
3389: several wordlists. When searching for a word in a wordlist,
3390: conceptually you start searching at the youngest and proceed towards
3391: older words (in reality most systems nowadays use hash-tables); i.e., if
3392: you define a word with the same name as an older word, the new word
3393: shadows the older word.
3394:
3395: Which wordlists are searched in which order is determined by the search
3396: order. You can display the search order with @code{order}. It displays
3397: first the search order, starting with the wordlist searched first, then
3398: it displays the wordlist that will contain newly defined words.
3399:
3400: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
3401:
3402: @example
3403: wordlist constant mywords
3404: @end example
3405:
3406: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3407: defined words (the @emph{current} wordlist):
3408:
3409: @example
3410: mywords set-current
3411: order
3412: @end example
3413:
3414: Gforth does not display a name for the wordlist in @code{mywords}
3415: because this wordlist was created anonymously with @code{wordlist}.
3416:
3417: You can get the current wordlist with @code{get-current ( -- wid)}. If
3418: you want to put something into a specific wordlist without overall
3419: effect on the current wordlist, this typically looks like this:
3420:
3421: @example
3422: get-current mywords set-current ( wid )
3423: create someword
3424: ( wid ) set-current
3425: @end example
3426:
3427: You can write the search order with @code{set-order ( wid1 .. widn n --
3428: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3429: searched wordlist is topmost.
3430:
3431: @example
3432: get-order mywords swap 1+ set-order
3433: order
3434: @end example
3435:
3436: Yes, the order of wordlists in the output of @code{order} is reversed
3437: from stack comments and the output of @code{.s} and thus unintuitive.
3438:
3439: @quotation Assignment
3440: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3441: wordlist to the search order. Define @code{previous ( -- )}, which
3442: removes the first searched wordlist from the search order. Experiment
3443: with boundary conditions (you will see some crashes or situations that
3444: are hard or impossible to leave).
3445: @end quotation
3446:
3447: The search order is a powerful foundation for providing features similar
3448: to Modula-2 modules and C++ namespaces. However, trying to modularize
3449: programs in this way has disadvantages for debugging and reuse/factoring
3450: that overcome the advantages in my experience (I don't do huge projects,
3451: though). These disadvantages are not so clear in other
3452: languages/programming environments, because these languages are not so
3453: strong in debugging and reuse.
3454:
3455: @c !! example
3456:
3457: Reference: @ref{Word Lists}.
3458:
3459: @c ******************************************************************
3460: @node Introduction, Words, Tutorial, Top
3461: @comment node-name, next, previous, up
3462: @chapter An Introduction to ANS Forth
3463: @cindex Forth - an introduction
3464:
3465: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3466: that it is slower-paced in its examples, but uses them to dive deep into
3467: explaining Forth internals (not covered by the Tutorial). Apart from
3468: that, this chapter covers far less material. It is suitable for reading
3469: without using a computer.
3470:
3471: The primary purpose of this manual is to document Gforth. However, since
3472: Forth is not a widely-known language and there is a lack of up-to-date
3473: teaching material, it seems worthwhile to provide some introductory
3474: material. For other sources of Forth-related
3475: information, see @ref{Forth-related information}.
3476:
3477: The examples in this section should work on any ANS Forth; the
3478: output shown was produced using Gforth. Each example attempts to
3479: reproduce the exact output that Gforth produces. If you try out the
3480: examples (and you should), what you should type is shown @kbd{like this}
3481: and Gforth's response is shown @code{like this}. The single exception is
3482: that, where the example shows @key{RET} it means that you should
3483: press the ``carriage return'' key. Unfortunately, some output formats for
3484: this manual cannot show the difference between @kbd{this} and
3485: @code{this} which will make trying out the examples harder (but not
3486: impossible).
3487:
3488: Forth is an unusual language. It provides an interactive development
3489: environment which includes both an interpreter and compiler. Forth
3490: programming style encourages you to break a problem down into many
3491: @cindex factoring
3492: small fragments (@dfn{factoring}), and then to develop and test each
3493: fragment interactively. Forth advocates assert that breaking the
3494: edit-compile-test cycle used by conventional programming languages can
3495: lead to great productivity improvements.
3496:
3497: @menu
3498: * Introducing the Text Interpreter::
3499: * Stacks and Postfix notation::
3500: * Your first definition::
3501: * How does that work?::
3502: * Forth is written in Forth::
3503: * Review - elements of a Forth system::
3504: * Where to go next::
3505: * Exercises::
3506: @end menu
3507:
3508: @comment ----------------------------------------------
3509: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3510: @section Introducing the Text Interpreter
3511: @cindex text interpreter
3512: @cindex outer interpreter
3513:
3514: @c IMO this is too detailed and the pace is too slow for
3515: @c an introduction. If you know German, take a look at
3516: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3517: @c to see how I do it - anton
3518:
3519: @c nac-> Where I have accepted your comments 100% and modified the text
3520: @c accordingly, I have deleted your comments. Elsewhere I have added a
3521: @c response like this to attempt to rationalise what I have done. Of
3522: @c course, this is a very clumsy mechanism for something that would be
3523: @c done far more efficiently over a beer. Please delete any dialogue
3524: @c you consider closed.
3525:
3526: When you invoke the Forth image, you will see a startup banner printed
3527: and nothing else (if you have Gforth installed on your system, try
3528: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
3529: its command line interpreter, which is called the @dfn{Text Interpreter}
3530: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
3531: about the text interpreter as you read through this chapter, for more
3532: detail @pxref{The Text Interpreter}).
3533:
3534: Although it's not obvious, Forth is actually waiting for your
3535: input. Type a number and press the @key{RET} key:
3536:
3537: @example
3538: @kbd{45@key{RET}} ok
3539: @end example
3540:
3541: Rather than give you a prompt to invite you to input something, the text
3542: interpreter prints a status message @i{after} it has processed a line
3543: of input. The status message in this case (``@code{ ok}'' followed by
3544: carriage-return) indicates that the text interpreter was able to process
3545: all of your input successfully. Now type something illegal:
3546:
3547: @example
3548: @kbd{qwer341@key{RET}}
3549: *the terminal*:2: Undefined word
3550: >>>qwer341<<<
3551: Backtrace:
3552: $2A95B42A20 throw
3553: $2A95B57FB8 no.extensions
3554: @end example
3555:
3556: The exact text, other than the ``Undefined word'' may differ slightly
3557: on your system, but the effect is the same; when the text interpreter
3558: detects an error, it discards any remaining text on a line, resets
3559: certain internal state and prints an error message. For a detailed
3560: description of error messages see @ref{Error messages}.
3561:
3562: The text interpreter waits for you to press carriage-return, and then
3563: processes your input line. Starting at the beginning of the line, it
3564: breaks the line into groups of characters separated by spaces. For each
3565: group of characters in turn, it makes two attempts to do something:
3566:
3567: @itemize @bullet
3568: @item
3569: @cindex name dictionary
3570: It tries to treat it as a command. It does this by searching a @dfn{name
3571: dictionary}. If the group of characters matches an entry in the name
3572: dictionary, the name dictionary provides the text interpreter with
3573: information that allows the text interpreter perform some actions. In
3574: Forth jargon, we say that the group
3575: @cindex word
3576: @cindex definition
3577: @cindex execution token
3578: @cindex xt
3579: of characters names a @dfn{word}, that the dictionary search returns an
3580: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3581: word, and that the text interpreter executes the xt. Often, the terms
3582: @dfn{word} and @dfn{definition} are used interchangeably.
3583: @item
3584: If the text interpreter fails to find a match in the name dictionary, it
3585: tries to treat the group of characters as a number in the current number
3586: base (when you start up Forth, the current number base is base 10). If
3587: the group of characters legitimately represents a number, the text
3588: interpreter pushes the number onto a stack (we'll learn more about that
3589: in the next section).
3590: @end itemize
3591:
3592: If the text interpreter is unable to do either of these things with any
3593: group of characters, it discards the group of characters and the rest of
3594: the line, then prints an error message. If the text interpreter reaches
3595: the end of the line without error, it prints the status message ``@code{ ok}''
3596: followed by carriage-return.
3597:
3598: This is the simplest command we can give to the text interpreter:
3599:
3600: @example
3601: @key{RET} ok
3602: @end example
3603:
3604: The text interpreter did everything we asked it to do (nothing) without
3605: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3606: command:
3607:
3608: @example
3609: @kbd{12 dup fred dup@key{RET}}
3610: *the terminal*:3: Undefined word
3611: 12 dup >>>fred<<< dup
3612: Backtrace:
3613: $2A95B42A20 throw
3614: $2A95B57FB8 no.extensions
3615: @end example
3616:
3617: When you press the carriage-return key, the text interpreter starts to
3618: work its way along the line:
3619:
3620: @itemize @bullet
3621: @item
3622: When it gets to the space after the @code{2}, it takes the group of
3623: characters @code{12} and looks them up in the name
3624: dictionary@footnote{We can't tell if it found them or not, but assume
3625: for now that it did not}. There is no match for this group of characters
3626: in the name dictionary, so it tries to treat them as a number. It is
3627: able to do this successfully, so it puts the number, 12, ``on the stack''
3628: (whatever that means).
3629: @item
3630: The text interpreter resumes scanning the line and gets the next group
3631: of characters, @code{dup}. It looks it up in the name dictionary and
3632: (you'll have to take my word for this) finds it, and executes the word
3633: @code{dup} (whatever that means).
3634: @item
3635: Once again, the text interpreter resumes scanning the line and gets the
3636: group of characters @code{fred}. It looks them up in the name
3637: dictionary, but can't find them. It tries to treat them as a number, but
3638: they don't represent any legal number.
3639: @end itemize
3640:
3641: At this point, the text interpreter gives up and prints an error
3642: message. The error message shows exactly how far the text interpreter
3643: got in processing the line. In particular, it shows that the text
3644: interpreter made no attempt to do anything with the final character
3645: group, @code{dup}, even though we have good reason to believe that the
3646: text interpreter would have no problem looking that word up and
3647: executing it a second time.
3648:
3649:
3650: @comment ----------------------------------------------
3651: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3652: @section Stacks, postfix notation and parameter passing
3653: @cindex text interpreter
3654: @cindex outer interpreter
3655:
3656: In procedural programming languages (like C and Pascal), the
3657: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3658: functions or procedures are called with @dfn{explicit parameters}. For
3659: example, in C we might write:
3660:
3661: @example
3662: total = total + new_volume(length,height,depth);
3663: @end example
3664:
3665: @noindent
3666: where new_volume is a function-call to another piece of code, and total,
3667: length, height and depth are all variables. length, height and depth are
3668: parameters to the function-call.
3669:
3670: In Forth, the equivalent of the function or procedure is the
3671: @dfn{definition} and parameters are implicitly passed between
3672: definitions using a shared stack that is visible to the
3673: programmer. Although Forth does support variables, the existence of the
3674: stack means that they are used far less often than in most other
3675: programming languages. When the text interpreter encounters a number, it
3676: will place (@dfn{push}) it on the stack. There are several stacks (the
3677: actual number is implementation-dependent ...) and the particular stack
3678: used for any operation is implied unambiguously by the operation being
3679: performed. The stack used for all integer operations is called the @dfn{data
3680: stack} and, since this is the stack used most commonly, references to
3681: ``the data stack'' are often abbreviated to ``the stack''.
3682:
3683: The stacks have a last-in, first-out (LIFO) organisation. If you type:
3684:
3685: @example
3686: @kbd{1 2 3@key{RET}} ok
3687: @end example
3688:
3689: Then this instructs the text interpreter to placed three numbers on the
3690: (data) stack. An analogy for the behaviour of the stack is to take a
3691: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3692: the table. The 3 was the last card onto the pile (``last-in'') and if
3693: you take a card off the pile then, unless you're prepared to fiddle a
3694: bit, the card that you take off will be the 3 (``first-out''). The
3695: number that will be first-out of the stack is called the @dfn{top of
3696: stack}, which
3697: @cindex TOS definition
3698: is often abbreviated to @dfn{TOS}.
3699:
3700: To understand how parameters are passed in Forth, consider the
3701: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3702: be surprised to learn that this definition performs addition. More
3703: precisely, it adds two number together and produces a result. Where does
3704: it get the two numbers from? It takes the top two numbers off the
3705: stack. Where does it place the result? On the stack. You can act-out the
3706: behaviour of @code{+} with your playing cards like this:
3707:
3708: @itemize @bullet
3709: @item
3710: Pick up two cards from the stack on the table
3711: @item
3712: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3713: numbers''
3714: @item
3715: Decide that the answer is 5
3716: @item
3717: Shuffle the two cards back into the pack and find a 5
3718: @item
3719: Put a 5 on the remaining ace that's on the table.
3720: @end itemize
3721:
3722: If you don't have a pack of cards handy but you do have Forth running,
3723: you can use the definition @code{.s} to show the current state of the stack,
3724: without affecting the stack. Type:
3725:
3726: @example
3727: @kbd{clearstacks 1 2 3@key{RET}} ok
3728: @kbd{.s@key{RET}} <3> 1 2 3 ok
3729: @end example
3730:
3731: The text interpreter looks up the word @code{clearstacks} and executes
3732: it; it tidies up the stacks and removes any entries that may have been
3733: left on it by earlier examples. The text interpreter pushes each of the
3734: three numbers in turn onto the stack. Finally, the text interpreter
3735: looks up the word @code{.s} and executes it. The effect of executing
3736: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3737: followed by a list of all the items on the stack; the item on the far
3738: right-hand side is the TOS.
3739:
3740: You can now type:
3741:
3742: @example
3743: @kbd{+ .s@key{RET}} <2> 1 5 ok
3744: @end example
3745:
3746: @noindent
3747: which is correct; there are now 2 items on the stack and the result of
3748: the addition is 5.
3749:
3750: If you're playing with cards, try doing a second addition: pick up the
3751: two cards, work out that their sum is 6, shuffle them into the pack,
3752: look for a 6 and place that on the table. You now have just one item on
3753: the stack. What happens if you try to do a third addition? Pick up the
3754: first card, pick up the second card -- ah! There is no second card. This
3755: is called a @dfn{stack underflow} and consitutes an error. If you try to
3756: do the same thing with Forth it often reports an error (probably a Stack
3757: Underflow or an Invalid Memory Address error).
3758:
3759: The opposite situation to a stack underflow is a @dfn{stack overflow},
3760: which simply accepts that there is a finite amount of storage space
3761: reserved for the stack. To stretch the playing card analogy, if you had
3762: enough packs of cards and you piled the cards up on the table, you would
3763: eventually be unable to add another card; you'd hit the ceiling. Gforth
3764: allows you to set the maximum size of the stacks. In general, the only
3765: time that you will get a stack overflow is because a definition has a
3766: bug in it and is generating data on the stack uncontrollably.
3767:
3768: There's one final use for the playing card analogy. If you model your
3769: stack using a pack of playing cards, the maximum number of items on
3770: your stack will be 52 (I assume you didn't use the Joker). The maximum
3771: @i{value} of any item on the stack is 13 (the King). In fact, the only
3772: possible numbers are positive integer numbers 1 through 13; you can't
3773: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3774: think about some of the cards, you can accommodate different
3775: numbers. For example, you could think of the Jack as representing 0,
3776: the Queen as representing -1 and the King as representing -2. Your
3777: @i{range} remains unchanged (you can still only represent a total of 13
3778: numbers) but the numbers that you can represent are -2 through 10.
3779:
3780: In that analogy, the limit was the amount of information that a single
3781: stack entry could hold, and Forth has a similar limit. In Forth, the
3782: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3783: implementation dependent and affects the maximum value that a stack
3784: entry can hold. A Standard Forth provides a cell size of at least
3785: 16-bits, and most desktop systems use a cell size of 32-bits.
3786:
3787: Forth does not do any type checking for you, so you are free to
3788: manipulate and combine stack items in any way you wish. A convenient way
3789: of treating stack items is as 2's complement signed integers, and that
3790: is what Standard words like @code{+} do. Therefore you can type:
3791:
3792: @example
3793: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
3794: @end example
3795:
3796: If you use numbers and definitions like @code{+} in order to turn Forth
3797: into a great big pocket calculator, you will realise that it's rather
3798: different from a normal calculator. Rather than typing 2 + 3 = you had
3799: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3800: result). The terminology used to describe this difference is to say that
3801: your calculator uses @dfn{Infix Notation} (parameters and operators are
3802: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3803: operators are separate), also called @dfn{Reverse Polish Notation}.
3804:
3805: Whilst postfix notation might look confusing to begin with, it has
3806: several important advantages:
3807:
3808: @itemize @bullet
3809: @item
3810: it is unambiguous
3811: @item
3812: it is more concise
3813: @item
3814: it fits naturally with a stack-based system
3815: @end itemize
3816:
3817: To examine these claims in more detail, consider these sums:
3818:
3819: @example
3820: 6 + 5 * 4 =
3821: 4 * 5 + 6 =
3822: @end example
3823:
3824: If you're just learning maths or your maths is very rusty, you will
3825: probably come up with the answer 44 for the first and 26 for the
3826: second. If you are a bit of a whizz at maths you will remember the
3827: @i{convention} that multiplication takes precendence over addition, and
3828: you'd come up with the answer 26 both times. To explain the answer 26
3829: to someone who got the answer 44, you'd probably rewrite the first sum
3830: like this:
3831:
3832: @example
3833: 6 + (5 * 4) =
3834: @end example
3835:
3836: If what you really wanted was to perform the addition before the
3837: multiplication, you would have to use parentheses to force it.
3838:
3839: If you did the first two sums on a pocket calculator you would probably
3840: get the right answers, unless you were very cautious and entered them using
3841: these keystroke sequences:
3842:
3843: 6 + 5 = * 4 =
3844: 4 * 5 = + 6 =
3845:
3846: Postfix notation is unambiguous because the order that the operators
3847: are applied is always explicit; that also means that parentheses are
3848: never required. The operators are @i{active} (the act of quoting the
3849: operator makes the operation occur) which removes the need for ``=''.
3850:
3851: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3852: equivalent ways:
3853:
3854: @example
3855: 6 5 4 * + or:
3856: 5 4 * 6 +
3857: @end example
3858:
3859: An important thing that you should notice about this notation is that
3860: the @i{order} of the numbers does not change; if you want to subtract
3861: 2 from 10 you type @code{10 2 -}.
3862:
3863: The reason that Forth uses postfix notation is very simple to explain: it
3864: makes the implementation extremely simple, and it follows naturally from
3865: using the stack as a mechanism for passing parameters. Another way of
3866: thinking about this is to realise that all Forth definitions are
3867: @i{active}; they execute as they are encountered by the text
3868: interpreter. The result of this is that the syntax of Forth is trivially
3869: simple.
3870:
3871:
3872:
3873: @comment ----------------------------------------------
3874: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3875: @section Your first Forth definition
3876: @cindex first definition
3877:
3878: Until now, the examples we've seen have been trivial; we've just been
3879: using Forth as a bigger-than-pocket calculator. Also, each calculation
3880: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3881: again@footnote{That's not quite true. If you press the up-arrow key on
3882: your keyboard you should be able to scroll back to any earlier command,
3883: edit it and re-enter it.} In this section we'll see how to add new
3884: words to Forth's vocabulary.
3885:
3886: The easiest way to create a new word is to use a @dfn{colon
3887: definition}. We'll define a few and try them out before worrying too
3888: much about how they work. Try typing in these examples; be careful to
3889: copy the spaces accurately:
3890:
3891: @example
3892: : add-two 2 + . ;
3893: : greet ." Hello and welcome" ;
3894: : demo 5 add-two ;
3895: @end example
3896:
3897: @noindent
3898: Now try them out:
3899:
3900: @example
3901: @kbd{greet@key{RET}} Hello and welcome ok
3902: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3903: @kbd{4 add-two@key{RET}} 6 ok
3904: @kbd{demo@key{RET}} 7 ok
3905: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
3906: @end example
3907:
3908: The first new thing that we've introduced here is the pair of words
3909: @code{:} and @code{;}. These are used to start and terminate a new
3910: definition, respectively. The first word after the @code{:} is the name
3911: for the new definition.
3912:
3913: As you can see from the examples, a definition is built up of words that
3914: have already been defined; Forth makes no distinction between
3915: definitions that existed when you started the system up, and those that
3916: you define yourself.
3917:
3918: The examples also introduce the words @code{.} (dot), @code{."}
3919: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3920: the stack and displays it. It's like @code{.s} except that it only
3921: displays the top item of the stack and it is destructive; after it has
3922: executed, the number is no longer on the stack. There is always one
3923: space printed after the number, and no spaces before it. Dot-quote
3924: defines a string (a sequence of characters) that will be printed when
3925: the word is executed. The string can contain any printable characters
3926: except @code{"}. A @code{"} has a special function; it is not a Forth
3927: word but it acts as a delimiter (the way that delimiters work is
3928: described in the next section). Finally, @code{dup} duplicates the value
3929: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
3930:
3931: We already know that the text interpreter searches through the
3932: dictionary to locate names. If you've followed the examples earlier, you
3933: will already have a definition called @code{add-two}. Lets try modifying
3934: it by typing in a new definition:
3935:
3936: @example
3937: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
3938: @end example
3939:
3940: Forth recognised that we were defining a word that already exists, and
3941: printed a message to warn us of that fact. Let's try out the new
3942: definition:
3943:
3944: @example
3945: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
3946: @end example
3947:
3948: @noindent
3949: All that we've actually done here, though, is to create a new
3950: definition, with a particular name. The fact that there was already a
3951: definition with the same name did not make any difference to the way
3952: that the new definition was created (except that Forth printed a warning
3953: message). The old definition of add-two still exists (try @code{demo}
3954: again to see that this is true). Any new definition will use the new
3955: definition of @code{add-two}, but old definitions continue to use the
3956: version that already existed at the time that they were @code{compiled}.
3957:
3958: Before you go on to the next section, try defining and redefining some
3959: words of your own.
3960:
3961: @comment ----------------------------------------------
3962: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3963: @section How does that work?
3964: @cindex parsing words
3965:
3966: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3967:
3968: @c Is it a good idea to talk about the interpretation semantics of a
3969: @c number? We don't have an xt to go along with it. - anton
3970:
3971: @c Now that I have eliminated execution semantics, I wonder if it would not
3972: @c be better to keep them (or add run-time semantics), to make it easier to
3973: @c explain what compilation semantics usually does. - anton
3974:
3975: @c nac-> I removed the term ``default compilation sematics'' from the
3976: @c introductory chapter. Removing ``execution semantics'' was making
3977: @c everything simpler to explain, then I think the use of this term made
3978: @c everything more complex again. I replaced it with ``default
3979: @c semantics'' (which is used elsewhere in the manual) by which I mean
3980: @c ``a definition that has neither the immediate nor the compile-only
3981: @c flag set''.
3982:
3983: @c anton: I have eliminated default semantics (except in one place where it
3984: @c means "default interpretation and compilation semantics"), because it
3985: @c makes no sense in the presence of combined words. I reverted to
3986: @c "execution semantics" where necessary.
3987:
3988: @c nac-> I reworded big chunks of the ``how does that work''
3989: @c section (and, unusually for me, I think I even made it shorter!). See
3990: @c what you think -- I know I have not addressed your primary concern
3991: @c that it is too heavy-going for an introduction. From what I understood
3992: @c of your course notes it looks as though they might be a good framework.
3993: @c Things that I've tried to capture here are some things that came as a
3994: @c great revelation here when I first understood them. Also, I like the
3995: @c fact that a very simple code example shows up almost all of the issues
3996: @c that you need to understand to see how Forth works. That's unique and
3997: @c worthwhile to emphasise.
3998:
3999: @c anton: I think it's a good idea to present the details, especially those
4000: @c that you found to be a revelation, and probably the tutorial tries to be
4001: @c too superficial and does not get some of the things across that make
4002: @c Forth special. I do believe that most of the time these things should
4003: @c be discussed at the end of a section or in separate sections instead of
4004: @c in the middle of a section (e.g., the stuff you added in "User-defined
4005: @c defining words" leads in a completely different direction from the rest
4006: @c of the section).
4007:
4008: Now we're going to take another look at the definition of @code{add-two}
4009: from the previous section. From our knowledge of the way that the text
4010: interpreter works, we would have expected this result when we tried to
4011: define @code{add-two}:
4012:
4013: @example
4014: @kbd{: add-two 2 + . ;@key{RET}}
4015: *the terminal*:4: Undefined word
4016: : >>>add-two<<< 2 + . ;
4017: @end example
4018:
4019: The reason that this didn't happen is bound up in the way that @code{:}
4020: works. The word @code{:} does two special things. The first special
4021: thing that it does prevents the text interpreter from ever seeing the
4022: characters @code{add-two}. The text interpreter uses a variable called
4023: @cindex modifying >IN
4024: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
4025: input line. When it encounters the word @code{:} it behaves in exactly
4026: the same way as it does for any other word; it looks it up in the name
4027: dictionary, finds its xt and executes it. When @code{:} executes, it
4028: looks at the input buffer, finds the word @code{add-two} and advances the
4029: value of @code{>IN} to point past it. It then does some other stuff
4030: associated with creating the new definition (including creating an entry
4031: for @code{add-two} in the name dictionary). When the execution of @code{:}
4032: completes, control returns to the text interpreter, which is oblivious
4033: to the fact that it has been tricked into ignoring part of the input
4034: line.
4035:
4036: @cindex parsing words
4037: Words like @code{:} -- words that advance the value of @code{>IN} and so
4038: prevent the text interpreter from acting on the whole of the input line
4039: -- are called @dfn{parsing words}.
4040:
4041: @cindex @code{state} - effect on the text interpreter
4042: @cindex text interpreter - effect of state
4043: The second special thing that @code{:} does is change the value of a
4044: variable called @code{state}, which affects the way that the text
4045: interpreter behaves. When Gforth starts up, @code{state} has the value
4046: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4047: colon definition (started with @code{:}), @code{state} is set to -1 and
4048: the text interpreter is said to be @dfn{compiling}.
4049:
4050: In this example, the text interpreter is compiling when it processes the
4051: string ``@code{2 + . ;}''. It still breaks the string down into
4052: character sequences in the same way. However, instead of pushing the
4053: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4054: into the definition of @code{add-two} that will make the number @code{2} get
4055: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4056: the behaviours of @code{+} and @code{.} are also compiled into the
4057: definition.
4058:
4059: One category of words don't get compiled. These so-called @dfn{immediate
4060: words} get executed (performed @i{now}) regardless of whether the text
4061: interpreter is interpreting or compiling. The word @code{;} is an
4062: immediate word. Rather than being compiled into the definition, it
4063: executes. Its effect is to terminate the current definition, which
4064: includes changing the value of @code{state} back to 0.
4065:
4066: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4067: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4068: definition.
4069:
4070: In Forth, every word or number can be described in terms of two
4071: properties:
4072:
4073: @itemize @bullet
4074: @item
4075: @cindex interpretation semantics
4076: Its @dfn{interpretation semantics} describe how it will behave when the
4077: text interpreter encounters it in @dfn{interpret} state. The
4078: interpretation semantics of a word are represented by an @dfn{execution
4079: token}.
4080: @item
4081: @cindex compilation semantics
4082: Its @dfn{compilation semantics} describe how it will behave when the
4083: text interpreter encounters it in @dfn{compile} state. The compilation
4084: semantics of a word are represented in an implementation-dependent way;
4085: Gforth uses a @dfn{compilation token}.
4086: @end itemize
4087:
4088: @noindent
4089: Numbers are always treated in a fixed way:
4090:
4091: @itemize @bullet
4092: @item
4093: When the number is @dfn{interpreted}, its behaviour is to push the
4094: number onto the stack.
4095: @item
4096: When the number is @dfn{compiled}, a piece of code is appended to the
4097: current definition that pushes the number when it runs. (In other words,
4098: the compilation semantics of a number are to postpone its interpretation
4099: semantics until the run-time of the definition that it is being compiled
4100: into.)
4101: @end itemize
4102:
4103: Words don't behave in such a regular way, but most have @i{default
4104: semantics} which means that they behave like this:
4105:
4106: @itemize @bullet
4107: @item
4108: The @dfn{interpretation semantics} of the word are to do something useful.
4109: @item
4110: The @dfn{compilation semantics} of the word are to append its
4111: @dfn{interpretation semantics} to the current definition (so that its
4112: run-time behaviour is to do something useful).
4113: @end itemize
4114:
4115: @cindex immediate words
4116: The actual behaviour of any particular word can be controlled by using
4117: the words @code{immediate} and @code{compile-only} when the word is
4118: defined. These words set flags in the name dictionary entry of the most
4119: recently defined word, and these flags are retrieved by the text
4120: interpreter when it finds the word in the name dictionary.
4121:
4122: A word that is marked as @dfn{immediate} has compilation semantics that
4123: are identical to its interpretation semantics. In other words, it
4124: behaves like this:
4125:
4126: @itemize @bullet
4127: @item
4128: The @dfn{interpretation semantics} of the word are to do something useful.
4129: @item
4130: The @dfn{compilation semantics} of the word are to do something useful
4131: (and actually the same thing); i.e., it is executed during compilation.
4132: @end itemize
4133:
4134: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4135: performing the interpretation semantics of the word directly; an attempt
4136: to do so will generate an error. It is never necessary to use
4137: @code{compile-only} (and it is not even part of ANS Forth, though it is
4138: provided by many implementations) but it is good etiquette to apply it
4139: to a word that will not behave correctly (and might have unexpected
4140: side-effects) in interpret state. For example, it is only legal to use
4141: the conditional word @code{IF} within a definition. If you forget this
4142: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4143: @code{compile-only} allows the text interpreter to generate a helpful
4144: error message rather than subjecting you to the consequences of your
4145: folly.
4146:
4147: This example shows the difference between an immediate and a
4148: non-immediate word:
4149:
4150: @example
4151: : show-state state @@ . ;
4152: : show-state-now show-state ; immediate
4153: : word1 show-state ;
4154: : word2 show-state-now ;
4155: @end example
4156:
4157: The word @code{immediate} after the definition of @code{show-state-now}
4158: makes that word an immediate word. These definitions introduce a new
4159: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4160: variable, and leaves it on the stack. Therefore, the behaviour of
4161: @code{show-state} is to print a number that represents the current value
4162: of @code{state}.
4163:
4164: When you execute @code{word1}, it prints the number 0, indicating that
4165: the system is interpreting. When the text interpreter compiled the
4166: definition of @code{word1}, it encountered @code{show-state} whose
4167: compilation semantics are to append its interpretation semantics to the
4168: current definition. When you execute @code{word1}, it performs the
4169: interpretation semantics of @code{show-state}. At the time that @code{word1}
4170: (and therefore @code{show-state}) are executed, the system is
4171: interpreting.
4172:
4173: When you pressed @key{RET} after entering the definition of @code{word2},
4174: you should have seen the number -1 printed, followed by ``@code{
4175: ok}''. When the text interpreter compiled the definition of
4176: @code{word2}, it encountered @code{show-state-now}, an immediate word,
4177: whose compilation semantics are therefore to perform its interpretation
4178: semantics. It is executed straight away (even before the text
4179: interpreter has moved on to process another group of characters; the
4180: @code{;} in this example). The effect of executing it are to display the
4181: value of @code{state} @i{at the time that the definition of}
4182: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4183: system is compiling at this time. If you execute @code{word2} it does
4184: nothing at all.
4185:
4186: @cindex @code{."}, how it works
4187: Before leaving the subject of immediate words, consider the behaviour of
4188: @code{."} in the definition of @code{greet}, in the previous
4189: section. This word is both a parsing word and an immediate word. Notice
4190: that there is a space between @code{."} and the start of the text
4191: @code{Hello and welcome}, but that there is no space between the last
4192: letter of @code{welcome} and the @code{"} character. The reason for this
4193: is that @code{."} is a Forth word; it must have a space after it so that
4194: the text interpreter can identify it. The @code{"} is not a Forth word;
4195: it is a @dfn{delimiter}. The examples earlier show that, when the string
4196: is displayed, there is neither a space before the @code{H} nor after the
4197: @code{e}. Since @code{."} is an immediate word, it executes at the time
4198: that @code{greet} is defined. When it executes, its behaviour is to
4199: search forward in the input line looking for the delimiter. When it
4200: finds the delimiter, it updates @code{>IN} to point past the
4201: delimiter. It also compiles some magic code into the definition of
4202: @code{greet}; the xt of a run-time routine that prints a text string. It
4203: compiles the string @code{Hello and welcome} into memory so that it is
4204: available to be printed later. When the text interpreter gains control,
4205: the next word it finds in the input stream is @code{;} and so it
4206: terminates the definition of @code{greet}.
4207:
4208:
4209: @comment ----------------------------------------------
4210: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4211: @section Forth is written in Forth
4212: @cindex structure of Forth programs
4213:
4214: When you start up a Forth compiler, a large number of definitions
4215: already exist. In Forth, you develop a new application using bottom-up
4216: programming techniques to create new definitions that are defined in
4217: terms of existing definitions. As you create each definition you can
4218: test and debug it interactively.
4219:
4220: If you have tried out the examples in this section, you will probably
4221: have typed them in by hand; when you leave Gforth, your definitions will
4222: be lost. You can avoid this by using a text editor to enter Forth source
4223: code into a file, and then loading code from the file using
4224: @code{include} (@pxref{Forth source files}). A Forth source file is
4225: processed by the text interpreter, just as though you had typed it in by
4226: hand@footnote{Actually, there are some subtle differences -- see
4227: @ref{The Text Interpreter}.}.
4228:
4229: Gforth also supports the traditional Forth alternative to using text
4230: files for program entry (@pxref{Blocks}).
4231:
4232: In common with many, if not most, Forth compilers, most of Gforth is
4233: actually written in Forth. All of the @file{.fs} files in the
4234: installation directory@footnote{For example,
4235: @file{/usr/local/share/gforth...}} are Forth source files, which you can
4236: study to see examples of Forth programming.
4237:
4238: Gforth maintains a history file that records every line that you type to
4239: the text interpreter. This file is preserved between sessions, and is
4240: used to provide a command-line recall facility. If you enter long
4241: definitions by hand, you can use a text editor to paste them out of the
4242: history file into a Forth source file for reuse at a later time
4243: (for more information @pxref{Command-line editing}).
4244:
4245:
4246: @comment ----------------------------------------------
4247: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4248: @section Review - elements of a Forth system
4249: @cindex elements of a Forth system
4250:
4251: To summarise this chapter:
4252:
4253: @itemize @bullet
4254: @item
4255: Forth programs use @dfn{factoring} to break a problem down into small
4256: fragments called @dfn{words} or @dfn{definitions}.
4257: @item
4258: Forth program development is an interactive process.
4259: @item
4260: The main command loop that accepts input, and controls both
4261: interpretation and compilation, is called the @dfn{text interpreter}
4262: (also known as the @dfn{outer interpreter}).
4263: @item
4264: Forth has a very simple syntax, consisting of words and numbers
4265: separated by spaces or carriage-return characters. Any additional syntax
4266: is imposed by @dfn{parsing words}.
4267: @item
4268: Forth uses a stack to pass parameters between words. As a result, it
4269: uses postfix notation.
4270: @item
4271: To use a word that has previously been defined, the text interpreter
4272: searches for the word in the @dfn{name dictionary}.
4273: @item
4274: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
4275: @item
4276: The text interpreter uses the value of @code{state} to select between
4277: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4278: semantics} of a word that it encounters.
4279: @item
4280: The relationship between the @dfn{interpretation semantics} and
4281: @dfn{compilation semantics} for a word
4282: depend upon the way in which the word was defined (for example, whether
4283: it is an @dfn{immediate} word).
4284: @item
4285: Forth definitions can be implemented in Forth (called @dfn{high-level
4286: definitions}) or in some other way (usually a lower-level language and
4287: as a result often called @dfn{low-level definitions}, @dfn{code
4288: definitions} or @dfn{primitives}).
4289: @item
4290: Many Forth systems are implemented mainly in Forth.
4291: @end itemize
4292:
4293:
4294: @comment ----------------------------------------------
4295: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
4296: @section Where To Go Next
4297: @cindex where to go next
4298:
4299: Amazing as it may seem, if you have read (and understood) this far, you
4300: know almost all the fundamentals about the inner workings of a Forth
4301: system. You certainly know enough to be able to read and understand the
4302: rest of this manual and the ANS Forth document, to learn more about the
4303: facilities that Forth in general and Gforth in particular provide. Even
4304: scarier, you know almost enough to implement your own Forth system.
4305: However, that's not a good idea just yet... better to try writing some
4306: programs in Gforth.
4307:
4308: Forth has such a rich vocabulary that it can be hard to know where to
4309: start in learning it. This section suggests a few sets of words that are
4310: enough to write small but useful programs. Use the word index in this
4311: document to learn more about each word, then try it out and try to write
4312: small definitions using it. Start by experimenting with these words:
4313:
4314: @itemize @bullet
4315: @item
4316: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4317: @item
4318: Comparison: @code{MIN MAX =}
4319: @item
4320: Logic: @code{AND OR XOR NOT}
4321: @item
4322: Stack manipulation: @code{DUP DROP SWAP OVER}
4323: @item
4324: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
4325: @item
4326: Input/Output: @code{. ." EMIT CR KEY}
4327: @item
4328: Defining words: @code{: ; CREATE}
4329: @item
4330: Memory allocation words: @code{ALLOT ,}
4331: @item
4332: Tools: @code{SEE WORDS .S MARKER}
4333: @end itemize
4334:
4335: When you have mastered those, go on to:
4336:
4337: @itemize @bullet
4338: @item
4339: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
4340: @item
4341: Memory access: @code{@@ !}
4342: @end itemize
4343:
4344: When you have mastered these, there's nothing for it but to read through
4345: the whole of this manual and find out what you've missed.
4346:
4347: @comment ----------------------------------------------
4348: @node Exercises, , Where to go next, Introduction
4349: @section Exercises
4350: @cindex exercises
4351:
4352: TODO: provide a set of programming excercises linked into the stuff done
4353: already and into other sections of the manual. Provide solutions to all
4354: the exercises in a .fs file in the distribution.
4355:
4356: @c Get some inspiration from Starting Forth and Kelly&Spies.
4357:
4358: @c excercises:
4359: @c 1. take inches and convert to feet and inches.
4360: @c 2. take temperature and convert from fahrenheight to celcius;
4361: @c may need to care about symmetric vs floored??
4362: @c 3. take input line and do character substitution
4363: @c to encipher or decipher
4364: @c 4. as above but work on a file for in and out
4365: @c 5. take input line and convert to pig-latin
4366: @c
4367: @c thing of sets of things to exercise then come up with
4368: @c problems that need those things.
4369:
4370:
4371: @c ******************************************************************
4372: @node Words, Error messages, Introduction, Top
4373: @chapter Forth Words
4374: @cindex words
4375:
4376: @menu
4377: * Notation::
4378: * Case insensitivity::
4379: * Comments::
4380: * Boolean Flags::
4381: * Arithmetic::
4382: * Stack Manipulation::
4383: * Memory::
4384: * Control Structures::
4385: * Defining Words::
4386: * Interpretation and Compilation Semantics::
4387: * Tokens for Words::
4388: * Compiling words::
4389: * The Text Interpreter::
4390: * The Input Stream::
4391: * Word Lists::
4392: * Environmental Queries::
4393: * Files::
4394: * Blocks::
4395: * Other I/O::
4396: * OS command line arguments::
4397: * Locals::
4398: * Structures::
4399: * Object-oriented Forth::
4400: * Programming Tools::
4401: * C Interface::
4402: * Assembler and Code Words::
4403: * Threading Words::
4404: * Passing Commands to the OS::
4405: * Keeping track of Time::
4406: * Miscellaneous Words::
4407: @end menu
4408:
4409: @node Notation, Case insensitivity, Words, Words
4410: @section Notation
4411: @cindex notation of glossary entries
4412: @cindex format of glossary entries
4413: @cindex glossary notation format
4414: @cindex word glossary entry format
4415:
4416: The Forth words are described in this section in the glossary notation
4417: that has become a de-facto standard for Forth texts:
4418:
4419: @format
4420: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
4421: @end format
4422: @i{Description}
4423:
4424: @table @var
4425: @item word
4426: The name of the word.
4427:
4428: @item Stack effect
4429: @cindex stack effect
4430: The stack effect is written in the notation @code{@i{before} --
4431: @i{after}}, where @i{before} and @i{after} describe the top of
4432: stack entries before and after the execution of the word. The rest of
4433: the stack is not touched by the word. The top of stack is rightmost,
4434: i.e., a stack sequence is written as it is typed in. Note that Gforth
4435: uses a separate floating point stack, but a unified stack
4436: notation. Also, return stack effects are not shown in @i{stack
4437: effect}, but in @i{Description}. The name of a stack item describes
4438: the type and/or the function of the item. See below for a discussion of
4439: the types.
4440:
4441: All words have two stack effects: A compile-time stack effect and a
4442: run-time stack effect. The compile-time stack-effect of most words is
4443: @i{ -- }. If the compile-time stack-effect of a word deviates from
4444: this standard behaviour, or the word does other unusual things at
4445: compile time, both stack effects are shown; otherwise only the run-time
4446: stack effect is shown.
4447:
4448: Also note that in code templates or examples there can be comments in
4449: parentheses that display the stack picture at this point; there is no
4450: @code{--} in these places, because there is no before-after situation.
4451:
4452: @cindex pronounciation of words
4453: @item pronunciation
4454: How the word is pronounced.
4455:
4456: @cindex wordset
4457: @cindex environment wordset
4458: @item wordset
4459: The ANS Forth standard is divided into several word sets. A standard
4460: system need not support all of them. Therefore, in theory, the fewer
4461: word sets your program uses the more portable it will be. However, we
4462: suspect that most ANS Forth systems on personal machines will feature
4463: all word sets. Words that are not defined in ANS Forth have
4464: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
4465: describes words that will work in future releases of Gforth;
4466: @code{gforth-internal} words are more volatile. Environmental query
4467: strings are also displayed like words; you can recognize them by the
4468: @code{environment} in the word set field.
4469:
4470: @item Description
4471: A description of the behaviour of the word.
4472: @end table
4473:
4474: @cindex types of stack items
4475: @cindex stack item types
4476: The type of a stack item is specified by the character(s) the name
4477: starts with:
4478:
4479: @table @code
4480: @item f
4481: @cindex @code{f}, stack item type
4482: Boolean flags, i.e. @code{false} or @code{true}.
4483: @item c
4484: @cindex @code{c}, stack item type
4485: Char
4486: @item w
4487: @cindex @code{w}, stack item type
4488: Cell, can contain an integer or an address
4489: @item n
4490: @cindex @code{n}, stack item type
4491: signed integer
4492: @item u
4493: @cindex @code{u}, stack item type
4494: unsigned integer
4495: @item d
4496: @cindex @code{d}, stack item type
4497: double sized signed integer
4498: @item ud
4499: @cindex @code{ud}, stack item type
4500: double sized unsigned integer
4501: @item r
4502: @cindex @code{r}, stack item type
4503: Float (on the FP stack)
4504: @item a-
4505: @cindex @code{a_}, stack item type
4506: Cell-aligned address
4507: @item c-
4508: @cindex @code{c_}, stack item type
4509: Char-aligned address (note that a Char may have two bytes in Windows NT)
4510: @item f-
4511: @cindex @code{f_}, stack item type
4512: Float-aligned address
4513: @item df-
4514: @cindex @code{df_}, stack item type
4515: Address aligned for IEEE double precision float
4516: @item sf-
4517: @cindex @code{sf_}, stack item type
4518: Address aligned for IEEE single precision float
4519: @item xt
4520: @cindex @code{xt}, stack item type
4521: Execution token, same size as Cell
4522: @item wid
4523: @cindex @code{wid}, stack item type
4524: Word list ID, same size as Cell
4525: @item ior, wior
4526: @cindex ior type description
4527: @cindex wior type description
4528: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
4529: @item f83name
4530: @cindex @code{f83name}, stack item type
4531: Pointer to a name structure
4532: @item "
4533: @cindex @code{"}, stack item type
4534: string in the input stream (not on the stack). The terminating character
4535: is a blank by default. If it is not a blank, it is shown in @code{<>}
4536: quotes.
4537: @end table
4538:
4539: @comment ----------------------------------------------
4540: @node Case insensitivity, Comments, Notation, Words
4541: @section Case insensitivity
4542: @cindex case sensitivity
4543: @cindex upper and lower case
4544:
4545: Gforth is case-insensitive; you can enter definitions and invoke
4546: Standard words using upper, lower or mixed case (however,
4547: @pxref{core-idef, Implementation-defined options, Implementation-defined
4548: options}).
4549:
4550: ANS Forth only @i{requires} implementations to recognise Standard words
4551: when they are typed entirely in upper case. Therefore, a Standard
4552: program must use upper case for all Standard words. You can use whatever
4553: case you like for words that you define, but in a Standard program you
4554: have to use the words in the same case that you defined them.
4555:
4556: Gforth supports case sensitivity through @code{table}s (case-sensitive
4557: wordlists, @pxref{Word Lists}).
4558:
4559: Two people have asked how to convert Gforth to be case-sensitive; while
4560: we think this is a bad idea, you can change all wordlists into tables
4561: like this:
4562:
4563: @example
4564: ' table-find forth-wordlist wordlist-map @ !
4565: @end example
4566:
4567: Note that you now have to type the predefined words in the same case
4568: that we defined them, which are varying. You may want to convert them
4569: to your favourite case before doing this operation (I won't explain how,
4570: because if you are even contemplating doing this, you'd better have
4571: enough knowledge of Forth systems to know this already).
4572:
4573: @node Comments, Boolean Flags, Case insensitivity, Words
4574: @section Comments
4575: @cindex comments
4576:
4577: Forth supports two styles of comment; the traditional @i{in-line} comment,
4578: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
4579:
4580:
4581: doc-(
4582: doc-\
4583: doc-\G
4584:
4585:
4586: @node Boolean Flags, Arithmetic, Comments, Words
4587: @section Boolean Flags
4588: @cindex Boolean flags
4589:
4590: A Boolean flag is cell-sized. A cell with all bits clear represents the
4591: flag @code{false} and a flag with all bits set represents the flag
4592: @code{true}. Words that check a flag (for example, @code{IF}) will treat
4593: a cell that has @i{any} bit set as @code{true}.
4594: @c on and off to Memory?
4595: @c true and false to "Bitwise operations" or "Numeric comparison"?
4596:
4597: doc-true
4598: doc-false
4599: doc-on
4600: doc-off
4601:
4602:
4603: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
4604: @section Arithmetic
4605: @cindex arithmetic words
4606:
4607: @cindex division with potentially negative operands
4608: Forth arithmetic is not checked, i.e., you will not hear about integer
4609: overflow on addition or multiplication, you may hear about division by
4610: zero if you are lucky. The operator is written after the operands, but
4611: the operands are still in the original order. I.e., the infix @code{2-1}
4612: corresponds to @code{2 1 -}. Forth offers a variety of division
4613: operators. If you perform division with potentially negative operands,
4614: you do not want to use @code{/} or @code{/mod} with its undefined
4615: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4616: former, @pxref{Mixed precision}).
4617: @comment TODO discuss the different division forms and the std approach
4618:
4619: @menu
4620: * Single precision::
4621: * Double precision:: Double-cell integer arithmetic
4622: * Bitwise operations::
4623: * Numeric comparison::
4624: * Mixed precision:: Operations with single and double-cell integers
4625: * Floating Point::
4626: @end menu
4627:
4628: @node Single precision, Double precision, Arithmetic, Arithmetic
4629: @subsection Single precision
4630: @cindex single precision arithmetic words
4631:
4632: @c !! cell undefined
4633:
4634: By default, numbers in Forth are single-precision integers that are one
4635: cell in size. They can be signed or unsigned, depending upon how you
4636: treat them. For the rules used by the text interpreter for recognising
4637: single-precision integers see @ref{Number Conversion}.
4638:
4639: These words are all defined for signed operands, but some of them also
4640: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4641: @code{*}.
4642:
4643: doc-+
4644: doc-1+
4645: doc-under+
4646: doc--
4647: doc-1-
4648: doc-*
4649: doc-/
4650: doc-mod
4651: doc-/mod
4652: doc-negate
4653: doc-abs
4654: doc-min
4655: doc-max
4656: doc-floored
4657:
4658:
4659: @node Double precision, Bitwise operations, Single precision, Arithmetic
4660: @subsection Double precision
4661: @cindex double precision arithmetic words
4662:
4663: For the rules used by the text interpreter for
4664: recognising double-precision integers, see @ref{Number Conversion}.
4665:
4666: A double precision number is represented by a cell pair, with the most
4667: significant cell at the TOS. It is trivial to convert an unsigned single
4668: to a double: simply push a @code{0} onto the TOS. Since numbers are
4669: represented by Gforth using 2's complement arithmetic, converting a
4670: signed single to a (signed) double requires sign-extension across the
4671: most significant cell. This can be achieved using @code{s>d}. The moral
4672: of the story is that you cannot convert a number without knowing whether
4673: it represents an unsigned or a signed number.
4674:
4675: These words are all defined for signed operands, but some of them also
4676: work for unsigned numbers: @code{d+}, @code{d-}.
4677:
4678: doc-s>d
4679: doc-d>s
4680: doc-d+
4681: doc-d-
4682: doc-dnegate
4683: doc-dabs
4684: doc-dmin
4685: doc-dmax
4686:
4687:
4688: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4689: @subsection Bitwise operations
4690: @cindex bitwise operation words
4691:
4692:
4693: doc-and
4694: doc-or
4695: doc-xor
4696: doc-invert
4697: doc-lshift
4698: doc-rshift
4699: doc-2*
4700: doc-d2*
4701: doc-2/
4702: doc-d2/
4703:
4704:
4705: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
4706: @subsection Numeric comparison
4707: @cindex numeric comparison words
4708:
4709: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4710: d0= d0<>}) work for for both signed and unsigned numbers.
4711:
4712: doc-<
4713: doc-<=
4714: doc-<>
4715: doc-=
4716: doc->
4717: doc->=
4718:
4719: doc-0<
4720: doc-0<=
4721: doc-0<>
4722: doc-0=
4723: doc-0>
4724: doc-0>=
4725:
4726: doc-u<
4727: doc-u<=
4728: @c u<> and u= exist but are the same as <> and =
4729: @c doc-u<>
4730: @c doc-u=
4731: doc-u>
4732: doc-u>=
4733:
4734: doc-within
4735:
4736: doc-d<
4737: doc-d<=
4738: doc-d<>
4739: doc-d=
4740: doc-d>
4741: doc-d>=
4742:
4743: doc-d0<
4744: doc-d0<=
4745: doc-d0<>
4746: doc-d0=
4747: doc-d0>
4748: doc-d0>=
4749:
4750: doc-du<
4751: doc-du<=
4752: @c du<> and du= exist but are the same as d<> and d=
4753: @c doc-du<>
4754: @c doc-du=
4755: doc-du>
4756: doc-du>=
4757:
4758:
4759: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
4760: @subsection Mixed precision
4761: @cindex mixed precision arithmetic words
4762:
4763:
4764: doc-m+
4765: doc-*/
4766: doc-*/mod
4767: doc-m*
4768: doc-um*
4769: doc-m*/
4770: doc-um/mod
4771: doc-fm/mod
4772: doc-sm/rem
4773:
4774:
4775: @node Floating Point, , Mixed precision, Arithmetic
4776: @subsection Floating Point
4777: @cindex floating point arithmetic words
4778:
4779: For the rules used by the text interpreter for
4780: recognising floating-point numbers see @ref{Number Conversion}.
4781:
4782: Gforth has a separate floating point stack, but the documentation uses
4783: the unified notation.@footnote{It's easy to generate the separate
4784: notation from that by just separating the floating-point numbers out:
4785: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4786: r3 )}.}
4787:
4788: @cindex floating-point arithmetic, pitfalls
4789: Floating point numbers have a number of unpleasant surprises for the
4790: unwary (e.g., floating point addition is not associative) and even a
4791: few for the wary. You should not use them unless you know what you are
4792: doing or you don't care that the results you get are totally bogus. If
4793: you want to learn about the problems of floating point numbers (and
4794: how to avoid them), you might start with @cite{David Goldberg,
4795: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
4796: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
4797: Computing Surveys 23(1):5@minus{}48, March 1991}.
4798:
4799:
4800: doc-d>f
4801: doc-f>d
4802: doc-f+
4803: doc-f-
4804: doc-f*
4805: doc-f/
4806: doc-fnegate
4807: doc-fabs
4808: doc-fmax
4809: doc-fmin
4810: doc-floor
4811: doc-fround
4812: doc-f**
4813: doc-fsqrt
4814: doc-fexp
4815: doc-fexpm1
4816: doc-fln
4817: doc-flnp1
4818: doc-flog
4819: doc-falog
4820: doc-f2*
4821: doc-f2/
4822: doc-1/f
4823: doc-precision
4824: doc-set-precision
4825:
4826: @cindex angles in trigonometric operations
4827: @cindex trigonometric operations
4828: Angles in floating point operations are given in radians (a full circle
4829: has 2 pi radians).
4830:
4831: doc-fsin
4832: doc-fcos
4833: doc-fsincos
4834: doc-ftan
4835: doc-fasin
4836: doc-facos
4837: doc-fatan
4838: doc-fatan2
4839: doc-fsinh
4840: doc-fcosh
4841: doc-ftanh
4842: doc-fasinh
4843: doc-facosh
4844: doc-fatanh
4845: doc-pi
4846:
4847: @cindex equality of floats
4848: @cindex floating-point comparisons
4849: One particular problem with floating-point arithmetic is that comparison
4850: for equality often fails when you would expect it to succeed. For this
4851: reason approximate equality is often preferred (but you still have to
4852: know what you are doing). Also note that IEEE NaNs may compare
4853: differently from what you might expect. The comparison words are:
4854:
4855: doc-f~rel
4856: doc-f~abs
4857: doc-f~
4858: doc-f=
4859: doc-f<>
4860:
4861: doc-f<
4862: doc-f<=
4863: doc-f>
4864: doc-f>=
4865:
4866: doc-f0<
4867: doc-f0<=
4868: doc-f0<>
4869: doc-f0=
4870: doc-f0>
4871: doc-f0>=
4872:
4873:
4874: @node Stack Manipulation, Memory, Arithmetic, Words
4875: @section Stack Manipulation
4876: @cindex stack manipulation words
4877:
4878: @cindex floating-point stack in the standard
4879: Gforth maintains a number of separate stacks:
4880:
4881: @cindex data stack
4882: @cindex parameter stack
4883: @itemize @bullet
4884: @item
4885: A data stack (also known as the @dfn{parameter stack}) -- for
4886: characters, cells, addresses, and double cells.
4887:
4888: @cindex floating-point stack
4889: @item
4890: A floating point stack -- for holding floating point (FP) numbers.
4891:
4892: @cindex return stack
4893: @item
4894: A return stack -- for holding the return addresses of colon
4895: definitions and other (non-FP) data.
4896:
4897: @cindex locals stack
4898: @item
4899: A locals stack -- for holding local variables.
4900: @end itemize
4901:
4902: @menu
4903: * Data stack::
4904: * Floating point stack::
4905: * Return stack::
4906: * Locals stack::
4907: * Stack pointer manipulation::
4908: @end menu
4909:
4910: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4911: @subsection Data stack
4912: @cindex data stack manipulation words
4913: @cindex stack manipulations words, data stack
4914:
4915:
4916: doc-drop
4917: doc-nip
4918: doc-dup
4919: doc-over
4920: doc-tuck
4921: doc-swap
4922: doc-pick
4923: doc-rot
4924: doc--rot
4925: doc-?dup
4926: doc-roll
4927: doc-2drop
4928: doc-2nip
4929: doc-2dup
4930: doc-2over
4931: doc-2tuck
4932: doc-2swap
4933: doc-2rot
4934:
4935:
4936: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4937: @subsection Floating point stack
4938: @cindex floating-point stack manipulation words
4939: @cindex stack manipulation words, floating-point stack
4940:
4941: Whilst every sane Forth has a separate floating-point stack, it is not
4942: strictly required; an ANS Forth system could theoretically keep
4943: floating-point numbers on the data stack. As an additional difficulty,
4944: you don't know how many cells a floating-point number takes. It is
4945: reportedly possible to write words in a way that they work also for a
4946: unified stack model, but we do not recommend trying it. Instead, just
4947: say that your program has an environmental dependency on a separate
4948: floating-point stack.
4949:
4950: doc-floating-stack
4951:
4952: doc-fdrop
4953: doc-fnip
4954: doc-fdup
4955: doc-fover
4956: doc-ftuck
4957: doc-fswap
4958: doc-fpick
4959: doc-frot
4960:
4961:
4962: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4963: @subsection Return stack
4964: @cindex return stack manipulation words
4965: @cindex stack manipulation words, return stack
4966:
4967: @cindex return stack and locals
4968: @cindex locals and return stack
4969: A Forth system is allowed to keep local variables on the
4970: return stack. This is reasonable, as local variables usually eliminate
4971: the need to use the return stack explicitly. So, if you want to produce
4972: a standard compliant program and you are using local variables in a
4973: word, forget about return stack manipulations in that word (refer to the
4974: standard document for the exact rules).
4975:
4976: doc->r
4977: doc-r>
4978: doc-r@
4979: doc-rdrop
4980: doc-2>r
4981: doc-2r>
4982: doc-2r@
4983: doc-2rdrop
4984:
4985:
4986: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4987: @subsection Locals stack
4988:
4989: Gforth uses an extra locals stack. It is described, along with the
4990: reasons for its existence, in @ref{Locals implementation}.
4991:
4992: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4993: @subsection Stack pointer manipulation
4994: @cindex stack pointer manipulation words
4995:
4996: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
4997: doc-sp0
4998: doc-sp@
4999: doc-sp!
5000: doc-fp0
5001: doc-fp@
5002: doc-fp!
5003: doc-rp0
5004: doc-rp@
5005: doc-rp!
5006: doc-lp0
5007: doc-lp@
5008: doc-lp!
5009:
5010:
5011: @node Memory, Control Structures, Stack Manipulation, Words
5012: @section Memory
5013: @cindex memory words
5014:
5015: @menu
5016: * Memory model::
5017: * Dictionary allocation::
5018: * Heap Allocation::
5019: * Memory Access::
5020: * Address arithmetic::
5021: * Memory Blocks::
5022: @end menu
5023:
5024: In addition to the standard Forth memory allocation words, there is also
5025: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
5026: garbage collector}.
5027:
5028: @node Memory model, Dictionary allocation, Memory, Memory
5029: @subsection ANS Forth and Gforth memory models
5030:
5031: @c The ANS Forth description is a mess (e.g., is the heap part of
5032: @c the dictionary?), so let's not stick to closely with it.
5033:
5034: ANS Forth considers a Forth system as consisting of several address
5035: spaces, of which only @dfn{data space} is managed and accessible with
5036: the memory words. Memory not necessarily in data space includes the
5037: stacks, the code (called code space) and the headers (called name
5038: space). In Gforth everything is in data space, but the code for the
5039: primitives is usually read-only.
5040:
5041: Data space is divided into a number of areas: The (data space portion of
5042: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
5043: refer to the search data structure embodied in word lists and headers,
5044: because it is used for looking up names, just as you would in a
5045: conventional dictionary.}, the heap, and a number of system-allocated
5046: buffers.
5047:
5048: @cindex address arithmetic restrictions, ANS vs. Gforth
5049: @cindex contiguous regions, ANS vs. Gforth
5050: In ANS Forth data space is also divided into contiguous regions. You
5051: can only use address arithmetic within a contiguous region, not between
5052: them. Usually each allocation gives you one contiguous region, but the
5053: dictionary allocation words have additional rules (@pxref{Dictionary
5054: allocation}).
5055:
5056: Gforth provides one big address space, and address arithmetic can be
5057: performed between any addresses. However, in the dictionary headers or
5058: code are interleaved with data, so almost the only contiguous data space
5059: regions there are those described by ANS Forth as contiguous; but you
5060: can be sure that the dictionary is allocated towards increasing
5061: addresses even between contiguous regions. The memory order of
5062: allocations in the heap is platform-dependent (and possibly different
5063: from one run to the next).
5064:
5065:
5066: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5067: @subsection Dictionary allocation
5068: @cindex reserving data space
5069: @cindex data space - reserving some
5070:
5071: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5072: you want to deallocate X, you also deallocate everything
5073: allocated after X.
5074:
5075: @cindex contiguous regions in dictionary allocation
5076: The allocations using the words below are contiguous and grow the region
5077: towards increasing addresses. Other words that allocate dictionary
5078: memory of any kind (i.e., defining words including @code{:noname}) end
5079: the contiguous region and start a new one.
5080:
5081: In ANS Forth only @code{create}d words are guaranteed to produce an
5082: address that is the start of the following contiguous region. In
5083: particular, the cell allocated by @code{variable} is not guaranteed to
5084: be contiguous with following @code{allot}ed memory.
5085:
5086: You can deallocate memory by using @code{allot} with a negative argument
5087: (with some restrictions, see @code{allot}). For larger deallocations use
5088: @code{marker}.
5089:
5090:
5091: doc-here
5092: doc-unused
5093: doc-allot
5094: doc-c,
5095: doc-f,
5096: doc-,
5097: doc-2,
5098:
5099: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5100: course you should allocate memory in an aligned way, too. I.e., before
5101: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5102: The words below align @code{here} if it is not already. Basically it is
5103: only already aligned for a type, if the last allocation was a multiple
5104: of the size of this type and if @code{here} was aligned for this type
5105: before.
5106:
5107: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5108: ANS Forth (@code{maxalign}ed in Gforth).
5109:
5110: doc-align
5111: doc-falign
5112: doc-sfalign
5113: doc-dfalign
5114: doc-maxalign
5115: doc-cfalign
5116:
5117:
5118: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5119: @subsection Heap allocation
5120: @cindex heap allocation
5121: @cindex dynamic allocation of memory
5122: @cindex memory-allocation word set
5123:
5124: @cindex contiguous regions and heap allocation
5125: Heap allocation supports deallocation of allocated memory in any
5126: order. Dictionary allocation is not affected by it (i.e., it does not
5127: end a contiguous region). In Gforth, these words are implemented using
5128: the standard C library calls malloc(), free() and resize().
5129:
5130: The memory region produced by one invocation of @code{allocate} or
5131: @code{resize} is internally contiguous. There is no contiguity between
5132: such a region and any other region (including others allocated from the
5133: heap).
5134:
5135: doc-allocate
5136: doc-free
5137: doc-resize
5138:
5139:
5140: @node Memory Access, Address arithmetic, Heap Allocation, Memory
5141: @subsection Memory Access
5142: @cindex memory access words
5143:
5144: doc-@
5145: doc-!
5146: doc-+!
5147: doc-c@
5148: doc-c!
5149: doc-2@
5150: doc-2!
5151: doc-f@
5152: doc-f!
5153: doc-sf@
5154: doc-sf!
5155: doc-df@
5156: doc-df!
5157: doc-sw@
5158: doc-uw@
5159: doc-w!
5160: doc-sl@
5161: doc-ul@
5162: doc-l!
5163:
5164: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5165: @subsection Address arithmetic
5166: @cindex address arithmetic words
5167:
5168: Address arithmetic is the foundation on which you can build data
5169: structures like arrays, records (@pxref{Structures}) and objects
5170: (@pxref{Object-oriented Forth}).
5171:
5172: @cindex address unit
5173: @cindex au (address unit)
5174: ANS Forth does not specify the sizes of the data types. Instead, it
5175: offers a number of words for computing sizes and doing address
5176: arithmetic. Address arithmetic is performed in terms of address units
5177: (aus); on most systems the address unit is one byte. Note that a
5178: character may have more than one au, so @code{chars} is no noop (on
5179: platforms where it is a noop, it compiles to nothing).
5180:
5181: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5182: you have the address of a cell, perform @code{1 cells +}, and you will
5183: have the address of the next cell.
5184:
5185: @cindex contiguous regions and address arithmetic
5186: In ANS Forth you can perform address arithmetic only within a contiguous
5187: region, i.e., if you have an address into one region, you can only add
5188: and subtract such that the result is still within the region; you can
5189: only subtract or compare addresses from within the same contiguous
5190: region. Reasons: several contiguous regions can be arranged in memory
5191: in any way; on segmented systems addresses may have unusual
5192: representations, such that address arithmetic only works within a
5193: region. Gforth provides a few more guarantees (linear address space,
5194: dictionary grows upwards), but in general I have found it easy to stay
5195: within contiguous regions (exception: computing and comparing to the
5196: address just beyond the end of an array).
5197:
5198: @cindex alignment of addresses for types
5199: ANS Forth also defines words for aligning addresses for specific
5200: types. Many computers require that accesses to specific data types
5201: must only occur at specific addresses; e.g., that cells may only be
5202: accessed at addresses divisible by 4. Even if a machine allows unaligned
5203: accesses, it can usually perform aligned accesses faster.
5204:
5205: For the performance-conscious: alignment operations are usually only
5206: necessary during the definition of a data structure, not during the
5207: (more frequent) accesses to it.
5208:
5209: ANS Forth defines no words for character-aligning addresses. This is not
5210: an oversight, but reflects the fact that addresses that are not
5211: char-aligned have no use in the standard and therefore will not be
5212: created.
5213:
5214: @cindex @code{CREATE} and alignment
5215: ANS Forth guarantees that addresses returned by @code{CREATE}d words
5216: are cell-aligned; in addition, Gforth guarantees that these addresses
5217: are aligned for all purposes.
5218:
5219: Note that the ANS Forth word @code{char} has nothing to do with address
5220: arithmetic.
5221:
5222:
5223: doc-chars
5224: doc-char+
5225: doc-cells
5226: doc-cell+
5227: doc-cell
5228: doc-aligned
5229: doc-floats
5230: doc-float+
5231: doc-float
5232: doc-faligned
5233: doc-sfloats
5234: doc-sfloat+
5235: doc-sfaligned
5236: doc-dfloats
5237: doc-dfloat+
5238: doc-dfaligned
5239: doc-maxaligned
5240: doc-cfaligned
5241: doc-address-unit-bits
5242: doc-/w
5243: doc-/l
5244:
5245: @node Memory Blocks, , Address arithmetic, Memory
5246: @subsection Memory Blocks
5247: @cindex memory block words
5248: @cindex character strings - moving and copying
5249:
5250: Memory blocks often represent character strings; For ways of storing
5251: character strings in memory see @ref{String Formats}. For other
5252: string-processing words see @ref{Displaying characters and strings}.
5253:
5254: A few of these words work on address unit blocks. In that case, you
5255: usually have to insert @code{CHARS} before the word when working on
5256: character strings. Most words work on character blocks, and expect a
5257: char-aligned address.
5258:
5259: When copying characters between overlapping memory regions, use
5260: @code{chars move} or choose carefully between @code{cmove} and
5261: @code{cmove>}.
5262:
5263: doc-move
5264: doc-erase
5265: doc-cmove
5266: doc-cmove>
5267: doc-fill
5268: doc-blank
5269: doc-compare
5270: doc-str=
5271: doc-str<
5272: doc-string-prefix?
5273: doc-search
5274: doc--trailing
5275: doc-/string
5276: doc-bounds
5277: doc-pad
5278:
5279: @comment TODO examples
5280:
5281:
5282: @node Control Structures, Defining Words, Memory, Words
5283: @section Control Structures
5284: @cindex control structures
5285:
5286: Control structures in Forth cannot be used interpretively, only in a
5287: colon definition@footnote{To be precise, they have no interpretation
5288: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5289: not like this limitation, but have not seen a satisfying way around it
5290: yet, although many schemes have been proposed.
5291:
5292: @menu
5293: * Selection:: IF ... ELSE ... ENDIF
5294: * Simple Loops:: BEGIN ...
5295: * Counted Loops:: DO
5296: * Arbitrary control structures::
5297: * Calls and returns::
5298: * Exception Handling::
5299: @end menu
5300:
5301: @node Selection, Simple Loops, Control Structures, Control Structures
5302: @subsection Selection
5303: @cindex selection control structures
5304: @cindex control structures for selection
5305:
5306: @cindex @code{IF} control structure
5307: @example
5308: @i{flag}
5309: IF
5310: @i{code}
5311: ENDIF
5312: @end example
5313: @noindent
5314:
5315: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5316: with any bit set represents truth) @i{code} is executed.
5317:
5318: @example
5319: @i{flag}
5320: IF
5321: @i{code1}
5322: ELSE
5323: @i{code2}
5324: ENDIF
5325: @end example
5326:
5327: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5328: executed.
5329:
5330: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5331: standard, and @code{ENDIF} is not, although it is quite popular. We
5332: recommend using @code{ENDIF}, because it is less confusing for people
5333: who also know other languages (and is not prone to reinforcing negative
5334: prejudices against Forth in these people). Adding @code{ENDIF} to a
5335: system that only supplies @code{THEN} is simple:
5336: @example
5337: : ENDIF POSTPONE then ; immediate
5338: @end example
5339:
5340: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5341: (adv.)} has the following meanings:
5342: @quotation
5343: ... 2b: following next after in order ... 3d: as a necessary consequence
5344: (if you were there, then you saw them).
5345: @end quotation
5346: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5347: and many other programming languages has the meaning 3d.]
5348:
5349: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
5350: you can avoid using @code{?dup}. Using these alternatives is also more
5351: efficient than using @code{?dup}. Definitions in ANS Forth
5352: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5353: @file{compat/control.fs}.
5354:
5355: @cindex @code{CASE} control structure
5356: @example
5357: @i{x}
5358: CASE
5359: @i{x1} OF @i{code1} ENDOF
5360: @i{x2} OF @i{code2} ENDOF
5361: @dots{}
5362: ( x ) @i{default-code} ( x )
5363: ENDCASE ( )
5364: @end example
5365:
5366: Executes the first @i{codei}, where the @i{xi} is equal to @i{x}. If no
5367: @i{xi} matches, the optional @i{default-code} is executed. The optional
5368: default case can be added by simply writing the code after the last
5369: @code{ENDOF}. It may use @i{x}, which is on top of the stack, but must
5370: not consume it. The value @i{x} is consumed by this construction
5371: (either by an @code{OF} that matches, or by the @code{ENDCASE}, if no OF
5372: matches). Example:
5373:
5374: @example
5375: : num-name ( n -- c-addr u )
5376: case
5377: 0 of s" zero " endof
5378: 1 of s" one " endof
5379: 2 of s" two " endof
5380: \ default case:
5381: s" other number"
5382: rot \ get n on top so ENDCASE can drop it
5383: endcase ;
5384: @end example
5385:
5386: @progstyle
5387: To keep the code understandable, you should ensure that you change the
5388: stack in the same way (wrt. number and types of stack items consumed
5389: and pushed) on all paths through a selection construct.
5390:
5391: @node Simple Loops, Counted Loops, Selection, Control Structures
5392: @subsection Simple Loops
5393: @cindex simple loops
5394: @cindex loops without count
5395:
5396: @cindex @code{WHILE} loop
5397: @example
5398: BEGIN
5399: @i{code1}
5400: @i{flag}
5401: WHILE
5402: @i{code2}
5403: REPEAT
5404: @end example
5405:
5406: @i{code1} is executed and @i{flag} is computed. If it is true,
5407: @i{code2} is executed and the loop is restarted; If @i{flag} is
5408: false, execution continues after the @code{REPEAT}.
5409:
5410: @cindex @code{UNTIL} loop
5411: @example
5412: BEGIN
5413: @i{code}
5414: @i{flag}
5415: UNTIL
5416: @end example
5417:
5418: @i{code} is executed. The loop is restarted if @code{flag} is false.
5419:
5420: @progstyle
5421: To keep the code understandable, a complete iteration of the loop should
5422: not change the number and types of the items on the stacks.
5423:
5424: @cindex endless loop
5425: @cindex loops, endless
5426: @example
5427: BEGIN
5428: @i{code}
5429: AGAIN
5430: @end example
5431:
5432: This is an endless loop.
5433:
5434: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5435: @subsection Counted Loops
5436: @cindex counted loops
5437: @cindex loops, counted
5438: @cindex @code{DO} loops
5439:
5440: The basic counted loop is:
5441: @example
5442: @i{limit} @i{start}
5443: ?DO
5444: @i{body}
5445: LOOP
5446: @end example
5447:
5448: This performs one iteration for every integer, starting from @i{start}
5449: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
5450: accessed with @code{i}. For example, the loop:
5451: @example
5452: 10 0 ?DO
5453: i .
5454: LOOP
5455: @end example
5456: @noindent
5457: prints @code{0 1 2 3 4 5 6 7 8 9}
5458:
5459: The index of the innermost loop can be accessed with @code{i}, the index
5460: of the next loop with @code{j}, and the index of the third loop with
5461: @code{k}.
5462:
5463:
5464: doc-i
5465: doc-j
5466: doc-k
5467:
5468:
5469: The loop control data are kept on the return stack, so there are some
5470: restrictions on mixing return stack accesses and counted loop words. In
5471: particuler, if you put values on the return stack outside the loop, you
5472: cannot read them inside the loop@footnote{well, not in a way that is
5473: portable.}. If you put values on the return stack within a loop, you
5474: have to remove them before the end of the loop and before accessing the
5475: index of the loop.
5476:
5477: There are several variations on the counted loop:
5478:
5479: @itemize @bullet
5480: @item
5481: @code{LEAVE} leaves the innermost counted loop immediately; execution
5482: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5483:
5484: @example
5485: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5486: @end example
5487: prints @code{0 1 2 3}
5488:
5489:
5490: @item
5491: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5492: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5493: return stack so @code{EXIT} can get to its return address. For example:
5494:
5495: @example
5496: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5497: @end example
5498: prints @code{0 1 2 3}
5499:
5500:
5501: @item
5502: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
5503: (and @code{LOOP} iterates until they become equal by wrap-around
5504: arithmetic). This behaviour is usually not what you want. Therefore,
5505: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
5506: @code{?DO}), which do not enter the loop if @i{start} is greater than
5507: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
5508: unsigned loop parameters.
5509:
5510: @item
5511: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5512: the loop, independent of the loop parameters. Do not use @code{DO}, even
5513: if you know that the loop is entered in any case. Such knowledge tends
5514: to become invalid during maintenance of a program, and then the
5515: @code{DO} will make trouble.
5516:
5517: @item
5518: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5519: index by @i{n} instead of by 1. The loop is terminated when the border
5520: between @i{limit-1} and @i{limit} is crossed. E.g.:
5521:
5522: @example
5523: 4 0 +DO i . 2 +LOOP
5524: @end example
5525: @noindent
5526: prints @code{0 2}
5527:
5528: @example
5529: 4 1 +DO i . 2 +LOOP
5530: @end example
5531: @noindent
5532: prints @code{1 3}
5533:
5534: @item
5535: @cindex negative increment for counted loops
5536: @cindex counted loops with negative increment
5537: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
5538:
5539: @example
5540: -1 0 ?DO i . -1 +LOOP
5541: @end example
5542: @noindent
5543: prints @code{0 -1}
5544:
5545: @example
5546: 0 0 ?DO i . -1 +LOOP
5547: @end example
5548: prints nothing.
5549:
5550: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5551: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5552: index by @i{u} each iteration. The loop is terminated when the border
5553: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
5554: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5555:
5556: @example
5557: -2 0 -DO i . 1 -LOOP
5558: @end example
5559: @noindent
5560: prints @code{0 -1}
5561:
5562: @example
5563: -1 0 -DO i . 1 -LOOP
5564: @end example
5565: @noindent
5566: prints @code{0}
5567:
5568: @example
5569: 0 0 -DO i . 1 -LOOP
5570: @end example
5571: @noindent
5572: prints nothing.
5573:
5574: @end itemize
5575:
5576: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
5577: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5578: for these words that uses only standard words is provided in
5579: @file{compat/loops.fs}.
5580:
5581:
5582: @cindex @code{FOR} loops
5583: Another counted loop is:
5584: @example
5585: @i{n}
5586: FOR
5587: @i{body}
5588: NEXT
5589: @end example
5590: This is the preferred loop of native code compiler writers who are too
5591: lazy to optimize @code{?DO} loops properly. This loop structure is not
5592: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5593: @code{i} produces values starting with @i{n} and ending with 0. Other
5594: Forth systems may behave differently, even if they support @code{FOR}
5595: loops. To avoid problems, don't use @code{FOR} loops.
5596:
5597: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5598: @subsection Arbitrary control structures
5599: @cindex control structures, user-defined
5600:
5601: @cindex control-flow stack
5602: ANS Forth permits and supports using control structures in a non-nested
5603: way. Information about incomplete control structures is stored on the
5604: control-flow stack. This stack may be implemented on the Forth data
5605: stack, and this is what we have done in Gforth.
5606:
5607: @cindex @code{orig}, control-flow stack item
5608: @cindex @code{dest}, control-flow stack item
5609: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5610: entry represents a backward branch target. A few words are the basis for
5611: building any control structure possible (except control structures that
5612: need storage, like calls, coroutines, and backtracking).
5613:
5614:
5615: doc-if
5616: doc-ahead
5617: doc-then
5618: doc-begin
5619: doc-until
5620: doc-again
5621: doc-cs-pick
5622: doc-cs-roll
5623:
5624:
5625: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5626: manipulate the control-flow stack in a portable way. Without them, you
5627: would need to know how many stack items are occupied by a control-flow
5628: entry (many systems use one cell. In Gforth they currently take three,
5629: but this may change in the future).
5630:
5631: Some standard control structure words are built from these words:
5632:
5633:
5634: doc-else
5635: doc-while
5636: doc-repeat
5637:
5638:
5639: @noindent
5640: Gforth adds some more control-structure words:
5641:
5642:
5643: doc-endif
5644: doc-?dup-if
5645: doc-?dup-0=-if
5646:
5647:
5648: @noindent
5649: Counted loop words constitute a separate group of words:
5650:
5651:
5652: doc-?do
5653: doc-+do
5654: doc-u+do
5655: doc--do
5656: doc-u-do
5657: doc-do
5658: doc-for
5659: doc-loop
5660: doc-+loop
5661: doc--loop
5662: doc-next
5663: doc-leave
5664: doc-?leave
5665: doc-unloop
5666: doc-done
5667:
5668:
5669: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5670: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
5671: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5672: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5673: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5674: resolved (by using one of the loop-ending words or @code{DONE}).
5675:
5676: @noindent
5677: Another group of control structure words are:
5678:
5679:
5680: doc-case
5681: doc-endcase
5682: doc-of
5683: doc-endof
5684:
5685:
5686: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5687: @code{CS-ROLL}.
5688:
5689: @subsubsection Programming Style
5690: @cindex control structures programming style
5691: @cindex programming style, arbitrary control structures
5692:
5693: In order to ensure readability we recommend that you do not create
5694: arbitrary control structures directly, but define new control structure
5695: words for the control structure you want and use these words in your
5696: program. For example, instead of writing:
5697:
5698: @example
5699: BEGIN
5700: ...
5701: IF [ 1 CS-ROLL ]
5702: ...
5703: AGAIN THEN
5704: @end example
5705:
5706: @noindent
5707: we recommend defining control structure words, e.g.,
5708:
5709: @example
5710: : WHILE ( DEST -- ORIG DEST )
5711: POSTPONE IF
5712: 1 CS-ROLL ; immediate
5713:
5714: : REPEAT ( orig dest -- )
5715: POSTPONE AGAIN
5716: POSTPONE THEN ; immediate
5717: @end example
5718:
5719: @noindent
5720: and then using these to create the control structure:
5721:
5722: @example
5723: BEGIN
5724: ...
5725: WHILE
5726: ...
5727: REPEAT
5728: @end example
5729:
5730: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5731: @code{WHILE} are predefined, so in this example it would not be
5732: necessary to define them.
5733:
5734: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5735: @subsection Calls and returns
5736: @cindex calling a definition
5737: @cindex returning from a definition
5738:
5739: @cindex recursive definitions
5740: A definition can be called simply be writing the name of the definition
5741: to be called. Normally a definition is invisible during its own
5742: definition. If you want to write a directly recursive definition, you
5743: can use @code{recursive} to make the current definition visible, or
5744: @code{recurse} to call the current definition directly.
5745:
5746:
5747: doc-recursive
5748: doc-recurse
5749:
5750:
5751: @comment TODO add example of the two recursion methods
5752: @quotation
5753: @progstyle
5754: I prefer using @code{recursive} to @code{recurse}, because calling the
5755: definition by name is more descriptive (if the name is well-chosen) than
5756: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5757: implementation, it is much better to read (and think) ``now sort the
5758: partitions'' than to read ``now do a recursive call''.
5759: @end quotation
5760:
5761: For mutual recursion, use @code{Defer}red words, like this:
5762:
5763: @example
5764: Defer foo
5765:
5766: : bar ( ... -- ... )
5767: ... foo ... ;
5768:
5769: :noname ( ... -- ... )
5770: ... bar ... ;
5771: IS foo
5772: @end example
5773:
5774: Deferred words are discussed in more detail in @ref{Deferred Words}.
5775:
5776: The current definition returns control to the calling definition when
5777: the end of the definition is reached or @code{EXIT} is encountered.
5778:
5779: doc-exit
5780: doc-;s
5781:
5782:
5783: @node Exception Handling, , Calls and returns, Control Structures
5784: @subsection Exception Handling
5785: @cindex exceptions
5786:
5787: @c quit is a very bad idea for error handling,
5788: @c because it does not translate into a THROW
5789: @c it also does not belong into this chapter
5790:
5791: If a word detects an error condition that it cannot handle, it can
5792: @code{throw} an exception. In the simplest case, this will terminate
5793: your program, and report an appropriate error.
5794:
5795: doc-throw
5796:
5797: @code{Throw} consumes a cell-sized error number on the stack. There are
5798: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5799: Gforth (and most other systems) you can use the iors produced by various
5800: words as error numbers (e.g., a typical use of @code{allocate} is
5801: @code{allocate throw}). Gforth also provides the word @code{exception}
5802: to define your own error numbers (with decent error reporting); an ANS
5803: Forth version of this word (but without the error messages) is available
5804: in @code{compat/except.fs}. And finally, you can use your own error
5805: numbers (anything outside the range -4095..0), but won't get nice error
5806: messages, only numbers. For example, try:
5807:
5808: @example
5809: -10 throw \ ANS defined
5810: -267 throw \ system defined
5811: s" my error" exception throw \ user defined
5812: 7 throw \ arbitrary number
5813: @end example
5814:
5815: doc---exception-exception
5816:
5817: A common idiom to @code{THROW} a specific error if a flag is true is
5818: this:
5819:
5820: @example
5821: @code{( flag ) 0<> @i{errno} and throw}
5822: @end example
5823:
5824: Your program can provide exception handlers to catch exceptions. An
5825: exception handler can be used to correct the problem, or to clean up
5826: some data structures and just throw the exception to the next exception
5827: handler. Note that @code{throw} jumps to the dynamically innermost
5828: exception handler. The system's exception handler is outermost, and just
5829: prints an error and restarts command-line interpretation (or, in batch
5830: mode (i.e., while processing the shell command line), leaves Gforth).
5831:
5832: The ANS Forth way to catch exceptions is @code{catch}:
5833:
5834: doc-catch
5835: doc-nothrow
5836:
5837: The most common use of exception handlers is to clean up the state when
5838: an error happens. E.g.,
5839:
5840: @example
5841: base @ >r hex \ actually the hex should be inside foo, or we h
5842: ['] foo catch ( nerror|0 )
5843: r> base !
5844: ( nerror|0 ) throw \ pass it on
5845: @end example
5846:
5847: A use of @code{catch} for handling the error @code{myerror} might look
5848: like this:
5849:
5850: @example
5851: ['] foo catch
5852: CASE
5853: myerror OF ... ( do something about it ) nothrow ENDOF
5854: dup throw \ default: pass other errors on, do nothing on non-errors
5855: ENDCASE
5856: @end example
5857:
5858: Having to wrap the code into a separate word is often cumbersome,
5859: therefore Gforth provides an alternative syntax:
5860:
5861: @example
5862: TRY
5863: @i{code1}
5864: IFERROR
5865: @i{code2}
5866: THEN
5867: @i{code3}
5868: ENDTRY
5869: @end example
5870:
5871: This performs @i{code1}. If @i{code1} completes normally, execution
5872: continues with @i{code3}. If there is an exception in @i{code1} or
5873: before @code{endtry}, the stacks are reset to the depth during
5874: @code{try}, the throw value is pushed on the data stack, and execution
5875: constinues at @i{code2}, and finally falls through to @i{code3}.
5876:
5877: doc-try
5878: doc-endtry
5879: doc-iferror
5880:
5881: If you don't need @i{code2}, you can write @code{restore} instead of
5882: @code{iferror then}:
5883:
5884: @example
5885: TRY
5886: @i{code1}
5887: RESTORE
5888: @i{code3}
5889: ENDTRY
5890: @end example
5891:
5892: @cindex unwind-protect
5893: The cleanup example from above in this syntax:
5894:
5895: @example
5896: base @@ @{ oldbase @}
5897: TRY
5898: hex foo \ now the hex is placed correctly
5899: 0 \ value for throw
5900: RESTORE
5901: oldbase base !
5902: ENDTRY
5903: throw
5904: @end example
5905:
5906: An additional advantage of this variant is that an exception between
5907: @code{restore} and @code{endtry} (e.g., from the user pressing
5908: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
5909: so the base will be restored under all circumstances.
5910:
5911: However, you have to ensure that this code does not cause an exception
5912: itself, otherwise the @code{iferror}/@code{restore} code will loop.
5913: Moreover, you should also make sure that the stack contents needed by
5914: the @code{iferror}/@code{restore} code exist everywhere between
5915: @code{try} and @code{endtry}; in our example this is achived by
5916: putting the data in a local before the @code{try} (you cannot use the
5917: return stack because the exception frame (@i{sys1}) is in the way
5918: there).
5919:
5920: This kind of usage corresponds to Lisp's @code{unwind-protect}.
5921:
5922: @cindex @code{recover} (old Gforth versions)
5923: If you do not want this exception-restarting behaviour, you achieve
5924: this as follows:
5925:
5926: @example
5927: TRY
5928: @i{code1}
5929: ENDTRY-IFERROR
5930: @i{code2}
5931: THEN
5932: @end example
5933:
5934: If there is an exception in @i{code1}, then @i{code2} is executed,
5935: otherwise execution continues behind the @code{then} (or in a possible
5936: @code{else} branch). This corresponds to the construct
5937:
5938: @example
5939: TRY
5940: @i{code1}
5941: RECOVER
5942: @i{code2}
5943: ENDTRY
5944: @end example
5945:
5946: in Gforth before version 0.7. So you can directly replace
5947: @code{recover}-using code; however, we recommend that you check if it
5948: would not be better to use one of the other @code{try} variants while
5949: you are at it.
5950:
5951: To ease the transition, Gforth provides two compatibility files:
5952: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
5953: ... then} syntax (but not @code{iferror} or @code{restore}) for old
5954: systems; @file{recover-endtry.fs} provides the @code{try ... recover
5955: ... endtry} syntax on new systems, so you can use that file as a
5956: stopgap to run old programs. Both files work on any system (they just
5957: do nothing if the system already has the syntax it implements), so you
5958: can unconditionally @code{require} one of these files, even if you use
5959: a mix old and new systems.
5960:
5961: doc-restore
5962: doc-endtry-iferror
5963:
5964: Here's the error handling example:
5965:
5966: @example
5967: TRY
5968: foo
5969: ENDTRY-IFERROR
5970: CASE
5971: myerror OF ... ( do something about it ) nothrow ENDOF
5972: throw \ pass other errors on
5973: ENDCASE
5974: THEN
5975: @end example
5976:
5977: @progstyle
5978: As usual, you should ensure that the stack depth is statically known at
5979: the end: either after the @code{throw} for passing on errors, or after
5980: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5981: selection construct for handling the error).
5982:
5983: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5984: and you can provide an error message. @code{Abort} just produces an
5985: ``Aborted'' error.
5986:
5987: The problem with these words is that exception handlers cannot
5988: differentiate between different @code{abort"}s; they just look like
5989: @code{-2 throw} to them (the error message cannot be accessed by
5990: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5991: exception handlers.
5992:
5993: doc-abort"
5994: doc-abort
5995:
5996:
5997:
5998: @c -------------------------------------------------------------
5999: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
6000: @section Defining Words
6001: @cindex defining words
6002:
6003: Defining words are used to extend Forth by creating new entries in the dictionary.
6004:
6005: @menu
6006: * CREATE::
6007: * Variables:: Variables and user variables
6008: * Constants::
6009: * Values:: Initialised variables
6010: * Colon Definitions::
6011: * Anonymous Definitions:: Definitions without names
6012: * Supplying names:: Passing definition names as strings
6013: * User-defined Defining Words::
6014: * Deferred Words:: Allow forward references
6015: * Aliases::
6016: @end menu
6017:
6018: @node CREATE, Variables, Defining Words, Defining Words
6019: @subsection @code{CREATE}
6020: @cindex simple defining words
6021: @cindex defining words, simple
6022:
6023: Defining words are used to create new entries in the dictionary. The
6024: simplest defining word is @code{CREATE}. @code{CREATE} is used like
6025: this:
6026:
6027: @example
6028: CREATE new-word1
6029: @end example
6030:
6031: @code{CREATE} is a parsing word, i.e., it takes an argument from the
6032: input stream (@code{new-word1} in our example). It generates a
6033: dictionary entry for @code{new-word1}. When @code{new-word1} is
6034: executed, all that it does is leave an address on the stack. The address
6035: represents the value of the data space pointer (@code{HERE}) at the time
6036: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
6037: associating a name with the address of a region of memory.
6038:
6039: doc-create
6040:
6041: Note that in ANS Forth guarantees only for @code{create} that its body
6042: is in dictionary data space (i.e., where @code{here}, @code{allot}
6043: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
6044: @code{create}d words can be modified with @code{does>}
6045: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
6046: can only be applied to @code{create}d words.
6047:
6048: By extending this example to reserve some memory in data space, we end
6049: up with something like a @i{variable}. Here are two different ways to do
6050: it:
6051:
6052: @example
6053: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
6054: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
6055: @end example
6056:
6057: The variable can be examined and modified using @code{@@} (``fetch'') and
6058: @code{!} (``store'') like this:
6059:
6060: @example
6061: new-word2 @@ . \ get address, fetch from it and display
6062: 1234 new-word2 ! \ new value, get address, store to it
6063: @end example
6064:
6065: @cindex arrays
6066: A similar mechanism can be used to create arrays. For example, an
6067: 80-character text input buffer:
6068:
6069: @example
6070: CREATE text-buf 80 chars allot
6071:
6072: text-buf 0 chars + c@@ \ the 1st character (offset 0)
6073: text-buf 3 chars + c@@ \ the 4th character (offset 3)
6074: @end example
6075:
6076: You can build arbitrarily complex data structures by allocating
6077: appropriate areas of memory. For further discussions of this, and to
6078: learn about some Gforth tools that make it easier,
6079: @xref{Structures}.
6080:
6081:
6082: @node Variables, Constants, CREATE, Defining Words
6083: @subsection Variables
6084: @cindex variables
6085:
6086: The previous section showed how a sequence of commands could be used to
6087: generate a variable. As a final refinement, the whole code sequence can
6088: be wrapped up in a defining word (pre-empting the subject of the next
6089: section), making it easier to create new variables:
6090:
6091: @example
6092: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
6093: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
6094:
6095: myvariableX foo \ variable foo starts off with an unknown value
6096: myvariable0 joe \ whilst joe is initialised to 0
6097:
6098: 45 3 * foo ! \ set foo to 135
6099: 1234 joe ! \ set joe to 1234
6100: 3 joe +! \ increment joe by 3.. to 1237
6101: @end example
6102:
6103: Not surprisingly, there is no need to define @code{myvariable}, since
6104: Forth already has a definition @code{Variable}. ANS Forth does not
6105: guarantee that a @code{Variable} is initialised when it is created
6106: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
6107: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
6108: like @code{myvariable0}). Forth also provides @code{2Variable} and
6109: @code{fvariable} for double and floating-point variables, respectively
6110: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
6111: store a boolean, you can use @code{on} and @code{off} to toggle its
6112: state.
6113:
6114: doc-variable
6115: doc-2variable
6116: doc-fvariable
6117:
6118: @cindex user variables
6119: @cindex user space
6120: The defining word @code{User} behaves in the same way as @code{Variable}.
6121: The difference is that it reserves space in @i{user (data) space} rather
6122: than normal data space. In a Forth system that has a multi-tasker, each
6123: task has its own set of user variables.
6124:
6125: doc-user
6126: @c doc-udp
6127: @c doc-uallot
6128:
6129: @comment TODO is that stuff about user variables strictly correct? Is it
6130: @comment just terminal tasks that have user variables?
6131: @comment should document tasker.fs (with some examples) elsewhere
6132: @comment in this manual, then expand on user space and user variables.
6133:
6134: @node Constants, Values, Variables, Defining Words
6135: @subsection Constants
6136: @cindex constants
6137:
6138: @code{Constant} allows you to declare a fixed value and refer to it by
6139: name. For example:
6140:
6141: @example
6142: 12 Constant INCHES-PER-FOOT
6143: 3E+08 fconstant SPEED-O-LIGHT
6144: @end example
6145:
6146: A @code{Variable} can be both read and written, so its run-time
6147: behaviour is to supply an address through which its current value can be
6148: manipulated. In contrast, the value of a @code{Constant} cannot be
6149: changed once it has been declared@footnote{Well, often it can be -- but
6150: not in a Standard, portable way. It's safer to use a @code{Value} (read
6151: on).} so it's not necessary to supply the address -- it is more
6152: efficient to return the value of the constant directly. That's exactly
6153: what happens; the run-time effect of a constant is to put its value on
6154: the top of the stack (You can find one
6155: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
6156:
6157: Forth also provides @code{2Constant} and @code{fconstant} for defining
6158: double and floating-point constants, respectively.
6159:
6160: doc-constant
6161: doc-2constant
6162: doc-fconstant
6163:
6164: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
6165: @c nac-> How could that not be true in an ANS Forth? You can't define a
6166: @c constant, use it and then delete the definition of the constant..
6167:
6168: @c anton->An ANS Forth system can compile a constant to a literal; On
6169: @c decompilation you would see only the number, just as if it had been used
6170: @c in the first place. The word will stay, of course, but it will only be
6171: @c used by the text interpreter (no run-time duties, except when it is
6172: @c POSTPONEd or somesuch).
6173:
6174: @c nac:
6175: @c I agree that it's rather deep, but IMO it is an important difference
6176: @c relative to other programming languages.. often it's annoying: it
6177: @c certainly changes my programming style relative to C.
6178:
6179: @c anton: In what way?
6180:
6181: Constants in Forth behave differently from their equivalents in other
6182: programming languages. In other languages, a constant (such as an EQU in
6183: assembler or a #define in C) only exists at compile-time; in the
6184: executable program the constant has been translated into an absolute
6185: number and, unless you are using a symbolic debugger, it's impossible to
6186: know what abstract thing that number represents. In Forth a constant has
6187: an entry in the header space and remains there after the code that uses
6188: it has been defined. In fact, it must remain in the dictionary since it
6189: has run-time duties to perform. For example:
6190:
6191: @example
6192: 12 Constant INCHES-PER-FOOT
6193: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6194: @end example
6195:
6196: @cindex in-lining of constants
6197: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6198: associated with the constant @code{INCHES-PER-FOOT}. If you use
6199: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6200: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6201: attempt to optimise constants by in-lining them where they are used. You
6202: can force Gforth to in-line a constant like this:
6203:
6204: @example
6205: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6206: @end example
6207:
6208: If you use @code{see} to decompile @i{this} version of
6209: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
6210: longer present. To understand how this works, read
6211: @ref{Interpret/Compile states}, and @ref{Literals}.
6212:
6213: In-lining constants in this way might improve execution time
6214: fractionally, and can ensure that a constant is now only referenced at
6215: compile-time. However, the definition of the constant still remains in
6216: the dictionary. Some Forth compilers provide a mechanism for controlling
6217: a second dictionary for holding transient words such that this second
6218: dictionary can be deleted later in order to recover memory
6219: space. However, there is no standard way of doing this.
6220:
6221:
6222: @node Values, Colon Definitions, Constants, Defining Words
6223: @subsection Values
6224: @cindex values
6225:
6226: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6227: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6228: (not in ANS Forth) you can access (and change) a @code{value} also with
6229: @code{>body}.
6230:
6231: Here are some
6232: examples:
6233:
6234: @example
6235: 12 Value APPLES \ Define APPLES with an initial value of 12
6236: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6237: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6238: APPLES \ puts 35 on the top of the stack.
6239: @end example
6240:
6241: doc-value
6242: doc-to
6243:
6244:
6245:
6246: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6247: @subsection Colon Definitions
6248: @cindex colon definitions
6249:
6250: @example
6251: : name ( ... -- ... )
6252: word1 word2 word3 ;
6253: @end example
6254:
6255: @noindent
6256: Creates a word called @code{name} that, upon execution, executes
6257: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
6258:
6259: The explanation above is somewhat superficial. For simple examples of
6260: colon definitions see @ref{Your first definition}. For an in-depth
6261: discussion of some of the issues involved, @xref{Interpretation and
6262: Compilation Semantics}.
6263:
6264: doc-:
6265: doc-;
6266:
6267:
6268: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
6269: @subsection Anonymous Definitions
6270: @cindex colon definitions
6271: @cindex defining words without name
6272:
6273: Sometimes you want to define an @dfn{anonymous word}; a word without a
6274: name. You can do this with:
6275:
6276: doc-:noname
6277:
6278: This leaves the execution token for the word on the stack after the
6279: closing @code{;}. Here's an example in which a deferred word is
6280: initialised with an @code{xt} from an anonymous colon definition:
6281:
6282: @example
6283: Defer deferred
6284: :noname ( ... -- ... )
6285: ... ;
6286: IS deferred
6287: @end example
6288:
6289: @noindent
6290: Gforth provides an alternative way of doing this, using two separate
6291: words:
6292:
6293: doc-noname
6294: @cindex execution token of last defined word
6295: doc-latestxt
6296:
6297: @noindent
6298: The previous example can be rewritten using @code{noname} and
6299: @code{latestxt}:
6300:
6301: @example
6302: Defer deferred
6303: noname : ( ... -- ... )
6304: ... ;
6305: latestxt IS deferred
6306: @end example
6307:
6308: @noindent
6309: @code{noname} works with any defining word, not just @code{:}.
6310:
6311: @code{latestxt} also works when the last word was not defined as
6312: @code{noname}. It does not work for combined words, though. It also has
6313: the useful property that is is valid as soon as the header for a
6314: definition has been built. Thus:
6315:
6316: @example
6317: latestxt . : foo [ latestxt . ] ; ' foo .
6318: @end example
6319:
6320: @noindent
6321: prints 3 numbers; the last two are the same.
6322:
6323: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6324: @subsection Supplying the name of a defined word
6325: @cindex names for defined words
6326: @cindex defining words, name given in a string
6327:
6328: By default, a defining word takes the name for the defined word from the
6329: input stream. Sometimes you want to supply the name from a string. You
6330: can do this with:
6331:
6332: doc-nextname
6333:
6334: For example:
6335:
6336: @example
6337: s" foo" nextname create
6338: @end example
6339:
6340: @noindent
6341: is equivalent to:
6342:
6343: @example
6344: create foo
6345: @end example
6346:
6347: @noindent
6348: @code{nextname} works with any defining word.
6349:
6350:
6351: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
6352: @subsection User-defined Defining Words
6353: @cindex user-defined defining words
6354: @cindex defining words, user-defined
6355:
6356: You can create a new defining word by wrapping defining-time code around
6357: an existing defining word and putting the sequence in a colon
6358: definition.
6359:
6360: @c anton: This example is very complex and leads in a quite different
6361: @c direction from the CREATE-DOES> stuff that follows. It should probably
6362: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6363: @c subsection of Defining Words)
6364:
6365: For example, suppose that you have a word @code{stats} that
6366: gathers statistics about colon definitions given the @i{xt} of the
6367: definition, and you want every colon definition in your application to
6368: make a call to @code{stats}. You can define and use a new version of
6369: @code{:} like this:
6370:
6371: @example
6372: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6373: ... ; \ other code
6374:
6375: : my: : latestxt postpone literal ['] stats compile, ;
6376:
6377: my: foo + - ;
6378: @end example
6379:
6380: When @code{foo} is defined using @code{my:} these steps occur:
6381:
6382: @itemize @bullet
6383: @item
6384: @code{my:} is executed.
6385: @item
6386: The @code{:} within the definition (the one between @code{my:} and
6387: @code{latestxt}) is executed, and does just what it always does; it parses
6388: the input stream for a name, builds a dictionary header for the name
6389: @code{foo} and switches @code{state} from interpret to compile.
6390: @item
6391: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
6392: being defined -- @code{foo} -- onto the stack.
6393: @item
6394: The code that was produced by @code{postpone literal} is executed; this
6395: causes the value on the stack to be compiled as a literal in the code
6396: area of @code{foo}.
6397: @item
6398: The code @code{['] stats} compiles a literal into the definition of
6399: @code{my:}. When @code{compile,} is executed, that literal -- the
6400: execution token for @code{stats} -- is layed down in the code area of
6401: @code{foo} , following the literal@footnote{Strictly speaking, the
6402: mechanism that @code{compile,} uses to convert an @i{xt} into something
6403: in the code area is implementation-dependent. A threaded implementation
6404: might spit out the execution token directly whilst another
6405: implementation might spit out a native code sequence.}.
6406: @item
6407: At this point, the execution of @code{my:} is complete, and control
6408: returns to the text interpreter. The text interpreter is in compile
6409: state, so subsequent text @code{+ -} is compiled into the definition of
6410: @code{foo} and the @code{;} terminates the definition as always.
6411: @end itemize
6412:
6413: You can use @code{see} to decompile a word that was defined using
6414: @code{my:} and see how it is different from a normal @code{:}
6415: definition. For example:
6416:
6417: @example
6418: : bar + - ; \ like foo but using : rather than my:
6419: see bar
6420: : bar
6421: + - ;
6422: see foo
6423: : foo
6424: 107645672 stats + - ;
6425:
6426: \ use ' foo . to show that 107645672 is the xt for foo
6427: @end example
6428:
6429: You can use techniques like this to make new defining words in terms of
6430: @i{any} existing defining word.
6431:
6432:
6433: @cindex defining defining words
6434: @cindex @code{CREATE} ... @code{DOES>}
6435: If you want the words defined with your defining words to behave
6436: differently from words defined with standard defining words, you can
6437: write your defining word like this:
6438:
6439: @example
6440: : def-word ( "name" -- )
6441: CREATE @i{code1}
6442: DOES> ( ... -- ... )
6443: @i{code2} ;
6444:
6445: def-word name
6446: @end example
6447:
6448: @cindex child words
6449: This fragment defines a @dfn{defining word} @code{def-word} and then
6450: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6451: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6452: is not executed at this time. The word @code{name} is sometimes called a
6453: @dfn{child} of @code{def-word}.
6454:
6455: When you execute @code{name}, the address of the body of @code{name} is
6456: put on the data stack and @i{code2} is executed (the address of the body
6457: of @code{name} is the address @code{HERE} returns immediately after the
6458: @code{CREATE}, i.e., the address a @code{create}d word returns by
6459: default).
6460:
6461: @c anton:
6462: @c www.dictionary.com says:
6463: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6464: @c several generations of absence, usually caused by the chance
6465: @c recombination of genes. 2.An individual or a part that exhibits
6466: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6467: @c of previous behavior after a period of absence.
6468: @c
6469: @c Doesn't seem to fit.
6470:
6471: @c @cindex atavism in child words
6472: You can use @code{def-word} to define a set of child words that behave
6473: similarly; they all have a common run-time behaviour determined by
6474: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6475: body of the child word. The structure of the data is common to all
6476: children of @code{def-word}, but the data values are specific -- and
6477: private -- to each child word. When a child word is executed, the
6478: address of its private data area is passed as a parameter on TOS to be
6479: used and manipulated@footnote{It is legitimate both to read and write to
6480: this data area.} by @i{code2}.
6481:
6482: The two fragments of code that make up the defining words act (are
6483: executed) at two completely separate times:
6484:
6485: @itemize @bullet
6486: @item
6487: At @i{define time}, the defining word executes @i{code1} to generate a
6488: child word
6489: @item
6490: At @i{child execution time}, when a child word is invoked, @i{code2}
6491: is executed, using parameters (data) that are private and specific to
6492: the child word.
6493: @end itemize
6494:
6495: Another way of understanding the behaviour of @code{def-word} and
6496: @code{name} is to say that, if you make the following definitions:
6497: @example
6498: : def-word1 ( "name" -- )
6499: CREATE @i{code1} ;
6500:
6501: : action1 ( ... -- ... )
6502: @i{code2} ;
6503:
6504: def-word1 name1
6505: @end example
6506:
6507: @noindent
6508: Then using @code{name1 action1} is equivalent to using @code{name}.
6509:
6510: The classic example is that you can define @code{CONSTANT} in this way:
6511:
6512: @example
6513: : CONSTANT ( w "name" -- )
6514: CREATE ,
6515: DOES> ( -- w )
6516: @@ ;
6517: @end example
6518:
6519: @comment There is a beautiful description of how this works and what
6520: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6521: @comment commentary on the Counting Fruits problem.
6522:
6523: When you create a constant with @code{5 CONSTANT five}, a set of
6524: define-time actions take place; first a new word @code{five} is created,
6525: then the value 5 is laid down in the body of @code{five} with
6526: @code{,}. When @code{five} is executed, the address of the body is put on
6527: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6528: no code of its own; it simply contains a data field and a pointer to the
6529: code that follows @code{DOES>} in its defining word. That makes words
6530: created in this way very compact.
6531:
6532: The final example in this section is intended to remind you that space
6533: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6534: both read and written by a Standard program@footnote{Exercise: use this
6535: example as a starting point for your own implementation of @code{Value}
6536: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6537: @code{[']}.}:
6538:
6539: @example
6540: : foo ( "name" -- )
6541: CREATE -1 ,
6542: DOES> ( -- )
6543: @@ . ;
6544:
6545: foo first-word
6546: foo second-word
6547:
6548: 123 ' first-word >BODY !
6549: @end example
6550:
6551: If @code{first-word} had been a @code{CREATE}d word, we could simply
6552: have executed it to get the address of its data field. However, since it
6553: was defined to have @code{DOES>} actions, its execution semantics are to
6554: perform those @code{DOES>} actions. To get the address of its data field
6555: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6556: translate the xt into the address of the data field. When you execute
6557: @code{first-word}, it will display @code{123}. When you execute
6558: @code{second-word} it will display @code{-1}.
6559:
6560: @cindex stack effect of @code{DOES>}-parts
6561: @cindex @code{DOES>}-parts, stack effect
6562: In the examples above the stack comment after the @code{DOES>} specifies
6563: the stack effect of the defined words, not the stack effect of the
6564: following code (the following code expects the address of the body on
6565: the top of stack, which is not reflected in the stack comment). This is
6566: the convention that I use and recommend (it clashes a bit with using
6567: locals declarations for stack effect specification, though).
6568:
6569: @menu
6570: * CREATE..DOES> applications::
6571: * CREATE..DOES> details::
6572: * Advanced does> usage example::
6573: * Const-does>::
6574: @end menu
6575:
6576: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
6577: @subsubsection Applications of @code{CREATE..DOES>}
6578: @cindex @code{CREATE} ... @code{DOES>}, applications
6579:
6580: You may wonder how to use this feature. Here are some usage patterns:
6581:
6582: @cindex factoring similar colon definitions
6583: When you see a sequence of code occurring several times, and you can
6584: identify a meaning, you will factor it out as a colon definition. When
6585: you see similar colon definitions, you can factor them using
6586: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6587: that look very similar:
6588: @example
6589: : ori, ( reg-target reg-source n -- )
6590: 0 asm-reg-reg-imm ;
6591: : andi, ( reg-target reg-source n -- )
6592: 1 asm-reg-reg-imm ;
6593: @end example
6594:
6595: @noindent
6596: This could be factored with:
6597: @example
6598: : reg-reg-imm ( op-code -- )
6599: CREATE ,
6600: DOES> ( reg-target reg-source n -- )
6601: @@ asm-reg-reg-imm ;
6602:
6603: 0 reg-reg-imm ori,
6604: 1 reg-reg-imm andi,
6605: @end example
6606:
6607: @cindex currying
6608: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6609: supply a part of the parameters for a word (known as @dfn{currying} in
6610: the functional language community). E.g., @code{+} needs two
6611: parameters. Creating versions of @code{+} with one parameter fixed can
6612: be done like this:
6613:
6614: @example
6615: : curry+ ( n1 "name" -- )
6616: CREATE ,
6617: DOES> ( n2 -- n1+n2 )
6618: @@ + ;
6619:
6620: 3 curry+ 3+
6621: -2 curry+ 2-
6622: @end example
6623:
6624:
6625: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
6626: @subsubsection The gory details of @code{CREATE..DOES>}
6627: @cindex @code{CREATE} ... @code{DOES>}, details
6628:
6629: doc-does>
6630:
6631: @cindex @code{DOES>} in a separate definition
6632: This means that you need not use @code{CREATE} and @code{DOES>} in the
6633: same definition; you can put the @code{DOES>}-part in a separate
6634: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
6635: @example
6636: : does1
6637: DOES> ( ... -- ... )
6638: ... ;
6639:
6640: : does2
6641: DOES> ( ... -- ... )
6642: ... ;
6643:
6644: : def-word ( ... -- ... )
6645: create ...
6646: IF
6647: does1
6648: ELSE
6649: does2
6650: ENDIF ;
6651: @end example
6652:
6653: In this example, the selection of whether to use @code{does1} or
6654: @code{does2} is made at definition-time; at the time that the child word is
6655: @code{CREATE}d.
6656:
6657: @cindex @code{DOES>} in interpretation state
6658: In a standard program you can apply a @code{DOES>}-part only if the last
6659: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6660: will override the behaviour of the last word defined in any case. In a
6661: standard program, you can use @code{DOES>} only in a colon
6662: definition. In Gforth, you can also use it in interpretation state, in a
6663: kind of one-shot mode; for example:
6664: @example
6665: CREATE name ( ... -- ... )
6666: @i{initialization}
6667: DOES>
6668: @i{code} ;
6669: @end example
6670:
6671: @noindent
6672: is equivalent to the standard:
6673: @example
6674: :noname
6675: DOES>
6676: @i{code} ;
6677: CREATE name EXECUTE ( ... -- ... )
6678: @i{initialization}
6679: @end example
6680:
6681: doc->body
6682:
6683: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
6684: @subsubsection Advanced does> usage example
6685:
6686: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6687: for disassembling instructions, that follow a very repetetive scheme:
6688:
6689: @example
6690: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6691: @var{entry-num} cells @var{table} + !
6692: @end example
6693:
6694: Of course, this inspires the idea to factor out the commonalities to
6695: allow a definition like
6696:
6697: @example
6698: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6699: @end example
6700:
6701: The parameters @var{disasm-operands} and @var{table} are usually
6702: correlated. Moreover, before I wrote the disassembler, there already
6703: existed code that defines instructions like this:
6704:
6705: @example
6706: @var{entry-num} @var{inst-format} @var{inst-name}
6707: @end example
6708:
6709: This code comes from the assembler and resides in
6710: @file{arch/mips/insts.fs}.
6711:
6712: So I had to define the @var{inst-format} words that performed the scheme
6713: above when executed. At first I chose to use run-time code-generation:
6714:
6715: @example
6716: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6717: :noname Postpone @var{disasm-operands}
6718: name Postpone sliteral Postpone type Postpone ;
6719: swap cells @var{table} + ! ;
6720: @end example
6721:
6722: Note that this supplies the other two parameters of the scheme above.
6723:
6724: An alternative would have been to write this using
6725: @code{create}/@code{does>}:
6726:
6727: @example
6728: : @var{inst-format} ( entry-num "name" -- )
6729: here name string, ( entry-num c-addr ) \ parse and save "name"
6730: noname create , ( entry-num )
6731: latestxt swap cells @var{table} + !
6732: does> ( addr w -- )
6733: \ disassemble instruction w at addr
6734: @@ >r
6735: @var{disasm-operands}
6736: r> count type ;
6737: @end example
6738:
6739: Somehow the first solution is simpler, mainly because it's simpler to
6740: shift a string from definition-time to use-time with @code{sliteral}
6741: than with @code{string,} and friends.
6742:
6743: I wrote a lot of words following this scheme and soon thought about
6744: factoring out the commonalities among them. Note that this uses a
6745: two-level defining word, i.e., a word that defines ordinary defining
6746: words.
6747:
6748: This time a solution involving @code{postpone} and friends seemed more
6749: difficult (try it as an exercise), so I decided to use a
6750: @code{create}/@code{does>} word; since I was already at it, I also used
6751: @code{create}/@code{does>} for the lower level (try using
6752: @code{postpone} etc. as an exercise), resulting in the following
6753: definition:
6754:
6755: @example
6756: : define-format ( disasm-xt table-xt -- )
6757: \ define an instruction format that uses disasm-xt for
6758: \ disassembling and enters the defined instructions into table
6759: \ table-xt
6760: create 2,
6761: does> ( u "inst" -- )
6762: \ defines an anonymous word for disassembling instruction inst,
6763: \ and enters it as u-th entry into table-xt
6764: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6765: noname create 2, \ define anonymous word
6766: execute latestxt swap ! \ enter xt of defined word into table-xt
6767: does> ( addr w -- )
6768: \ disassemble instruction w at addr
6769: 2@@ >r ( addr w disasm-xt R: c-addr )
6770: execute ( R: c-addr ) \ disassemble operands
6771: r> count type ; \ print name
6772: @end example
6773:
6774: Note that the tables here (in contrast to above) do the @code{cells +}
6775: by themselves (that's why you have to pass an xt). This word is used in
6776: the following way:
6777:
6778: @example
6779: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6780: @end example
6781:
6782: As shown above, the defined instruction format is then used like this:
6783:
6784: @example
6785: @var{entry-num} @var{inst-format} @var{inst-name}
6786: @end example
6787:
6788: In terms of currying, this kind of two-level defining word provides the
6789: parameters in three stages: first @var{disasm-operands} and @var{table},
6790: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6791: the instruction to be disassembled.
6792:
6793: Of course this did not quite fit all the instruction format names used
6794: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6795: the parameters into the right form.
6796:
6797: If you have trouble following this section, don't worry. First, this is
6798: involved and takes time (and probably some playing around) to
6799: understand; second, this is the first two-level
6800: @code{create}/@code{does>} word I have written in seventeen years of
6801: Forth; and if I did not have @file{insts.fs} to start with, I may well
6802: have elected to use just a one-level defining word (with some repeating
6803: of parameters when using the defining word). So it is not necessary to
6804: understand this, but it may improve your understanding of Forth.
6805:
6806:
6807: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
6808: @subsubsection @code{Const-does>}
6809:
6810: A frequent use of @code{create}...@code{does>} is for transferring some
6811: values from definition-time to run-time. Gforth supports this use with
6812:
6813: doc-const-does>
6814:
6815: A typical use of this word is:
6816:
6817: @example
6818: : curry+ ( n1 "name" -- )
6819: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6820: + ;
6821:
6822: 3 curry+ 3+
6823: @end example
6824:
6825: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6826: definition to run-time.
6827:
6828: The advantages of using @code{const-does>} are:
6829:
6830: @itemize
6831:
6832: @item
6833: You don't have to deal with storing and retrieving the values, i.e.,
6834: your program becomes more writable and readable.
6835:
6836: @item
6837: When using @code{does>}, you have to introduce a @code{@@} that cannot
6838: be optimized away (because you could change the data using
6839: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6840:
6841: @end itemize
6842:
6843: An ANS Forth implementation of @code{const-does>} is available in
6844: @file{compat/const-does.fs}.
6845:
6846:
6847: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
6848: @subsection Deferred Words
6849: @cindex deferred words
6850:
6851: The defining word @code{Defer} allows you to define a word by name
6852: without defining its behaviour; the definition of its behaviour is
6853: deferred. Here are two situation where this can be useful:
6854:
6855: @itemize @bullet
6856: @item
6857: Where you want to allow the behaviour of a word to be altered later, and
6858: for all precompiled references to the word to change when its behaviour
6859: is changed.
6860: @item
6861: For mutual recursion; @xref{Calls and returns}.
6862: @end itemize
6863:
6864: In the following example, @code{foo} always invokes the version of
6865: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6866: always invokes the version that prints ``@code{Hello}''. There is no way
6867: of getting @code{foo} to use the later version without re-ordering the
6868: source code and recompiling it.
6869:
6870: @example
6871: : greet ." Good morning" ;
6872: : foo ... greet ... ;
6873: : greet ." Hello" ;
6874: : bar ... greet ... ;
6875: @end example
6876:
6877: This problem can be solved by defining @code{greet} as a @code{Defer}red
6878: word. The behaviour of a @code{Defer}red word can be defined and
6879: redefined at any time by using @code{IS} to associate the xt of a
6880: previously-defined word with it. The previous example becomes:
6881:
6882: @example
6883: Defer greet ( -- )
6884: : foo ... greet ... ;
6885: : bar ... greet ... ;
6886: : greet1 ( -- ) ." Good morning" ;
6887: : greet2 ( -- ) ." Hello" ;
6888: ' greet2 IS greet \ make greet behave like greet2
6889: @end example
6890:
6891: @progstyle
6892: You should write a stack comment for every deferred word, and put only
6893: XTs into deferred words that conform to this stack effect. Otherwise
6894: it's too difficult to use the deferred word.
6895:
6896: A deferred word can be used to improve the statistics-gathering example
6897: from @ref{User-defined Defining Words}; rather than edit the
6898: application's source code to change every @code{:} to a @code{my:}, do
6899: this:
6900:
6901: @example
6902: : real: : ; \ retain access to the original
6903: defer : \ redefine as a deferred word
6904: ' my: IS : \ use special version of :
6905: \
6906: \ load application here
6907: \
6908: ' real: IS : \ go back to the original
6909: @end example
6910:
6911:
6912: One thing to note is that @code{IS} has special compilation semantics,
6913: such that it parses the name at compile time (like @code{TO}):
6914:
6915: @example
6916: : set-greet ( xt -- )
6917: IS greet ;
6918:
6919: ' greet1 set-greet
6920: @end example
6921:
6922: In situations where @code{IS} does not fit, use @code{defer!} instead.
6923:
6924: A deferred word can only inherit execution semantics from the xt
6925: (because that is all that an xt can represent -- for more discussion of
6926: this @pxref{Tokens for Words}); by default it will have default
6927: interpretation and compilation semantics deriving from this execution
6928: semantics. However, you can change the interpretation and compilation
6929: semantics of the deferred word in the usual ways:
6930:
6931: @example
6932: : bar .... ; immediate
6933: Defer fred immediate
6934: Defer jim
6935:
6936: ' bar IS jim \ jim has default semantics
6937: ' bar IS fred \ fred is immediate
6938: @end example
6939:
6940: doc-defer
6941: doc-defer!
6942: doc-is
6943: doc-defer@
6944: doc-action-of
6945: @comment TODO document these: what's defers [is]
6946: doc-defers
6947:
6948: @c Use @code{words-deferred} to see a list of deferred words.
6949:
6950: Definitions of these words (except @code{defers}) in ANS Forth are
6951: provided in @file{compat/defer.fs}.
6952:
6953:
6954: @node Aliases, , Deferred Words, Defining Words
6955: @subsection Aliases
6956: @cindex aliases
6957:
6958: The defining word @code{Alias} allows you to define a word by name that
6959: has the same behaviour as some other word. Here are two situation where
6960: this can be useful:
6961:
6962: @itemize @bullet
6963: @item
6964: When you want access to a word's definition from a different word list
6965: (for an example of this, see the definition of the @code{Root} word list
6966: in the Gforth source).
6967: @item
6968: When you want to create a synonym; a definition that can be known by
6969: either of two names (for example, @code{THEN} and @code{ENDIF} are
6970: aliases).
6971: @end itemize
6972:
6973: Like deferred words, an alias has default compilation and interpretation
6974: semantics at the beginning (not the modifications of the other word),
6975: but you can change them in the usual ways (@code{immediate},
6976: @code{compile-only}). For example:
6977:
6978: @example
6979: : foo ... ; immediate
6980:
6981: ' foo Alias bar \ bar is not an immediate word
6982: ' foo Alias fooby immediate \ fooby is an immediate word
6983: @end example
6984:
6985: Words that are aliases have the same xt, different headers in the
6986: dictionary, and consequently different name tokens (@pxref{Tokens for
6987: Words}) and possibly different immediate flags. An alias can only have
6988: default or immediate compilation semantics; you can define aliases for
6989: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
6990:
6991: doc-alias
6992:
6993:
6994: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6995: @section Interpretation and Compilation Semantics
6996: @cindex semantics, interpretation and compilation
6997:
6998: @c !! state and ' are used without explanation
6999: @c example for immediate/compile-only? or is the tutorial enough
7000:
7001: @cindex interpretation semantics
7002: The @dfn{interpretation semantics} of a (named) word are what the text
7003: interpreter does when it encounters the word in interpret state. It also
7004: appears in some other contexts, e.g., the execution token returned by
7005: @code{' @i{word}} identifies the interpretation semantics of @i{word}
7006: (in other words, @code{' @i{word} execute} is equivalent to
7007: interpret-state text interpretation of @code{@i{word}}).
7008:
7009: @cindex compilation semantics
7010: The @dfn{compilation semantics} of a (named) word are what the text
7011: interpreter does when it encounters the word in compile state. It also
7012: appears in other contexts, e.g, @code{POSTPONE @i{word}}
7013: compiles@footnote{In standard terminology, ``appends to the current
7014: definition''.} the compilation semantics of @i{word}.
7015:
7016: @cindex execution semantics
7017: The standard also talks about @dfn{execution semantics}. They are used
7018: only for defining the interpretation and compilation semantics of many
7019: words. By default, the interpretation semantics of a word are to
7020: @code{execute} its execution semantics, and the compilation semantics of
7021: a word are to @code{compile,} its execution semantics.@footnote{In
7022: standard terminology: The default interpretation semantics are its
7023: execution semantics; the default compilation semantics are to append its
7024: execution semantics to the execution semantics of the current
7025: definition.}
7026:
7027: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
7028: the text interpreter, ticked, or @code{postpone}d, so they have no
7029: interpretation or compilation semantics. Their behaviour is represented
7030: by their XT (@pxref{Tokens for Words}), and we call it execution
7031: semantics, too.
7032:
7033: @comment TODO expand, make it co-operate with new sections on text interpreter.
7034:
7035: @cindex immediate words
7036: @cindex compile-only words
7037: You can change the semantics of the most-recently defined word:
7038:
7039:
7040: doc-immediate
7041: doc-compile-only
7042: doc-restrict
7043:
7044: By convention, words with non-default compilation semantics (e.g.,
7045: immediate words) often have names surrounded with brackets (e.g.,
7046: @code{[']}, @pxref{Execution token}).
7047:
7048: Note that ticking (@code{'}) a compile-only word gives an error
7049: (``Interpreting a compile-only word'').
7050:
7051: @menu
7052: * Combined words::
7053: @end menu
7054:
7055:
7056: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
7057: @subsection Combined Words
7058: @cindex combined words
7059:
7060: Gforth allows you to define @dfn{combined words} -- words that have an
7061: arbitrary combination of interpretation and compilation semantics.
7062:
7063: doc-interpret/compile:
7064:
7065: This feature was introduced for implementing @code{TO} and @code{S"}. I
7066: recommend that you do not define such words, as cute as they may be:
7067: they make it hard to get at both parts of the word in some contexts.
7068: E.g., assume you want to get an execution token for the compilation
7069: part. Instead, define two words, one that embodies the interpretation
7070: part, and one that embodies the compilation part. Once you have done
7071: that, you can define a combined word with @code{interpret/compile:} for
7072: the convenience of your users.
7073:
7074: You might try to use this feature to provide an optimizing
7075: implementation of the default compilation semantics of a word. For
7076: example, by defining:
7077: @example
7078: :noname
7079: foo bar ;
7080: :noname
7081: POSTPONE foo POSTPONE bar ;
7082: interpret/compile: opti-foobar
7083: @end example
7084:
7085: @noindent
7086: as an optimizing version of:
7087:
7088: @example
7089: : foobar
7090: foo bar ;
7091: @end example
7092:
7093: Unfortunately, this does not work correctly with @code{[compile]},
7094: because @code{[compile]} assumes that the compilation semantics of all
7095: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
7096: opti-foobar} would compile compilation semantics, whereas
7097: @code{[compile] foobar} would compile interpretation semantics.
7098:
7099: @cindex state-smart words (are a bad idea)
7100: @anchor{state-smartness}
7101: Some people try to use @dfn{state-smart} words to emulate the feature provided
7102: by @code{interpret/compile:} (words are state-smart if they check
7103: @code{STATE} during execution). E.g., they would try to code
7104: @code{foobar} like this:
7105:
7106: @example
7107: : foobar
7108: STATE @@
7109: IF ( compilation state )
7110: POSTPONE foo POSTPONE bar
7111: ELSE
7112: foo bar
7113: ENDIF ; immediate
7114: @end example
7115:
7116: Although this works if @code{foobar} is only processed by the text
7117: interpreter, it does not work in other contexts (like @code{'} or
7118: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
7119: for a state-smart word, not for the interpretation semantics of the
7120: original @code{foobar}; when you execute this execution token (directly
7121: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
7122: state, the result will not be what you expected (i.e., it will not
7123: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
7124: write them@footnote{For a more detailed discussion of this topic, see
7125: M. Anton Ertl,
7126: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
7127: it is Evil and How to Exorcise it}}, EuroForth '98.}!
7128:
7129: @cindex defining words with arbitrary semantics combinations
7130: It is also possible to write defining words that define words with
7131: arbitrary combinations of interpretation and compilation semantics. In
7132: general, they look like this:
7133:
7134: @example
7135: : def-word
7136: create-interpret/compile
7137: @i{code1}
7138: interpretation>
7139: @i{code2}
7140: <interpretation
7141: compilation>
7142: @i{code3}
7143: <compilation ;
7144: @end example
7145:
7146: For a @i{word} defined with @code{def-word}, the interpretation
7147: semantics are to push the address of the body of @i{word} and perform
7148: @i{code2}, and the compilation semantics are to push the address of
7149: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
7150: can also be defined like this (except that the defined constants don't
7151: behave correctly when @code{[compile]}d):
7152:
7153: @example
7154: : constant ( n "name" -- )
7155: create-interpret/compile
7156: ,
7157: interpretation> ( -- n )
7158: @@
7159: <interpretation
7160: compilation> ( compilation. -- ; run-time. -- n )
7161: @@ postpone literal
7162: <compilation ;
7163: @end example
7164:
7165:
7166: doc-create-interpret/compile
7167: doc-interpretation>
7168: doc-<interpretation
7169: doc-compilation>
7170: doc-<compilation
7171:
7172:
7173: Words defined with @code{interpret/compile:} and
7174: @code{create-interpret/compile} have an extended header structure that
7175: differs from other words; however, unless you try to access them with
7176: plain address arithmetic, you should not notice this. Words for
7177: accessing the header structure usually know how to deal with this; e.g.,
7178: @code{'} @i{word} @code{>body} also gives you the body of a word created
7179: with @code{create-interpret/compile}.
7180:
7181:
7182: @c -------------------------------------------------------------
7183: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
7184: @section Tokens for Words
7185: @cindex tokens for words
7186:
7187: This section describes the creation and use of tokens that represent
7188: words.
7189:
7190: @menu
7191: * Execution token:: represents execution/interpretation semantics
7192: * Compilation token:: represents compilation semantics
7193: * Name token:: represents named words
7194: @end menu
7195:
7196: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7197: @subsection Execution token
7198:
7199: @cindex xt
7200: @cindex execution token
7201: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7202: You can use @code{execute} to invoke this behaviour.
7203:
7204: @cindex tick (')
7205: You can use @code{'} to get an execution token that represents the
7206: interpretation semantics of a named word:
7207:
7208: @example
7209: 5 ' . ( n xt )
7210: execute ( ) \ execute the xt (i.e., ".")
7211: @end example
7212:
7213: doc-'
7214:
7215: @code{'} parses at run-time; there is also a word @code{[']} that parses
7216: when it is compiled, and compiles the resulting XT:
7217:
7218: @example
7219: : foo ['] . execute ;
7220: 5 foo
7221: : bar ' execute ; \ by contrast,
7222: 5 bar . \ ' parses "." when bar executes
7223: @end example
7224:
7225: doc-[']
7226:
7227: If you want the execution token of @i{word}, write @code{['] @i{word}}
7228: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7229: @code{'} and @code{[']} behave somewhat unusually by complaining about
7230: compile-only words (because these words have no interpretation
7231: semantics). You might get what you want by using @code{COMP' @i{word}
7232: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7233: token}).
7234:
7235: Another way to get an XT is @code{:noname} or @code{latestxt}
7236: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7237: for the only behaviour the word has (the execution semantics). For
7238: named words, @code{latestxt} produces an XT for the same behaviour it
7239: would produce if the word was defined anonymously.
7240:
7241: @example
7242: :noname ." hello" ;
7243: execute
7244: @end example
7245:
7246: An XT occupies one cell and can be manipulated like any other cell.
7247:
7248: @cindex code field address
7249: @cindex CFA
7250: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7251: operations that produce or consume it). For old hands: In Gforth, the
7252: XT is implemented as a code field address (CFA).
7253:
7254: doc-execute
7255: doc-perform
7256:
7257: @node Compilation token, Name token, Execution token, Tokens for Words
7258: @subsection Compilation token
7259:
7260: @cindex compilation token
7261: @cindex CT (compilation token)
7262: Gforth represents the compilation semantics of a named word by a
7263: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7264: @i{xt} is an execution token. The compilation semantics represented by
7265: the compilation token can be performed with @code{execute}, which
7266: consumes the whole compilation token, with an additional stack effect
7267: determined by the represented compilation semantics.
7268:
7269: At present, the @i{w} part of a compilation token is an execution token,
7270: and the @i{xt} part represents either @code{execute} or
7271: @code{compile,}@footnote{Depending upon the compilation semantics of the
7272: word. If the word has default compilation semantics, the @i{xt} will
7273: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7274: @i{xt} will represent @code{execute}.}. However, don't rely on that
7275: knowledge, unless necessary; future versions of Gforth may introduce
7276: unusual compilation tokens (e.g., a compilation token that represents
7277: the compilation semantics of a literal).
7278:
7279: You can perform the compilation semantics represented by the compilation
7280: token with @code{execute}. You can compile the compilation semantics
7281: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7282: equivalent to @code{postpone @i{word}}.
7283:
7284: doc-[comp']
7285: doc-comp'
7286: doc-postpone,
7287:
7288: @node Name token, , Compilation token, Tokens for Words
7289: @subsection Name token
7290:
7291: @cindex name token
7292: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7293: token is an abstract data type that occurs as argument or result of the
7294: words below.
7295:
7296: @c !! put this elswhere?
7297: @cindex name field address
7298: @cindex NFA
7299: The closest thing to the nt in older Forth systems is the name field
7300: address (NFA), but there are significant differences: in older Forth
7301: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7302: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7303: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7304: is a link field in the structure identified by the name token, but
7305: searching usually uses a hash table external to these structures; the
7306: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7307: implemented as the address of that count field.
7308:
7309: doc-find-name
7310: doc-latest
7311: doc->name
7312: doc-name>int
7313: doc-name?int
7314: doc-name>comp
7315: doc-name>string
7316: doc-id.
7317: doc-.name
7318: doc-.id
7319:
7320: @c ----------------------------------------------------------
7321: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7322: @section Compiling words
7323: @cindex compiling words
7324: @cindex macros
7325:
7326: In contrast to most other languages, Forth has no strict boundary
7327: between compilation and run-time. E.g., you can run arbitrary code
7328: between defining words (or for computing data used by defining words
7329: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7330: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7331: running arbitrary code while compiling a colon definition (exception:
7332: you must not allot dictionary space).
7333:
7334: @menu
7335: * Literals:: Compiling data values
7336: * Macros:: Compiling words
7337: @end menu
7338:
7339: @node Literals, Macros, Compiling words, Compiling words
7340: @subsection Literals
7341: @cindex Literals
7342:
7343: The simplest and most frequent example is to compute a literal during
7344: compilation. E.g., the following definition prints an array of strings,
7345: one string per line:
7346:
7347: @example
7348: : .strings ( addr u -- ) \ gforth
7349: 2* cells bounds U+DO
7350: cr i 2@@ type
7351: 2 cells +LOOP ;
7352: @end example
7353:
7354: With a simple-minded compiler like Gforth's, this computes @code{2
7355: cells} on every loop iteration. You can compute this value once and for
7356: all at compile time and compile it into the definition like this:
7357:
7358: @example
7359: : .strings ( addr u -- ) \ gforth
7360: 2* cells bounds U+DO
7361: cr i 2@@ type
7362: [ 2 cells ] literal +LOOP ;
7363: @end example
7364:
7365: @code{[} switches the text interpreter to interpret state (you will get
7366: an @code{ok} prompt if you type this example interactively and insert a
7367: newline between @code{[} and @code{]}), so it performs the
7368: interpretation semantics of @code{2 cells}; this computes a number.
7369: @code{]} switches the text interpreter back into compile state. It then
7370: performs @code{Literal}'s compilation semantics, which are to compile
7371: this number into the current word. You can decompile the word with
7372: @code{see .strings} to see the effect on the compiled code.
7373:
7374: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7375: *} in this way.
7376:
7377: doc-[
7378: doc-]
7379: doc-literal
7380: doc-]L
7381:
7382: There are also words for compiling other data types than single cells as
7383: literals:
7384:
7385: doc-2literal
7386: doc-fliteral
7387: doc-sliteral
7388:
7389: @cindex colon-sys, passing data across @code{:}
7390: @cindex @code{:}, passing data across
7391: You might be tempted to pass data from outside a colon definition to the
7392: inside on the data stack. This does not work, because @code{:} puhes a
7393: colon-sys, making stuff below unaccessible. E.g., this does not work:
7394:
7395: @example
7396: 5 : foo literal ; \ error: "unstructured"
7397: @end example
7398:
7399: Instead, you have to pass the value in some other way, e.g., through a
7400: variable:
7401:
7402: @example
7403: variable temp
7404: 5 temp !
7405: : foo [ temp @@ ] literal ;
7406: @end example
7407:
7408:
7409: @node Macros, , Literals, Compiling words
7410: @subsection Macros
7411: @cindex Macros
7412: @cindex compiling compilation semantics
7413:
7414: @code{Literal} and friends compile data values into the current
7415: definition. You can also write words that compile other words into the
7416: current definition. E.g.,
7417:
7418: @example
7419: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7420: POSTPONE + ;
7421:
7422: : foo ( n1 n2 -- n )
7423: [ compile-+ ] ;
7424: 1 2 foo .
7425: @end example
7426:
7427: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7428: What happens in this example? @code{Postpone} compiles the compilation
7429: semantics of @code{+} into @code{compile-+}; later the text interpreter
7430: executes @code{compile-+} and thus the compilation semantics of +, which
7431: compile (the execution semantics of) @code{+} into
7432: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7433: should only be executed in compile state, so this example is not
7434: guaranteed to work on all standard systems, but on any decent system it
7435: will work.}
7436:
7437: doc-postpone
7438:
7439: Compiling words like @code{compile-+} are usually immediate (or similar)
7440: so you do not have to switch to interpret state to execute them;
7441: modifying the last example accordingly produces:
7442:
7443: @example
7444: : [compile-+] ( compilation: --; interpretation: -- )
7445: \ compiled code: ( n1 n2 -- n )
7446: POSTPONE + ; immediate
7447:
7448: : foo ( n1 n2 -- n )
7449: [compile-+] ;
7450: 1 2 foo .
7451: @end example
7452:
7453: You will occassionally find the need to POSTPONE several words;
7454: putting POSTPONE before each such word is cumbersome, so Gforth
7455: provides a more convenient syntax: @code{]] ... [[}. This
7456: allows us to write @code{[compile-+]} as:
7457:
7458: @example
7459: : [compile-+] ( compilation: --; interpretation: -- )
7460: ]] + [[ ; immediate
7461: @end example
7462:
7463: doc-]]
7464: doc-[[
7465:
7466: The unusual direction of the brackets indicates their function:
7467: @code{]]} switches from compilation to postponing (i.e., compilation
7468: of compilation), just like @code{]} switches from immediate execution
7469: (interpretation) to compilation. Conversely, @code{[[} switches from
7470: postponing to compilation, ananlogous to @code{[} which switches from
7471: compilation to immediate execution.
7472:
7473: The real advantage of @code{]] }...@code{ [[} becomes apparent when
7474: there are many words to POSTPONE. E.g., the word
7475: @code{compile-map-array} (@pxref{Advanced macros Tutorial}) can be
7476: written much shorter as follows:
7477:
7478: @example
7479: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
7480: \ at run-time, execute xt ( ... x -- ... ) for each element of the
7481: \ array beginning at addr and containing u elements
7482: @{ xt @}
7483: ]] cells over + swap ?do
7484: i @@ [[ xt compile,
7485: 1 cells ]]L +loop [[ ;
7486: @end example
7487:
7488: This example also uses @code{]]L} as a shortcut for @code{]] literal}.
7489: There are also other shortcuts
7490:
7491: doc-]]L
7492: doc-]]2L
7493: doc-]]FL
7494: doc-]]SL
7495:
7496: Note that parsing words don't parse at postpone time; if you want to
7497: provide the parsed string right away, you have to switch back to
7498: compilation:
7499:
7500: @example
7501: ]] ... [[ s" some string" ]]2L ... [[
7502: ]] ... [[ ['] + ]]L ... [[
7503: @end example
7504:
7505: Definitions of @code{]]} and friends in ANS Forth are provided in
7506: @file{compat/macros.fs}.
7507:
7508: Immediate compiling words are similar to macros in other languages (in
7509: particular, Lisp). The important differences to macros in, e.g., C are:
7510:
7511: @itemize @bullet
7512:
7513: @item
7514: You use the same language for defining and processing macros, not a
7515: separate preprocessing language and processor.
7516:
7517: @item
7518: Consequently, the full power of Forth is available in macro definitions.
7519: E.g., you can perform arbitrarily complex computations, or generate
7520: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7521: Tutorial}). This power is very useful when writing a parser generators
7522: or other code-generating software.
7523:
7524: @item
7525: Macros defined using @code{postpone} etc. deal with the language at a
7526: higher level than strings; name binding happens at macro definition
7527: time, so you can avoid the pitfalls of name collisions that can happen
7528: in C macros. Of course, Forth is a liberal language and also allows to
7529: shoot yourself in the foot with text-interpreted macros like
7530:
7531: @example
7532: : [compile-+] s" +" evaluate ; immediate
7533: @end example
7534:
7535: Apart from binding the name at macro use time, using @code{evaluate}
7536: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7537: @end itemize
7538:
7539: You may want the macro to compile a number into a word. The word to do
7540: it is @code{literal}, but you have to @code{postpone} it, so its
7541: compilation semantics take effect when the macro is executed, not when
7542: it is compiled:
7543:
7544: @example
7545: : [compile-5] ( -- ) \ compiled code: ( -- n )
7546: 5 POSTPONE literal ; immediate
7547:
7548: : foo [compile-5] ;
7549: foo .
7550: @end example
7551:
7552: You may want to pass parameters to a macro, that the macro should
7553: compile into the current definition. If the parameter is a number, then
7554: you can use @code{postpone literal} (similar for other values).
7555:
7556: If you want to pass a word that is to be compiled, the usual way is to
7557: pass an execution token and @code{compile,} it:
7558:
7559: @example
7560: : twice1 ( xt -- ) \ compiled code: ... -- ...
7561: dup compile, compile, ;
7562:
7563: : 2+ ( n1 -- n2 )
7564: [ ' 1+ twice1 ] ;
7565: @end example
7566:
7567: doc-compile,
7568:
7569: An alternative available in Gforth, that allows you to pass compile-only
7570: words as parameters is to use the compilation token (@pxref{Compilation
7571: token}). The same example in this technique:
7572:
7573: @example
7574: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7575: 2dup 2>r execute 2r> execute ;
7576:
7577: : 2+ ( n1 -- n2 )
7578: [ comp' 1+ twice ] ;
7579: @end example
7580:
7581: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7582: works even if the executed compilation semantics has an effect on the
7583: data stack.
7584:
7585: You can also define complete definitions with these words; this provides
7586: an alternative to using @code{does>} (@pxref{User-defined Defining
7587: Words}). E.g., instead of
7588:
7589: @example
7590: : curry+ ( n1 "name" -- )
7591: CREATE ,
7592: DOES> ( n2 -- n1+n2 )
7593: @@ + ;
7594: @end example
7595:
7596: you could define
7597:
7598: @example
7599: : curry+ ( n1 "name" -- )
7600: \ name execution: ( n2 -- n1+n2 )
7601: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
7602:
7603: -3 curry+ 3-
7604: see 3-
7605: @end example
7606:
7607: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7608: colon-sys on the data stack that makes everything below it unaccessible.
7609:
7610: This way of writing defining words is sometimes more, sometimes less
7611: convenient than using @code{does>} (@pxref{Advanced does> usage
7612: example}). One advantage of this method is that it can be optimized
7613: better, because the compiler knows that the value compiled with
7614: @code{literal} is fixed, whereas the data associated with a
7615: @code{create}d word can be changed.
7616:
7617: @c doc-[compile] !! not properly documented
7618:
7619: @c ----------------------------------------------------------
7620: @node The Text Interpreter, The Input Stream, Compiling words, Words
7621: @section The Text Interpreter
7622: @cindex interpreter - outer
7623: @cindex text interpreter
7624: @cindex outer interpreter
7625:
7626: @c Should we really describe all these ugly details? IMO the text
7627: @c interpreter should be much cleaner, but that may not be possible within
7628: @c ANS Forth. - anton
7629: @c nac-> I wanted to explain how it works to show how you can exploit
7630: @c it in your own programs. When I was writing a cross-compiler, figuring out
7631: @c some of these gory details was very helpful to me. None of the textbooks
7632: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7633: @c seems to positively avoid going into too much detail for some of
7634: @c the internals.
7635:
7636: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7637: @c it is; for the ugly details, I would prefer another place. I wonder
7638: @c whether we should have a chapter before "Words" that describes some
7639: @c basic concepts referred to in words, and a chapter after "Words" that
7640: @c describes implementation details.
7641:
7642: The text interpreter@footnote{This is an expanded version of the
7643: material in @ref{Introducing the Text Interpreter}.} is an endless loop
7644: that processes input from the current input device. It is also called
7645: the outer interpreter, in contrast to the inner interpreter
7646: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7647: implementations.
7648:
7649: @cindex interpret state
7650: @cindex compile state
7651: The text interpreter operates in one of two states: @dfn{interpret
7652: state} and @dfn{compile state}. The current state is defined by the
7653: aptly-named variable @code{state}.
7654:
7655: This section starts by describing how the text interpreter behaves when
7656: it is in interpret state, processing input from the user input device --
7657: the keyboard. This is the mode that a Forth system is in after it starts
7658: up.
7659:
7660: @cindex input buffer
7661: @cindex terminal input buffer
7662: The text interpreter works from an area of memory called the @dfn{input
7663: buffer}@footnote{When the text interpreter is processing input from the
7664: keyboard, this area of memory is called the @dfn{terminal input buffer}
7665: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7666: @code{#TIB}.}, which stores your keyboard input when you press the
7667: @key{RET} key. Starting at the beginning of the input buffer, it skips
7668: leading spaces (called @dfn{delimiters}) then parses a string (a
7669: sequence of non-space characters) until it reaches either a space
7670: character or the end of the buffer. Having parsed a string, it makes two
7671: attempts to process it:
7672:
7673: @cindex dictionary
7674: @itemize @bullet
7675: @item
7676: It looks for the string in a @dfn{dictionary} of definitions. If the
7677: string is found, the string names a @dfn{definition} (also known as a
7678: @dfn{word}) and the dictionary search returns information that allows
7679: the text interpreter to perform the word's @dfn{interpretation
7680: semantics}. In most cases, this simply means that the word will be
7681: executed.
7682: @item
7683: If the string is not found in the dictionary, the text interpreter
7684: attempts to treat it as a number, using the rules described in
7685: @ref{Number Conversion}. If the string represents a legal number in the
7686: current radix, the number is pushed onto a parameter stack (the data
7687: stack for integers, the floating-point stack for floating-point
7688: numbers).
7689: @end itemize
7690:
7691: If both attempts fail, or if the word is found in the dictionary but has
7692: no interpretation semantics@footnote{This happens if the word was
7693: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7694: remainder of the input buffer, issues an error message and waits for
7695: more input. If one of the attempts succeeds, the text interpreter
7696: repeats the parsing process until the whole of the input buffer has been
7697: processed, at which point it prints the status message ``@code{ ok}''
7698: and waits for more input.
7699:
7700: @c anton: this should be in the input stream subsection (or below it)
7701:
7702: @cindex parse area
7703: The text interpreter keeps track of its position in the input buffer by
7704: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7705: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7706: of the input buffer. The region from offset @code{>IN @@} to the end of
7707: the input buffer is called the @dfn{parse area}@footnote{In other words,
7708: the text interpreter processes the contents of the input buffer by
7709: parsing strings from the parse area until the parse area is empty.}.
7710: This example shows how @code{>IN} changes as the text interpreter parses
7711: the input buffer:
7712:
7713: @example
7714: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7715: CR ." ->" TYPE ." <-" ; IMMEDIATE
7716:
7717: 1 2 3 remaining + remaining .
7718:
7719: : foo 1 2 3 remaining SWAP remaining ;
7720: @end example
7721:
7722: @noindent
7723: The result is:
7724:
7725: @example
7726: ->+ remaining .<-
7727: ->.<-5 ok
7728:
7729: ->SWAP remaining ;-<
7730: ->;<- ok
7731: @end example
7732:
7733: @cindex parsing words
7734: The value of @code{>IN} can also be modified by a word in the input
7735: buffer that is executed by the text interpreter. This means that a word
7736: can ``trick'' the text interpreter into either skipping a section of the
7737: input buffer@footnote{This is how parsing words work.} or into parsing a
7738: section twice. For example:
7739:
7740: @example
7741: : lat ." <<foo>>" ;
7742: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
7743: @end example
7744:
7745: @noindent
7746: When @code{flat} is executed, this output is produced@footnote{Exercise
7747: for the reader: what would happen if the @code{3} were replaced with
7748: @code{4}?}:
7749:
7750: @example
7751: <<bar>><<foo>>
7752: @end example
7753:
7754: This technique can be used to work around some of the interoperability
7755: problems of parsing words. Of course, it's better to avoid parsing
7756: words where possible.
7757:
7758: @noindent
7759: Two important notes about the behaviour of the text interpreter:
7760:
7761: @itemize @bullet
7762: @item
7763: It processes each input string to completion before parsing additional
7764: characters from the input buffer.
7765: @item
7766: It treats the input buffer as a read-only region (and so must your code).
7767: @end itemize
7768:
7769: @noindent
7770: When the text interpreter is in compile state, its behaviour changes in
7771: these ways:
7772:
7773: @itemize @bullet
7774: @item
7775: If a parsed string is found in the dictionary, the text interpreter will
7776: perform the word's @dfn{compilation semantics}. In most cases, this
7777: simply means that the execution semantics of the word will be appended
7778: to the current definition.
7779: @item
7780: When a number is encountered, it is compiled into the current definition
7781: (as a literal) rather than being pushed onto a parameter stack.
7782: @item
7783: If an error occurs, @code{state} is modified to put the text interpreter
7784: back into interpret state.
7785: @item
7786: Each time a line is entered from the keyboard, Gforth prints
7787: ``@code{ compiled}'' rather than `` @code{ok}''.
7788: @end itemize
7789:
7790: @cindex text interpreter - input sources
7791: When the text interpreter is using an input device other than the
7792: keyboard, its behaviour changes in these ways:
7793:
7794: @itemize @bullet
7795: @item
7796: When the parse area is empty, the text interpreter attempts to refill
7797: the input buffer from the input source. When the input source is
7798: exhausted, the input source is set back to the previous input source.
7799: @item
7800: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7801: time the parse area is emptied.
7802: @item
7803: If an error occurs, the input source is set back to the user input
7804: device.
7805: @end itemize
7806:
7807: You can read about this in more detail in @ref{Input Sources}.
7808:
7809: doc->in
7810: doc-source
7811:
7812: doc-tib
7813: doc-#tib
7814:
7815:
7816: @menu
7817: * Input Sources::
7818: * Number Conversion::
7819: * Interpret/Compile states::
7820: * Interpreter Directives::
7821: @end menu
7822:
7823: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7824: @subsection Input Sources
7825: @cindex input sources
7826: @cindex text interpreter - input sources
7827:
7828: By default, the text interpreter processes input from the user input
7829: device (the keyboard) when Forth starts up. The text interpreter can
7830: process input from any of these sources:
7831:
7832: @itemize @bullet
7833: @item
7834: The user input device -- the keyboard.
7835: @item
7836: A file, using the words described in @ref{Forth source files}.
7837: @item
7838: A block, using the words described in @ref{Blocks}.
7839: @item
7840: A text string, using @code{evaluate}.
7841: @end itemize
7842:
7843: A program can identify the current input device from the values of
7844: @code{source-id} and @code{blk}.
7845:
7846:
7847: doc-source-id
7848: doc-blk
7849:
7850: doc-save-input
7851: doc-restore-input
7852:
7853: doc-evaluate
7854: doc-query
7855:
7856:
7857:
7858: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
7859: @subsection Number Conversion
7860: @cindex number conversion
7861: @cindex double-cell numbers, input format
7862: @cindex input format for double-cell numbers
7863: @cindex single-cell numbers, input format
7864: @cindex input format for single-cell numbers
7865: @cindex floating-point numbers, input format
7866: @cindex input format for floating-point numbers
7867:
7868: This section describes the rules that the text interpreter uses when it
7869: tries to convert a string into a number.
7870:
7871: Let <digit> represent any character that is a legal digit in the current
7872: number base@footnote{For example, 0-9 when the number base is decimal or
7873: 0-9, A-F when the number base is hexadecimal.}.
7874:
7875: Let <decimal digit> represent any character in the range 0-9.
7876:
7877: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7878: in the braces (@i{a} or @i{b} or neither).
7879:
7880: Let * represent any number of instances of the previous character
7881: (including none).
7882:
7883: Let any other character represent itself.
7884:
7885: @noindent
7886: Now, the conversion rules are:
7887:
7888: @itemize @bullet
7889: @item
7890: A string of the form <digit><digit>* is treated as a single-precision
7891: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
7892: @item
7893: A string of the form -<digit><digit>* is treated as a single-precision
7894: (cell-sized) negative integer, and is represented using 2's-complement
7895: arithmetic. Examples are -45 -5681 -0
7896: @item
7897: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
7898: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7899: (all three of these represent the same number).
7900: @item
7901: A string of the form -<digit><digit>*.<digit>* is treated as a
7902: double-precision (double-cell-sized) negative integer, and is
7903: represented using 2's-complement arithmetic. Examples are -3465. -3.465
7904: -34.65 (all three of these represent the same number).
7905: @item
7906: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7907: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
7908: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
7909: number) +12.E-4
7910: @end itemize
7911:
7912: By default, the number base used for integer number conversion is
7913: given by the contents of the variable @code{base}. Note that a lot of
7914: confusion can result from unexpected values of @code{base}. If you
7915: change @code{base} anywhere, make sure to save the old value and
7916: restore it afterwards; better yet, use @code{base-execute}, which does
7917: this for you. In general I recommend keeping @code{base} decimal, and
7918: using the prefixes described below for the popular non-decimal bases.
7919:
7920: doc-dpl
7921: doc-base-execute
7922: doc-base
7923: doc-hex
7924: doc-decimal
7925:
7926: @cindex '-prefix for character strings
7927: @cindex &-prefix for decimal numbers
7928: @cindex #-prefix for decimal numbers
7929: @cindex %-prefix for binary numbers
7930: @cindex $-prefix for hexadecimal numbers
7931: @cindex 0x-prefix for hexadecimal numbers
7932: Gforth allows you to override the value of @code{base} by using a
7933: prefix@footnote{Some Forth implementations provide a similar scheme by
7934: implementing @code{$} etc. as parsing words that process the subsequent
7935: number in the input stream and push it onto the stack. For example, see
7936: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7937: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7938: is required between the prefix and the number.} before the first digit
7939: of an (integer) number. The following prefixes are supported:
7940:
7941: @itemize @bullet
7942: @item
7943: @code{&} -- decimal
7944: @item
7945: @code{#} -- decimal
7946: @item
7947: @code{%} -- binary
7948: @item
7949: @code{$} -- hexadecimal
7950: @item
7951: @code{0x} -- hexadecimal, if base<33.
7952: @item
7953: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7954: optional @code{'} may be present after the character.
7955: @end itemize
7956:
7957: Here are some examples, with the equivalent decimal number shown after
7958: in braces:
7959:
7960: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
7961: 'A (65),
7962: -'a' (-97),
7963: &905 (905), $abc (2478), $ABC (2478).
7964:
7965: @cindex number conversion - traps for the unwary
7966: @noindent
7967: Number conversion has a number of traps for the unwary:
7968:
7969: @itemize @bullet
7970: @item
7971: You cannot determine the current number base using the code sequence
7972: @code{base @@ .} -- the number base is always 10 in the current number
7973: base. Instead, use something like @code{base @@ dec.}
7974: @item
7975: If the number base is set to a value greater than 14 (for example,
7976: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7977: it to be intepreted as either a single-precision integer or a
7978: floating-point number (Gforth treats it as an integer). The ambiguity
7979: can be resolved by explicitly stating the sign of the mantissa and/or
7980: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7981: ambiguity arises; either representation will be treated as a
7982: floating-point number.
7983: @item
7984: There is a word @code{bin} but it does @i{not} set the number base!
7985: It is used to specify file types.
7986: @item
7987: ANS Forth requires the @code{.} of a double-precision number to be the
7988: final character in the string. Gforth allows the @code{.} to be
7989: anywhere after the first digit.
7990: @item
7991: The number conversion process does not check for overflow.
7992: @item
7993: In an ANS Forth program @code{base} is required to be decimal when
7994: converting floating-point numbers. In Gforth, number conversion to
7995: floating-point numbers always uses base &10, irrespective of the value
7996: of @code{base}.
7997: @end itemize
7998:
7999: You can read numbers into your programs with the words described in
8000: @ref{Line input and conversion}.
8001:
8002: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
8003: @subsection Interpret/Compile states
8004: @cindex Interpret/Compile states
8005:
8006: A standard program is not permitted to change @code{state}
8007: explicitly. However, it can change @code{state} implicitly, using the
8008: words @code{[} and @code{]}. When @code{[} is executed it switches
8009: @code{state} to interpret state, and therefore the text interpreter
8010: starts interpreting. When @code{]} is executed it switches @code{state}
8011: to compile state and therefore the text interpreter starts
8012: compiling. The most common usage for these words is for switching into
8013: interpret state and back from within a colon definition; this technique
8014: can be used to compile a literal (for an example, @pxref{Literals}) or
8015: for conditional compilation (for an example, @pxref{Interpreter
8016: Directives}).
8017:
8018:
8019: @c This is a bad example: It's non-standard, and it's not necessary.
8020: @c However, I can't think of a good example for switching into compile
8021: @c state when there is no current word (@code{state}-smart words are not a
8022: @c good reason). So maybe we should use an example for switching into
8023: @c interpret @code{state} in a colon def. - anton
8024: @c nac-> I agree. I started out by putting in the example, then realised
8025: @c that it was non-ANS, so wrote more words around it. I hope this
8026: @c re-written version is acceptable to you. I do want to keep the example
8027: @c as it is helpful for showing what is and what is not portable, particularly
8028: @c where it outlaws a style in common use.
8029:
8030: @c anton: it's more important to show what's portable. After we have done
8031: @c that, we can also show what's not. In any case, I have written a
8032: @c section Compiling Words which also deals with [ ].
8033:
8034: @c !! The following example does not work in Gforth 0.5.9 or later.
8035:
8036: @c @code{[} and @code{]} also give you the ability to switch into compile
8037: @c state and back, but we cannot think of any useful Standard application
8038: @c for this ability. Pre-ANS Forth textbooks have examples like this:
8039:
8040: @c @example
8041: @c : AA ." this is A" ;
8042: @c : BB ." this is B" ;
8043: @c : CC ." this is C" ;
8044:
8045: @c create table ] aa bb cc [
8046:
8047: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
8048: @c cells table + @@ execute ;
8049: @c @end example
8050:
8051: @c This example builds a jump table; @code{0 go} will display ``@code{this
8052: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
8053: @c defining @code{table} like this:
8054:
8055: @c @example
8056: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
8057: @c @end example
8058:
8059: @c The problem with this code is that the definition of @code{table} is not
8060: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
8061: @c @i{may} work on systems where code space and data space co-incide, the
8062: @c Standard only allows data space to be assigned for a @code{CREATE}d
8063: @c word. In addition, the Standard only allows @code{@@} to access data
8064: @c space, whilst this example is using it to access code space. The only
8065: @c portable, Standard way to build this table is to build it in data space,
8066: @c like this:
8067:
8068: @c @example
8069: @c create table ' aa , ' bb , ' cc ,
8070: @c @end example
8071:
8072: @c doc-state
8073:
8074:
8075: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
8076: @subsection Interpreter Directives
8077: @cindex interpreter directives
8078: @cindex conditional compilation
8079:
8080: These words are usually used in interpret state; typically to control
8081: which parts of a source file are processed by the text
8082: interpreter. There are only a few ANS Forth Standard words, but Gforth
8083: supplements these with a rich set of immediate control structure words
8084: to compensate for the fact that the non-immediate versions can only be
8085: used in compile state (@pxref{Control Structures}). Typical usages:
8086:
8087: @example
8088: FALSE Constant HAVE-ASSEMBLER
8089: .
8090: .
8091: HAVE-ASSEMBLER [IF]
8092: : ASSEMBLER-FEATURE
8093: ...
8094: ;
8095: [ENDIF]
8096: .
8097: .
8098: : SEE
8099: ... \ general-purpose SEE code
8100: [ HAVE-ASSEMBLER [IF] ]
8101: ... \ assembler-specific SEE code
8102: [ [ENDIF] ]
8103: ;
8104: @end example
8105:
8106:
8107: doc-[IF]
8108: doc-[ELSE]
8109: doc-[THEN]
8110: doc-[ENDIF]
8111:
8112: doc-[IFDEF]
8113: doc-[IFUNDEF]
8114:
8115: doc-[?DO]
8116: doc-[DO]
8117: doc-[FOR]
8118: doc-[LOOP]
8119: doc-[+LOOP]
8120: doc-[NEXT]
8121:
8122: doc-[BEGIN]
8123: doc-[UNTIL]
8124: doc-[AGAIN]
8125: doc-[WHILE]
8126: doc-[REPEAT]
8127:
8128:
8129: @c -------------------------------------------------------------
8130: @node The Input Stream, Word Lists, The Text Interpreter, Words
8131: @section The Input Stream
8132: @cindex input stream
8133:
8134: @c !! integrate this better with the "Text Interpreter" section
8135: The text interpreter reads from the input stream, which can come from
8136: several sources (@pxref{Input Sources}). Some words, in particular
8137: defining words, but also words like @code{'}, read parameters from the
8138: input stream instead of from the stack.
8139:
8140: Such words are called parsing words, because they parse the input
8141: stream. Parsing words are hard to use in other words, because it is
8142: hard to pass program-generated parameters through the input stream.
8143: They also usually have an unintuitive combination of interpretation and
8144: compilation semantics when implemented naively, leading to various
8145: approaches that try to produce a more intuitive behaviour
8146: (@pxref{Combined words}).
8147:
8148: It should be obvious by now that parsing words are a bad idea. If you
8149: want to implement a parsing word for convenience, also provide a factor
8150: of the word that does not parse, but takes the parameters on the stack.
8151: To implement the parsing word on top if it, you can use the following
8152: words:
8153:
8154: @c anton: these belong in the input stream section
8155: doc-parse
8156: doc-parse-name
8157: doc-parse-word
8158: doc-name
8159: doc-word
8160: doc-refill
8161:
8162: Conversely, if you have the bad luck (or lack of foresight) to have to
8163: deal with parsing words without having such factors, how do you pass a
8164: string that is not in the input stream to it?
8165:
8166: doc-execute-parsing
8167:
8168: A definition of this word in ANS Forth is provided in
8169: @file{compat/execute-parsing.fs}.
8170:
8171: If you want to run a parsing word on a file, the following word should
8172: help:
8173:
8174: doc-execute-parsing-file
8175:
8176: @c -------------------------------------------------------------
8177: @node Word Lists, Environmental Queries, The Input Stream, Words
8178: @section Word Lists
8179: @cindex word lists
8180: @cindex header space
8181:
8182: A wordlist is a list of named words; you can add new words and look up
8183: words by name (and you can remove words in a restricted way with
8184: markers). Every named (and @code{reveal}ed) word is in one wordlist.
8185:
8186: @cindex search order stack
8187: The text interpreter searches the wordlists present in the search order
8188: (a stack of wordlists), from the top to the bottom. Within each
8189: wordlist, the search starts conceptually at the newest word; i.e., if
8190: two words in a wordlist have the same name, the newer word is found.
8191:
8192: @cindex compilation word list
8193: New words are added to the @dfn{compilation wordlist} (aka current
8194: wordlist).
8195:
8196: @cindex wid
8197: A word list is identified by a cell-sized word list identifier (@i{wid})
8198: in much the same way as a file is identified by a file handle. The
8199: numerical value of the wid has no (portable) meaning, and might change
8200: from session to session.
8201:
8202: The ANS Forth ``Search order'' word set is intended to provide a set of
8203: low-level tools that allow various different schemes to be
8204: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
8205: word. @file{compat/vocabulary.fs} provides an implementation in ANS
8206: Forth.
8207:
8208: @comment TODO: locals section refers to here, saying that every word list (aka
8209: @comment vocabulary) has its own methods for searching etc. Need to document that.
8210: @c anton: but better in a separate subsection on wordlist internals
8211:
8212: @comment TODO: document markers, reveal, tables, mappedwordlist
8213:
8214: @comment the gforthman- prefix is used to pick out the true definition of a
8215: @comment word from the source files, rather than some alias.
8216:
8217: doc-forth-wordlist
8218: doc-definitions
8219: doc-get-current
8220: doc-set-current
8221: doc-get-order
8222: doc-set-order
8223: doc-wordlist
8224: doc-table
8225: doc->order
8226: doc-previous
8227: doc-also
8228: doc-forth
8229: doc-only
8230: doc-order
8231:
8232: doc-find
8233: doc-search-wordlist
8234:
8235: doc-words
8236: doc-vlist
8237: @c doc-words-deferred
8238:
8239: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
8240: doc-root
8241: doc-vocabulary
8242: doc-seal
8243: doc-vocs
8244: doc-current
8245: doc-context
8246:
8247:
8248: @menu
8249: * Vocabularies::
8250: * Why use word lists?::
8251: * Word list example::
8252: @end menu
8253:
8254: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8255: @subsection Vocabularies
8256: @cindex Vocabularies, detailed explanation
8257:
8258: Here is an example of creating and using a new wordlist using ANS
8259: Forth words:
8260:
8261: @example
8262: wordlist constant my-new-words-wordlist
8263: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8264:
8265: \ add it to the search order
8266: also my-new-words
8267:
8268: \ alternatively, add it to the search order and make it
8269: \ the compilation word list
8270: also my-new-words definitions
8271: \ type "order" to see the problem
8272: @end example
8273:
8274: The problem with this example is that @code{order} has no way to
8275: associate the name @code{my-new-words} with the wid of the word list (in
8276: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8277: that has no associated name). There is no Standard way of associating a
8278: name with a wid.
8279:
8280: In Gforth, this example can be re-coded using @code{vocabulary}, which
8281: associates a name with a wid:
8282:
8283: @example
8284: vocabulary my-new-words
8285:
8286: \ add it to the search order
8287: also my-new-words
8288:
8289: \ alternatively, add it to the search order and make it
8290: \ the compilation word list
8291: my-new-words definitions
8292: \ type "order" to see that the problem is solved
8293: @end example
8294:
8295:
8296: @node Why use word lists?, Word list example, Vocabularies, Word Lists
8297: @subsection Why use word lists?
8298: @cindex word lists - why use them?
8299:
8300: Here are some reasons why people use wordlists:
8301:
8302: @itemize @bullet
8303:
8304: @c anton: Gforth's hashing implementation makes the search speed
8305: @c independent from the number of words. But it is linear with the number
8306: @c of wordlists that have to be searched, so in effect using more wordlists
8307: @c actually slows down compilation.
8308:
8309: @c @item
8310: @c To improve compilation speed by reducing the number of header space
8311: @c entries that must be searched. This is achieved by creating a new
8312: @c word list that contains all of the definitions that are used in the
8313: @c definition of a Forth system but which would not usually be used by
8314: @c programs running on that system. That word list would be on the search
8315: @c list when the Forth system was compiled but would be removed from the
8316: @c search list for normal operation. This can be a useful technique for
8317: @c low-performance systems (for example, 8-bit processors in embedded
8318: @c systems) but is unlikely to be necessary in high-performance desktop
8319: @c systems.
8320:
8321: @item
8322: To prevent a set of words from being used outside the context in which
8323: they are valid. Two classic examples of this are an integrated editor
8324: (all of the edit commands are defined in a separate word list; the
8325: search order is set to the editor word list when the editor is invoked;
8326: the old search order is restored when the editor is terminated) and an
8327: integrated assembler (the op-codes for the machine are defined in a
8328: separate word list which is used when a @code{CODE} word is defined).
8329:
8330: @item
8331: To organize the words of an application or library into a user-visible
8332: set (in @code{forth-wordlist} or some other common wordlist) and a set
8333: of helper words used just for the implementation (hidden in a separate
8334: wordlist). This keeps @code{words}' output smaller, separates
8335: implementation and interface, and reduces the chance of name conflicts
8336: within the common wordlist.
8337:
8338: @item
8339: To prevent a name-space clash between multiple definitions with the same
8340: name. For example, when building a cross-compiler you might have a word
8341: @code{IF} that generates conditional code for your target system. By
8342: placing this definition in a different word list you can control whether
8343: the host system's @code{IF} or the target system's @code{IF} get used in
8344: any particular context by controlling the order of the word lists on the
8345: search order stack.
8346:
8347: @end itemize
8348:
8349: The downsides of using wordlists are:
8350:
8351: @itemize
8352:
8353: @item
8354: Debugging becomes more cumbersome.
8355:
8356: @item
8357: Name conflicts worked around with wordlists are still there, and you
8358: have to arrange the search order carefully to get the desired results;
8359: if you forget to do that, you get hard-to-find errors (as in any case
8360: where you read the code differently from the compiler; @code{see} can
8361: help seeing which of several possible words the name resolves to in such
8362: cases). @code{See} displays just the name of the words, not what
8363: wordlist they belong to, so it might be misleading. Using unique names
8364: is a better approach to avoid name conflicts.
8365:
8366: @item
8367: You have to explicitly undo any changes to the search order. In many
8368: cases it would be more convenient if this happened implicitly. Gforth
8369: currently does not provide such a feature, but it may do so in the
8370: future.
8371: @end itemize
8372:
8373:
8374: @node Word list example, , Why use word lists?, Word Lists
8375: @subsection Word list example
8376: @cindex word lists - example
8377:
8378: The following example is from the
8379: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8380: garbage collector} and uses wordlists to separate public words from
8381: helper words:
8382:
8383: @example
8384: get-current ( wid )
8385: vocabulary garbage-collector also garbage-collector definitions
8386: ... \ define helper words
8387: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8388: ... \ define the public (i.e., API) words
8389: \ they can refer to the helper words
8390: previous \ restore original search order (helper words become invisible)
8391: @end example
8392:
8393: @c -------------------------------------------------------------
8394: @node Environmental Queries, Files, Word Lists, Words
8395: @section Environmental Queries
8396: @cindex environmental queries
8397:
8398: ANS Forth introduced the idea of ``environmental queries'' as a way
8399: for a program running on a system to determine certain characteristics of the system.
8400: The Standard specifies a number of strings that might be recognised by a system.
8401:
8402: The Standard requires that the header space used for environmental queries
8403: be distinct from the header space used for definitions.
8404:
8405: Typically, environmental queries are supported by creating a set of
8406: definitions in a word list that is @i{only} used during environmental
8407: queries; that is what Gforth does. There is no Standard way of adding
8408: definitions to the set of recognised environmental queries, but any
8409: implementation that supports the loading of optional word sets must have
8410: some mechanism for doing this (after loading the word set, the
8411: associated environmental query string must return @code{true}). In
8412: Gforth, the word list used to honour environmental queries can be
8413: manipulated just like any other word list.
8414:
8415:
8416: doc-environment?
8417: doc-environment-wordlist
8418:
8419: doc-gforth
8420: doc-os-class
8421:
8422:
8423: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8424: returning two items on the stack, querying it using @code{environment?}
8425: will return an additional item; the @code{true} flag that shows that the
8426: string was recognised.
8427:
8428: @comment TODO Document the standard strings or note where they are documented herein
8429:
8430: Here are some examples of using environmental queries:
8431:
8432: @example
8433: s" address-unit-bits" environment? 0=
8434: [IF]
8435: cr .( environmental attribute address-units-bits unknown... ) cr
8436: [ELSE]
8437: drop \ ensure balanced stack effect
8438: [THEN]
8439:
8440: \ this might occur in the prelude of a standard program that uses THROW
8441: s" exception" environment? [IF]
8442: 0= [IF]
8443: : throw abort" exception thrown" ;
8444: [THEN]
8445: [ELSE] \ we don't know, so make sure
8446: : throw abort" exception thrown" ;
8447: [THEN]
8448:
8449: s" gforth" environment? [IF] .( Gforth version ) TYPE
8450: [ELSE] .( Not Gforth..) [THEN]
8451:
8452: \ a program using v*
8453: s" gforth" environment? [IF]
8454: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8455: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8456: >r swap 2swap swap 0e r> 0 ?DO
8457: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
8458: LOOP
8459: 2drop 2drop ;
8460: [THEN]
8461: [ELSE] \
8462: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8463: ...
8464: [THEN]
8465: @end example
8466:
8467: Here is an example of adding a definition to the environment word list:
8468:
8469: @example
8470: get-current environment-wordlist set-current
8471: true constant block
8472: true constant block-ext
8473: set-current
8474: @end example
8475:
8476: You can see what definitions are in the environment word list like this:
8477:
8478: @example
8479: environment-wordlist >order words previous
8480: @end example
8481:
8482:
8483: @c -------------------------------------------------------------
8484: @node Files, Blocks, Environmental Queries, Words
8485: @section Files
8486: @cindex files
8487: @cindex I/O - file-handling
8488:
8489: Gforth provides facilities for accessing files that are stored in the
8490: host operating system's file-system. Files that are processed by Gforth
8491: can be divided into two categories:
8492:
8493: @itemize @bullet
8494: @item
8495: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
8496: @item
8497: Files that are processed by some other program (@dfn{general files}).
8498: @end itemize
8499:
8500: @menu
8501: * Forth source files::
8502: * General files::
8503: * Redirection::
8504: * Search Paths::
8505: @end menu
8506:
8507: @c -------------------------------------------------------------
8508: @node Forth source files, General files, Files, Files
8509: @subsection Forth source files
8510: @cindex including files
8511: @cindex Forth source files
8512:
8513: The simplest way to interpret the contents of a file is to use one of
8514: these two formats:
8515:
8516: @example
8517: include mysource.fs
8518: s" mysource.fs" included
8519: @end example
8520:
8521: You usually want to include a file only if it is not included already
8522: (by, say, another source file). In that case, you can use one of these
8523: three formats:
8524:
8525: @example
8526: require mysource.fs
8527: needs mysource.fs
8528: s" mysource.fs" required
8529: @end example
8530:
8531: @cindex stack effect of included files
8532: @cindex including files, stack effect
8533: It is good practice to write your source files such that interpreting them
8534: does not change the stack. Source files designed in this way can be used with
8535: @code{required} and friends without complications. For example:
8536:
8537: @example
8538: 1024 require foo.fs drop
8539: @end example
8540:
8541: Here you want to pass the argument 1024 (e.g., a buffer size) to
8542: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8543: ), which allows its use with @code{require}. Of course with such
8544: parameters to required files, you have to ensure that the first
8545: @code{require} fits for all uses (i.e., @code{require} it early in the
8546: master load file).
8547:
8548: doc-include-file
8549: doc-included
8550: doc-included?
8551: doc-include
8552: doc-required
8553: doc-require
8554: doc-needs
8555: @c doc-init-included-files @c internal
8556: doc-sourcefilename
8557: doc-sourceline#
8558:
8559: A definition in ANS Forth for @code{required} is provided in
8560: @file{compat/required.fs}.
8561:
8562: @c -------------------------------------------------------------
8563: @node General files, Redirection, Forth source files, Files
8564: @subsection General files
8565: @cindex general files
8566: @cindex file-handling
8567:
8568: Files are opened/created by name and type. The following file access
8569: methods (FAMs) are recognised:
8570:
8571: @cindex fam (file access method)
8572: doc-r/o
8573: doc-r/w
8574: doc-w/o
8575: doc-bin
8576:
8577:
8578: When a file is opened/created, it returns a file identifier,
8579: @i{wfileid} that is used for all other file commands. All file
8580: commands also return a status value, @i{wior}, that is 0 for a
8581: successful operation and an implementation-defined non-zero value in the
8582: case of an error.
8583:
8584:
8585: doc-open-file
8586: doc-create-file
8587:
8588: doc-close-file
8589: doc-delete-file
8590: doc-rename-file
8591: doc-read-file
8592: doc-read-line
8593: doc-key-file
8594: doc-key?-file
8595: doc-write-file
8596: doc-write-line
8597: doc-emit-file
8598: doc-flush-file
8599:
8600: doc-file-status
8601: doc-file-position
8602: doc-reposition-file
8603: doc-file-size
8604: doc-resize-file
8605:
8606: doc-slurp-file
8607: doc-slurp-fid
8608: doc-stdin
8609: doc-stdout
8610: doc-stderr
8611:
8612: @c ---------------------------------------------------------
8613: @node Redirection, Search Paths, General files, Files
8614: @subsection Redirection
8615: @cindex Redirection
8616: @cindex Input Redirection
8617: @cindex Output Redirection
8618:
8619: You can redirect the output of @code{type} and @code{emit} and all the
8620: words that use them (all output words that don't have an explicit
8621: target file) to an arbitrary file with the @code{outfile-execute},
8622: used like this:
8623:
8624: @example
8625: : some-warning ( n -- )
8626: cr ." warning# " . ;
8627:
8628: : print-some-warning ( n -- )
8629: ['] some-warning stderr outfile-execute ;
8630: @end example
8631:
8632: After @code{some-warning} is executed, the original output direction
8633: is restored; this construct is safe against exceptions. Similarly,
8634: there is @code{infile-execute} for redirecting the input of @code{key}
8635: and its users (any input word that does not take a file explicitly).
8636:
8637: doc-outfile-execute
8638: doc-infile-execute
8639:
8640: If you do not want to redirect the input or output to a file, you can
8641: also make use of the fact that @code{key}, @code{emit} and @code{type}
8642: are deferred words (@pxref{Deferred Words}). However, in that case
8643: you have to worry about the restoration and the protection against
8644: exceptions yourself; also, note that for redirecting the output in
8645: this way, you have to redirect both @code{emit} and @code{type}.
8646:
8647: @c ---------------------------------------------------------
8648: @node Search Paths, , Redirection, Files
8649: @subsection Search Paths
8650: @cindex path for @code{included}
8651: @cindex file search path
8652: @cindex @code{include} search path
8653: @cindex search path for files
8654:
8655: If you specify an absolute filename (i.e., a filename starting with
8656: @file{/} or @file{~}, or with @file{:} in the second position (as in
8657: @samp{C:...})) for @code{included} and friends, that file is included
8658: just as you would expect.
8659:
8660: If the filename starts with @file{./}, this refers to the directory that
8661: the present file was @code{included} from. This allows files to include
8662: other files relative to their own position (irrespective of the current
8663: working directory or the absolute position). This feature is essential
8664: for libraries consisting of several files, where a file may include
8665: other files from the library. It corresponds to @code{#include "..."}
8666: in C. If the current input source is not a file, @file{.} refers to the
8667: directory of the innermost file being included, or, if there is no file
8668: being included, to the current working directory.
8669:
8670: For relative filenames (not starting with @file{./}), Gforth uses a
8671: search path similar to Forth's search order (@pxref{Word Lists}). It
8672: tries to find the given filename in the directories present in the path,
8673: and includes the first one it finds. There are separate search paths for
8674: Forth source files and general files. If the search path contains the
8675: directory @file{.}, this refers to the directory of the current file, or
8676: the working directory, as if the file had been specified with @file{./}.
8677:
8678: Use @file{~+} to refer to the current working directory (as in the
8679: @code{bash}).
8680:
8681: @c anton: fold the following subsubsections into this subsection?
8682:
8683: @menu
8684: * Source Search Paths::
8685: * General Search Paths::
8686: @end menu
8687:
8688: @c ---------------------------------------------------------
8689: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8690: @subsubsection Source Search Paths
8691: @cindex search path control, source files
8692:
8693: The search path is initialized when you start Gforth (@pxref{Invoking
8694: Gforth}). You can display it and change it using @code{fpath} in
8695: combination with the general path handling words.
8696:
8697: doc-fpath
8698: @c the functionality of the following words is easily available through
8699: @c fpath and the general path words. The may go away.
8700: @c doc-.fpath
8701: @c doc-fpath+
8702: @c doc-fpath=
8703: @c doc-open-fpath-file
8704:
8705: @noindent
8706: Here is an example of using @code{fpath} and @code{require}:
8707:
8708: @example
8709: fpath path= /usr/lib/forth/|./
8710: require timer.fs
8711: @end example
8712:
8713:
8714: @c ---------------------------------------------------------
8715: @node General Search Paths, , Source Search Paths, Search Paths
8716: @subsubsection General Search Paths
8717: @cindex search path control, source files
8718:
8719: Your application may need to search files in several directories, like
8720: @code{included} does. To facilitate this, Gforth allows you to define
8721: and use your own search paths, by providing generic equivalents of the
8722: Forth search path words:
8723:
8724: doc-open-path-file
8725: doc-path-allot
8726: doc-clear-path
8727: doc-also-path
8728: doc-.path
8729: doc-path+
8730: doc-path=
8731:
8732: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
8733:
8734: Here's an example of creating an empty search path:
8735: @c
8736: @example
8737: create mypath 500 path-allot \ maximum length 500 chars (is checked)
8738: @end example
8739:
8740: @c -------------------------------------------------------------
8741: @node Blocks, Other I/O, Files, Words
8742: @section Blocks
8743: @cindex I/O - blocks
8744: @cindex blocks
8745:
8746: When you run Gforth on a modern desk-top computer, it runs under the
8747: control of an operating system which provides certain services. One of
8748: these services is @var{file services}, which allows Forth source code
8749: and data to be stored in files and read into Gforth (@pxref{Files}).
8750:
8751: Traditionally, Forth has been an important programming language on
8752: systems where it has interfaced directly to the underlying hardware with
8753: no intervening operating system. Forth provides a mechanism, called
8754: @dfn{blocks}, for accessing mass storage on such systems.
8755:
8756: A block is a 1024-byte data area, which can be used to hold data or
8757: Forth source code. No structure is imposed on the contents of the
8758: block. A block is identified by its number; blocks are numbered
8759: contiguously from 1 to an implementation-defined maximum.
8760:
8761: A typical system that used blocks but no operating system might use a
8762: single floppy-disk drive for mass storage, with the disks formatted to
8763: provide 256-byte sectors. Blocks would be implemented by assigning the
8764: first four sectors of the disk to block 1, the second four sectors to
8765: block 2 and so on, up to the limit of the capacity of the disk. The disk
8766: would not contain any file system information, just the set of blocks.
8767:
8768: @cindex blocks file
8769: On systems that do provide file services, blocks are typically
8770: implemented by storing a sequence of blocks within a single @dfn{blocks
8771: file}. The size of the blocks file will be an exact multiple of 1024
8772: bytes, corresponding to the number of blocks it contains. This is the
8773: mechanism that Gforth uses.
8774:
8775: @cindex @file{blocks.fb}
8776: Only one blocks file can be open at a time. If you use block words without
8777: having specified a blocks file, Gforth defaults to the blocks file
8778: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
8779: locate a blocks file (@pxref{Source Search Paths}).
8780:
8781: @cindex block buffers
8782: When you read and write blocks under program control, Gforth uses a
8783: number of @dfn{block buffers} as intermediate storage. These buffers are
8784: not used when you use @code{load} to interpret the contents of a block.
8785:
8786: The behaviour of the block buffers is analagous to that of a cache.
8787: Each block buffer has three states:
8788:
8789: @itemize @bullet
8790: @item
8791: Unassigned
8792: @item
8793: Assigned-clean
8794: @item
8795: Assigned-dirty
8796: @end itemize
8797:
8798: Initially, all block buffers are @i{unassigned}. In order to access a
8799: block, the block (specified by its block number) must be assigned to a
8800: block buffer.
8801:
8802: The assignment of a block to a block buffer is performed by @code{block}
8803: or @code{buffer}. Use @code{block} when you wish to modify the existing
8804: contents of a block. Use @code{buffer} when you don't care about the
8805: existing contents of the block@footnote{The ANS Forth definition of
8806: @code{buffer} is intended not to cause disk I/O; if the data associated
8807: with the particular block is already stored in a block buffer due to an
8808: earlier @code{block} command, @code{buffer} will return that block
8809: buffer and the existing contents of the block will be
8810: available. Otherwise, @code{buffer} will simply assign a new, empty
8811: block buffer for the block.}.
8812:
8813: Once a block has been assigned to a block buffer using @code{block} or
8814: @code{buffer}, that block buffer becomes the @i{current block
8815: buffer}. Data may only be manipulated (read or written) within the
8816: current block buffer.
8817:
8818: When the contents of the current block buffer has been modified it is
8819: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
8820: either abandon the changes (by doing nothing) or mark the block as
8821: changed (assigned-dirty), using @code{update}. Using @code{update} does
8822: not change the blocks file; it simply changes a block buffer's state to
8823: @i{assigned-dirty}. The block will be written implicitly when it's
8824: buffer is needed for another block, or explicitly by @code{flush} or
8825: @code{save-buffers}.
8826:
8827: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8828: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8829: @code{flush}.
8830:
8831: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
8832: algorithm to assign a block buffer to a block. That means that any
8833: particular block can only be assigned to one specific block buffer,
8834: called (for the particular operation) the @i{victim buffer}. If the
8835: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8836: the new block immediately. If it is @i{assigned-dirty} its current
8837: contents are written back to the blocks file on disk before it is
8838: allocated to the new block.
8839:
8840: Although no structure is imposed on the contents of a block, it is
8841: traditional to display the contents as 16 lines each of 64 characters. A
8842: block provides a single, continuous stream of input (for example, it
8843: acts as a single parse area) -- there are no end-of-line characters
8844: within a block, and no end-of-file character at the end of a
8845: block. There are two consequences of this:
8846:
8847: @itemize @bullet
8848: @item
8849: The last character of one line wraps straight into the first character
8850: of the following line
8851: @item
8852: The word @code{\} -- comment to end of line -- requires special
8853: treatment; in the context of a block it causes all characters until the
8854: end of the current 64-character ``line'' to be ignored.
8855: @end itemize
8856:
8857: In Gforth, when you use @code{block} with a non-existent block number,
8858: the current blocks file will be extended to the appropriate size and the
8859: block buffer will be initialised with spaces.
8860:
8861: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8862: for details) but doesn't encourage the use of blocks; the mechanism is
8863: only provided for backward compatibility -- ANS Forth requires blocks to
8864: be available when files are.
8865:
8866: Common techniques that are used when working with blocks include:
8867:
8868: @itemize @bullet
8869: @item
8870: A screen editor that allows you to edit blocks without leaving the Forth
8871: environment.
8872: @item
8873: Shadow screens; where every code block has an associated block
8874: containing comments (for example: code in odd block numbers, comments in
8875: even block numbers). Typically, the block editor provides a convenient
8876: mechanism to toggle between code and comments.
8877: @item
8878: Load blocks; a single block (typically block 1) contains a number of
8879: @code{thru} commands which @code{load} the whole of the application.
8880: @end itemize
8881:
8882: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8883: integrated into a Forth programming environment.
8884:
8885: @comment TODO what about errors on open-blocks?
8886:
8887: doc-open-blocks
8888: doc-use
8889: doc-block-offset
8890: doc-get-block-fid
8891: doc-block-position
8892:
8893: doc-list
8894: doc-scr
8895:
8896: doc-block
8897: doc-buffer
8898:
8899: doc-empty-buffers
8900: doc-empty-buffer
8901: doc-update
8902: doc-updated?
8903: doc-save-buffers
8904: doc-save-buffer
8905: doc-flush
8906:
8907: doc-load
8908: doc-thru
8909: doc-+load
8910: doc-+thru
8911: doc---gforthman--->
8912: doc-block-included
8913:
8914:
8915: @c -------------------------------------------------------------
8916: @node Other I/O, OS command line arguments, Blocks, Words
8917: @section Other I/O
8918: @cindex I/O - keyboard and display
8919:
8920: @menu
8921: * Simple numeric output:: Predefined formats
8922: * Formatted numeric output:: Formatted (pictured) output
8923: * String Formats:: How Forth stores strings in memory
8924: * Displaying characters and strings:: Other stuff
8925: * Terminal output:: Cursor positioning etc.
8926: * Single-key input::
8927: * Line input and conversion::
8928: * Pipes:: How to create your own pipes
8929: * Xchars and Unicode:: Non-ASCII characters
8930: @end menu
8931:
8932: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8933: @subsection Simple numeric output
8934: @cindex numeric output - simple/free-format
8935:
8936: The simplest output functions are those that display numbers from the
8937: data or floating-point stacks. Floating-point output is always displayed
8938: using base 10. Numbers displayed from the data stack use the value stored
8939: in @code{base}.
8940:
8941:
8942: doc-.
8943: doc-dec.
8944: doc-hex.
8945: doc-u.
8946: doc-.r
8947: doc-u.r
8948: doc-d.
8949: doc-ud.
8950: doc-d.r
8951: doc-ud.r
8952: doc-f.
8953: doc-fe.
8954: doc-fs.
8955: doc-f.rdp
8956:
8957: Examples of printing the number 1234.5678E23 in the different floating-point output
8958: formats are shown below:
8959:
8960: @example
8961: f. 123456779999999000000000000.
8962: fe. 123.456779999999E24
8963: fs. 1.23456779999999E26
8964: @end example
8965:
8966:
8967: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8968: @subsection Formatted numeric output
8969: @cindex formatted numeric output
8970: @cindex pictured numeric output
8971: @cindex numeric output - formatted
8972:
8973: Forth traditionally uses a technique called @dfn{pictured numeric
8974: output} for formatted printing of integers. In this technique, digits
8975: are extracted from the number (using the current output radix defined by
8976: @code{base}), converted to ASCII codes and appended to a string that is
8977: built in a scratch-pad area of memory (@pxref{core-idef,
8978: Implementation-defined options, Implementation-defined
8979: options}). Arbitrary characters can be appended to the string during the
8980: extraction process. The completed string is specified by an address
8981: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8982: under program control.
8983:
8984: All of the integer output words described in the previous section
8985: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8986: numeric output.
8987:
8988: Three important things to remember about pictured numeric output:
8989:
8990: @itemize @bullet
8991: @item
8992: It always operates on double-precision numbers; to display a
8993: single-precision number, convert it first (for ways of doing this
8994: @pxref{Double precision}).
8995: @item
8996: It always treats the double-precision number as though it were
8997: unsigned. The examples below show ways of printing signed numbers.
8998: @item
8999: The string is built up from right to left; least significant digit first.
9000: @end itemize
9001:
9002:
9003: doc-<#
9004: doc-<<#
9005: doc-#
9006: doc-#s
9007: doc-hold
9008: doc-sign
9009: doc-#>
9010: doc-#>>
9011:
9012: doc-represent
9013: doc-f>str-rdp
9014: doc-f>buf-rdp
9015:
9016:
9017: @noindent
9018: Here are some examples of using pictured numeric output:
9019:
9020: @example
9021: : my-u. ( u -- )
9022: \ Simplest use of pns.. behaves like Standard u.
9023: 0 \ convert to unsigned double
9024: <<# \ start conversion
9025: #s \ convert all digits
9026: #> \ complete conversion
9027: TYPE SPACE \ display, with trailing space
9028: #>> ; \ release hold area
9029:
9030: : cents-only ( u -- )
9031: 0 \ convert to unsigned double
9032: <<# \ start conversion
9033: # # \ convert two least-significant digits
9034: #> \ complete conversion, discard other digits
9035: TYPE SPACE \ display, with trailing space
9036: #>> ; \ release hold area
9037:
9038: : dollars-and-cents ( u -- )
9039: 0 \ convert to unsigned double
9040: <<# \ start conversion
9041: # # \ convert two least-significant digits
9042: [char] . hold \ insert decimal point
9043: #s \ convert remaining digits
9044: [char] $ hold \ append currency symbol
9045: #> \ complete conversion
9046: TYPE SPACE \ display, with trailing space
9047: #>> ; \ release hold area
9048:
9049: : my-. ( n -- )
9050: \ handling negatives.. behaves like Standard .
9051: s>d \ convert to signed double
9052: swap over dabs \ leave sign byte followed by unsigned double
9053: <<# \ start conversion
9054: #s \ convert all digits
9055: rot sign \ get at sign byte, append "-" if needed
9056: #> \ complete conversion
9057: TYPE SPACE \ display, with trailing space
9058: #>> ; \ release hold area
9059:
9060: : account. ( n -- )
9061: \ accountants don't like minus signs, they use parentheses
9062: \ for negative numbers
9063: s>d \ convert to signed double
9064: swap over dabs \ leave sign byte followed by unsigned double
9065: <<# \ start conversion
9066: 2 pick \ get copy of sign byte
9067: 0< IF [char] ) hold THEN \ right-most character of output
9068: #s \ convert all digits
9069: rot \ get at sign byte
9070: 0< IF [char] ( hold THEN
9071: #> \ complete conversion
9072: TYPE SPACE \ display, with trailing space
9073: #>> ; \ release hold area
9074:
9075: @end example
9076:
9077: Here are some examples of using these words:
9078:
9079: @example
9080: 1 my-u. 1
9081: hex -1 my-u. decimal FFFFFFFF
9082: 1 cents-only 01
9083: 1234 cents-only 34
9084: 2 dollars-and-cents $0.02
9085: 1234 dollars-and-cents $12.34
9086: 123 my-. 123
9087: -123 my. -123
9088: 123 account. 123
9089: -456 account. (456)
9090: @end example
9091:
9092:
9093: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
9094: @subsection String Formats
9095: @cindex strings - see character strings
9096: @cindex character strings - formats
9097: @cindex I/O - see character strings
9098: @cindex counted strings
9099:
9100: @c anton: this does not really belong here; maybe the memory section,
9101: @c or the principles chapter
9102:
9103: Forth commonly uses two different methods for representing character
9104: strings:
9105:
9106: @itemize @bullet
9107: @item
9108: @cindex address of counted string
9109: @cindex counted string
9110: As a @dfn{counted string}, represented by a @i{c-addr}. The char
9111: addressed by @i{c-addr} contains a character-count, @i{n}, of the
9112: string and the string occupies the subsequent @i{n} char addresses in
9113: memory.
9114: @item
9115: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
9116: of the string in characters, and @i{c-addr} is the address of the
9117: first byte of the string.
9118: @end itemize
9119:
9120: ANS Forth encourages the use of the second format when representing
9121: strings.
9122:
9123:
9124: doc-count
9125:
9126:
9127: For words that move, copy and search for strings see @ref{Memory
9128: Blocks}. For words that display characters and strings see
9129: @ref{Displaying characters and strings}.
9130:
9131: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
9132: @subsection Displaying characters and strings
9133: @cindex characters - compiling and displaying
9134: @cindex character strings - compiling and displaying
9135:
9136: This section starts with a glossary of Forth words and ends with a set
9137: of examples.
9138:
9139: doc-bl
9140: doc-space
9141: doc-spaces
9142: doc-emit
9143: doc-toupper
9144: doc-."
9145: doc-.(
9146: doc-.\"
9147: doc-type
9148: doc-typewhite
9149: doc-cr
9150: @cindex cursor control
9151: doc-s"
9152: doc-s\"
9153: doc-c"
9154: doc-char
9155: doc-[char]
9156:
9157:
9158: @noindent
9159: As an example, consider the following text, stored in a file @file{test.fs}:
9160:
9161: @example
9162: .( text-1)
9163: : my-word
9164: ." text-2" cr
9165: .( text-3)
9166: ;
9167:
9168: ." text-4"
9169:
9170: : my-char
9171: [char] ALPHABET emit
9172: char emit
9173: ;
9174: @end example
9175:
9176: When you load this code into Gforth, the following output is generated:
9177:
9178: @example
9179: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
9180: @end example
9181:
9182: @itemize @bullet
9183: @item
9184: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
9185: is an immediate word; it behaves in the same way whether it is used inside
9186: or outside a colon definition.
9187: @item
9188: Message @code{text-4} is displayed because of Gforth's added interpretation
9189: semantics for @code{."}.
9190: @item
9191: Message @code{text-2} is @i{not} displayed, because the text interpreter
9192: performs the compilation semantics for @code{."} within the definition of
9193: @code{my-word}.
9194: @end itemize
9195:
9196: Here are some examples of executing @code{my-word} and @code{my-char}:
9197:
9198: @example
9199: @kbd{my-word @key{RET}} text-2
9200: ok
9201: @kbd{my-char fred @key{RET}} Af ok
9202: @kbd{my-char jim @key{RET}} Aj ok
9203: @end example
9204:
9205: @itemize @bullet
9206: @item
9207: Message @code{text-2} is displayed because of the run-time behaviour of
9208: @code{."}.
9209: @item
9210: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
9211: on the stack at run-time. @code{emit} always displays the character
9212: when @code{my-char} is executed.
9213: @item
9214: @code{char} parses a string at run-time and the second @code{emit} displays
9215: the first character of the string.
9216: @item
9217: If you type @code{see my-char} you can see that @code{[char]} discarded
9218: the text ``LPHABET'' and only compiled the display code for ``A'' into the
9219: definition of @code{my-char}.
9220: @end itemize
9221:
9222:
9223: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
9224: @subsection Terminal output
9225: @cindex output to terminal
9226: @cindex terminal output
9227:
9228: If you are outputting to a terminal, you may want to control the
9229: positioning of the cursor:
9230: @cindex cursor positioning
9231:
9232: doc-at-xy
9233:
9234: In order to know where to position the cursor, it is often helpful to
9235: know the size of the screen:
9236: @cindex terminal size
9237:
9238: doc-form
9239:
9240: And sometimes you want to use:
9241: @cindex clear screen
9242:
9243: doc-page
9244:
9245: Note that on non-terminals you should use @code{12 emit}, not
9246: @code{page}, to get a form feed.
9247:
9248:
9249: @node Single-key input, Line input and conversion, Terminal output, Other I/O
9250: @subsection Single-key input
9251: @cindex single-key input
9252: @cindex input, single-key
9253:
9254: If you want to get a single printable character, you can use
9255: @code{key}; to check whether a character is available for @code{key},
9256: you can use @code{key?}.
9257:
9258: doc-key
9259: doc-key?
9260:
9261: If you want to process a mix of printable and non-printable
9262: characters, you can do that with @code{ekey} and friends. @code{Ekey}
9263: produces a keyboard event that you have to convert into a character
9264: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
9265:
9266: Typical code for using EKEY looks like this:
9267:
9268: @example
9269: ekey ekey>char if ( c )
9270: ... \ do something with the character
9271: else ekey>fkey if ( key-id )
9272: case
9273: k-up of ... endof
9274: k-f1 of ... endof
9275: k-left k-shift-mask or k-ctrl-mask or of ... endof
9276: ...
9277: endcase
9278: else ( keyboard-event )
9279: drop \ just ignore an unknown keyboard event type
9280: then then
9281: @end example
9282:
9283: doc-ekey
9284: doc-ekey>char
9285: doc-ekey>fkey
9286: doc-ekey?
9287:
9288: The key identifiers for cursor keys are:
9289:
9290: doc-k-left
9291: doc-k-right
9292: doc-k-up
9293: doc-k-down
9294: doc-k-home
9295: doc-k-end
9296: doc-k-prior
9297: doc-k-next
9298: doc-k-insert
9299: doc-k-delete
9300:
9301: The key identifiers for function keys (aka keypad keys) are:
9302:
9303: doc-k-f1
9304: doc-k-f2
9305: doc-k-f3
9306: doc-k-f4
9307: doc-k-f5
9308: doc-k-f6
9309: doc-k-f7
9310: doc-k-f8
9311: doc-k-f9
9312: doc-k-f10
9313: doc-k-f11
9314: doc-k-f12
9315:
9316: Note that @code{k-f11} and @code{k-f12} are not as widely available.
9317:
9318: You can combine these key identifiers with masks for various shift keys:
9319:
9320: doc-k-shift-mask
9321: doc-k-ctrl-mask
9322: doc-k-alt-mask
9323:
9324: Note that, even if a Forth system has @code{ekey>fkey} and the key
9325: identifier words, the keys are not necessarily available or it may not
9326: necessarily be able to report all the keys and all the possible
9327: combinations with shift masks. Therefore, write your programs in such
9328: a way that they are still useful even if the keys and key combinations
9329: cannot be pressed or are not recognized.
9330:
9331: Examples: Older keyboards often do not have an F11 and F12 key. If
9332: you run Gforth in an xterm, the xterm catches a number of combinations
9333: (e.g., @key{Shift-Up}), and never passes it to Gforth. Finally,
9334: Gforth currently does not recognize and report combinations with
9335: multiple shift keys (so the @key{shift-ctrl-left} case in the example
9336: above would never be entered).
9337:
9338: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
9339: you need the ANSI.SYS driver to get that behaviour); it works by
9340: recognizing the escape sequences that ANSI terminals send when such a
9341: key is pressed. If you have a terminal that sends other escape
9342: sequences, you will not get useful results on Gforth. Other Forth
9343: systems may work in a different way.
9344:
9345: Gforth also provides a few words for outputting names of function
9346: keys:
9347:
9348: doc-fkey.
9349: doc-simple-fkey-string
9350:
9351:
9352: @node Line input and conversion, Pipes, Single-key input, Other I/O
9353: @subsection Line input and conversion
9354: @cindex line input from terminal
9355: @cindex input, linewise from terminal
9356: @cindex convertin strings to numbers
9357: @cindex I/O - see input
9358:
9359: For ways of storing character strings in memory see @ref{String Formats}.
9360:
9361: @comment TODO examples for >number >float accept key key? pad parse word refill
9362: @comment then index them
9363:
9364: Words for inputting one line from the keyboard:
9365:
9366: doc-accept
9367: doc-edit-line
9368:
9369: Conversion words:
9370:
9371: doc-s>number?
9372: doc-s>unumber?
9373: doc->number
9374: doc->float
9375:
9376:
9377: @comment obsolescent words..
9378: Obsolescent input and conversion words:
9379:
9380: doc-convert
9381: doc-expect
9382: doc-span
9383:
9384:
9385: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
9386: @subsection Pipes
9387: @cindex pipes, creating your own
9388:
9389: In addition to using Gforth in pipes created by other processes
9390: (@pxref{Gforth in pipes}), you can create your own pipe with
9391: @code{open-pipe}, and read from or write to it.
9392:
9393: doc-open-pipe
9394: doc-close-pipe
9395:
9396: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
9397: you don't catch this exception, Gforth will catch it and exit, usually
9398: silently (@pxref{Gforth in pipes}). Since you probably do not want
9399: this, you should wrap a @code{catch} or @code{try} block around the code
9400: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9401: problem yourself, and then return to regular processing.
9402:
9403: doc-broken-pipe-error
9404:
9405: @node Xchars and Unicode, , Pipes, Other I/O
9406: @subsection Xchars and Unicode
9407:
9408: ASCII is only appropriate for the English language. Most western
9409: languages however fit somewhat into the Forth frame, since a byte is
9410: sufficient to encode the few special characters in each (though not
9411: always the same encoding can be used; latin-1 is most widely used,
9412: though). For other languages, different char-sets have to be used,
9413: several of them variable-width. Most prominent representant is
9414: UTF-8. Let's call these extended characters xchars. The primitive
9415: fixed-size characters stored as bytes are called pchars in this
9416: section.
9417:
9418: The xchar words add a few data types:
9419:
9420: @itemize
9421:
9422: @item
9423: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
9424: and is a subset of unsigned cell. Note: UTF-8 can not store more that
9425: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
9426: character set can be used.
9427:
9428: @item
9429: @var{xc-addr} is the address of an xchar in memory. Alignment
9430: requirements are the same as @var{c-addr}. The memory representation of an
9431: xchar differs from the stack representation, and depends on the
9432: encoding used. An xchar may use a variable number of pchars in memory.
9433:
9434: @item
9435: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
9436: @var{xc-addr}, @var{u} pchars long.
9437:
9438: @end itemize
9439:
9440: doc-xc-size
9441: doc-x-size
9442: doc-xc@+
9443: doc-xc!+?
9444: doc-xchar+
9445: doc-xchar-
9446: doc-+x/string
9447: doc-x\string-
9448: doc--trailing-garbage
9449: doc-x-width
9450: doc-xkey
9451: doc-xemit
9452:
9453: There's a new environment query
9454:
9455: doc-xchar-encoding
9456:
9457: @node OS command line arguments, Locals, Other I/O, Words
9458: @section OS command line arguments
9459: @cindex OS command line arguments
9460: @cindex command line arguments, OS
9461: @cindex arguments, OS command line
9462:
9463: The usual way to pass arguments to Gforth programs on the command line
9464: is via the @option{-e} option, e.g.
9465:
9466: @example
9467: gforth -e "123 456" foo.fs -e bye
9468: @end example
9469:
9470: However, you may want to interpret the command-line arguments directly.
9471: In that case, you can access the (image-specific) command-line arguments
9472: through @code{next-arg}:
9473:
9474: doc-next-arg
9475:
9476: Here's an example program @file{echo.fs} for @code{next-arg}:
9477:
9478: @example
9479: : echo ( -- )
9480: begin
9481: next-arg 2dup 0 0 d<> while
9482: type space
9483: repeat
9484: 2drop ;
9485:
9486: echo cr bye
9487: @end example
9488:
9489: This can be invoked with
9490:
9491: @example
9492: gforth echo.fs hello world
9493: @end example
9494:
9495: and it will print
9496:
9497: @example
9498: hello world
9499: @end example
9500:
9501: The next lower level of dealing with the OS command line are the
9502: following words:
9503:
9504: doc-arg
9505: doc-shift-args
9506:
9507: Finally, at the lowest level Gforth provides the following words:
9508:
9509: doc-argc
9510: doc-argv
9511:
9512: @c -------------------------------------------------------------
9513: @node Locals, Structures, OS command line arguments, Words
9514: @section Locals
9515: @cindex locals
9516:
9517: Local variables can make Forth programming more enjoyable and Forth
9518: programs easier to read. Unfortunately, the locals of ANS Forth are
9519: laden with restrictions. Therefore, we provide not only the ANS Forth
9520: locals wordset, but also our own, more powerful locals wordset (we
9521: implemented the ANS Forth locals wordset through our locals wordset).
9522:
9523: The ideas in this section have also been published in M. Anton Ertl,
9524: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9525: Automatic Scoping of Local Variables}}, EuroForth '94.
9526:
9527: @menu
9528: * Gforth locals::
9529: * ANS Forth locals::
9530: @end menu
9531:
9532: @node Gforth locals, ANS Forth locals, Locals, Locals
9533: @subsection Gforth locals
9534: @cindex Gforth locals
9535: @cindex locals, Gforth style
9536:
9537: Locals can be defined with
9538:
9539: @example
9540: @{ local1 local2 ... -- comment @}
9541: @end example
9542: or
9543: @example
9544: @{ local1 local2 ... @}
9545: @end example
9546:
9547: E.g.,
9548: @example
9549: : max @{ n1 n2 -- n3 @}
9550: n1 n2 > if
9551: n1
9552: else
9553: n2
9554: endif ;
9555: @end example
9556:
9557: The similarity of locals definitions with stack comments is intended. A
9558: locals definition often replaces the stack comment of a word. The order
9559: of the locals corresponds to the order in a stack comment and everything
9560: after the @code{--} is really a comment.
9561:
9562: This similarity has one disadvantage: It is too easy to confuse locals
9563: declarations with stack comments, causing bugs and making them hard to
9564: find. However, this problem can be avoided by appropriate coding
9565: conventions: Do not use both notations in the same program. If you do,
9566: they should be distinguished using additional means, e.g. by position.
9567:
9568: @cindex types of locals
9569: @cindex locals types
9570: The name of the local may be preceded by a type specifier, e.g.,
9571: @code{F:} for a floating point value:
9572:
9573: @example
9574: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9575: \ complex multiplication
9576: Ar Br f* Ai Bi f* f-
9577: Ar Bi f* Ai Br f* f+ ;
9578: @end example
9579:
9580: @cindex flavours of locals
9581: @cindex locals flavours
9582: @cindex value-flavoured locals
9583: @cindex variable-flavoured locals
9584: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9585: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9586: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9587: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9588: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9589: produces its address (which becomes invalid when the variable's scope is
9590: left). E.g., the standard word @code{emit} can be defined in terms of
9591: @code{type} like this:
9592:
9593: @example
9594: : emit @{ C^ char* -- @}
9595: char* 1 type ;
9596: @end example
9597:
9598: @cindex default type of locals
9599: @cindex locals, default type
9600: A local without type specifier is a @code{W:} local. Both flavours of
9601: locals are initialized with values from the data or FP stack.
9602:
9603: Currently there is no way to define locals with user-defined data
9604: structures, but we are working on it.
9605:
9606: Gforth allows defining locals everywhere in a colon definition. This
9607: poses the following questions:
9608:
9609: @menu
9610: * Where are locals visible by name?::
9611: * How long do locals live?::
9612: * Locals programming style::
9613: * Locals implementation::
9614: @end menu
9615:
9616: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9617: @subsubsection Where are locals visible by name?
9618: @cindex locals visibility
9619: @cindex visibility of locals
9620: @cindex scope of locals
9621:
9622: Basically, the answer is that locals are visible where you would expect
9623: it in block-structured languages, and sometimes a little longer. If you
9624: want to restrict the scope of a local, enclose its definition in
9625: @code{SCOPE}...@code{ENDSCOPE}.
9626:
9627:
9628: doc-scope
9629: doc-endscope
9630:
9631:
9632: These words behave like control structure words, so you can use them
9633: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9634: arbitrary ways.
9635:
9636: If you want a more exact answer to the visibility question, here's the
9637: basic principle: A local is visible in all places that can only be
9638: reached through the definition of the local@footnote{In compiler
9639: construction terminology, all places dominated by the definition of the
9640: local.}. In other words, it is not visible in places that can be reached
9641: without going through the definition of the local. E.g., locals defined
9642: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9643: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9644: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
9645:
9646: The reasoning behind this solution is: We want to have the locals
9647: visible as long as it is meaningful. The user can always make the
9648: visibility shorter by using explicit scoping. In a place that can
9649: only be reached through the definition of a local, the meaning of a
9650: local name is clear. In other places it is not: How is the local
9651: initialized at the control flow path that does not contain the
9652: definition? Which local is meant, if the same name is defined twice in
9653: two independent control flow paths?
9654:
9655: This should be enough detail for nearly all users, so you can skip the
9656: rest of this section. If you really must know all the gory details and
9657: options, read on.
9658:
9659: In order to implement this rule, the compiler has to know which places
9660: are unreachable. It knows this automatically after @code{AHEAD},
9661: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9662: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9663: compiler that the control flow never reaches that place. If
9664: @code{UNREACHABLE} is not used where it could, the only consequence is
9665: that the visibility of some locals is more limited than the rule above
9666: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9667: lie to the compiler), buggy code will be produced.
9668:
9669:
9670: doc-unreachable
9671:
9672:
9673: Another problem with this rule is that at @code{BEGIN}, the compiler
9674: does not know which locals will be visible on the incoming
9675: back-edge. All problems discussed in the following are due to this
9676: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9677: loops as examples; the discussion also applies to @code{?DO} and other
9678: loops). Perhaps the most insidious example is:
9679: @example
9680: AHEAD
9681: BEGIN
9682: x
9683: [ 1 CS-ROLL ] THEN
9684: @{ x @}
9685: ...
9686: UNTIL
9687: @end example
9688:
9689: This should be legal according to the visibility rule. The use of
9690: @code{x} can only be reached through the definition; but that appears
9691: textually below the use.
9692:
9693: From this example it is clear that the visibility rules cannot be fully
9694: implemented without major headaches. Our implementation treats common
9695: cases as advertised and the exceptions are treated in a safe way: The
9696: compiler makes a reasonable guess about the locals visible after a
9697: @code{BEGIN}; if it is too pessimistic, the
9698: user will get a spurious error about the local not being defined; if the
9699: compiler is too optimistic, it will notice this later and issue a
9700: warning. In the case above the compiler would complain about @code{x}
9701: being undefined at its use. You can see from the obscure examples in
9702: this section that it takes quite unusual control structures to get the
9703: compiler into trouble, and even then it will often do fine.
9704:
9705: If the @code{BEGIN} is reachable from above, the most optimistic guess
9706: is that all locals visible before the @code{BEGIN} will also be
9707: visible after the @code{BEGIN}. This guess is valid for all loops that
9708: are entered only through the @code{BEGIN}, in particular, for normal
9709: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9710: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9711: compiler. When the branch to the @code{BEGIN} is finally generated by
9712: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9713: warns the user if it was too optimistic:
9714: @example
9715: IF
9716: @{ x @}
9717: BEGIN
9718: \ x ?
9719: [ 1 cs-roll ] THEN
9720: ...
9721: UNTIL
9722: @end example
9723:
9724: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9725: optimistically assumes that it lives until the @code{THEN}. It notices
9726: this difference when it compiles the @code{UNTIL} and issues a
9727: warning. The user can avoid the warning, and make sure that @code{x}
9728: is not used in the wrong area by using explicit scoping:
9729: @example
9730: IF
9731: SCOPE
9732: @{ x @}
9733: ENDSCOPE
9734: BEGIN
9735: [ 1 cs-roll ] THEN
9736: ...
9737: UNTIL
9738: @end example
9739:
9740: Since the guess is optimistic, there will be no spurious error messages
9741: about undefined locals.
9742:
9743: If the @code{BEGIN} is not reachable from above (e.g., after
9744: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9745: optimistic guess, as the locals visible after the @code{BEGIN} may be
9746: defined later. Therefore, the compiler assumes that no locals are
9747: visible after the @code{BEGIN}. However, the user can use
9748: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9749: visible at the BEGIN as at the point where the top control-flow stack
9750: item was created.
9751:
9752:
9753: doc-assume-live
9754:
9755:
9756: @noindent
9757: E.g.,
9758: @example
9759: @{ x @}
9760: AHEAD
9761: ASSUME-LIVE
9762: BEGIN
9763: x
9764: [ 1 CS-ROLL ] THEN
9765: ...
9766: UNTIL
9767: @end example
9768:
9769: Other cases where the locals are defined before the @code{BEGIN} can be
9770: handled by inserting an appropriate @code{CS-ROLL} before the
9771: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9772: behind the @code{ASSUME-LIVE}).
9773:
9774: Cases where locals are defined after the @code{BEGIN} (but should be
9775: visible immediately after the @code{BEGIN}) can only be handled by
9776: rearranging the loop. E.g., the ``most insidious'' example above can be
9777: arranged into:
9778: @example
9779: BEGIN
9780: @{ x @}
9781: ... 0=
9782: WHILE
9783: x
9784: REPEAT
9785: @end example
9786:
9787: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9788: @subsubsection How long do locals live?
9789: @cindex locals lifetime
9790: @cindex lifetime of locals
9791:
9792: The right answer for the lifetime question would be: A local lives at
9793: least as long as it can be accessed. For a value-flavoured local this
9794: means: until the end of its visibility. However, a variable-flavoured
9795: local could be accessed through its address far beyond its visibility
9796: scope. Ultimately, this would mean that such locals would have to be
9797: garbage collected. Since this entails un-Forth-like implementation
9798: complexities, I adopted the same cowardly solution as some other
9799: languages (e.g., C): The local lives only as long as it is visible;
9800: afterwards its address is invalid (and programs that access it
9801: afterwards are erroneous).
9802:
9803: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9804: @subsubsection Locals programming style
9805: @cindex locals programming style
9806: @cindex programming style, locals
9807:
9808: The freedom to define locals anywhere has the potential to change
9809: programming styles dramatically. In particular, the need to use the
9810: return stack for intermediate storage vanishes. Moreover, all stack
9811: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9812: determined arguments) can be eliminated: If the stack items are in the
9813: wrong order, just write a locals definition for all of them; then
9814: write the items in the order you want.
9815:
9816: This seems a little far-fetched and eliminating stack manipulations is
9817: unlikely to become a conscious programming objective. Still, the number
9818: of stack manipulations will be reduced dramatically if local variables
9819: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9820: a traditional implementation of @code{max}).
9821:
9822: This shows one potential benefit of locals: making Forth programs more
9823: readable. Of course, this benefit will only be realized if the
9824: programmers continue to honour the principle of factoring instead of
9825: using the added latitude to make the words longer.
9826:
9827: @cindex single-assignment style for locals
9828: Using @code{TO} can and should be avoided. Without @code{TO},
9829: every value-flavoured local has only a single assignment and many
9830: advantages of functional languages apply to Forth. I.e., programs are
9831: easier to analyse, to optimize and to read: It is clear from the
9832: definition what the local stands for, it does not turn into something
9833: different later.
9834:
9835: E.g., a definition using @code{TO} might look like this:
9836: @example
9837: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9838: u1 u2 min 0
9839: ?do
9840: addr1 c@@ addr2 c@@ -
9841: ?dup-if
9842: unloop exit
9843: then
9844: addr1 char+ TO addr1
9845: addr2 char+ TO addr2
9846: loop
9847: u1 u2 - ;
9848: @end example
9849: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9850: every loop iteration. @code{strcmp} is a typical example of the
9851: readability problems of using @code{TO}. When you start reading
9852: @code{strcmp}, you think that @code{addr1} refers to the start of the
9853: string. Only near the end of the loop you realize that it is something
9854: else.
9855:
9856: This can be avoided by defining two locals at the start of the loop that
9857: are initialized with the right value for the current iteration.
9858: @example
9859: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9860: addr1 addr2
9861: u1 u2 min 0
9862: ?do @{ s1 s2 @}
9863: s1 c@@ s2 c@@ -
9864: ?dup-if
9865: unloop exit
9866: then
9867: s1 char+ s2 char+
9868: loop
9869: 2drop
9870: u1 u2 - ;
9871: @end example
9872: Here it is clear from the start that @code{s1} has a different value
9873: in every loop iteration.
9874:
9875: @node Locals implementation, , Locals programming style, Gforth locals
9876: @subsubsection Locals implementation
9877: @cindex locals implementation
9878: @cindex implementation of locals
9879:
9880: @cindex locals stack
9881: Gforth uses an extra locals stack. The most compelling reason for
9882: this is that the return stack is not float-aligned; using an extra stack
9883: also eliminates the problems and restrictions of using the return stack
9884: as locals stack. Like the other stacks, the locals stack grows toward
9885: lower addresses. A few primitives allow an efficient implementation:
9886:
9887:
9888: doc-@local#
9889: doc-f@local#
9890: doc-laddr#
9891: doc-lp+!#
9892: doc-lp!
9893: doc->l
9894: doc-f>l
9895:
9896:
9897: In addition to these primitives, some specializations of these
9898: primitives for commonly occurring inline arguments are provided for
9899: efficiency reasons, e.g., @code{@@local0} as specialization of
9900: @code{@@local#} for the inline argument 0. The following compiling words
9901: compile the right specialized version, or the general version, as
9902: appropriate:
9903:
9904:
9905: @c doc-compile-@local
9906: @c doc-compile-f@local
9907: doc-compile-lp+!
9908:
9909:
9910: Combinations of conditional branches and @code{lp+!#} like
9911: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9912: is taken) are provided for efficiency and correctness in loops.
9913:
9914: A special area in the dictionary space is reserved for keeping the
9915: local variable names. @code{@{} switches the dictionary pointer to this
9916: area and @code{@}} switches it back and generates the locals
9917: initializing code. @code{W:} etc.@ are normal defining words. This
9918: special area is cleared at the start of every colon definition.
9919:
9920: @cindex word list for defining locals
9921: A special feature of Gforth's dictionary is used to implement the
9922: definition of locals without type specifiers: every word list (aka
9923: vocabulary) has its own methods for searching
9924: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9925: with a special search method: When it is searched for a word, it
9926: actually creates that word using @code{W:}. @code{@{} changes the search
9927: order to first search the word list containing @code{@}}, @code{W:} etc.,
9928: and then the word list for defining locals without type specifiers.
9929:
9930: The lifetime rules support a stack discipline within a colon
9931: definition: The lifetime of a local is either nested with other locals
9932: lifetimes or it does not overlap them.
9933:
9934: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9935: pointer manipulation is generated. Between control structure words
9936: locals definitions can push locals onto the locals stack. @code{AGAIN}
9937: is the simplest of the other three control flow words. It has to
9938: restore the locals stack depth of the corresponding @code{BEGIN}
9939: before branching. The code looks like this:
9940: @format
9941: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9942: @code{branch} <begin>
9943: @end format
9944:
9945: @code{UNTIL} is a little more complicated: If it branches back, it
9946: must adjust the stack just like @code{AGAIN}. But if it falls through,
9947: the locals stack must not be changed. The compiler generates the
9948: following code:
9949: @format
9950: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9951: @end format
9952: The locals stack pointer is only adjusted if the branch is taken.
9953:
9954: @code{THEN} can produce somewhat inefficient code:
9955: @format
9956: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9957: <orig target>:
9958: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9959: @end format
9960: The second @code{lp+!#} adjusts the locals stack pointer from the
9961: level at the @i{orig} point to the level after the @code{THEN}. The
9962: first @code{lp+!#} adjusts the locals stack pointer from the current
9963: level to the level at the orig point, so the complete effect is an
9964: adjustment from the current level to the right level after the
9965: @code{THEN}.
9966:
9967: @cindex locals information on the control-flow stack
9968: @cindex control-flow stack items, locals information
9969: In a conventional Forth implementation a dest control-flow stack entry
9970: is just the target address and an orig entry is just the address to be
9971: patched. Our locals implementation adds a word list to every orig or dest
9972: item. It is the list of locals visible (or assumed visible) at the point
9973: described by the entry. Our implementation also adds a tag to identify
9974: the kind of entry, in particular to differentiate between live and dead
9975: (reachable and unreachable) orig entries.
9976:
9977: A few unusual operations have to be performed on locals word lists:
9978:
9979:
9980: doc-common-list
9981: doc-sub-list?
9982: doc-list-size
9983:
9984:
9985: Several features of our locals word list implementation make these
9986: operations easy to implement: The locals word lists are organised as
9987: linked lists; the tails of these lists are shared, if the lists
9988: contain some of the same locals; and the address of a name is greater
9989: than the address of the names behind it in the list.
9990:
9991: Another important implementation detail is the variable
9992: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9993: determine if they can be reached directly or only through the branch
9994: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9995: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9996: definition, by @code{BEGIN} and usually by @code{THEN}.
9997:
9998: Counted loops are similar to other loops in most respects, but
9999: @code{LEAVE} requires special attention: It performs basically the same
10000: service as @code{AHEAD}, but it does not create a control-flow stack
10001: entry. Therefore the information has to be stored elsewhere;
10002: traditionally, the information was stored in the target fields of the
10003: branches created by the @code{LEAVE}s, by organizing these fields into a
10004: linked list. Unfortunately, this clever trick does not provide enough
10005: space for storing our extended control flow information. Therefore, we
10006: introduce another stack, the leave stack. It contains the control-flow
10007: stack entries for all unresolved @code{LEAVE}s.
10008:
10009: Local names are kept until the end of the colon definition, even if
10010: they are no longer visible in any control-flow path. In a few cases
10011: this may lead to increased space needs for the locals name area, but
10012: usually less than reclaiming this space would cost in code size.
10013:
10014:
10015: @node ANS Forth locals, , Gforth locals, Locals
10016: @subsection ANS Forth locals
10017: @cindex locals, ANS Forth style
10018:
10019: The ANS Forth locals wordset does not define a syntax for locals, but
10020: words that make it possible to define various syntaxes. One of the
10021: possible syntaxes is a subset of the syntax we used in the Gforth locals
10022: wordset, i.e.:
10023:
10024: @example
10025: @{ local1 local2 ... -- comment @}
10026: @end example
10027: @noindent
10028: or
10029: @example
10030: @{ local1 local2 ... @}
10031: @end example
10032:
10033: The order of the locals corresponds to the order in a stack comment. The
10034: restrictions are:
10035:
10036: @itemize @bullet
10037: @item
10038: Locals can only be cell-sized values (no type specifiers are allowed).
10039: @item
10040: Locals can be defined only outside control structures.
10041: @item
10042: Locals can interfere with explicit usage of the return stack. For the
10043: exact (and long) rules, see the standard. If you don't use return stack
10044: accessing words in a definition using locals, you will be all right. The
10045: purpose of this rule is to make locals implementation on the return
10046: stack easier.
10047: @item
10048: The whole definition must be in one line.
10049: @end itemize
10050:
10051: Locals defined in ANS Forth behave like @code{VALUE}s
10052: (@pxref{Values}). I.e., they are initialized from the stack. Using their
10053: name produces their value. Their value can be changed using @code{TO}.
10054:
10055: Since the syntax above is supported by Gforth directly, you need not do
10056: anything to use it. If you want to port a program using this syntax to
10057: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
10058: syntax on the other system.
10059:
10060: Note that a syntax shown in the standard, section A.13 looks
10061: similar, but is quite different in having the order of locals
10062: reversed. Beware!
10063:
10064: The ANS Forth locals wordset itself consists of one word:
10065:
10066: doc-(local)
10067:
10068: The ANS Forth locals extension wordset defines a syntax using
10069: @code{locals|}, but it is so awful that we strongly recommend not to use
10070: it. We have implemented this syntax to make porting to Gforth easy, but
10071: do not document it here. The problem with this syntax is that the locals
10072: are defined in an order reversed with respect to the standard stack
10073: comment notation, making programs harder to read, and easier to misread
10074: and miswrite. The only merit of this syntax is that it is easy to
10075: implement using the ANS Forth locals wordset.
10076:
10077:
10078: @c ----------------------------------------------------------
10079: @node Structures, Object-oriented Forth, Locals, Words
10080: @section Structures
10081: @cindex structures
10082: @cindex records
10083:
10084: This section presents the structure package that comes with Gforth. A
10085: version of the package implemented in ANS Forth is available in
10086: @file{compat/struct.fs}. This package was inspired by a posting on
10087: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
10088: possibly John Hayes). A version of this section has been published in
10089: M. Anton Ertl,
10090: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
10091: Another Forth Structures Package}, Forth Dimensions 19(3), pages
10092: 13--16. Marcel Hendrix provided helpful comments.
10093:
10094: @menu
10095: * Why explicit structure support?::
10096: * Structure Usage::
10097: * Structure Naming Convention::
10098: * Structure Implementation::
10099: * Structure Glossary::
10100: * Forth200x Structures::
10101: @end menu
10102:
10103: @node Why explicit structure support?, Structure Usage, Structures, Structures
10104: @subsection Why explicit structure support?
10105:
10106: @cindex address arithmetic for structures
10107: @cindex structures using address arithmetic
10108: If we want to use a structure containing several fields, we could simply
10109: reserve memory for it, and access the fields using address arithmetic
10110: (@pxref{Address arithmetic}). As an example, consider a structure with
10111: the following fields
10112:
10113: @table @code
10114: @item a
10115: is a float
10116: @item b
10117: is a cell
10118: @item c
10119: is a float
10120: @end table
10121:
10122: Given the (float-aligned) base address of the structure we get the
10123: address of the field
10124:
10125: @table @code
10126: @item a
10127: without doing anything further.
10128: @item b
10129: with @code{float+}
10130: @item c
10131: with @code{float+ cell+ faligned}
10132: @end table
10133:
10134: It is easy to see that this can become quite tiring.
10135:
10136: Moreover, it is not very readable, because seeing a
10137: @code{cell+} tells us neither which kind of structure is
10138: accessed nor what field is accessed; we have to somehow infer the kind
10139: of structure, and then look up in the documentation, which field of
10140: that structure corresponds to that offset.
10141:
10142: Finally, this kind of address arithmetic also causes maintenance
10143: troubles: If you add or delete a field somewhere in the middle of the
10144: structure, you have to find and change all computations for the fields
10145: afterwards.
10146:
10147: So, instead of using @code{cell+} and friends directly, how
10148: about storing the offsets in constants:
10149:
10150: @example
10151: 0 constant a-offset
10152: 0 float+ constant b-offset
10153: 0 float+ cell+ faligned c-offset
10154: @end example
10155:
10156: Now we can get the address of field @code{x} with @code{x-offset
10157: +}. This is much better in all respects. Of course, you still
10158: have to change all later offset definitions if you add a field. You can
10159: fix this by declaring the offsets in the following way:
10160:
10161: @example
10162: 0 constant a-offset
10163: a-offset float+ constant b-offset
10164: b-offset cell+ faligned constant c-offset
10165: @end example
10166:
10167: Since we always use the offsets with @code{+}, we could use a defining
10168: word @code{cfield} that includes the @code{+} in the action of the
10169: defined word:
10170:
10171: @example
10172: : cfield ( n "name" -- )
10173: create ,
10174: does> ( name execution: addr1 -- addr2 )
10175: @@ + ;
10176:
10177: 0 cfield a
10178: 0 a float+ cfield b
10179: 0 b cell+ faligned cfield c
10180: @end example
10181:
10182: Instead of @code{x-offset +}, we now simply write @code{x}.
10183:
10184: The structure field words now can be used quite nicely. However,
10185: their definition is still a bit cumbersome: We have to repeat the
10186: name, the information about size and alignment is distributed before
10187: and after the field definitions etc. The structure package presented
10188: here addresses these problems.
10189:
10190: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10191: @subsection Structure Usage
10192: @cindex structure usage
10193:
10194: @cindex @code{field} usage
10195: @cindex @code{struct} usage
10196: @cindex @code{end-struct} usage
10197: You can define a structure for a (data-less) linked list with:
10198: @example
10199: struct
10200: cell% field list-next
10201: end-struct list%
10202: @end example
10203:
10204: With the address of the list node on the stack, you can compute the
10205: address of the field that contains the address of the next node with
10206: @code{list-next}. E.g., you can determine the length of a list
10207: with:
10208:
10209: @example
10210: : list-length ( list -- n )
10211: \ "list" is a pointer to the first element of a linked list
10212: \ "n" is the length of the list
10213: 0 BEGIN ( list1 n1 )
10214: over
10215: WHILE ( list1 n1 )
10216: 1+ swap list-next @@ swap
10217: REPEAT
10218: nip ;
10219: @end example
10220:
10221: You can reserve memory for a list node in the dictionary with
10222: @code{list% %allot}, which leaves the address of the list node on the
10223: stack. For the equivalent allocation on the heap you can use @code{list%
10224: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10225: use @code{list% %allocate}). You can get the the size of a list
10226: node with @code{list% %size} and its alignment with @code{list%
10227: %alignment}.
10228:
10229: Note that in ANS Forth the body of a @code{create}d word is
10230: @code{aligned} but not necessarily @code{faligned};
10231: therefore, if you do a:
10232:
10233: @example
10234: create @emph{name} foo% %allot drop
10235: @end example
10236:
10237: @noindent
10238: then the memory alloted for @code{foo%} is guaranteed to start at the
10239: body of @code{@emph{name}} only if @code{foo%} contains only character,
10240: cell and double fields. Therefore, if your structure contains floats,
10241: better use
10242:
10243: @example
10244: foo% %allot constant @emph{name}
10245: @end example
10246:
10247: @cindex structures containing structures
10248: You can include a structure @code{foo%} as a field of
10249: another structure, like this:
10250: @example
10251: struct
10252: ...
10253: foo% field ...
10254: ...
10255: end-struct ...
10256: @end example
10257:
10258: @cindex structure extension
10259: @cindex extended records
10260: Instead of starting with an empty structure, you can extend an
10261: existing structure. E.g., a plain linked list without data, as defined
10262: above, is hardly useful; You can extend it to a linked list of integers,
10263: like this:@footnote{This feature is also known as @emph{extended
10264: records}. It is the main innovation in the Oberon language; in other
10265: words, adding this feature to Modula-2 led Wirth to create a new
10266: language, write a new compiler etc. Adding this feature to Forth just
10267: required a few lines of code.}
10268:
10269: @example
10270: list%
10271: cell% field intlist-int
10272: end-struct intlist%
10273: @end example
10274:
10275: @code{intlist%} is a structure with two fields:
10276: @code{list-next} and @code{intlist-int}.
10277:
10278: @cindex structures containing arrays
10279: You can specify an array type containing @emph{n} elements of
10280: type @code{foo%} like this:
10281:
10282: @example
10283: foo% @emph{n} *
10284: @end example
10285:
10286: You can use this array type in any place where you can use a normal
10287: type, e.g., when defining a @code{field}, or with
10288: @code{%allot}.
10289:
10290: @cindex first field optimization
10291: The first field is at the base address of a structure and the word for
10292: this field (e.g., @code{list-next}) actually does not change the address
10293: on the stack. You may be tempted to leave it away in the interest of
10294: run-time and space efficiency. This is not necessary, because the
10295: structure package optimizes this case: If you compile a first-field
10296: words, no code is generated. So, in the interest of readability and
10297: maintainability you should include the word for the field when accessing
10298: the field.
10299:
10300:
10301: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10302: @subsection Structure Naming Convention
10303: @cindex structure naming convention
10304:
10305: The field names that come to (my) mind are often quite generic, and,
10306: if used, would cause frequent name clashes. E.g., many structures
10307: probably contain a @code{counter} field. The structure names
10308: that come to (my) mind are often also the logical choice for the names
10309: of words that create such a structure.
10310:
10311: Therefore, I have adopted the following naming conventions:
10312:
10313: @itemize @bullet
10314: @cindex field naming convention
10315: @item
10316: The names of fields are of the form
10317: @code{@emph{struct}-@emph{field}}, where
10318: @code{@emph{struct}} is the basic name of the structure, and
10319: @code{@emph{field}} is the basic name of the field. You can
10320: think of field words as converting the (address of the)
10321: structure into the (address of the) field.
10322:
10323: @cindex structure naming convention
10324: @item
10325: The names of structures are of the form
10326: @code{@emph{struct}%}, where
10327: @code{@emph{struct}} is the basic name of the structure.
10328: @end itemize
10329:
10330: This naming convention does not work that well for fields of extended
10331: structures; e.g., the integer list structure has a field
10332: @code{intlist-int}, but has @code{list-next}, not
10333: @code{intlist-next}.
10334:
10335: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10336: @subsection Structure Implementation
10337: @cindex structure implementation
10338: @cindex implementation of structures
10339:
10340: The central idea in the implementation is to pass the data about the
10341: structure being built on the stack, not in some global
10342: variable. Everything else falls into place naturally once this design
10343: decision is made.
10344:
10345: The type description on the stack is of the form @emph{align
10346: size}. Keeping the size on the top-of-stack makes dealing with arrays
10347: very simple.
10348:
10349: @code{field} is a defining word that uses @code{Create}
10350: and @code{DOES>}. The body of the field contains the offset
10351: of the field, and the normal @code{DOES>} action is simply:
10352:
10353: @example
10354: @@ +
10355: @end example
10356:
10357: @noindent
10358: i.e., add the offset to the address, giving the stack effect
10359: @i{addr1 -- addr2} for a field.
10360:
10361: @cindex first field optimization, implementation
10362: This simple structure is slightly complicated by the optimization
10363: for fields with offset 0, which requires a different
10364: @code{DOES>}-part (because we cannot rely on there being
10365: something on the stack if such a field is invoked during
10366: compilation). Therefore, we put the different @code{DOES>}-parts
10367: in separate words, and decide which one to invoke based on the
10368: offset. For a zero offset, the field is basically a noop; it is
10369: immediate, and therefore no code is generated when it is compiled.
10370:
10371: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
10372: @subsection Structure Glossary
10373: @cindex structure glossary
10374:
10375:
10376: doc-%align
10377: doc-%alignment
10378: doc-%alloc
10379: doc-%allocate
10380: doc-%allot
10381: doc-cell%
10382: doc-char%
10383: doc-dfloat%
10384: doc-double%
10385: doc-end-struct
10386: doc-field
10387: doc-float%
10388: doc-naligned
10389: doc-sfloat%
10390: doc-%size
10391: doc-struct
10392:
10393:
10394: @node Forth200x Structures, , Structure Glossary, Structures
10395: @subsection Forth200x Structures
10396: @cindex Structures in Forth200x
10397:
10398: The Forth 200x standard defines a slightly less convenient form of
10399: structures. In general (when using @code{field+}, you have to perform
10400: the alignment yourself, but there are a number of convenience words
10401: (e.g., @code{field:} that perform the alignment for you.
10402:
10403: A typical usage example is:
10404:
10405: @example
10406: 0
10407: field: s-a
10408: faligned 2 floats +field s-b
10409: constant s-struct
10410: @end example
10411:
10412: An alternative way of writing this structure is:
10413:
10414: @example
10415: begin-structure s-struct
10416: field: s-a
10417: faligned 2 floats +field s-b
10418: end-structure
10419: @end example
10420:
10421: doc-begin-structure
10422: doc-end-structure
10423: doc-+field
10424: doc-cfield:
10425: doc-field:
10426: doc-2field:
10427: doc-ffield:
10428: doc-sffield:
10429: doc-dffield:
10430:
10431: @c -------------------------------------------------------------
10432: @node Object-oriented Forth, Programming Tools, Structures, Words
10433: @section Object-oriented Forth
10434:
10435: Gforth comes with three packages for object-oriented programming:
10436: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10437: is preloaded, so you have to @code{include} them before use. The most
10438: important differences between these packages (and others) are discussed
10439: in @ref{Comparison with other object models}. All packages are written
10440: in ANS Forth and can be used with any other ANS Forth.
10441:
10442: @menu
10443: * Why object-oriented programming?::
10444: * Object-Oriented Terminology::
10445: * Objects::
10446: * OOF::
10447: * Mini-OOF::
10448: * Comparison with other object models::
10449: @end menu
10450:
10451: @c ----------------------------------------------------------------
10452: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10453: @subsection Why object-oriented programming?
10454: @cindex object-oriented programming motivation
10455: @cindex motivation for object-oriented programming
10456:
10457: Often we have to deal with several data structures (@emph{objects}),
10458: that have to be treated similarly in some respects, but differently in
10459: others. Graphical objects are the textbook example: circles, triangles,
10460: dinosaurs, icons, and others, and we may want to add more during program
10461: development. We want to apply some operations to any graphical object,
10462: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10463: has to do something different for every kind of object.
10464: @comment TODO add some other operations eg perimeter, area
10465: @comment and tie in to concrete examples later..
10466:
10467: We could implement @code{draw} as a big @code{CASE}
10468: control structure that executes the appropriate code depending on the
10469: kind of object to be drawn. This would be not be very elegant, and,
10470: moreover, we would have to change @code{draw} every time we add
10471: a new kind of graphical object (say, a spaceship).
10472:
10473: What we would rather do is: When defining spaceships, we would tell
10474: the system: ``Here's how you @code{draw} a spaceship; you figure
10475: out the rest''.
10476:
10477: This is the problem that all systems solve that (rightfully) call
10478: themselves object-oriented; the object-oriented packages presented here
10479: solve this problem (and not much else).
10480: @comment TODO ?list properties of oo systems.. oo vs o-based?
10481:
10482: @c ------------------------------------------------------------------------
10483: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10484: @subsection Object-Oriented Terminology
10485: @cindex object-oriented terminology
10486: @cindex terminology for object-oriented programming
10487:
10488: This section is mainly for reference, so you don't have to understand
10489: all of it right away. The terminology is mainly Smalltalk-inspired. In
10490: short:
10491:
10492: @table @emph
10493: @cindex class
10494: @item class
10495: a data structure definition with some extras.
10496:
10497: @cindex object
10498: @item object
10499: an instance of the data structure described by the class definition.
10500:
10501: @cindex instance variables
10502: @item instance variables
10503: fields of the data structure.
10504:
10505: @cindex selector
10506: @cindex method selector
10507: @cindex virtual function
10508: @item selector
10509: (or @emph{method selector}) a word (e.g.,
10510: @code{draw}) that performs an operation on a variety of data
10511: structures (classes). A selector describes @emph{what} operation to
10512: perform. In C++ terminology: a (pure) virtual function.
10513:
10514: @cindex method
10515: @item method
10516: the concrete definition that performs the operation
10517: described by the selector for a specific class. A method specifies
10518: @emph{how} the operation is performed for a specific class.
10519:
10520: @cindex selector invocation
10521: @cindex message send
10522: @cindex invoking a selector
10523: @item selector invocation
10524: a call of a selector. One argument of the call (the TOS (top-of-stack))
10525: is used for determining which method is used. In Smalltalk terminology:
10526: a message (consisting of the selector and the other arguments) is sent
10527: to the object.
10528:
10529: @cindex receiving object
10530: @item receiving object
10531: the object used for determining the method executed by a selector
10532: invocation. In the @file{objects.fs} model, it is the object that is on
10533: the TOS when the selector is invoked. (@emph{Receiving} comes from
10534: the Smalltalk @emph{message} terminology.)
10535:
10536: @cindex child class
10537: @cindex parent class
10538: @cindex inheritance
10539: @item child class
10540: a class that has (@emph{inherits}) all properties (instance variables,
10541: selectors, methods) from a @emph{parent class}. In Smalltalk
10542: terminology: The subclass inherits from the superclass. In C++
10543: terminology: The derived class inherits from the base class.
10544:
10545: @end table
10546:
10547: @c If you wonder about the message sending terminology, it comes from
10548: @c a time when each object had it's own task and objects communicated via
10549: @c message passing; eventually the Smalltalk developers realized that
10550: @c they can do most things through simple (indirect) calls. They kept the
10551: @c terminology.
10552:
10553: @c --------------------------------------------------------------
10554: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10555: @subsection The @file{objects.fs} model
10556: @cindex objects
10557: @cindex object-oriented programming
10558:
10559: @cindex @file{objects.fs}
10560: @cindex @file{oof.fs}
10561:
10562: This section describes the @file{objects.fs} package. This material also
10563: has been published in M. Anton Ertl,
10564: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10565: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10566: 37--43.
10567: @c McKewan's and Zsoter's packages
10568:
10569: This section assumes that you have read @ref{Structures}.
10570:
10571: The techniques on which this model is based have been used to implement
10572: the parser generator, Gray, and have also been used in Gforth for
10573: implementing the various flavours of word lists (hashed or not,
10574: case-sensitive or not, special-purpose word lists for locals etc.).
10575:
10576:
10577: @menu
10578: * Properties of the Objects model::
10579: * Basic Objects Usage::
10580: * The Objects base class::
10581: * Creating objects::
10582: * Object-Oriented Programming Style::
10583: * Class Binding::
10584: * Method conveniences::
10585: * Classes and Scoping::
10586: * Dividing classes::
10587: * Object Interfaces::
10588: * Objects Implementation::
10589: * Objects Glossary::
10590: @end menu
10591:
10592: Marcel Hendrix provided helpful comments on this section.
10593:
10594: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10595: @subsubsection Properties of the @file{objects.fs} model
10596: @cindex @file{objects.fs} properties
10597:
10598: @itemize @bullet
10599: @item
10600: It is straightforward to pass objects on the stack. Passing
10601: selectors on the stack is a little less convenient, but possible.
10602:
10603: @item
10604: Objects are just data structures in memory, and are referenced by their
10605: address. You can create words for objects with normal defining words
10606: like @code{constant}. Likewise, there is no difference between instance
10607: variables that contain objects and those that contain other data.
10608:
10609: @item
10610: Late binding is efficient and easy to use.
10611:
10612: @item
10613: It avoids parsing, and thus avoids problems with state-smartness
10614: and reduced extensibility; for convenience there are a few parsing
10615: words, but they have non-parsing counterparts. There are also a few
10616: defining words that parse. This is hard to avoid, because all standard
10617: defining words parse (except @code{:noname}); however, such
10618: words are not as bad as many other parsing words, because they are not
10619: state-smart.
10620:
10621: @item
10622: It does not try to incorporate everything. It does a few things and does
10623: them well (IMO). In particular, this model was not designed to support
10624: information hiding (although it has features that may help); you can use
10625: a separate package for achieving this.
10626:
10627: @item
10628: It is layered; you don't have to learn and use all features to use this
10629: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10630: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10631: are optional and independent of each other.
10632:
10633: @item
10634: An implementation in ANS Forth is available.
10635:
10636: @end itemize
10637:
10638:
10639: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10640: @subsubsection Basic @file{objects.fs} Usage
10641: @cindex basic objects usage
10642: @cindex objects, basic usage
10643:
10644: You can define a class for graphical objects like this:
10645:
10646: @cindex @code{class} usage
10647: @cindex @code{end-class} usage
10648: @cindex @code{selector} usage
10649: @example
10650: object class \ "object" is the parent class
10651: selector draw ( x y graphical -- )
10652: end-class graphical
10653: @end example
10654:
10655: This code defines a class @code{graphical} with an
10656: operation @code{draw}. We can perform the operation
10657: @code{draw} on any @code{graphical} object, e.g.:
10658:
10659: @example
10660: 100 100 t-rex draw
10661: @end example
10662:
10663: @noindent
10664: where @code{t-rex} is a word (say, a constant) that produces a
10665: graphical object.
10666:
10667: @comment TODO add a 2nd operation eg perimeter.. and use for
10668: @comment a concrete example
10669:
10670: @cindex abstract class
10671: How do we create a graphical object? With the present definitions,
10672: we cannot create a useful graphical object. The class
10673: @code{graphical} describes graphical objects in general, but not
10674: any concrete graphical object type (C++ users would call it an
10675: @emph{abstract class}); e.g., there is no method for the selector
10676: @code{draw} in the class @code{graphical}.
10677:
10678: For concrete graphical objects, we define child classes of the
10679: class @code{graphical}, e.g.:
10680:
10681: @cindex @code{overrides} usage
10682: @cindex @code{field} usage in class definition
10683: @example
10684: graphical class \ "graphical" is the parent class
10685: cell% field circle-radius
10686:
10687: :noname ( x y circle -- )
10688: circle-radius @@ draw-circle ;
10689: overrides draw
10690:
10691: :noname ( n-radius circle -- )
10692: circle-radius ! ;
10693: overrides construct
10694:
10695: end-class circle
10696: @end example
10697:
10698: Here we define a class @code{circle} as a child of @code{graphical},
10699: with field @code{circle-radius} (which behaves just like a field
10700: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10701: for the selectors @code{draw} and @code{construct} (@code{construct} is
10702: defined in @code{object}, the parent class of @code{graphical}).
10703:
10704: Now we can create a circle on the heap (i.e.,
10705: @code{allocate}d memory) with:
10706:
10707: @cindex @code{heap-new} usage
10708: @example
10709: 50 circle heap-new constant my-circle
10710: @end example
10711:
10712: @noindent
10713: @code{heap-new} invokes @code{construct}, thus
10714: initializing the field @code{circle-radius} with 50. We can draw
10715: this new circle at (100,100) with:
10716:
10717: @example
10718: 100 100 my-circle draw
10719: @end example
10720:
10721: @cindex selector invocation, restrictions
10722: @cindex class definition, restrictions
10723: Note: You can only invoke a selector if the object on the TOS
10724: (the receiving object) belongs to the class where the selector was
10725: defined or one of its descendents; e.g., you can invoke
10726: @code{draw} only for objects belonging to @code{graphical}
10727: or its descendents (e.g., @code{circle}). Immediately before
10728: @code{end-class}, the search order has to be the same as
10729: immediately after @code{class}.
10730:
10731: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10732: @subsubsection The @file{object.fs} base class
10733: @cindex @code{object} class
10734:
10735: When you define a class, you have to specify a parent class. So how do
10736: you start defining classes? There is one class available from the start:
10737: @code{object}. It is ancestor for all classes and so is the
10738: only class that has no parent. It has two selectors: @code{construct}
10739: and @code{print}.
10740:
10741: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10742: @subsubsection Creating objects
10743: @cindex creating objects
10744: @cindex object creation
10745: @cindex object allocation options
10746:
10747: @cindex @code{heap-new} discussion
10748: @cindex @code{dict-new} discussion
10749: @cindex @code{construct} discussion
10750: You can create and initialize an object of a class on the heap with
10751: @code{heap-new} ( ... class -- object ) and in the dictionary
10752: (allocation with @code{allot}) with @code{dict-new} (
10753: ... class -- object ). Both words invoke @code{construct}, which
10754: consumes the stack items indicated by "..." above.
10755:
10756: @cindex @code{init-object} discussion
10757: @cindex @code{class-inst-size} discussion
10758: If you want to allocate memory for an object yourself, you can get its
10759: alignment and size with @code{class-inst-size 2@@} ( class --
10760: align size ). Once you have memory for an object, you can initialize
10761: it with @code{init-object} ( ... class object -- );
10762: @code{construct} does only a part of the necessary work.
10763:
10764: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10765: @subsubsection Object-Oriented Programming Style
10766: @cindex object-oriented programming style
10767: @cindex programming style, object-oriented
10768:
10769: This section is not exhaustive.
10770:
10771: @cindex stack effects of selectors
10772: @cindex selectors and stack effects
10773: In general, it is a good idea to ensure that all methods for the
10774: same selector have the same stack effect: when you invoke a selector,
10775: you often have no idea which method will be invoked, so, unless all
10776: methods have the same stack effect, you will not know the stack effect
10777: of the selector invocation.
10778:
10779: One exception to this rule is methods for the selector
10780: @code{construct}. We know which method is invoked, because we
10781: specify the class to be constructed at the same place. Actually, I
10782: defined @code{construct} as a selector only to give the users a
10783: convenient way to specify initialization. The way it is used, a
10784: mechanism different from selector invocation would be more natural
10785: (but probably would take more code and more space to explain).
10786:
10787: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10788: @subsubsection Class Binding
10789: @cindex class binding
10790: @cindex early binding
10791:
10792: @cindex late binding
10793: Normal selector invocations determine the method at run-time depending
10794: on the class of the receiving object. This run-time selection is called
10795: @i{late binding}.
10796:
10797: Sometimes it's preferable to invoke a different method. For example,
10798: you might want to use the simple method for @code{print}ing
10799: @code{object}s instead of the possibly long-winded @code{print} method
10800: of the receiver class. You can achieve this by replacing the invocation
10801: of @code{print} with:
10802:
10803: @cindex @code{[bind]} usage
10804: @example
10805: [bind] object print
10806: @end example
10807:
10808: @noindent
10809: in compiled code or:
10810:
10811: @cindex @code{bind} usage
10812: @example
10813: bind object print
10814: @end example
10815:
10816: @cindex class binding, alternative to
10817: @noindent
10818: in interpreted code. Alternatively, you can define the method with a
10819: name (e.g., @code{print-object}), and then invoke it through the
10820: name. Class binding is just a (often more convenient) way to achieve
10821: the same effect; it avoids name clutter and allows you to invoke
10822: methods directly without naming them first.
10823:
10824: @cindex superclass binding
10825: @cindex parent class binding
10826: A frequent use of class binding is this: When we define a method
10827: for a selector, we often want the method to do what the selector does
10828: in the parent class, and a little more. There is a special word for
10829: this purpose: @code{[parent]}; @code{[parent]
10830: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10831: selector}}, where @code{@emph{parent}} is the parent
10832: class of the current class. E.g., a method definition might look like:
10833:
10834: @cindex @code{[parent]} usage
10835: @example
10836: :noname
10837: dup [parent] foo \ do parent's foo on the receiving object
10838: ... \ do some more
10839: ; overrides foo
10840: @end example
10841:
10842: @cindex class binding as optimization
10843: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10844: March 1997), Andrew McKewan presents class binding as an optimization
10845: technique. I recommend not using it for this purpose unless you are in
10846: an emergency. Late binding is pretty fast with this model anyway, so the
10847: benefit of using class binding is small; the cost of using class binding
10848: where it is not appropriate is reduced maintainability.
10849:
10850: While we are at programming style questions: You should bind
10851: selectors only to ancestor classes of the receiving object. E.g., say,
10852: you know that the receiving object is of class @code{foo} or its
10853: descendents; then you should bind only to @code{foo} and its
10854: ancestors.
10855:
10856: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10857: @subsubsection Method conveniences
10858: @cindex method conveniences
10859:
10860: In a method you usually access the receiving object pretty often. If
10861: you define the method as a plain colon definition (e.g., with
10862: @code{:noname}), you may have to do a lot of stack
10863: gymnastics. To avoid this, you can define the method with @code{m:
10864: ... ;m}. E.g., you could define the method for
10865: @code{draw}ing a @code{circle} with
10866:
10867: @cindex @code{this} usage
10868: @cindex @code{m:} usage
10869: @cindex @code{;m} usage
10870: @example
10871: m: ( x y circle -- )
10872: ( x y ) this circle-radius @@ draw-circle ;m
10873: @end example
10874:
10875: @cindex @code{exit} in @code{m: ... ;m}
10876: @cindex @code{exitm} discussion
10877: @cindex @code{catch} in @code{m: ... ;m}
10878: When this method is executed, the receiver object is removed from the
10879: stack; you can access it with @code{this} (admittedly, in this
10880: example the use of @code{m: ... ;m} offers no advantage). Note
10881: that I specify the stack effect for the whole method (i.e. including
10882: the receiver object), not just for the code between @code{m:}
10883: and @code{;m}. You cannot use @code{exit} in
10884: @code{m:...;m}; instead, use
10885: @code{exitm}.@footnote{Moreover, for any word that calls
10886: @code{catch} and was defined before loading
10887: @code{objects.fs}, you have to redefine it like I redefined
10888: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10889:
10890: @cindex @code{inst-var} usage
10891: You will frequently use sequences of the form @code{this
10892: @emph{field}} (in the example above: @code{this
10893: circle-radius}). If you use the field only in this way, you can
10894: define it with @code{inst-var} and eliminate the
10895: @code{this} before the field name. E.g., the @code{circle}
10896: class above could also be defined with:
10897:
10898: @example
10899: graphical class
10900: cell% inst-var radius
10901:
10902: m: ( x y circle -- )
10903: radius @@ draw-circle ;m
10904: overrides draw
10905:
10906: m: ( n-radius circle -- )
10907: radius ! ;m
10908: overrides construct
10909:
10910: end-class circle
10911: @end example
10912:
10913: @code{radius} can only be used in @code{circle} and its
10914: descendent classes and inside @code{m:...;m}.
10915:
10916: @cindex @code{inst-value} usage
10917: You can also define fields with @code{inst-value}, which is
10918: to @code{inst-var} what @code{value} is to
10919: @code{variable}. You can change the value of such a field with
10920: @code{[to-inst]}. E.g., we could also define the class
10921: @code{circle} like this:
10922:
10923: @example
10924: graphical class
10925: inst-value radius
10926:
10927: m: ( x y circle -- )
10928: radius draw-circle ;m
10929: overrides draw
10930:
10931: m: ( n-radius circle -- )
10932: [to-inst] radius ;m
10933: overrides construct
10934:
10935: end-class circle
10936: @end example
10937:
10938: @c !! :m is easy to confuse with m:. Another name would be better.
10939:
10940: @c Finally, you can define named methods with @code{:m}. One use of this
10941: @c feature is the definition of words that occur only in one class and are
10942: @c not intended to be overridden, but which still need method context
10943: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10944: @c would be bound frequently, if defined anonymously.
10945:
10946:
10947: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10948: @subsubsection Classes and Scoping
10949: @cindex classes and scoping
10950: @cindex scoping and classes
10951:
10952: Inheritance is frequent, unlike structure extension. This exacerbates
10953: the problem with the field name convention (@pxref{Structure Naming
10954: Convention}): One always has to remember in which class the field was
10955: originally defined; changing a part of the class structure would require
10956: changes for renaming in otherwise unaffected code.
10957:
10958: @cindex @code{inst-var} visibility
10959: @cindex @code{inst-value} visibility
10960: To solve this problem, I added a scoping mechanism (which was not in my
10961: original charter): A field defined with @code{inst-var} (or
10962: @code{inst-value}) is visible only in the class where it is defined and in
10963: the descendent classes of this class. Using such fields only makes
10964: sense in @code{m:}-defined methods in these classes anyway.
10965:
10966: This scoping mechanism allows us to use the unadorned field name,
10967: because name clashes with unrelated words become much less likely.
10968:
10969: @cindex @code{protected} discussion
10970: @cindex @code{private} discussion
10971: Once we have this mechanism, we can also use it for controlling the
10972: visibility of other words: All words defined after
10973: @code{protected} are visible only in the current class and its
10974: descendents. @code{public} restores the compilation
10975: (i.e. @code{current}) word list that was in effect before. If you
10976: have several @code{protected}s without an intervening
10977: @code{public} or @code{set-current}, @code{public}
10978: will restore the compilation word list in effect before the first of
10979: these @code{protected}s.
10980:
10981: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10982: @subsubsection Dividing classes
10983: @cindex Dividing classes
10984: @cindex @code{methods}...@code{end-methods}
10985:
10986: You may want to do the definition of methods separate from the
10987: definition of the class, its selectors, fields, and instance variables,
10988: i.e., separate the implementation from the definition. You can do this
10989: in the following way:
10990:
10991: @example
10992: graphical class
10993: inst-value radius
10994: end-class circle
10995:
10996: ... \ do some other stuff
10997:
10998: circle methods \ now we are ready
10999:
11000: m: ( x y circle -- )
11001: radius draw-circle ;m
11002: overrides draw
11003:
11004: m: ( n-radius circle -- )
11005: [to-inst] radius ;m
11006: overrides construct
11007:
11008: end-methods
11009: @end example
11010:
11011: You can use several @code{methods}...@code{end-methods} sections. The
11012: only things you can do to the class in these sections are: defining
11013: methods, and overriding the class's selectors. You must not define new
11014: selectors or fields.
11015:
11016: Note that you often have to override a selector before using it. In
11017: particular, you usually have to override @code{construct} with a new
11018: method before you can invoke @code{heap-new} and friends. E.g., you
11019: must not create a circle before the @code{overrides construct} sequence
11020: in the example above.
11021:
11022: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
11023: @subsubsection Object Interfaces
11024: @cindex object interfaces
11025: @cindex interfaces for objects
11026:
11027: In this model you can only call selectors defined in the class of the
11028: receiving objects or in one of its ancestors. If you call a selector
11029: with a receiving object that is not in one of these classes, the
11030: result is undefined; if you are lucky, the program crashes
11031: immediately.
11032:
11033: @cindex selectors common to hardly-related classes
11034: Now consider the case when you want to have a selector (or several)
11035: available in two classes: You would have to add the selector to a
11036: common ancestor class, in the worst case to @code{object}. You
11037: may not want to do this, e.g., because someone else is responsible for
11038: this ancestor class.
11039:
11040: The solution for this problem is interfaces. An interface is a
11041: collection of selectors. If a class implements an interface, the
11042: selectors become available to the class and its descendents. A class
11043: can implement an unlimited number of interfaces. For the problem
11044: discussed above, we would define an interface for the selector(s), and
11045: both classes would implement the interface.
11046:
11047: As an example, consider an interface @code{storage} for
11048: writing objects to disk and getting them back, and a class
11049: @code{foo} that implements it. The code would look like this:
11050:
11051: @cindex @code{interface} usage
11052: @cindex @code{end-interface} usage
11053: @cindex @code{implementation} usage
11054: @example
11055: interface
11056: selector write ( file object -- )
11057: selector read1 ( file object -- )
11058: end-interface storage
11059:
11060: bar class
11061: storage implementation
11062:
11063: ... overrides write
11064: ... overrides read1
11065: ...
11066: end-class foo
11067: @end example
11068:
11069: @noindent
11070: (I would add a word @code{read} @i{( file -- object )} that uses
11071: @code{read1} internally, but that's beyond the point illustrated
11072: here.)
11073:
11074: Note that you cannot use @code{protected} in an interface; and
11075: of course you cannot define fields.
11076:
11077: In the Neon model, all selectors are available for all classes;
11078: therefore it does not need interfaces. The price you pay in this model
11079: is slower late binding, and therefore, added complexity to avoid late
11080: binding.
11081:
11082: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
11083: @subsubsection @file{objects.fs} Implementation
11084: @cindex @file{objects.fs} implementation
11085:
11086: @cindex @code{object-map} discussion
11087: An object is a piece of memory, like one of the data structures
11088: described with @code{struct...end-struct}. It has a field
11089: @code{object-map} that points to the method map for the object's
11090: class.
11091:
11092: @cindex method map
11093: @cindex virtual function table
11094: The @emph{method map}@footnote{This is Self terminology; in C++
11095: terminology: virtual function table.} is an array that contains the
11096: execution tokens (@i{xt}s) of the methods for the object's class. Each
11097: selector contains an offset into a method map.
11098:
11099: @cindex @code{selector} implementation, class
11100: @code{selector} is a defining word that uses
11101: @code{CREATE} and @code{DOES>}. The body of the
11102: selector contains the offset; the @code{DOES>} action for a
11103: class selector is, basically:
11104:
11105: @example
11106: ( object addr ) @@ over object-map @@ + @@ execute
11107: @end example
11108:
11109: Since @code{object-map} is the first field of the object, it
11110: does not generate any code. As you can see, calling a selector has a
11111: small, constant cost.
11112:
11113: @cindex @code{current-interface} discussion
11114: @cindex class implementation and representation
11115: A class is basically a @code{struct} combined with a method
11116: map. During the class definition the alignment and size of the class
11117: are passed on the stack, just as with @code{struct}s, so
11118: @code{field} can also be used for defining class
11119: fields. However, passing more items on the stack would be
11120: inconvenient, so @code{class} builds a data structure in memory,
11121: which is accessed through the variable
11122: @code{current-interface}. After its definition is complete, the
11123: class is represented on the stack by a pointer (e.g., as parameter for
11124: a child class definition).
11125:
11126: A new class starts off with the alignment and size of its parent,
11127: and a copy of the parent's method map. Defining new fields extends the
11128: size and alignment; likewise, defining new selectors extends the
11129: method map. @code{overrides} just stores a new @i{xt} in the method
11130: map at the offset given by the selector.
11131:
11132: @cindex class binding, implementation
11133: Class binding just gets the @i{xt} at the offset given by the selector
11134: from the class's method map and @code{compile,}s (in the case of
11135: @code{[bind]}) it.
11136:
11137: @cindex @code{this} implementation
11138: @cindex @code{catch} and @code{this}
11139: @cindex @code{this} and @code{catch}
11140: I implemented @code{this} as a @code{value}. At the
11141: start of an @code{m:...;m} method the old @code{this} is
11142: stored to the return stack and restored at the end; and the object on
11143: the TOS is stored @code{TO this}. This technique has one
11144: disadvantage: If the user does not leave the method via
11145: @code{;m}, but via @code{throw} or @code{exit},
11146: @code{this} is not restored (and @code{exit} may
11147: crash). To deal with the @code{throw} problem, I have redefined
11148: @code{catch} to save and restore @code{this}; the same
11149: should be done with any word that can catch an exception. As for
11150: @code{exit}, I simply forbid it (as a replacement, there is
11151: @code{exitm}).
11152:
11153: @cindex @code{inst-var} implementation
11154: @code{inst-var} is just the same as @code{field}, with
11155: a different @code{DOES>} action:
11156: @example
11157: @@ this +
11158: @end example
11159: Similar for @code{inst-value}.
11160:
11161: @cindex class scoping implementation
11162: Each class also has a word list that contains the words defined with
11163: @code{inst-var} and @code{inst-value}, and its protected
11164: words. It also has a pointer to its parent. @code{class} pushes
11165: the word lists of the class and all its ancestors onto the search order stack,
11166: and @code{end-class} drops them.
11167:
11168: @cindex interface implementation
11169: An interface is like a class without fields, parent and protected
11170: words; i.e., it just has a method map. If a class implements an
11171: interface, its method map contains a pointer to the method map of the
11172: interface. The positive offsets in the map are reserved for class
11173: methods, therefore interface map pointers have negative
11174: offsets. Interfaces have offsets that are unique throughout the
11175: system, unlike class selectors, whose offsets are only unique for the
11176: classes where the selector is available (invokable).
11177:
11178: This structure means that interface selectors have to perform one
11179: indirection more than class selectors to find their method. Their body
11180: contains the interface map pointer offset in the class method map, and
11181: the method offset in the interface method map. The
11182: @code{does>} action for an interface selector is, basically:
11183:
11184: @example
11185: ( object selector-body )
11186: 2dup selector-interface @@ ( object selector-body object interface-offset )
11187: swap object-map @@ + @@ ( object selector-body map )
11188: swap selector-offset @@ + @@ execute
11189: @end example
11190:
11191: where @code{object-map} and @code{selector-offset} are
11192: first fields and generate no code.
11193:
11194: As a concrete example, consider the following code:
11195:
11196: @example
11197: interface
11198: selector if1sel1
11199: selector if1sel2
11200: end-interface if1
11201:
11202: object class
11203: if1 implementation
11204: selector cl1sel1
11205: cell% inst-var cl1iv1
11206:
11207: ' m1 overrides construct
11208: ' m2 overrides if1sel1
11209: ' m3 overrides if1sel2
11210: ' m4 overrides cl1sel2
11211: end-class cl1
11212:
11213: create obj1 object dict-new drop
11214: create obj2 cl1 dict-new drop
11215: @end example
11216:
11217: The data structure created by this code (including the data structure
11218: for @code{object}) is shown in the
11219: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11220: @comment TODO add this diagram..
11221:
11222: @node Objects Glossary, , Objects Implementation, Objects
11223: @subsubsection @file{objects.fs} Glossary
11224: @cindex @file{objects.fs} Glossary
11225:
11226:
11227: doc---objects-bind
11228: doc---objects-<bind>
11229: doc---objects-bind'
11230: doc---objects-[bind]
11231: doc---objects-class
11232: doc---objects-class->map
11233: doc---objects-class-inst-size
11234: doc---objects-class-override!
11235: doc---objects-class-previous
11236: doc---objects-class>order
11237: doc---objects-construct
11238: doc---objects-current'
11239: doc---objects-[current]
11240: doc---objects-current-interface
11241: doc---objects-dict-new
11242: doc---objects-end-class
11243: doc---objects-end-class-noname
11244: doc---objects-end-interface
11245: doc---objects-end-interface-noname
11246: doc---objects-end-methods
11247: doc---objects-exitm
11248: doc---objects-heap-new
11249: doc---objects-implementation
11250: doc---objects-init-object
11251: doc---objects-inst-value
11252: doc---objects-inst-var
11253: doc---objects-interface
11254: doc---objects-m:
11255: doc---objects-:m
11256: doc---objects-;m
11257: doc---objects-method
11258: doc---objects-methods
11259: doc---objects-object
11260: doc---objects-overrides
11261: doc---objects-[parent]
11262: doc---objects-print
11263: doc---objects-protected
11264: doc---objects-public
11265: doc---objects-selector
11266: doc---objects-this
11267: doc---objects-<to-inst>
11268: doc---objects-[to-inst]
11269: doc---objects-to-this
11270: doc---objects-xt-new
11271:
11272:
11273: @c -------------------------------------------------------------
11274: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11275: @subsection The @file{oof.fs} model
11276: @cindex oof
11277: @cindex object-oriented programming
11278:
11279: @cindex @file{objects.fs}
11280: @cindex @file{oof.fs}
11281:
11282: This section describes the @file{oof.fs} package.
11283:
11284: The package described in this section has been used in bigFORTH since 1991, and
11285: used for two large applications: a chromatographic system used to
11286: create new medicaments, and a graphic user interface library (MINOS).
11287:
11288: You can find a description (in German) of @file{oof.fs} in @cite{Object
11289: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11290: 10(2), 1994.
11291:
11292: @menu
11293: * Properties of the OOF model::
11294: * Basic OOF Usage::
11295: * The OOF base class::
11296: * Class Declaration::
11297: * Class Implementation::
11298: @end menu
11299:
11300: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11301: @subsubsection Properties of the @file{oof.fs} model
11302: @cindex @file{oof.fs} properties
11303:
11304: @itemize @bullet
11305: @item
11306: This model combines object oriented programming with information
11307: hiding. It helps you writing large application, where scoping is
11308: necessary, because it provides class-oriented scoping.
11309:
11310: @item
11311: Named objects, object pointers, and object arrays can be created,
11312: selector invocation uses the ``object selector'' syntax. Selector invocation
11313: to objects and/or selectors on the stack is a bit less convenient, but
11314: possible.
11315:
11316: @item
11317: Selector invocation and instance variable usage of the active object is
11318: straightforward, since both make use of the active object.
11319:
11320: @item
11321: Late binding is efficient and easy to use.
11322:
11323: @item
11324: State-smart objects parse selectors. However, extensibility is provided
11325: using a (parsing) selector @code{postpone} and a selector @code{'}.
11326:
11327: @item
11328: An implementation in ANS Forth is available.
11329:
11330: @end itemize
11331:
11332:
11333: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11334: @subsubsection Basic @file{oof.fs} Usage
11335: @cindex @file{oof.fs} usage
11336:
11337: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
11338:
11339: You can define a class for graphical objects like this:
11340:
11341: @cindex @code{class} usage
11342: @cindex @code{class;} usage
11343: @cindex @code{method} usage
11344: @example
11345: object class graphical \ "object" is the parent class
11346: method draw ( x y -- )
11347: class;
11348: @end example
11349:
11350: This code defines a class @code{graphical} with an
11351: operation @code{draw}. We can perform the operation
11352: @code{draw} on any @code{graphical} object, e.g.:
11353:
11354: @example
11355: 100 100 t-rex draw
11356: @end example
11357:
11358: @noindent
11359: where @code{t-rex} is an object or object pointer, created with e.g.
11360: @code{graphical : t-rex}.
11361:
11362: @cindex abstract class
11363: How do we create a graphical object? With the present definitions,
11364: we cannot create a useful graphical object. The class
11365: @code{graphical} describes graphical objects in general, but not
11366: any concrete graphical object type (C++ users would call it an
11367: @emph{abstract class}); e.g., there is no method for the selector
11368: @code{draw} in the class @code{graphical}.
11369:
11370: For concrete graphical objects, we define child classes of the
11371: class @code{graphical}, e.g.:
11372:
11373: @example
11374: graphical class circle \ "graphical" is the parent class
11375: cell var circle-radius
11376: how:
11377: : draw ( x y -- )
11378: circle-radius @@ draw-circle ;
11379:
11380: : init ( n-radius -- )
11381: circle-radius ! ;
11382: class;
11383: @end example
11384:
11385: Here we define a class @code{circle} as a child of @code{graphical},
11386: with a field @code{circle-radius}; it defines new methods for the
11387: selectors @code{draw} and @code{init} (@code{init} is defined in
11388: @code{object}, the parent class of @code{graphical}).
11389:
11390: Now we can create a circle in the dictionary with:
11391:
11392: @example
11393: 50 circle : my-circle
11394: @end example
11395:
11396: @noindent
11397: @code{:} invokes @code{init}, thus initializing the field
11398: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11399: with:
11400:
11401: @example
11402: 100 100 my-circle draw
11403: @end example
11404:
11405: @cindex selector invocation, restrictions
11406: @cindex class definition, restrictions
11407: Note: You can only invoke a selector if the receiving object belongs to
11408: the class where the selector was defined or one of its descendents;
11409: e.g., you can invoke @code{draw} only for objects belonging to
11410: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11411: mechanism will check if you try to invoke a selector that is not
11412: defined in this class hierarchy, so you'll get an error at compilation
11413: time.
11414:
11415:
11416: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11417: @subsubsection The @file{oof.fs} base class
11418: @cindex @file{oof.fs} base class
11419:
11420: When you define a class, you have to specify a parent class. So how do
11421: you start defining classes? There is one class available from the start:
11422: @code{object}. You have to use it as ancestor for all classes. It is the
11423: only class that has no parent. Classes are also objects, except that
11424: they don't have instance variables; class manipulation such as
11425: inheritance or changing definitions of a class is handled through
11426: selectors of the class @code{object}.
11427:
11428: @code{object} provides a number of selectors:
11429:
11430: @itemize @bullet
11431: @item
11432: @code{class} for subclassing, @code{definitions} to add definitions
11433: later on, and @code{class?} to get type informations (is the class a
11434: subclass of the class passed on the stack?).
11435:
11436: doc---object-class
11437: doc---object-definitions
11438: doc---object-class?
11439:
11440:
11441: @item
11442: @code{init} and @code{dispose} as constructor and destructor of the
11443: object. @code{init} is invocated after the object's memory is allocated,
11444: while @code{dispose} also handles deallocation. Thus if you redefine
11445: @code{dispose}, you have to call the parent's dispose with @code{super
11446: dispose}, too.
11447:
11448: doc---object-init
11449: doc---object-dispose
11450:
11451:
11452: @item
11453: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11454: @code{[]} to create named and unnamed objects and object arrays or
11455: object pointers.
11456:
11457: doc---object-new
11458: doc---object-new[]
11459: doc---object-:
11460: doc---object-ptr
11461: doc---object-asptr
11462: doc---object-[]
11463:
11464:
11465: @item
11466: @code{::} and @code{super} for explicit scoping. You should use explicit
11467: scoping only for super classes or classes with the same set of instance
11468: variables. Explicitly-scoped selectors use early binding.
11469:
11470: doc---object-::
11471: doc---object-super
11472:
11473:
11474: @item
11475: @code{self} to get the address of the object
11476:
11477: doc---object-self
11478:
11479:
11480: @item
11481: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11482: pointers and instance defers.
11483:
11484: doc---object-bind
11485: doc---object-bound
11486: doc---object-link
11487: doc---object-is
11488:
11489:
11490: @item
11491: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11492: form the stack, and @code{postpone} to generate selector invocation code.
11493:
11494: doc---object-'
11495: doc---object-postpone
11496:
11497:
11498: @item
11499: @code{with} and @code{endwith} to select the active object from the
11500: stack, and enable its scope. Using @code{with} and @code{endwith}
11501: also allows you to create code using selector @code{postpone} without being
11502: trapped by the state-smart objects.
11503:
11504: doc---object-with
11505: doc---object-endwith
11506:
11507:
11508: @end itemize
11509:
11510: @node Class Declaration, Class Implementation, The OOF base class, OOF
11511: @subsubsection Class Declaration
11512: @cindex class declaration
11513:
11514: @itemize @bullet
11515: @item
11516: Instance variables
11517:
11518: doc---oof-var
11519:
11520:
11521: @item
11522: Object pointers
11523:
11524: doc---oof-ptr
11525: doc---oof-asptr
11526:
11527:
11528: @item
11529: Instance defers
11530:
11531: doc---oof-defer
11532:
11533:
11534: @item
11535: Method selectors
11536:
11537: doc---oof-early
11538: doc---oof-method
11539:
11540:
11541: @item
11542: Class-wide variables
11543:
11544: doc---oof-static
11545:
11546:
11547: @item
11548: End declaration
11549:
11550: doc---oof-how:
11551: doc---oof-class;
11552:
11553:
11554: @end itemize
11555:
11556: @c -------------------------------------------------------------
11557: @node Class Implementation, , Class Declaration, OOF
11558: @subsubsection Class Implementation
11559: @cindex class implementation
11560:
11561: @c -------------------------------------------------------------
11562: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11563: @subsection The @file{mini-oof.fs} model
11564: @cindex mini-oof
11565:
11566: Gforth's third object oriented Forth package is a 12-liner. It uses a
11567: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
11568: and reduces to the bare minimum of features. This is based on a posting
11569: of Bernd Paysan in comp.lang.forth.
11570:
11571: @menu
11572: * Basic Mini-OOF Usage::
11573: * Mini-OOF Example::
11574: * Mini-OOF Implementation::
11575: @end menu
11576:
11577: @c -------------------------------------------------------------
11578: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11579: @subsubsection Basic @file{mini-oof.fs} Usage
11580: @cindex mini-oof usage
11581:
11582: There is a base class (@code{class}, which allocates one cell for the
11583: object pointer) plus seven other words: to define a method, a variable,
11584: a class; to end a class, to resolve binding, to allocate an object and
11585: to compile a class method.
11586: @comment TODO better description of the last one
11587:
11588:
11589: doc-object
11590: doc-method
11591: doc-var
11592: doc-class
11593: doc-end-class
11594: doc-defines
11595: doc-new
11596: doc-::
11597:
11598:
11599:
11600: @c -------------------------------------------------------------
11601: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11602: @subsubsection Mini-OOF Example
11603: @cindex mini-oof example
11604:
11605: A short example shows how to use this package. This example, in slightly
11606: extended form, is supplied as @file{moof-exm.fs}
11607: @comment TODO could flesh this out with some comments from the Forthwrite article
11608:
11609: @example
11610: object class
11611: method init
11612: method draw
11613: end-class graphical
11614: @end example
11615:
11616: This code defines a class @code{graphical} with an
11617: operation @code{draw}. We can perform the operation
11618: @code{draw} on any @code{graphical} object, e.g.:
11619:
11620: @example
11621: 100 100 t-rex draw
11622: @end example
11623:
11624: where @code{t-rex} is an object or object pointer, created with e.g.
11625: @code{graphical new Constant t-rex}.
11626:
11627: For concrete graphical objects, we define child classes of the
11628: class @code{graphical}, e.g.:
11629:
11630: @example
11631: graphical class
11632: cell var circle-radius
11633: end-class circle \ "graphical" is the parent class
11634:
11635: :noname ( x y -- )
11636: circle-radius @@ draw-circle ; circle defines draw
11637: :noname ( r -- )
11638: circle-radius ! ; circle defines init
11639: @end example
11640:
11641: There is no implicit init method, so we have to define one. The creation
11642: code of the object now has to call init explicitely.
11643:
11644: @example
11645: circle new Constant my-circle
11646: 50 my-circle init
11647: @end example
11648:
11649: It is also possible to add a function to create named objects with
11650: automatic call of @code{init}, given that all objects have @code{init}
11651: on the same place:
11652:
11653: @example
11654: : new: ( .. o "name" -- )
11655: new dup Constant init ;
11656: 80 circle new: large-circle
11657: @end example
11658:
11659: We can draw this new circle at (100,100) with:
11660:
11661: @example
11662: 100 100 my-circle draw
11663: @end example
11664:
11665: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11666: @subsubsection @file{mini-oof.fs} Implementation
11667:
11668: Object-oriented systems with late binding typically use a
11669: ``vtable''-approach: the first variable in each object is a pointer to a
11670: table, which contains the methods as function pointers. The vtable
11671: may also contain other information.
11672:
11673: So first, let's declare selectors:
11674:
11675: @example
11676: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
11677: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11678: @end example
11679:
11680: During selector declaration, the number of selectors and instance
11681: variables is on the stack (in address units). @code{method} creates one
11682: selector and increments the selector number. To execute a selector, it
11683: takes the object, fetches the vtable pointer, adds the offset, and
11684: executes the method @i{xt} stored there. Each selector takes the object
11685: it is invoked with as top of stack parameter; it passes the parameters
11686: (including the object) unchanged to the appropriate method which should
11687: consume that object.
11688:
11689: Now, we also have to declare instance variables
11690:
11691: @example
11692: : var ( m v size "name" -- m v' ) Create over , +
11693: DOES> ( o -- addr ) @@ + ;
11694: @end example
11695:
11696: As before, a word is created with the current offset. Instance
11697: variables can have different sizes (cells, floats, doubles, chars), so
11698: all we do is take the size and add it to the offset. If your machine
11699: has alignment restrictions, put the proper @code{aligned} or
11700: @code{faligned} before the variable, to adjust the variable
11701: offset. That's why it is on the top of stack.
11702:
11703: We need a starting point (the base object) and some syntactic sugar:
11704:
11705: @example
11706: Create object 1 cells , 2 cells ,
11707: : class ( class -- class selectors vars ) dup 2@@ ;
11708: @end example
11709:
11710: For inheritance, the vtable of the parent object has to be
11711: copied when a new, derived class is declared. This gives all the
11712: methods of the parent class, which can be overridden, though.
11713:
11714: @example
11715: : end-class ( class selectors vars "name" -- )
11716: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11717: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11718: @end example
11719:
11720: The first line creates the vtable, initialized with
11721: @code{noop}s. The second line is the inheritance mechanism, it
11722: copies the xts from the parent vtable.
11723:
11724: We still have no way to define new methods, let's do that now:
11725:
11726: @example
11727: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11728: @end example
11729:
11730: To allocate a new object, we need a word, too:
11731:
11732: @example
11733: : new ( class -- o ) here over @@ allot swap over ! ;
11734: @end example
11735:
11736: Sometimes derived classes want to access the method of the
11737: parent object. There are two ways to achieve this with Mini-OOF:
11738: first, you could use named words, and second, you could look up the
11739: vtable of the parent object.
11740:
11741: @example
11742: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11743: @end example
11744:
11745:
11746: Nothing can be more confusing than a good example, so here is
11747: one. First let's declare a text object (called
11748: @code{button}), that stores text and position:
11749:
11750: @example
11751: object class
11752: cell var text
11753: cell var len
11754: cell var x
11755: cell var y
11756: method init
11757: method draw
11758: end-class button
11759: @end example
11760:
11761: @noindent
11762: Now, implement the two methods, @code{draw} and @code{init}:
11763:
11764: @example
11765: :noname ( o -- )
11766: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11767: button defines draw
11768: :noname ( addr u o -- )
11769: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11770: button defines init
11771: @end example
11772:
11773: @noindent
11774: To demonstrate inheritance, we define a class @code{bold-button}, with no
11775: new data and no new selectors:
11776:
11777: @example
11778: button class
11779: end-class bold-button
11780:
11781: : bold 27 emit ." [1m" ;
11782: : normal 27 emit ." [0m" ;
11783: @end example
11784:
11785: @noindent
11786: The class @code{bold-button} has a different draw method to
11787: @code{button}, but the new method is defined in terms of the draw method
11788: for @code{button}:
11789:
11790: @example
11791: :noname bold [ button :: draw ] normal ; bold-button defines draw
11792: @end example
11793:
11794: @noindent
11795: Finally, create two objects and apply selectors:
11796:
11797: @example
11798: button new Constant foo
11799: s" thin foo" foo init
11800: page
11801: foo draw
11802: bold-button new Constant bar
11803: s" fat bar" bar init
11804: 1 bar y !
11805: bar draw
11806: @end example
11807:
11808:
11809: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11810: @subsection Comparison with other object models
11811: @cindex comparison of object models
11812: @cindex object models, comparison
11813:
11814: Many object-oriented Forth extensions have been proposed (@cite{A survey
11815: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11816: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11817: relation of the object models described here to two well-known and two
11818: closely-related (by the use of method maps) models. Andras Zsoter
11819: helped us with this section.
11820:
11821: @cindex Neon model
11822: The most popular model currently seems to be the Neon model (see
11823: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11824: 1997) by Andrew McKewan) but this model has a number of limitations
11825: @footnote{A longer version of this critique can be
11826: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11827: Dimensions, May 1997) by Anton Ertl.}:
11828:
11829: @itemize @bullet
11830: @item
11831: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11832: to pass objects on the stack.
11833:
11834: @item
11835: It requires that the selector parses the input stream (at
11836: compile time); this leads to reduced extensibility and to bugs that are
11837: hard to find.
11838:
11839: @item
11840: It allows using every selector on every object; this eliminates the
11841: need for interfaces, but makes it harder to create efficient
11842: implementations.
11843: @end itemize
11844:
11845: @cindex Pountain's object-oriented model
11846: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11847: Press, London, 1987) by Dick Pountain. However, it is not really about
11848: object-oriented programming, because it hardly deals with late
11849: binding. Instead, it focuses on features like information hiding and
11850: overloading that are characteristic of modular languages like Ada (83).
11851:
11852: @cindex Zsoter's object-oriented model
11853: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11854: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11855: describes a model that makes heavy use of an active object (like
11856: @code{this} in @file{objects.fs}): The active object is not only used
11857: for accessing all fields, but also specifies the receiving object of
11858: every selector invocation; you have to change the active object
11859: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11860: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11861: the method entry point is unnecessary with Zsoter's model, because the
11862: receiving object is the active object already. On the other hand, the
11863: explicit change is absolutely necessary in that model, because otherwise
11864: no one could ever change the active object. An ANS Forth implementation
11865: of this model is available through
11866: @uref{http://www.forth.org/oopf.html}.
11867:
11868: @cindex @file{oof.fs}, differences to other models
11869: The @file{oof.fs} model combines information hiding and overloading
11870: resolution (by keeping names in various word lists) with object-oriented
11871: programming. It sets the active object implicitly on method entry, but
11872: also allows explicit changing (with @code{>o...o>} or with
11873: @code{with...endwith}). It uses parsing and state-smart objects and
11874: classes for resolving overloading and for early binding: the object or
11875: class parses the selector and determines the method from this. If the
11876: selector is not parsed by an object or class, it performs a call to the
11877: selector for the active object (late binding), like Zsoter's model.
11878: Fields are always accessed through the active object. The big
11879: disadvantage of this model is the parsing and the state-smartness, which
11880: reduces extensibility and increases the opportunities for subtle bugs;
11881: essentially, you are only safe if you never tick or @code{postpone} an
11882: object or class (Bernd disagrees, but I (Anton) am not convinced).
11883:
11884: @cindex @file{mini-oof.fs}, differences to other models
11885: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11886: version of the @file{objects.fs} model, but syntactically it is a
11887: mixture of the @file{objects.fs} and @file{oof.fs} models.
11888:
11889:
11890: @c -------------------------------------------------------------
11891: @node Programming Tools, C Interface, Object-oriented Forth, Words
11892: @section Programming Tools
11893: @cindex programming tools
11894:
11895: @c !! move this and assembler down below OO stuff.
11896:
11897: @menu
11898: * Examining:: Data and Code.
11899: * Forgetting words:: Usually before reloading.
11900: * Debugging:: Simple and quick.
11901: * Assertions:: Making your programs self-checking.
11902: * Singlestep Debugger:: Executing your program word by word.
11903: @end menu
11904:
11905: @node Examining, Forgetting words, Programming Tools, Programming Tools
11906: @subsection Examining data and code
11907: @cindex examining data and code
11908: @cindex data examination
11909: @cindex code examination
11910:
11911: The following words inspect the stack non-destructively:
11912:
11913: doc-.s
11914: doc-f.s
11915: doc-maxdepth-.s
11916:
11917: There is a word @code{.r} but it does @i{not} display the return stack!
11918: It is used for formatted numeric output (@pxref{Simple numeric output}).
11919:
11920: doc-depth
11921: doc-fdepth
11922: doc-clearstack
11923: doc-clearstacks
11924:
11925: The following words inspect memory.
11926:
11927: doc-?
11928: doc-dump
11929:
11930: And finally, @code{see} allows to inspect code:
11931:
11932: doc-see
11933: doc-xt-see
11934: doc-simple-see
11935: doc-simple-see-range
11936: doc-see-code
11937: doc-see-code-range
11938:
11939: @node Forgetting words, Debugging, Examining, Programming Tools
11940: @subsection Forgetting words
11941: @cindex words, forgetting
11942: @cindex forgeting words
11943:
11944: @c anton: other, maybe better places for this subsection: Defining Words;
11945: @c Dictionary allocation. At least a reference should be there.
11946:
11947: Forth allows you to forget words (and everything that was alloted in the
11948: dictonary after them) in a LIFO manner.
11949:
11950: doc-marker
11951:
11952: The most common use of this feature is during progam development: when
11953: you change a source file, forget all the words it defined and load it
11954: again (since you also forget everything defined after the source file
11955: was loaded, you have to reload that, too). Note that effects like
11956: storing to variables and destroyed system words are not undone when you
11957: forget words. With a system like Gforth, that is fast enough at
11958: starting up and compiling, I find it more convenient to exit and restart
11959: Gforth, as this gives me a clean slate.
11960:
11961: Here's an example of using @code{marker} at the start of a source file
11962: that you are debugging; it ensures that you only ever have one copy of
11963: the file's definitions compiled at any time:
11964:
11965: @example
11966: [IFDEF] my-code
11967: my-code
11968: [ENDIF]
11969:
11970: marker my-code
11971: init-included-files
11972:
11973: \ .. definitions start here
11974: \ .
11975: \ .
11976: \ end
11977: @end example
11978:
11979:
11980: @node Debugging, Assertions, Forgetting words, Programming Tools
11981: @subsection Debugging
11982: @cindex debugging
11983:
11984: Languages with a slow edit/compile/link/test development loop tend to
11985: require sophisticated tracing/stepping debuggers to facilate debugging.
11986:
11987: A much better (faster) way in fast-compiling languages is to add
11988: printing code at well-selected places, let the program run, look at
11989: the output, see where things went wrong, add more printing code, etc.,
11990: until the bug is found.
11991:
11992: The simple debugging aids provided in @file{debugs.fs}
11993: are meant to support this style of debugging.
11994:
11995: The word @code{~~} prints debugging information (by default the source
11996: location and the stack contents). It is easy to insert. If you use Emacs
11997: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11998: query-replace them with nothing). The deferred words
11999: @code{printdebugdata} and @code{.debugline} control the output of
12000: @code{~~}. The default source location output format works well with
12001: Emacs' compilation mode, so you can step through the program at the
12002: source level using @kbd{C-x `} (the advantage over a stepping debugger
12003: is that you can step in any direction and you know where the crash has
12004: happened or where the strange data has occurred).
12005:
12006: doc-~~
12007: doc-printdebugdata
12008: doc-.debugline
12009: doc-debug-fid
12010:
12011: @cindex filenames in @code{~~} output
12012: @code{~~} (and assertions) will usually print the wrong file name if a
12013: marker is executed in the same file after their occurance. They will
12014: print @samp{*somewhere*} as file name if a marker is executed in the
12015: same file before their occurance.
12016:
12017:
12018: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
12019: @subsection Assertions
12020: @cindex assertions
12021:
12022: It is a good idea to make your programs self-checking, especially if you
12023: make an assumption that may become invalid during maintenance (for
12024: example, that a certain field of a data structure is never zero). Gforth
12025: supports @dfn{assertions} for this purpose. They are used like this:
12026:
12027: @example
12028: assert( @i{flag} )
12029: @end example
12030:
12031: The code between @code{assert(} and @code{)} should compute a flag, that
12032: should be true if everything is alright and false otherwise. It should
12033: not change anything else on the stack. The overall stack effect of the
12034: assertion is @code{( -- )}. E.g.
12035:
12036: @example
12037: assert( 1 1 + 2 = ) \ what we learn in school
12038: assert( dup 0<> ) \ assert that the top of stack is not zero
12039: assert( false ) \ this code should not be reached
12040: @end example
12041:
12042: The need for assertions is different at different times. During
12043: debugging, we want more checking, in production we sometimes care more
12044: for speed. Therefore, assertions can be turned off, i.e., the assertion
12045: becomes a comment. Depending on the importance of an assertion and the
12046: time it takes to check it, you may want to turn off some assertions and
12047: keep others turned on. Gforth provides several levels of assertions for
12048: this purpose:
12049:
12050:
12051: doc-assert0(
12052: doc-assert1(
12053: doc-assert2(
12054: doc-assert3(
12055: doc-assert(
12056: doc-)
12057:
12058:
12059: The variable @code{assert-level} specifies the highest assertions that
12060: are turned on. I.e., at the default @code{assert-level} of one,
12061: @code{assert0(} and @code{assert1(} assertions perform checking, while
12062: @code{assert2(} and @code{assert3(} assertions are treated as comments.
12063:
12064: The value of @code{assert-level} is evaluated at compile-time, not at
12065: run-time. Therefore you cannot turn assertions on or off at run-time;
12066: you have to set the @code{assert-level} appropriately before compiling a
12067: piece of code. You can compile different pieces of code at different
12068: @code{assert-level}s (e.g., a trusted library at level 1 and
12069: newly-written code at level 3).
12070:
12071:
12072: doc-assert-level
12073:
12074:
12075: If an assertion fails, a message compatible with Emacs' compilation mode
12076: is produced and the execution is aborted (currently with @code{ABORT"}.
12077: If there is interest, we will introduce a special throw code. But if you
12078: intend to @code{catch} a specific condition, using @code{throw} is
12079: probably more appropriate than an assertion).
12080:
12081: @cindex filenames in assertion output
12082: Assertions (and @code{~~}) will usually print the wrong file name if a
12083: marker is executed in the same file after their occurance. They will
12084: print @samp{*somewhere*} as file name if a marker is executed in the
12085: same file before their occurance.
12086:
12087: Definitions in ANS Forth for these assertion words are provided
12088: in @file{compat/assert.fs}.
12089:
12090:
12091: @node Singlestep Debugger, , Assertions, Programming Tools
12092: @subsection Singlestep Debugger
12093: @cindex singlestep Debugger
12094: @cindex debugging Singlestep
12095:
12096: The singlestep debugger works only with the engine @code{gforth-itc}.
12097:
12098: When you create a new word there's often the need to check whether it
12099: behaves correctly or not. You can do this by typing @code{dbg
12100: badword}. A debug session might look like this:
12101:
12102: @example
12103: : badword 0 DO i . LOOP ; ok
12104: 2 dbg badword
12105: : badword
12106: Scanning code...
12107:
12108: Nesting debugger ready!
12109:
12110: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
12111: 400D4740 8049F68 DO -> [ 0 ]
12112: 400D4744 804A0C8 i -> [ 1 ] 00000
12113: 400D4748 400C5E60 . -> 0 [ 0 ]
12114: 400D474C 8049D0C LOOP -> [ 0 ]
12115: 400D4744 804A0C8 i -> [ 1 ] 00001
12116: 400D4748 400C5E60 . -> 1 [ 0 ]
12117: 400D474C 8049D0C LOOP -> [ 0 ]
12118: 400D4758 804B384 ; -> ok
12119: @end example
12120:
12121: Each line displayed is one step. You always have to hit return to
12122: execute the next word that is displayed. If you don't want to execute
12123: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
12124: an overview what keys are available:
12125:
12126: @table @i
12127:
12128: @item @key{RET}
12129: Next; Execute the next word.
12130:
12131: @item n
12132: Nest; Single step through next word.
12133:
12134: @item u
12135: Unnest; Stop debugging and execute rest of word. If we got to this word
12136: with nest, continue debugging with the calling word.
12137:
12138: @item d
12139: Done; Stop debugging and execute rest.
12140:
12141: @item s
12142: Stop; Abort immediately.
12143:
12144: @end table
12145:
12146: Debugging large application with this mechanism is very difficult, because
12147: you have to nest very deeply into the program before the interesting part
12148: begins. This takes a lot of time.
12149:
12150: To do it more directly put a @code{BREAK:} command into your source code.
12151: When program execution reaches @code{BREAK:} the single step debugger is
12152: invoked and you have all the features described above.
12153:
12154: If you have more than one part to debug it is useful to know where the
12155: program has stopped at the moment. You can do this by the
12156: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
12157: string is typed out when the ``breakpoint'' is reached.
12158:
12159:
12160: doc-dbg
12161: doc-break:
12162: doc-break"
12163:
12164: @c ------------------------------------------------------------
12165: @node C Interface, Assembler and Code Words, Programming Tools, Words
12166: @section C Interface
12167: @cindex C interface
12168: @cindex foreign language interface
12169: @cindex interface to C functions
12170:
12171: Note that the C interface is not yet complete; callbacks are missing,
12172: as well as a way of declaring structs, unions, and their fields.
12173:
12174: @menu
12175: * Calling C Functions::
12176: * Declaring C Functions::
12177: * Calling C function pointers::
12178: * Defining library interfaces::
12179: * Declaring OS-level libraries::
12180: * Callbacks::
12181: * C interface internals::
12182: * Low-Level C Interface Words::
12183: @end menu
12184:
12185: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
12186: @subsection Calling C functions
12187: @cindex C functions, calls to
12188: @cindex calling C functions
12189:
12190: Once a C function is declared (see @pxref{Declaring C Functions}), you
12191: can call it as follows: You push the arguments on the stack(s), and
12192: then call the word for the C function. The arguments have to be
12193: pushed in the same order as the arguments appear in the C
12194: documentation (i.e., the first argument is deepest on the stack).
12195: Integer and pointer arguments have to be pushed on the data stack,
12196: floating-point arguments on the FP stack; these arguments are consumed
12197: by the called C function.
12198:
12199: On returning from the C function, the return value, if any, resides on
12200: the appropriate stack: an integer return value is pushed on the data
12201: stack, an FP return value on the FP stack, and a void return value
12202: results in not pushing anything. Note that most C functions have a
12203: return value, even if that is often not used in C; in Forth, you have
12204: to @code{drop} this return value explicitly if you do not use it.
12205:
12206: The C interface automatically converts between the C type and the
12207: Forth type as necessary, on a best-effort basis (in some cases, there
12208: may be some loss).
12209:
12210: As an example, consider the POSIX function @code{lseek()}:
12211:
12212: @example
12213: off_t lseek(int fd, off_t offset, int whence);
12214: @end example
12215:
12216: This function takes three integer arguments, and returns an integer
12217: argument, so a Forth call for setting the current file offset to the
12218: start of the file could look like this:
12219:
12220: @example
12221: fd @@ 0 SEEK_SET lseek -1 = if
12222: ... \ error handling
12223: then
12224: @end example
12225:
12226: You might be worried that an @code{off_t} does not fit into a cell, so
12227: you could not pass larger offsets to lseek, and might get only a part
12228: of the return values. In that case, in your declaration of the
12229: function (@pxref{Declaring C Functions}) you should declare it to use
12230: double-cells for the off_t argument and return value, and maybe give
12231: the resulting Forth word a different name, like @code{dlseek}; the
12232: result could be called like this:
12233:
12234: @example
12235: fd @@ 0. SEEK_SET dlseek -1. d= if
12236: ... \ error handling
12237: then
12238: @end example
12239:
12240: Passing and returning structs or unions is currently not supported by
12241: our interface@footnote{If you know the calling convention of your C
12242: compiler, you usually can call such functions in some way, but that
12243: way is usually not portable between platforms, and sometimes not even
12244: between C compilers.}.
12245:
12246: Calling functions with a variable number of arguments (@emph{variadic}
12247: functions, e.g., @code{printf()}) is only supported by having you
12248: declare one function-calling word for each argument pattern, and
12249: calling the appropriate word for the desired pattern.
12250:
12251:
12252:
12253: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
12254: @subsection Declaring C Functions
12255: @cindex C functions, declarations
12256: @cindex declaring C functions
12257:
12258: Before you can call @code{lseek} or @code{dlseek}, you have to declare
12259: it. The declaration consists of two parts:
12260:
12261: @table @b
12262:
12263: @item The C part
12264: is the C declaration of the function, or more typically and portably,
12265: a C-style @code{#include} of a file that contains the declaration of
12266: the C function.
12267:
12268: @item The Forth part
12269: declares the Forth types of the parameters and the Forth word name
12270: corresponding to the C function.
12271:
12272: @end table
12273:
12274: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12275: declarations are:
12276:
12277: @example
12278: \c #define _FILE_OFFSET_BITS 64
12279: \c #include <sys/types.h>
12280: \c #include <unistd.h>
12281: c-function lseek lseek n n n -- n
12282: c-function dlseek lseek n d n -- d
12283: @end example
12284:
12285: The C part of the declarations is prefixed by @code{\c}, and the rest
12286: of the line is ordinary C code. You can use as many lines of C
12287: declarations as you like, and they are visible for all further
12288: function declarations.
12289:
12290: The Forth part declares each interface word with @code{c-function},
12291: followed by the Forth name of the word, the C name of the called
12292: function, and the stack effect of the word. The stack effect contains
12293: an arbitrary number of types of parameters, then @code{--}, and then
12294: exactly one type for the return value. The possible types are:
12295:
12296: @table @code
12297:
12298: @item n
12299: single-cell integer
12300:
12301: @item a
12302: address (single-cell)
12303:
12304: @item d
12305: double-cell integer
12306:
12307: @item r
12308: floating-point value
12309:
12310: @item func
12311: C function pointer
12312:
12313: @item void
12314: no value (used as return type for void functions)
12315:
12316: @end table
12317:
12318: @cindex variadic C functions
12319:
12320: To deal with variadic C functions, you can declare one Forth word for
12321: every pattern you want to use, e.g.:
12322:
12323: @example
12324: \c #include <stdio.h>
12325: c-function printf-nr printf a n r -- n
12326: c-function printf-rn printf a r n -- n
12327: @end example
12328:
12329: Note that with C functions declared as variadic (or if you don't
12330: provide a prototype), the C interface has no C type to convert to, so
12331: no automatic conversion happens, which may lead to portability
12332: problems in some cases. In such cases you can perform the conversion
12333: explicitly on the C level, e.g., as follows:
12334:
12335: @example
12336: \c #define printfll(s,ll) printf(s,(long long)ll)
12337: c-function printfll printfll a n -- n
12338: @end example
12339:
12340: Here, instead of calling @code{printf()} directly, we define a macro
12341: that casts (converts) the Forth single-cell integer into a
12342: C @code{long long} before calling @code{printf()}.
12343:
12344: doc-\c
12345: doc-c-function
12346: doc-c-value
12347: doc-c-variable
12348:
12349: In order to work, this C interface invokes GCC at run-time and uses
12350: dynamic linking. If these features are not available, there are
12351: other, less convenient and less portable C interfaces in @file{lib.fs}
12352: and @file{oldlib.fs}. These interfaces are mostly undocumented and
12353: mostly incompatible with each other and with the documented C
12354: interface; you can find some examples for the @file{lib.fs} interface
12355: in @file{lib.fs}.
12356:
12357:
12358: @node Calling C function pointers, Defining library interfaces, Declaring C Functions, C Interface
12359: @subsection Calling C function pointers from Forth
12360: @cindex C function pointers, calling from Forth
12361:
12362: If you come across a C function pointer (e.g., in some C-constructed
12363: structure) and want to call it from your Forth program, you can also
12364: use the features explained until now to achieve that, as follows:
12365:
12366: Let us assume that there is a C function pointer type @code{func1}
12367: defined in some header file @file{func1.h}, and you know that these
12368: functions take one integer argument and return an integer result; and
12369: you want to call functions through such pointers. Just define
12370:
12371: @example
12372: \c #include <func1.h>
12373: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12374: c-function call-func1 call_func1 n func -- n
12375: @end example
12376:
12377: and then you can call a function pointed to by, say @code{func1a} as
12378: follows:
12379:
12380: @example
12381: -5 func1a call-func1 .
12382: @end example
12383:
12384: In the C part, @code{call_func} is defined as a macro to avoid having
12385: to declare the exact parameter and return types, so the C compiler
12386: knows them from the declaration of @code{func1}.
12387:
12388: The Forth word @code{call-func1} is similar to @code{execute}, except
12389: that it takes a C @code{func1} pointer instead of a Forth execution
12390: token, and it is specific to @code{func1} pointers. For each type of
12391: function pointer you want to call from Forth, you have to define
12392: a separate calling word.
12393:
12394:
12395: @node Defining library interfaces, Declaring OS-level libraries, Calling C function pointers, C Interface
12396: @subsection Defining library interfaces
12397: @cindex giving a name to a library interface
12398: @cindex library interface names
12399:
12400: You can give a name to a bunch of C function declarations (a library
12401: interface), as follows:
12402:
12403: @example
12404: c-library lseek-lib
12405: \c #define _FILE_OFFSET_BITS 64
12406: ...
12407: end-c-library
12408: @end example
12409:
12410: The effect of giving such a name to the interface is that the names of
12411: the generated files will contain that name, and when you use the
12412: interface a second time, it will use the existing files instead of
12413: generating and compiling them again, saving you time. Note that even
12414: if you change the declarations, the old (stale) files will be used,
12415: probably leading to errors. So, during development of the
12416: declarations we recommend not using @code{c-library}. Normally these
12417: files are cached in @file{$HOME/.gforth/libcc-named}, so by deleting
12418: that directory you can get rid of stale files.
12419:
12420: Note that you should use @code{c-library} before everything else
12421: having anything to do with that library, as it resets some setup
12422: stuff. The idea is that the typical use is to put each
12423: @code{c-library}...@code{end-library} unit in its own file, and to be
12424: able to include these files in any order.
12425:
12426: Note that the library name is not allocated in the dictionary and
12427: therefore does not shadow dictionary names. It is used in the file
12428: system, so you have to use naming conventions appropriate for file
12429: systems. Also, you must not call a function you declare after
12430: @code{c-library} before you perform @code{end-c-library}.
12431:
12432: A major benefit of these named library interfaces is that, once they
12433: are generated, the tools used to generated them (in particular, the C
12434: compiler and libtool) are no longer needed, so the interface can be
12435: used even on machines that do not have the tools installed.
12436:
12437: doc-c-library-name
12438: doc-c-library
12439: doc-end-c-library
12440:
12441:
12442: @node Declaring OS-level libraries, Callbacks, Defining library interfaces, C Interface
12443: @subsection Declaring OS-level libraries
12444: @cindex Shared libraries in C interface
12445: @cindex Dynamically linked libraries in C interface
12446: @cindex Libraries in C interface
12447:
12448: For calling some C functions, you need to link with a specific
12449: OS-level library that contains that function. E.g., the @code{sin}
12450: function requires linking a special library by using the command line
12451: switch @code{-lm}. In our C iterface you do the equivalent thing by
12452: calling @code{add-lib} as follows:
12453:
12454: @example
12455: clear-libs
12456: s" m" add-lib
12457: \c #include <math.h>
12458: c-function sin sin r -- r
12459: @end example
12460:
12461: First, you clear any libraries that may have been declared earlier
12462: (you don't need them for @code{sin}); then you add the @code{m}
12463: library (actually @code{libm.so} or somesuch) to the currently
12464: declared libraries; you can add as many as you need. Finally you
12465: declare the function as shown above. Typically you will use the same
12466: set of library declarations for many function declarations; you need
12467: to write only one set for that, right at the beginning.
12468:
12469: Note that you must not call @code{clear-libs} inside
12470: @code{c-library...end-c-library}; however, @code{c-library} performs
12471: the function of @code{clear-libs}, so @code{clear-libs} is not
12472: necessary, and you usually want to put @code{add-lib} calls inside
12473: @code{c-library...end-c-library}.
12474:
12475: doc-clear-libs
12476: doc-add-lib
12477:
12478:
12479: @node Callbacks, C interface internals, Declaring OS-level libraries, C Interface
12480: @subsection Callbacks
12481: @cindex Callback functions written in Forth
12482: @cindex C function pointers to Forth words
12483:
12484: Callbacks are not yet supported by the documented C interface. You
12485: can use the undocumented @file{lib.fs} interface for callbacks.
12486:
12487: In some cases you have to pass a function pointer to a C function,
12488: i.e., the library wants to call back to your application (and the
12489: pointed-to function is called a callback function). You can pass the
12490: address of an existing C function (that you get with @code{lib-sym},
12491: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12492: function, you probably want to define the function as a Forth word.
12493:
12494: @c I don't understand the existing callback interface from the example - anton
12495:
12496:
12497: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12498: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12499: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12500: @c > > C-Funktionsadresse auf dem TOS).
12501: @c >
12502: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12503: @c > gesehen habe, wozu das gut ist.
12504: @c
12505: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch
12506: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen
12507: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit
12508: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte
12509: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit
12510: @c demselben Prototyp.
12511:
12512:
12513: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
12514: @subsection How the C interface works
12515:
12516: The documented C interface works by generating a C code out of the
12517: declarations.
12518:
12519: In particular, for every Forth word declared with @code{c-function},
12520: it generates a wrapper function in C that takes the Forth data from
12521: the Forth stacks, and calls the target C function with these data as
12522: arguments. The C compiler then performs an implicit conversion
12523: between the Forth type from the stack, and the C type for the
12524: parameter, which is given by the C function prototype. After the C
12525: function returns, the return value is likewise implicitly converted to
12526: a Forth type and written back on the stack.
12527:
12528: The @code{\c} lines are literally included in the C code (but without
12529: the @code{\c}), and provide the necessary declarations so that the C
12530: compiler knows the C types and has enough information to perform the
12531: conversion.
12532:
12533: These wrapper functions are eventually compiled and dynamically linked
12534: into Gforth, and then they can be called.
12535:
12536: The libraries added with @code{add-lib} are used in the compile
12537: command line to specify dependent libraries with @code{-l@var{lib}},
12538: causing these libraries to be dynamically linked when the wrapper
12539: function is linked.
12540:
12541:
12542: @node Low-Level C Interface Words, , C interface internals, C Interface
12543: @subsection Low-Level C Interface Words
12544:
12545: doc-open-lib
12546: doc-lib-sym
12547: doc-lib-error
12548: doc-call-c
12549:
12550: @c -------------------------------------------------------------
12551: @node Assembler and Code Words, Threading Words, C Interface, Words
12552: @section Assembler and Code Words
12553: @cindex assembler
12554: @cindex code words
12555:
12556: @menu
12557: * Assembler Definitions:: Definitions in assembly language
12558: * Common Assembler:: Assembler Syntax
12559: * Common Disassembler::
12560: * 386 Assembler:: Deviations and special cases
12561: * AMD64 Assembler::
12562: * Alpha Assembler:: Deviations and special cases
12563: * MIPS assembler:: Deviations and special cases
12564: * PowerPC assembler:: Deviations and special cases
12565: * ARM Assembler:: Deviations and special cases
12566: * Other assemblers:: How to write them
12567: @end menu
12568:
12569: @node Assembler Definitions, Common Assembler, Assembler and Code Words, Assembler and Code Words
12570: @subsection Definitions in assembly language
12571:
12572: Gforth provides ways to implement words in assembly language (using
12573: @code{abi-code}...@code{end-code}), and also ways to define defining
12574: words with arbitrary run-time behaviour (like @code{does>}), where
12575: (unlike @code{does>}) the behaviour is not defined in Forth, but in
12576: assembly language (with @code{;code}).
12577:
12578: However, the machine-independent nature of Gforth poses a few
12579: problems: First of all, Gforth runs on several architectures, so it
12580: can provide no standard assembler. It does provide assemblers for
12581: several of the architectures it runs on, though. Moreover, you can
12582: use a system-independent assembler in Gforth, or compile machine code
12583: directly with @code{,} and @code{c,}.
12584:
12585: Another problem is that the virtual machine registers of Gforth (the
12586: stack pointers and the virtual machine instruction pointer) depend on
12587: the installation and engine. Also, which registers are free to use
12588: also depend on the installation and engine. So any code written to
12589: run in the context of the Gforth virtual machine is essentially
12590: limited to the installation and engine it was developed for (it may
12591: run elsewhere, but you cannot rely on that).
12592:
12593: Fortunately, you can define @code{abi-code} words in Gforth that are
12594: portable to any Gforth running on a platform with the same calling
12595: convention (ABI); typically this means portability to the same
12596: architecture/OS combination, sometimes crossing OS boundaries).
12597:
12598: doc-assembler
12599: doc-init-asm
12600: doc-abi-code
12601: doc-end-code
12602: doc-code
12603: doc-;code
12604: doc-flush-icache
12605:
12606:
12607: If @code{flush-icache} does not work correctly, @code{abi-code} words
12608: etc. will not work (reliably), either.
12609:
12610: The typical usage of these words can be shown most easily by analogy
12611: to the equivalent high-level defining words:
12612:
12613: @example
12614: : foo abi-code foo
12615: <high-level Forth words> <assembler>
12616: ; end-code
12617:
12618: : bar : bar
12619: <high-level Forth words> <high-level Forth words>
12620: CREATE CREATE
12621: <high-level Forth words> <high-level Forth words>
12622: DOES> ;code
12623: <high-level Forth words> <assembler>
12624: ; end-code
12625: @end example
12626:
12627: For using @code{abi-code}, take a look at the ABI documentation of
12628: your platform to see how the parameters are passed (so you know where
12629: you get the stack pointers) and how the return value is passed (so you
12630: know where the data stack pointer is returned). The ABI documentation
12631: also tells you which registers are saved by the caller (caller-saved),
12632: so you are free to destroy them in your code, and which registers have
12633: to be preserved by the called word (callee-saved), so you have to save
12634: them before using them, and restore them afterwards. For some
12635: architectures and OSs we give short summaries of the parts of the
12636: calling convention in the appropriate sections. More
12637: reverse-engineering oriented people can also find out about the
12638: passing and returning of the stack pointers through @code{see
12639: abi-call}.
12640:
12641: Most ABIs pass the parameters through registers, but some (in
12642: particular the most common 386 (aka IA-32) calling conventions) pass
12643: them on the architectural stack. The common ABIs all pass the return
12644: value in a register.
12645:
12646: Other things you need to know for using @code{abi-code} is that both
12647: the data and the FP stack grow downwards (towards lower addresses) in
12648: Gforth, with @code{1 cells} size per cell, and @code{1 floats} size
12649: per FP value.
12650:
12651: Here's an example of using @code{abi-code} on the 386 architecture:
12652:
12653: @example
12654: abi-code my+ ( n1 n2 -- n )
12655: 4 sp d) ax mov \ sp into return reg
12656: ax ) cx mov \ tos
12657: 4 # ax add \ update sp (pop)
12658: cx ax ) add \ sec = sec+tos
12659: ret \ return from my+
12660: end-code
12661: @end example
12662:
12663: An AMD64 variant of this example can be found in @ref{AMD64 Assembler}.
12664:
12665: Here's a 386 example that deals with FP values:
12666:
12667: @example
12668: abi-code my-f+ ( r1 r2 -- r )
12669: 8 sp d) cx mov \ load address of fp
12670: cx ) dx mov \ load fp
12671: .fl dx ) fld \ r2
12672: 8 # dx add \ update fp
12673: .fl dx ) fadd \ r1+r2
12674: .fl dx ) fstp \ store r
12675: dx cx ) mov \ store new fp
12676: 4 sp d) ax mov \ sp into return reg
12677: ret \ return from my-f+
12678: end-code
12679: @end example
12680:
12681:
12682: @node Common Assembler, Common Disassembler, Assembler Definitions, Assembler and Code Words
12683: @subsection Common Assembler
12684:
12685: The assemblers in Gforth generally use a postfix syntax, i.e., the
12686: instruction name follows the operands.
12687:
12688: The operands are passed in the usual order (the same that is used in the
12689: manual of the architecture). Since they all are Forth words, they have
12690: to be separated by spaces; you can also use Forth words to compute the
12691: operands.
12692:
12693: The instruction names usually end with a @code{,}. This makes it easier
12694: to visually separate instructions if you put several of them on one
12695: line; it also avoids shadowing other Forth words (e.g., @code{and}).
12696:
12697: Registers are usually specified by number; e.g., (decimal) @code{11}
12698: specifies registers R11 and F11 on the Alpha architecture (which one,
12699: depends on the instruction). The usual names are also available, e.g.,
12700: @code{s2} for R11 on Alpha.
12701:
12702: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12703: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12704: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12705: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12706: conditions are specified in a way specific to each assembler.
12707:
12708: The rest of this section is of interest mainly for those who want to
12709: define @code{code} words (instead of the more portable @code{abi-code}
12710: words).
12711:
12712: Note that the register assignments of the Gforth engine can change
12713: between Gforth versions, or even between different compilations of the
12714: same Gforth version (e.g., if you use a different GCC version). If
12715: you are using @code{CODE} instead of @code{ABI-CODE}, and you want to
12716: refer to Gforth's registers (e.g., the stack pointer or TOS), I
12717: recommend defining your own words for refering to these registers, and
12718: using them later on; then you can adapt to a changed register
12719: assignment.
12720:
12721: The most common use of these registers is to end a @code{code}
12722: definition with a dispatch to the next word (the @code{next} routine).
12723: A portable way to do this is to jump to @code{' noop >code-address}
12724: (of course, this is less efficient than integrating the @code{next}
12725: code and scheduling it well). When using @code{ABI-CODE}, you can
12726: just assemble a normal subroutine return (but make sure you return the
12727: data stack pointer).
12728:
12729: Another difference between Gforth versions is that the top of stack is
12730: kept in memory in @code{gforth} and, on most platforms, in a register
12731: in @code{gforth-fast}. For @code{ABI-CODE} definitions, any stack
12732: caching registers are guaranteed to be flushed to the stack, allowing
12733: you to reliably access the top of stack in memory.
12734:
12735: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12736: @subsection Common Disassembler
12737: @cindex disassembler, general
12738: @cindex gdb disassembler
12739:
12740: You can disassemble a @code{code} word with @code{see}
12741: (@pxref{Debugging}). You can disassemble a section of memory with
12742:
12743: doc-discode
12744:
12745: There are two kinds of disassembler for Gforth: The Forth disassembler
12746: (available on some CPUs) and the gdb disassembler (available on
12747: platforms with @command{gdb} and @command{mktemp}). If both are
12748: available, the Forth disassembler is used by default. If you prefer
12749: the gdb disassembler, say
12750:
12751: @example
12752: ' disasm-gdb is discode
12753: @end example
12754:
12755: If neither is available, @code{discode} performs @code{dump}.
12756:
12757: The Forth disassembler generally produces output that can be fed into the
12758: assembler (i.e., same syntax, etc.). It also includes additional
12759: information in comments. In particular, the address of the instruction
12760: is given in a comment before the instruction.
12761:
12762: The gdb disassembler produces output in the same format as the gdb
12763: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12764: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12765: the 386 and AMD64 architectures).
12766:
12767: @code{See} may display more or less than the actual code of the word,
12768: because the recognition of the end of the code is unreliable. You can
12769: use @code{discode} if it did not display enough. It may display more, if
12770: the code word is not immediately followed by a named word. If you have
12771: something else there, you can follow the word with @code{align latest ,}
12772: to ensure that the end is recognized.
12773:
12774: @node 386 Assembler, AMD64 Assembler, Common Disassembler, Assembler and Code Words
12775: @subsection 386 Assembler
12776:
12777: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12778: available under GPL, and originally part of bigFORTH.
12779:
12780: The 386 disassembler included in Gforth was written by Andrew McKewan
12781: and is in the public domain.
12782:
12783: The disassembler displays code in an Intel-like prefix syntax.
12784:
12785: The assembler uses a postfix syntax with AT&T-style parameter order
12786: (i.e., destination last).
12787:
12788: The assembler includes all instruction of the Athlon, i.e. 486 core
12789: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12790: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12791: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
12792:
12793: There are several prefixes to switch between different operation sizes,
12794: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12795: double-word accesses. Addressing modes can be switched with @code{.wa}
12796: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12797: need a prefix for byte register names (@code{AL} et al).
12798:
12799: For floating point operations, the prefixes are @code{.fs} (IEEE
12800: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12801: (word), @code{.fd} (double-word), and @code{.fq} (quad-word). The
12802: default is @code{.fx}, so you need to specify @code{.fl} explicitly
12803: when dealing with Gforth FP values.
12804:
12805: The MMX opcodes don't have size prefixes, they are spelled out like in
12806: the Intel assembler. Instead of move from and to memory, there are
12807: PLDQ/PLDD and PSTQ/PSTD.
12808:
12809: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12810: ax. Immediate values are indicated by postfixing them with @code{#},
12811: e.g., @code{3 #}. Here are some examples of addressing modes in various
12812: syntaxes:
12813:
12814: @example
12815: Gforth Intel (NASM) AT&T (gas) Name
12816: .w ax ax %ax register (16 bit)
12817: ax eax %eax register (32 bit)
12818: 3 # offset 3 $3 immediate
12819: 1000 #) byte ptr 1000 1000 displacement
12820: bx ) [ebx] (%ebx) base
12821: 100 di d) 100[edi] 100(%edi) base+displacement
12822: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12823: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12824: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12825: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12826: @end example
12827:
12828: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12829: @code{DI)} to enforce 32-bit displacement fields (useful for
12830: later patching).
12831:
12832: Some example of instructions are:
12833:
12834: @example
12835: ax bx mov \ move ebx,eax
12836: 3 # ax mov \ mov eax,3
12837: 100 di d) ax mov \ mov eax,100[edi]
12838: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12839: .w ax bx mov \ mov bx,ax
12840: @end example
12841:
12842: The following forms are supported for binary instructions:
12843:
12844: @example
12845: <reg> <reg> <inst>
12846: <n> # <reg> <inst>
12847: <mem> <reg> <inst>
12848: <reg> <mem> <inst>
12849: <n> # <mem> <inst>
12850: @end example
12851:
12852: The shift/rotate syntax is:
12853:
12854: @example
12855: <reg/mem> 1 # shl \ shortens to shift without immediate
12856: <reg/mem> 4 # shl
12857: <reg/mem> cl shl
12858: @end example
12859:
12860: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12861: the byte version.
12862:
12863: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12864: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12865: pc < >= <= >}. (Note that most of these words shadow some Forth words
12866: when @code{assembler} is in front of @code{forth} in the search path,
12867: e.g., in @code{code} words). Currently the control structure words use
12868: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12869: to shuffle them (you can also use @code{swap} etc.).
12870:
12871: Based on the Intel ABI (used in Linux), @code{abi-code} words can find
12872: the data stack pointer at @code{4 sp d)}, and the address of the FP
12873: stack pointer at @code{8 sp d)}; the data stack pointer is returned in
12874: @code{ax}; @code{Ax}, @code{cx}, and @code{dx} are caller-saved, so
12875: you do not need to preserve their values inside the word. You can
12876: return from the word with @code{ret}, the parameters are cleaned up by
12877: the caller.
12878:
12879: For examples of 386 @code{abi-code} words, see @ref{Assembler Definitions}.
12880:
12881:
12882: @node AMD64 Assembler, Alpha Assembler, 386 Assembler, Assembler and Code Words
12883: @subsection AMD64 (x86_64) Assembler
12884:
12885: The AMD64 assembler is a slightly modified version of the 386
12886: assembler, and as such shares most of the syntax. Two new prefixes,
12887: @code{.q} and @code{.qa}, are provided to select 64-bit operand and
12888: address sizes respectively. 64-bit sizes are the default, so normally
12889: you only have to use the other prefixes. Also there are additional
12890: register operands @code{R8}-@code{R15}.
12891:
12892: The registers lack the 'e' or 'r' prefix; even in 64 bit mode,
12893: @code{rax} is called @code{ax}. Additional register operands are
12894: available to refer to the lowest-significant byte of all registers:
12895: @code{R8L}-@code{R15L}, @code{SPL}, @code{BPL}, @code{SIL},
12896: @code{DIL}.
12897:
12898: The Linux-AMD64 calling convention is to pass the first 6 integer
12899: parameters in rdi, rsi, rdx, rcx, r8 and r9 and to return the result
12900: in rax and rdx; to pass the first 8 FP parameters in xmm0--xmm7 and to
12901: return FP results in xmm0--xmm1. So @code{abi-code} words get the
12902: data stack pointer in @code{di} and the address of the FP stack
12903: pointer in @code{si}, and return the data stack pointer in @code{ax}.
12904: The other caller-saved registers are: r10, r11, xmm8-xmm15. This
12905: calling convention reportedly is also used in other non-Microsoft OSs.
12906: @c source: http://en.wikipedia.org/wiki/X86_calling_conventions#AMD64_ABI_convention
12907:
12908: @c source: http://msdn.microsoft.com/en-us/library/9b372w95(v=VS.90).aspx
12909: Windows x64 passes the first four integer parameters in rcx, rdx, r8
12910: and r9 and return the integer result in rax. The other caller-saved
12911: registers are r10 and r11.
12912:
12913: Here is an example of an AMD64 @code{abi-code} word:
12914:
12915: @example
12916: abi-code my+ ( n1 n2 -- n3 )
12917: \ SP passed in di, returned in ax, address of FP passed in si
12918: 8 di d) ax lea \ compute new sp in result reg
12919: di ) dx mov \ get old tos
12920: dx ax ) add \ add to new tos
12921: ret
12922: end-code
12923: @end example
12924:
12925: @node Alpha Assembler, MIPS assembler, AMD64 Assembler, Assembler and Code Words
12926: @subsection Alpha Assembler
12927:
12928: The Alpha assembler and disassembler were originally written by Bernd
12929: Thallner.
12930:
12931: The register names @code{a0}--@code{a5} are not available to avoid
12932: shadowing hex numbers.
12933:
12934: Immediate forms of arithmetic instructions are distinguished by a
12935: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12936: does not count as arithmetic instruction).
12937:
12938: You have to specify all operands to an instruction, even those that
12939: other assemblers consider optional, e.g., the destination register for
12940: @code{br,}, or the destination register and hint for @code{jmp,}.
12941:
12942: You can specify conditions for @code{if,} by removing the first @code{b}
12943: and the trailing @code{,} from a branch with a corresponding name; e.g.,
12944:
12945: @example
12946: 11 fgt if, \ if F11>0e
12947: ...
12948: endif,
12949: @end example
12950:
12951: @code{fbgt,} gives @code{fgt}.
12952:
12953: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
12954: @subsection MIPS assembler
12955:
12956: The MIPS assembler was originally written by Christian Pirker.
12957:
12958: Currently the assembler and disassembler covers most of the MIPS32
12959: architecture and doesn't support FP instructions.
12960:
12961: The register names @code{$a0}--@code{$a3} are not available to avoid
12962: shadowing hex numbers. Use register numbers @code{$4}--@code{$7}
12963: instead.
12964:
12965: Nothing distinguishes registers from immediate values. Use explicit
12966: opcode names with the @code{i} suffix for instructions with immediate
12967: argument. E.g. @code{addiu,} in place of @code{addu,}.
12968:
12969: Where the architecture manual specifies several formats for the
12970: instruction (e.g., for @code{jalr,}),use the one with more arguments
12971: (i.e. two for @code{jalr,}). When in doubt, see
12972: @code{arch/mips/testasm.fs} for an example of correct use.
12973:
12974: Branches and jumps in the MIPS architecture have a delay slot. You
12975: have to fill it manually (the simplest way is to use @code{nop,}), the
12976: assembler does not do it for you (unlike @command{as}). Even
12977: @code{if,}, @code{ahead,}, @code{until,}, @code{again,},
12978: @code{while,}, @code{else,} and @code{repeat,} need a delay slot.
12979: Since @code{begin,} and @code{then,} just specify branch targets, they
12980: are not affected. For branches the argument specifying the target is
12981: a relative address. Add the address of the delay slot to get the
12982: absolute address.
12983:
12984: Note that you must not put branches nor jumps (nor control-flow
12985: instructions) into the delay slot. Also it is a bad idea to put
12986: pseudo-ops such as @code{li,} into a delay slot, as these may expand
12987: to several instructions. The MIPS I architecture also had load delay
12988: slots, and newer MIPSes still have restrictions on using @code{mfhi,}
12989: and @code{mflo,}. Be careful to satisfy these restrictions, the
12990: assembler does not do it for you.
12991:
12992: Some example of instructions are:
12993:
12994: @example
12995: $ra 12 $sp sw, \ sw ra,12(sp)
12996: $4 8 $s0 lw, \ lw a0,8(s0)
12997: $v0 $0 lui, \ lui v0,0x0
12998: $s0 $s4 $12 addiu, \ addiu s0,s4,0x12
12999: $s0 $s4 $4 addu, \ addu s0,s4,$a0
13000: $ra $t9 jalr, \ jalr t9
13001: @end example
13002:
13003: You can specify the conditions for @code{if,} etc. by taking a
13004: conditional branch and leaving away the @code{b} at the start and the
13005: @code{,} at the end. E.g.,
13006:
13007: @example
13008: 4 5 eq if,
13009: ... \ do something if $4 equals $5
13010: then,
13011: @end example
13012:
13013: The calling conventions for 32-bit MIPS machines is to pass the first
13014: 4 arguments in registers @code{$4}..@code{$7}, and to use
13015: @code{$v0}-@code{$v1} for return values. In addition to these
13016: registers, it is ok to clobber registers @code{$t0}-@code{$t8} without
13017: saving and restoring them.
13018:
13019: If you use @code{jalr,} to call into dynamic library routines, you
13020: must first load the called function's address into @code{$t9}, which
13021: is used by position-indirect code to do relative memory accesses.
13022:
13023: Here is an example of a MIPS32 @code{abi-code} word:
13024:
13025: @example
13026: abi-code my+ ( n1 n2 -- n3 )
13027: \ SP passed in $4, returned in $v0
13028: $t0 0 $4 lw, \ load n1, n2 from stack
13029: $t1 4 $4 lw,
13030: $t0 $t0 $t1 addu, \ add n1+n2, result in $t0
13031: $t0 4 $4 sw, \ store result (overwriting n1)
13032: $ra jr, \ return to caller
13033: $v0 $4 4 addiu, \ (delay slot) return uptated SP in $v0
13034: end-code
13035: @end example
13036:
13037: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
13038: @subsection PowerPC assembler
13039:
13040: The PowerPC assembler and disassembler were contributed by Michal
13041: Revucky.
13042:
13043: This assembler does not follow the convention of ending mnemonic names
13044: with a ``,'', so some mnemonic names shadow regular Forth words (in
13045: particular: @code{and or xor fabs}); so if you want to use the Forth
13046: words, you have to make them visible first, e.g., with @code{also
13047: forth}.
13048:
13049: Registers are referred to by their number, e.g., @code{9} means the
13050: integer register 9 or the FP register 9 (depending on the
13051: instruction).
13052:
13053: Because there is no way to distinguish registers from immediate values,
13054: you have to explicitly use the immediate forms of instructions, i.e.,
13055: @code{addi,}, not just @code{add,}.
13056:
13057: The assembler and disassembler usually support the most general form
13058: of an instruction, but usually not the shorter forms (especially for
13059: branches).
13060:
13061:
13062: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
13063: @subsection ARM Assembler
13064:
13065: The ARM assembler includes all instruction of ARM architecture version
13066: 4, and the BLX instruction from architecture 5. It does not (yet)
13067: have support for Thumb instructions. It also lacks support for any
13068: co-processors.
13069:
13070: The assembler uses a postfix syntax with the same operand order as
13071: used in the ARM Architecture Reference Manual. Mnemonics are suffixed
13072: by a comma.
13073:
13074: Registers are specified by their names @code{r0} through @code{r15},
13075: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
13076: @code{fp} provided for convenience. Note that @code{ip} refers to
13077: the``intra procedure call scratch register'' (@code{r12}) and does not
13078: refer to an instruction pointer. @code{sp} refers to the ARM ABI
13079: stack pointer (@code{r13}) and not the Forth stack pointer.
13080:
13081: Condition codes can be specified anywhere in the instruction, but will
13082: be most readable if specified just in front of the mnemonic. The 'S'
13083: flag is not a separate word, but encoded into instruction mnemonics,
13084: ie. just use @code{adds,} instead of @code{add,} if you want the
13085: status register to be updated.
13086:
13087: The following table lists the syntax of operands for general
13088: instructions:
13089:
13090: @example
13091: Gforth normal assembler description
13092: 123 # #123 immediate
13093: r12 r12 register
13094: r12 4 #LSL r12, LSL #4 shift left by immediate
13095: r12 r1 #LSL r12, LSL r1 shift left by register
13096: r12 4 #LSR r12, LSR #4 shift right by immediate
13097: r12 r1 #LSR r12, LSR r1 shift right by register
13098: r12 4 #ASR r12, ASR #4 arithmetic shift right
13099: r12 r1 #ASR r12, ASR r1 ... by register
13100: r12 4 #ROR r12, ROR #4 rotate right by immediate
13101: r12 r1 #ROR r12, ROR r1 ... by register
13102: r12 RRX r12, RRX rotate right with extend by 1
13103: @end example
13104:
13105: Memory operand syntax is listed in this table:
13106:
13107: @example
13108: Gforth normal assembler description
13109: r4 ] [r4] register
13110: r4 4 #] [r4, #+4] register with immediate offset
13111: r4 -4 #] [r4, #-4] with negative offset
13112: r4 r1 +] [r4, +r1] register with register offset
13113: r4 r1 -] [r4, -r1] with negated register offset
13114: r4 r1 2 #LSL -] [r4, -r1, LSL #2] with negated and shifted offset
13115: r4 4 #]! [r4, #+4]! immediate preincrement
13116: r4 r1 +]! [r4, +r1]! register preincrement
13117: r4 r1 -]! [r4, +r1]! register predecrement
13118: r4 r1 2 #LSL +]! [r4, +r1, LSL #2]! shifted preincrement
13119: r4 -4 ]# [r4], #-4 immediate postdecrement
13120: r4 r1 ]+ [r4], r1 register postincrement
13121: r4 r1 ]- [r4], -r1 register postdecrement
13122: r4 r1 2 #LSL ]- [r4], -r1, LSL #2 shifted postdecrement
13123: ' xyz >body [#] xyz PC-relative addressing
13124: @end example
13125:
13126: Register lists for load/store multiple instructions are started and
13127: terminated by using the words @code{@{} and @code{@}} respectively.
13128: Between braces, register names can be listed one by one or register
13129: ranges can be formed by using the postfix operator @code{r-r}. The
13130: @code{^} flag is not encoded in the register list operand, but instead
13131: directly encoded into the instruction mnemonic, ie. use @code{^ldm,}
13132: and @code{^stm,}.
13133:
13134: Addressing modes for load/store multiple are not encoded as
13135: instruction suffixes, but instead specified like an addressing mode,
13136: Use one of @code{DA}, @code{IA}, @code{DB}, @code{IB}, @code{DA!},
13137: @code{IA!}, @code{DB!} or @code{IB!}.
13138:
13139: The following table gives some examples:
13140:
13141: @example
13142: Gforth normal assembler
13143: r4 ia @{ r0 r7 r8 @} stm, stmia r4, @{r0,r7,r8@}
13144: r4 db! @{ r0 r7 r8 @} ldm, ldmdb r4!, @{r0,r7,r8@}
13145: sp ia! @{ r0 r15 r-r @} ^ldm, ldmfd sp!, @{r0-r15@}^
13146: @end example
13147:
13148: Control structure words typical for Forth assemblers are available:
13149: @code{if,} @code{ahead,} @code{then,} @code{else,} @code{begin,}
13150: @code{until,} @code{again,} @code{while,} @code{repeat,}
13151: @code{repeat-until,}. Conditions are specified in front of these words:
13152:
13153: @example
13154: r1 r2 cmp, \ compare r1 and r2
13155: eq if, \ equal?
13156: ... \ code executed if r1 == r2
13157: then,
13158: @end example
13159:
13160: Example of a definition using the ARM assembler:
13161:
13162: @example
13163: abi-code my+ ( n1 n2 -- n3 )
13164: \ arm abi: r0=SP, r1=&FP, r2,r3,r12 saved by caller
13165: r0 IA! @{ r2 r3 @} ldm, \ pop r2 = n2, r3 = n1
13166: r3 r2 r3 add, \ r3 = n1+n1
13167: r3 r0 -4 #]! str, \ push r3
13168: pc lr mov, \ return to caller, new SP in r0
13169: end-code
13170: @end example
13171:
13172: @node Other assemblers, , ARM Assembler, Assembler and Code Words
13173: @subsection Other assemblers
13174:
13175: If you want to contribute another assembler/disassembler, please contact
13176: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
13177: an assembler already. If you are writing them from scratch, please use
13178: a similar syntax style as the one we use (i.e., postfix, commas at the
13179: end of the instruction names, @pxref{Common Assembler}); make the output
13180: of the disassembler be valid input for the assembler, and keep the style
13181: similar to the style we used.
13182:
13183: Hints on implementation: The most important part is to have a good test
13184: suite that contains all instructions. Once you have that, the rest is
13185: easy. For actual coding you can take a look at
13186: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
13187: the assembler and disassembler, avoiding redundancy and some potential
13188: bugs. You can also look at that file (and @pxref{Advanced does> usage
13189: example}) to get ideas how to factor a disassembler.
13190:
13191: Start with the disassembler, because it's easier to reuse data from the
13192: disassembler for the assembler than the other way round.
13193:
13194: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
13195: how simple it can be.
13196:
13197:
13198:
13199:
13200: @c -------------------------------------------------------------
13201: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
13202: @section Threading Words
13203: @cindex threading words
13204:
13205: @cindex code address
13206: These words provide access to code addresses and other threading stuff
13207: in Gforth (and, possibly, other interpretive Forths). It more or less
13208: abstracts away the differences between direct and indirect threading
13209: (and, for direct threading, the machine dependences). However, at
13210: present this wordset is still incomplete. It is also pretty low-level;
13211: some day it will hopefully be made unnecessary by an internals wordset
13212: that abstracts implementation details away completely.
13213:
13214: The terminology used here stems from indirect threaded Forth systems; in
13215: such a system, the XT of a word is represented by the CFA (code field
13216: address) of a word; the CFA points to a cell that contains the code
13217: address. The code address is the address of some machine code that
13218: performs the run-time action of invoking the word (e.g., the
13219: @code{dovar:} routine pushes the address of the body of the word (a
13220: variable) on the stack
13221: ).
13222:
13223: @cindex code address
13224: @cindex code field address
13225: In an indirect threaded Forth, you can get the code address of @i{name}
13226: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
13227: >code-address}, independent of the threading method.
13228:
13229: doc-threading-method
13230: doc->code-address
13231: doc-code-address!
13232:
13233: @cindex @code{does>}-handler
13234: @cindex @code{does>}-code
13235: For a word defined with @code{DOES>}, the code address usually points to
13236: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
13237: routine (in Gforth on some platforms, it can also point to the dodoes
13238: routine itself). What you are typically interested in, though, is
13239: whether a word is a @code{DOES>}-defined word, and what Forth code it
13240: executes; @code{>does-code} tells you that.
13241:
13242: doc->does-code
13243:
13244: To create a @code{DOES>}-defined word with the following basic words,
13245: you have to set up a @code{DOES>}-handler with @code{does-handler!};
13246: @code{/does-handler} aus behind you have to place your executable Forth
13247: code. Finally you have to create a word and modify its behaviour with
13248: @code{does-handler!}.
13249:
13250: doc-does-code!
13251: doc-does-handler!
13252: doc-/does-handler
13253:
13254: The code addresses produced by various defining words are produced by
13255: the following words:
13256:
13257: doc-docol:
13258: doc-docon:
13259: doc-dovar:
13260: doc-douser:
13261: doc-dodefer:
13262: doc-dofield:
13263:
13264: @cindex definer
13265: The following two words generalize @code{>code-address},
13266: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
13267:
13268: doc->definer
13269: doc-definer!
13270:
13271: @c -------------------------------------------------------------
13272: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
13273: @section Passing Commands to the Operating System
13274: @cindex operating system - passing commands
13275: @cindex shell commands
13276:
13277: Gforth allows you to pass an arbitrary string to the host operating
13278: system shell (if such a thing exists) for execution.
13279:
13280: doc-sh
13281: doc-system
13282: doc-$?
13283: doc-getenv
13284:
13285: @c -------------------------------------------------------------
13286: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
13287: @section Keeping track of Time
13288: @cindex time-related words
13289:
13290: doc-ms
13291: doc-time&date
13292: doc-utime
13293: doc-cputime
13294:
13295:
13296: @c -------------------------------------------------------------
13297: @node Miscellaneous Words, , Keeping track of Time, Words
13298: @section Miscellaneous Words
13299: @cindex miscellaneous words
13300:
13301: @comment TODO find homes for these
13302:
13303: These section lists the ANS Forth words that are not documented
13304: elsewhere in this manual. Ultimately, they all need proper homes.
13305:
13306: doc-quit
13307:
13308: The following ANS Forth words are not currently supported by Gforth
13309: (@pxref{ANS conformance}):
13310:
13311: @code{EDITOR}
13312: @code{EMIT?}
13313: @code{FORGET}
13314:
13315: @c ******************************************************************
13316: @node Error messages, Tools, Words, Top
13317: @chapter Error messages
13318: @cindex error messages
13319: @cindex backtrace
13320:
13321: A typical Gforth error message looks like this:
13322:
13323: @example
13324: in file included from \evaluated string/:-1
13325: in file included from ./yyy.fs:1
13326: ./xxx.fs:4: Invalid memory address
13327: >>>bar<<<
13328: Backtrace:
13329: $400E664C @@
13330: $400E6664 foo
13331: @end example
13332:
13333: The message identifying the error is @code{Invalid memory address}. The
13334: error happened when text-interpreting line 4 of the file
13335: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
13336: word on the line where the error happened, is pointed out (with
13337: @code{>>>} and @code{<<<}).
13338:
13339: The file containing the error was included in line 1 of @file{./yyy.fs},
13340: and @file{yyy.fs} was included from a non-file (in this case, by giving
13341: @file{yyy.fs} as command-line parameter to Gforth).
13342:
13343: At the end of the error message you find a return stack dump that can be
13344: interpreted as a backtrace (possibly empty). On top you find the top of
13345: the return stack when the @code{throw} happened, and at the bottom you
13346: find the return stack entry just above the return stack of the topmost
13347: text interpreter.
13348:
13349: To the right of most return stack entries you see a guess for the word
13350: that pushed that return stack entry as its return address. This gives a
13351: backtrace. In our case we see that @code{bar} called @code{foo}, and
13352: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
13353: address} exception).
13354:
13355: Note that the backtrace is not perfect: We don't know which return stack
13356: entries are return addresses (so we may get false positives); and in
13357: some cases (e.g., for @code{abort"}) we cannot determine from the return
13358: address the word that pushed the return address, so for some return
13359: addresses you see no names in the return stack dump.
13360:
13361: @cindex @code{catch} and backtraces
13362: The return stack dump represents the return stack at the time when a
13363: specific @code{throw} was executed. In programs that make use of
13364: @code{catch}, it is not necessarily clear which @code{throw} should be
13365: used for the return stack dump (e.g., consider one @code{throw} that
13366: indicates an error, which is caught, and during recovery another error
13367: happens; which @code{throw} should be used for the stack dump?).
13368: Gforth presents the return stack dump for the first @code{throw} after
13369: the last executed (not returned-to) @code{catch} or @code{nothrow};
13370: this works well in the usual case. To get the right backtrace, you
13371: usually want to insert @code{nothrow} or @code{['] false catch drop}
13372: after a @code{catch} if the error is not rethrown.
13373:
13374: @cindex @code{gforth-fast} and backtraces
13375: @cindex @code{gforth-fast}, difference from @code{gforth}
13376: @cindex backtraces with @code{gforth-fast}
13377: @cindex return stack dump with @code{gforth-fast}
13378: @code{Gforth} is able to do a return stack dump for throws generated
13379: from primitives (e.g., invalid memory address, stack empty etc.);
13380: @code{gforth-fast} is only able to do a return stack dump from a
13381: directly called @code{throw} (including @code{abort} etc.). Given an
13382: exception caused by a primitive in @code{gforth-fast}, you will
13383: typically see no return stack dump at all; however, if the exception is
13384: caught by @code{catch} (e.g., for restoring some state), and then
13385: @code{throw}n again, the return stack dump will be for the first such
13386: @code{throw}.
13387:
13388: @c ******************************************************************
13389: @node Tools, ANS conformance, Error messages, Top
13390: @chapter Tools
13391:
13392: @menu
13393: * ANS Report:: Report the words used, sorted by wordset.
13394: * Stack depth changes:: Where does this stack item come from?
13395: @end menu
13396:
13397: See also @ref{Emacs and Gforth}.
13398:
13399: @node ANS Report, Stack depth changes, Tools, Tools
13400: @section @file{ans-report.fs}: Report the words used, sorted by wordset
13401: @cindex @file{ans-report.fs}
13402: @cindex report the words used in your program
13403: @cindex words used in your program
13404:
13405: If you want to label a Forth program as ANS Forth Program, you must
13406: document which wordsets the program uses; for extension wordsets, it is
13407: helpful to list the words the program requires from these wordsets
13408: (because Forth systems are allowed to provide only some words of them).
13409:
13410: The @file{ans-report.fs} tool makes it easy for you to determine which
13411: words from which wordset and which non-ANS words your application
13412: uses. You simply have to include @file{ans-report.fs} before loading the
13413: program you want to check. After loading your program, you can get the
13414: report with @code{print-ans-report}. A typical use is to run this as
13415: batch job like this:
13416: @example
13417: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
13418: @end example
13419:
13420: The output looks like this (for @file{compat/control.fs}):
13421: @example
13422: The program uses the following words
13423: from CORE :
13424: : POSTPONE THEN ; immediate ?dup IF 0=
13425: from BLOCK-EXT :
13426: \
13427: from FILE :
13428: (
13429: @end example
13430:
13431: @subsection Caveats
13432:
13433: Note that @file{ans-report.fs} just checks which words are used, not whether
13434: they are used in an ANS Forth conforming way!
13435:
13436: Some words are defined in several wordsets in the
13437: standard. @file{ans-report.fs} reports them for only one of the
13438: wordsets, and not necessarily the one you expect. It depends on usage
13439: which wordset is the right one to specify. E.g., if you only use the
13440: compilation semantics of @code{S"}, it is a Core word; if you also use
13441: its interpretation semantics, it is a File word.
13442:
13443:
13444: @node Stack depth changes, , ANS Report, Tools
13445: @section Stack depth changes during interpretation
13446: @cindex @file{depth-changes.fs}
13447: @cindex depth changes during interpretation
13448: @cindex stack depth changes during interpretation
13449: @cindex items on the stack after interpretation
13450:
13451: Sometimes you notice that, after loading a file, there are items left
13452: on the stack. The tool @file{depth-changes.fs} helps you find out
13453: quickly where in the file these stack items are coming from.
13454:
13455: The simplest way of using @file{depth-changes.fs} is to include it
13456: before the file(s) you want to check, e.g.:
13457:
13458: @example
13459: gforth depth-changes.fs my-file.fs
13460: @end example
13461:
13462: This will compare the stack depths of the data and FP stack at every
13463: empty line (in interpretation state) against these depths at the last
13464: empty line (in interpretation state). If the depths are not equal,
13465: the position in the file and the stack contents are printed with
13466: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
13467: change has occured in the paragraph of non-empty lines before the
13468: indicated line. It is a good idea to leave an empty line at the end
13469: of the file, so the last paragraph is checked, too.
13470:
13471: Checking only at empty lines usually works well, but sometimes you
13472: have big blocks of non-empty lines (e.g., when building a big table),
13473: and you want to know where in this block the stack depth changed. You
13474: can check all interpreted lines with
13475:
13476: @example
13477: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
13478: @end example
13479:
13480: This checks the stack depth at every end-of-line. So the depth change
13481: occured in the line reported by the @code{~~} (not in the line
13482: before).
13483:
13484: Note that, while this offers better accuracy in indicating where the
13485: stack depth changes, it will often report many intentional stack depth
13486: changes (e.g., when an interpreted computation stretches across
13487: several lines). You can suppress the checking of some lines by
13488: putting backslashes at the end of these lines (not followed by white
13489: space), and using
13490:
13491: @example
13492: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
13493: @end example
13494:
13495: @c ******************************************************************
13496: @node ANS conformance, Standard vs Extensions, Tools, Top
13497: @chapter ANS conformance
13498: @cindex ANS conformance of Gforth
13499:
13500: To the best of our knowledge, Gforth is an
13501:
13502: ANS Forth System
13503: @itemize @bullet
13504: @item providing the Core Extensions word set
13505: @item providing the Block word set
13506: @item providing the Block Extensions word set
13507: @item providing the Double-Number word set
13508: @item providing the Double-Number Extensions word set
13509: @item providing the Exception word set
13510: @item providing the Exception Extensions word set
13511: @item providing the Facility word set
13512: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
13513: @item providing the File Access word set
13514: @item providing the File Access Extensions word set
13515: @item providing the Floating-Point word set
13516: @item providing the Floating-Point Extensions word set
13517: @item providing the Locals word set
13518: @item providing the Locals Extensions word set
13519: @item providing the Memory-Allocation word set
13520: @item providing the Memory-Allocation Extensions word set (that one's easy)
13521: @item providing the Programming-Tools word set
13522: @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
13523: @item providing the Search-Order word set
13524: @item providing the Search-Order Extensions word set
13525: @item providing the String word set
13526: @item providing the String Extensions word set (another easy one)
13527: @end itemize
13528:
13529: Gforth has the following environmental restrictions:
13530:
13531: @cindex environmental restrictions
13532: @itemize @bullet
13533: @item
13534: While processing the OS command line, if an exception is not caught,
13535: Gforth exits with a non-zero exit code instyead of performing QUIT.
13536:
13537: @item
13538: When an @code{throw} is performed after a @code{query}, Gforth does not
13539: allways restore the input source specification in effect at the
13540: corresponding catch.
13541:
13542: @end itemize
13543:
13544:
13545: @cindex system documentation
13546: In addition, ANS Forth systems are required to document certain
13547: implementation choices. This chapter tries to meet these
13548: requirements. In many cases it gives a way to ask the system for the
13549: information instead of providing the information directly, in
13550: particular, if the information depends on the processor, the operating
13551: system or the installation options chosen, or if they are likely to
13552: change during the maintenance of Gforth.
13553:
13554: @comment The framework for the rest has been taken from pfe.
13555:
13556: @menu
13557: * The Core Words::
13558: * The optional Block word set::
13559: * The optional Double Number word set::
13560: * The optional Exception word set::
13561: * The optional Facility word set::
13562: * The optional File-Access word set::
13563: * The optional Floating-Point word set::
13564: * The optional Locals word set::
13565: * The optional Memory-Allocation word set::
13566: * The optional Programming-Tools word set::
13567: * The optional Search-Order word set::
13568: @end menu
13569:
13570:
13571: @c =====================================================================
13572: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13573: @comment node-name, next, previous, up
13574: @section The Core Words
13575: @c =====================================================================
13576: @cindex core words, system documentation
13577: @cindex system documentation, core words
13578:
13579: @menu
13580: * core-idef:: Implementation Defined Options
13581: * core-ambcond:: Ambiguous Conditions
13582: * core-other:: Other System Documentation
13583: @end menu
13584:
13585: @c ---------------------------------------------------------------------
13586: @node core-idef, core-ambcond, The Core Words, The Core Words
13587: @subsection Implementation Defined Options
13588: @c ---------------------------------------------------------------------
13589: @cindex core words, implementation-defined options
13590: @cindex implementation-defined options, core words
13591:
13592:
13593: @table @i
13594: @item (Cell) aligned addresses:
13595: @cindex cell-aligned addresses
13596: @cindex aligned addresses
13597: processor-dependent. Gforth's alignment words perform natural alignment
13598: (e.g., an address aligned for a datum of size 8 is divisible by
13599: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13600:
13601: @item @code{EMIT} and non-graphic characters:
13602: @cindex @code{EMIT} and non-graphic characters
13603: @cindex non-graphic characters and @code{EMIT}
13604: The character is output using the C library function (actually, macro)
13605: @code{putc}.
13606:
13607: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13608: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13609: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13610: @cindex @code{ACCEPT}, editing
13611: @cindex @code{EXPECT}, editing
13612: This is modeled on the GNU readline library (@pxref{Readline
13613: Interaction, , Command Line Editing, readline, The GNU Readline
13614: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13615: producing a full word completion every time you type it (instead of
13616: producing the common prefix of all completions). @xref{Command-line editing}.
13617:
13618: @item character set:
13619: @cindex character set
13620: The character set of your computer and display device. Gforth is
13621: 8-bit-clean (but some other component in your system may make trouble).
13622:
13623: @item Character-aligned address requirements:
13624: @cindex character-aligned address requirements
13625: installation-dependent. Currently a character is represented by a C
13626: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13627: (Comments on that requested).
13628:
13629: @item character-set extensions and matching of names:
13630: @cindex character-set extensions and matching of names
13631: @cindex case-sensitivity for name lookup
13632: @cindex name lookup, case-sensitivity
13633: @cindex locale and case-sensitivity
13634: Any character except the ASCII NUL character can be used in a
13635: name. Matching is case-insensitive (except in @code{TABLE}s). The
13636: matching is performed using the C library function @code{strncasecmp}, whose
13637: function is probably influenced by the locale. E.g., the @code{C} locale
13638: does not know about accents and umlauts, so they are matched
13639: case-sensitively in that locale. For portability reasons it is best to
13640: write programs such that they work in the @code{C} locale. Then one can
13641: use libraries written by a Polish programmer (who might use words
13642: containing ISO Latin-2 encoded characters) and by a French programmer
13643: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13644: funny results for some of the words (which ones, depends on the font you
13645: are using)). Also, the locale you prefer may not be available in other
13646: operating systems. Hopefully, Unicode will solve these problems one day.
13647:
13648: @item conditions under which control characters match a space delimiter:
13649: @cindex space delimiters
13650: @cindex control characters as delimiters
13651: If @code{word} is called with the space character as a delimiter, all
13652: white-space characters (as identified by the C macro @code{isspace()})
13653: are delimiters. @code{Parse}, on the other hand, treats space like other
13654: delimiters. @code{Parse-name}, which is used by the outer
13655: interpreter (aka text interpreter) by default, treats all white-space
13656: characters as delimiters.
13657:
13658: @item format of the control-flow stack:
13659: @cindex control-flow stack, format
13660: The data stack is used as control-flow stack. The size of a control-flow
13661: stack item in cells is given by the constant @code{cs-item-size}. At the
13662: time of this writing, an item consists of a (pointer to a) locals list
13663: (third), an address in the code (second), and a tag for identifying the
13664: item (TOS). The following tags are used: @code{defstart},
13665: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13666: @code{scopestart}.
13667:
13668: @item conversion of digits > 35
13669: @cindex digits > 35
13670: The characters @code{[\]^_'} are the digits with the decimal value
13671: 36@minus{}41. There is no way to input many of the larger digits.
13672:
13673: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13674: @cindex @code{EXPECT}, display after end of input
13675: @cindex @code{ACCEPT}, display after end of input
13676: The cursor is moved to the end of the entered string. If the input is
13677: terminated using the @kbd{Return} key, a space is typed.
13678:
13679: @item exception abort sequence of @code{ABORT"}:
13680: @cindex exception abort sequence of @code{ABORT"}
13681: @cindex @code{ABORT"}, exception abort sequence
13682: The error string is stored into the variable @code{"error} and a
13683: @code{-2 throw} is performed.
13684:
13685: @item input line terminator:
13686: @cindex input line terminator
13687: @cindex line terminator on input
13688: @cindex newline character on input
13689: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13690: lines. One of these characters is typically produced when you type the
13691: @kbd{Enter} or @kbd{Return} key.
13692:
13693: @item maximum size of a counted string:
13694: @cindex maximum size of a counted string
13695: @cindex counted string, maximum size
13696: @code{s" /counted-string" environment? drop .}. Currently 255 characters
13697: on all platforms, but this may change.
13698:
13699: @item maximum size of a parsed string:
13700: @cindex maximum size of a parsed string
13701: @cindex parsed string, maximum size
13702: Given by the constant @code{/line}. Currently 255 characters.
13703:
13704: @item maximum size of a definition name, in characters:
13705: @cindex maximum size of a definition name, in characters
13706: @cindex name, maximum length
13707: MAXU/8
13708:
13709: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13710: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13711: @cindex @code{ENVIRONMENT?} string length, maximum
13712: MAXU/8
13713:
13714: @item method of selecting the user input device:
13715: @cindex user input device, method of selecting
13716: The user input device is the standard input. There is currently no way to
13717: change it from within Gforth. However, the input can typically be
13718: redirected in the command line that starts Gforth.
13719:
13720: @item method of selecting the user output device:
13721: @cindex user output device, method of selecting
13722: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
13723: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13724: output when the user output device is a terminal, otherwise the output
13725: is buffered.
13726:
13727: @item methods of dictionary compilation:
13728: What are we expected to document here?
13729:
13730: @item number of bits in one address unit:
13731: @cindex number of bits in one address unit
13732: @cindex address unit, size in bits
13733: @code{s" address-units-bits" environment? drop .}. 8 in all current
13734: platforms.
13735:
13736: @item number representation and arithmetic:
13737: @cindex number representation and arithmetic
13738: Processor-dependent. Binary two's complement on all current platforms.
13739:
13740: @item ranges for integer types:
13741: @cindex ranges for integer types
13742: @cindex integer types, ranges
13743: Installation-dependent. Make environmental queries for @code{MAX-N},
13744: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13745: unsigned (and positive) types is 0. The lower bound for signed types on
13746: two's complement and one's complement machines machines can be computed
13747: by adding 1 to the upper bound.
13748:
13749: @item read-only data space regions:
13750: @cindex read-only data space regions
13751: @cindex data-space, read-only regions
13752: The whole Forth data space is writable.
13753:
13754: @item size of buffer at @code{WORD}:
13755: @cindex size of buffer at @code{WORD}
13756: @cindex @code{WORD} buffer size
13757: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13758: shared with the pictured numeric output string. If overwriting
13759: @code{PAD} is acceptable, it is as large as the remaining dictionary
13760: space, although only as much can be sensibly used as fits in a counted
13761: string.
13762:
13763: @item size of one cell in address units:
13764: @cindex cell size
13765: @code{1 cells .}.
13766:
13767: @item size of one character in address units:
13768: @cindex char size
13769: @code{1 chars .}. 1 on all current platforms.
13770:
13771: @item size of the keyboard terminal buffer:
13772: @cindex size of the keyboard terminal buffer
13773: @cindex terminal buffer, size
13774: Varies. You can determine the size at a specific time using @code{lp@@
13775: tib - .}. It is shared with the locals stack and TIBs of files that
13776: include the current file. You can change the amount of space for TIBs
13777: and locals stack at Gforth startup with the command line option
13778: @code{-l}.
13779:
13780: @item size of the pictured numeric output buffer:
13781: @cindex size of the pictured numeric output buffer
13782: @cindex pictured numeric output buffer, size
13783: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13784: shared with @code{WORD}.
13785:
13786: @item size of the scratch area returned by @code{PAD}:
13787: @cindex size of the scratch area returned by @code{PAD}
13788: @cindex @code{PAD} size
13789: The remainder of dictionary space. @code{unused pad here - - .}.
13790:
13791: @item system case-sensitivity characteristics:
13792: @cindex case-sensitivity characteristics
13793: Dictionary searches are case-insensitive (except in
13794: @code{TABLE}s). However, as explained above under @i{character-set
13795: extensions}, the matching for non-ASCII characters is determined by the
13796: locale you are using. In the default @code{C} locale all non-ASCII
13797: characters are matched case-sensitively.
13798:
13799: @item system prompt:
13800: @cindex system prompt
13801: @cindex prompt
13802: @code{ ok} in interpret state, @code{ compiled} in compile state.
13803:
13804: @item division rounding:
13805: @cindex division rounding
13806: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13807: division (with the default installation of Gforth). You can check
13808: this with @code{s" floored" environment? drop .}. If you write
13809: programs that need a specific division rounding, best use
13810: @code{fm/mod} or @code{sm/rem} for portability.
13811:
13812: @item values of @code{STATE} when true:
13813: @cindex @code{STATE} values
13814: -1.
13815:
13816: @item values returned after arithmetic overflow:
13817: On two's complement machines, arithmetic is performed modulo
13818: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13819: arithmetic (with appropriate mapping for signed types). Division by
13820: zero typically results in a @code{-55 throw} (Floating-point
13821: unidentified fault) or @code{-10 throw} (divide by zero). Integer
13822: division overflow can result in these throws, or in @code{-11 throw};
13823: in @code{gforth-fast} division overflow and divide by zero may also
13824: result in returning bogus results without producing an exception.
13825:
13826: @item whether the current definition can be found after @t{DOES>}:
13827: @cindex @t{DOES>}, visibility of current definition
13828: No.
13829:
13830: @end table
13831:
13832: @c ---------------------------------------------------------------------
13833: @node core-ambcond, core-other, core-idef, The Core Words
13834: @subsection Ambiguous conditions
13835: @c ---------------------------------------------------------------------
13836: @cindex core words, ambiguous conditions
13837: @cindex ambiguous conditions, core words
13838:
13839: @table @i
13840:
13841: @item a name is neither a word nor a number:
13842: @cindex name not found
13843: @cindex undefined word
13844: @code{-13 throw} (Undefined word).
13845:
13846: @item a definition name exceeds the maximum length allowed:
13847: @cindex word name too long
13848: @code{-19 throw} (Word name too long)
13849:
13850: @item addressing a region not inside the various data spaces of the forth system:
13851: @cindex Invalid memory address
13852: The stacks, code space and header space are accessible. Machine code space is
13853: typically readable. Accessing other addresses gives results dependent on
13854: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13855: address).
13856:
13857: @item argument type incompatible with parameter:
13858: @cindex argument type mismatch
13859: This is usually not caught. Some words perform checks, e.g., the control
13860: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13861: mismatch).
13862:
13863: @item attempting to obtain the execution token of a word with undefined execution semantics:
13864: @cindex Interpreting a compile-only word, for @code{'} etc.
13865: @cindex execution token of words with undefined execution semantics
13866: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13867: get an execution token for @code{compile-only-error} (which performs a
13868: @code{-14 throw} when executed).
13869:
13870: @item dividing by zero:
13871: @cindex dividing by zero
13872: @cindex floating point unidentified fault, integer division
13873: On some platforms, this produces a @code{-10 throw} (Division by
13874: zero); on other systems, this typically results in a @code{-55 throw}
13875: (Floating-point unidentified fault).
13876:
13877: @item insufficient data stack or return stack space:
13878: @cindex insufficient data stack or return stack space
13879: @cindex stack overflow
13880: @cindex address alignment exception, stack overflow
13881: @cindex Invalid memory address, stack overflow
13882: Depending on the operating system, the installation, and the invocation
13883: of Gforth, this is either checked by the memory management hardware, or
13884: it is not checked. If it is checked, you typically get a @code{-3 throw}
13885: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13886: throw} (Invalid memory address) (depending on the platform and how you
13887: achieved the overflow) as soon as the overflow happens. If it is not
13888: checked, overflows typically result in mysterious illegal memory
13889: accesses, producing @code{-9 throw} (Invalid memory address) or
13890: @code{-23 throw} (Address alignment exception); they might also destroy
13891: the internal data structure of @code{ALLOCATE} and friends, resulting in
13892: various errors in these words.
13893:
13894: @item insufficient space for loop control parameters:
13895: @cindex insufficient space for loop control parameters
13896: Like other return stack overflows.
13897:
13898: @item insufficient space in the dictionary:
13899: @cindex insufficient space in the dictionary
13900: @cindex dictionary overflow
13901: If you try to allot (either directly with @code{allot}, or indirectly
13902: with @code{,}, @code{create} etc.) more memory than available in the
13903: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13904: to access memory beyond the end of the dictionary, the results are
13905: similar to stack overflows.
13906:
13907: @item interpreting a word with undefined interpretation semantics:
13908: @cindex interpreting a word with undefined interpretation semantics
13909: @cindex Interpreting a compile-only word
13910: For some words, we have defined interpretation semantics. For the
13911: others: @code{-14 throw} (Interpreting a compile-only word).
13912:
13913: @item modifying the contents of the input buffer or a string literal:
13914: @cindex modifying the contents of the input buffer or a string literal
13915: These are located in writable memory and can be modified.
13916:
13917: @item overflow of the pictured numeric output string:
13918: @cindex overflow of the pictured numeric output string
13919: @cindex pictured numeric output string, overflow
13920: @code{-17 throw} (Pictured numeric ouput string overflow).
13921:
13922: @item parsed string overflow:
13923: @cindex parsed string overflow
13924: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13925:
13926: @item producing a result out of range:
13927: @cindex result out of range
13928: On two's complement machines, arithmetic is performed modulo
13929: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13930: arithmetic (with appropriate mapping for signed types). Division by
13931: zero typically results in a @code{-10 throw} (divide by zero) or
13932: @code{-55 throw} (floating point unidentified fault). Overflow on
13933: division may result in these errors or in @code{-11 throw} (result out
13934: of range). @code{Gforth-fast} may silently produce bogus results on
13935: division overflow or division by zero. @code{Convert} and
13936: @code{>number} currently overflow silently.
13937:
13938: @item reading from an empty data or return stack:
13939: @cindex stack empty
13940: @cindex stack underflow
13941: @cindex return stack underflow
13942: The data stack is checked by the outer (aka text) interpreter after
13943: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13944: underflow) is performed. Apart from that, stacks may be checked or not,
13945: depending on operating system, installation, and invocation. If they are
13946: caught by a check, they typically result in @code{-4 throw} (Stack
13947: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13948: (Invalid memory address), depending on the platform and which stack
13949: underflows and by how much. Note that even if the system uses checking
13950: (through the MMU), your program may have to underflow by a significant
13951: number of stack items to trigger the reaction (the reason for this is
13952: that the MMU, and therefore the checking, works with a page-size
13953: granularity). If there is no checking, the symptoms resulting from an
13954: underflow are similar to those from an overflow. Unbalanced return
13955: stack errors can result in a variety of symptoms, including @code{-9 throw}
13956: (Invalid memory address) and Illegal Instruction (typically @code{-260
13957: throw}).
13958:
13959: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13960: @cindex unexpected end of the input buffer
13961: @cindex zero-length string as a name
13962: @cindex Attempt to use zero-length string as a name
13963: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13964: use zero-length string as a name). Words like @code{'} probably will not
13965: find what they search. Note that it is possible to create zero-length
13966: names with @code{nextname} (should it not?).
13967:
13968: @item @code{>IN} greater than input buffer:
13969: @cindex @code{>IN} greater than input buffer
13970: The next invocation of a parsing word returns a string with length 0.
13971:
13972: @item @code{RECURSE} appears after @code{DOES>}:
13973: @cindex @code{RECURSE} appears after @code{DOES>}
13974: Compiles a recursive call to the defining word, not to the defined word.
13975:
13976: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13977: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
13978: @cindex argument type mismatch, @code{RESTORE-INPUT}
13979: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13980: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13981: the end of the file was reached), its source-id may be
13982: reused. Therefore, restoring an input source specification referencing a
13983: closed file may lead to unpredictable results instead of a @code{-12
13984: THROW}.
13985:
13986: In the future, Gforth may be able to restore input source specifications
13987: from other than the current input source.
13988:
13989: @item data space containing definitions gets de-allocated:
13990: @cindex data space containing definitions gets de-allocated
13991: Deallocation with @code{allot} is not checked. This typically results in
13992: memory access faults or execution of illegal instructions.
13993:
13994: @item data space read/write with incorrect alignment:
13995: @cindex data space read/write with incorrect alignment
13996: @cindex alignment faults
13997: @cindex address alignment exception
13998: Processor-dependent. Typically results in a @code{-23 throw} (Address
13999: alignment exception). Under Linux-Intel on a 486 or later processor with
14000: alignment turned on, incorrect alignment results in a @code{-9 throw}
14001: (Invalid memory address). There are reportedly some processors with
14002: alignment restrictions that do not report violations.
14003:
14004: @item data space pointer not properly aligned, @code{,}, @code{C,}:
14005: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
14006: Like other alignment errors.
14007:
14008: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
14009: Like other stack underflows.
14010:
14011: @item loop control parameters not available:
14012: @cindex loop control parameters not available
14013: Not checked. The counted loop words simply assume that the top of return
14014: stack items are loop control parameters and behave accordingly.
14015:
14016: @item most recent definition does not have a name (@code{IMMEDIATE}):
14017: @cindex most recent definition does not have a name (@code{IMMEDIATE})
14018: @cindex last word was headerless
14019: @code{abort" last word was headerless"}.
14020:
14021: @item name not defined by @code{VALUE} used by @code{TO}:
14022: @cindex name not defined by @code{VALUE} used by @code{TO}
14023: @cindex @code{TO} on non-@code{VALUE}s
14024: @cindex Invalid name argument, @code{TO}
14025: @code{-32 throw} (Invalid name argument) (unless name is a local or was
14026: defined by @code{CONSTANT}; in the latter case it just changes the constant).
14027:
14028: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
14029: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
14030: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
14031: @code{-13 throw} (Undefined word)
14032:
14033: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
14034: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
14035: Gforth behaves as if they were of the same type. I.e., you can predict
14036: the behaviour by interpreting all parameters as, e.g., signed.
14037:
14038: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
14039: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
14040: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
14041: compilation semantics of @code{TO}.
14042:
14043: @item String longer than a counted string returned by @code{WORD}:
14044: @cindex string longer than a counted string returned by @code{WORD}
14045: @cindex @code{WORD}, string overflow
14046: Not checked. The string will be ok, but the count will, of course,
14047: contain only the least significant bits of the length.
14048:
14049: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
14050: @cindex @code{LSHIFT}, large shift counts
14051: @cindex @code{RSHIFT}, large shift counts
14052: Processor-dependent. Typical behaviours are returning 0 and using only
14053: the low bits of the shift count.
14054:
14055: @item word not defined via @code{CREATE}:
14056: @cindex @code{>BODY} of non-@code{CREATE}d words
14057: @code{>BODY} produces the PFA of the word no matter how it was defined.
14058:
14059: @cindex @code{DOES>} of non-@code{CREATE}d words
14060: @code{DOES>} changes the execution semantics of the last defined word no
14061: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
14062: @code{CREATE , DOES>}.
14063:
14064: @item words improperly used outside @code{<#} and @code{#>}:
14065: Not checked. As usual, you can expect memory faults.
14066:
14067: @end table
14068:
14069:
14070: @c ---------------------------------------------------------------------
14071: @node core-other, , core-ambcond, The Core Words
14072: @subsection Other system documentation
14073: @c ---------------------------------------------------------------------
14074: @cindex other system documentation, core words
14075: @cindex core words, other system documentation
14076:
14077: @table @i
14078: @item nonstandard words using @code{PAD}:
14079: @cindex @code{PAD} use by nonstandard words
14080: None.
14081:
14082: @item operator's terminal facilities available:
14083: @cindex operator's terminal facilities available
14084: After processing the OS's command line, Gforth goes into interactive mode,
14085: and you can give commands to Gforth interactively. The actual facilities
14086: available depend on how you invoke Gforth.
14087:
14088: @item program data space available:
14089: @cindex program data space available
14090: @cindex data space available
14091: @code{UNUSED .} gives the remaining dictionary space. The total
14092: dictionary space can be specified with the @code{-m} switch
14093: (@pxref{Invoking Gforth}) when Gforth starts up.
14094:
14095: @item return stack space available:
14096: @cindex return stack space available
14097: You can compute the total return stack space in cells with
14098: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
14099: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
14100:
14101: @item stack space available:
14102: @cindex stack space available
14103: You can compute the total data stack space in cells with
14104: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
14105: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
14106:
14107: @item system dictionary space required, in address units:
14108: @cindex system dictionary space required, in address units
14109: Type @code{here forthstart - .} after startup. At the time of this
14110: writing, this gives 80080 (bytes) on a 32-bit system.
14111: @end table
14112:
14113:
14114: @c =====================================================================
14115: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
14116: @section The optional Block word set
14117: @c =====================================================================
14118: @cindex system documentation, block words
14119: @cindex block words, system documentation
14120:
14121: @menu
14122: * block-idef:: Implementation Defined Options
14123: * block-ambcond:: Ambiguous Conditions
14124: * block-other:: Other System Documentation
14125: @end menu
14126:
14127:
14128: @c ---------------------------------------------------------------------
14129: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
14130: @subsection Implementation Defined Options
14131: @c ---------------------------------------------------------------------
14132: @cindex implementation-defined options, block words
14133: @cindex block words, implementation-defined options
14134:
14135: @table @i
14136: @item the format for display by @code{LIST}:
14137: @cindex @code{LIST} display format
14138: First the screen number is displayed, then 16 lines of 64 characters,
14139: each line preceded by the line number.
14140:
14141: @item the length of a line affected by @code{\}:
14142: @cindex length of a line affected by @code{\}
14143: @cindex @code{\}, line length in blocks
14144: 64 characters.
14145: @end table
14146:
14147:
14148: @c ---------------------------------------------------------------------
14149: @node block-ambcond, block-other, block-idef, The optional Block word set
14150: @subsection Ambiguous conditions
14151: @c ---------------------------------------------------------------------
14152: @cindex block words, ambiguous conditions
14153: @cindex ambiguous conditions, block words
14154:
14155: @table @i
14156: @item correct block read was not possible:
14157: @cindex block read not possible
14158: Typically results in a @code{throw} of some OS-derived value (between
14159: -512 and -2048). If the blocks file was just not long enough, blanks are
14160: supplied for the missing portion.
14161:
14162: @item I/O exception in block transfer:
14163: @cindex I/O exception in block transfer
14164: @cindex block transfer, I/O exception
14165: Typically results in a @code{throw} of some OS-derived value (between
14166: -512 and -2048).
14167:
14168: @item invalid block number:
14169: @cindex invalid block number
14170: @cindex block number invalid
14171: @code{-35 throw} (Invalid block number)
14172:
14173: @item a program directly alters the contents of @code{BLK}:
14174: @cindex @code{BLK}, altering @code{BLK}
14175: The input stream is switched to that other block, at the same
14176: position. If the storing to @code{BLK} happens when interpreting
14177: non-block input, the system will get quite confused when the block ends.
14178:
14179: @item no current block buffer for @code{UPDATE}:
14180: @cindex @code{UPDATE}, no current block buffer
14181: @code{UPDATE} has no effect.
14182:
14183: @end table
14184:
14185: @c ---------------------------------------------------------------------
14186: @node block-other, , block-ambcond, The optional Block word set
14187: @subsection Other system documentation
14188: @c ---------------------------------------------------------------------
14189: @cindex other system documentation, block words
14190: @cindex block words, other system documentation
14191:
14192: @table @i
14193: @item any restrictions a multiprogramming system places on the use of buffer addresses:
14194: No restrictions (yet).
14195:
14196: @item the number of blocks available for source and data:
14197: depends on your disk space.
14198:
14199: @end table
14200:
14201:
14202: @c =====================================================================
14203: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
14204: @section The optional Double Number word set
14205: @c =====================================================================
14206: @cindex system documentation, double words
14207: @cindex double words, system documentation
14208:
14209: @menu
14210: * double-ambcond:: Ambiguous Conditions
14211: @end menu
14212:
14213:
14214: @c ---------------------------------------------------------------------
14215: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
14216: @subsection Ambiguous conditions
14217: @c ---------------------------------------------------------------------
14218: @cindex double words, ambiguous conditions
14219: @cindex ambiguous conditions, double words
14220:
14221: @table @i
14222: @item @i{d} outside of range of @i{n} in @code{D>S}:
14223: @cindex @code{D>S}, @i{d} out of range of @i{n}
14224: The least significant cell of @i{d} is produced.
14225:
14226: @end table
14227:
14228:
14229: @c =====================================================================
14230: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
14231: @section The optional Exception word set
14232: @c =====================================================================
14233: @cindex system documentation, exception words
14234: @cindex exception words, system documentation
14235:
14236: @menu
14237: * exception-idef:: Implementation Defined Options
14238: @end menu
14239:
14240:
14241: @c ---------------------------------------------------------------------
14242: @node exception-idef, , The optional Exception word set, The optional Exception word set
14243: @subsection Implementation Defined Options
14244: @c ---------------------------------------------------------------------
14245: @cindex implementation-defined options, exception words
14246: @cindex exception words, implementation-defined options
14247:
14248: @table @i
14249: @item @code{THROW}-codes used in the system:
14250: @cindex @code{THROW}-codes used in the system
14251: The codes -256@minus{}-511 are used for reporting signals. The mapping
14252: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
14253: codes -512@minus{}-2047 are used for OS errors (for file and memory
14254: allocation operations). The mapping from OS error numbers to throw codes
14255: is -512@minus{}@code{errno}. One side effect of this mapping is that
14256: undefined OS errors produce a message with a strange number; e.g.,
14257: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
14258: @end table
14259:
14260: @c =====================================================================
14261: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
14262: @section The optional Facility word set
14263: @c =====================================================================
14264: @cindex system documentation, facility words
14265: @cindex facility words, system documentation
14266:
14267: @menu
14268: * facility-idef:: Implementation Defined Options
14269: * facility-ambcond:: Ambiguous Conditions
14270: @end menu
14271:
14272:
14273: @c ---------------------------------------------------------------------
14274: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
14275: @subsection Implementation Defined Options
14276: @c ---------------------------------------------------------------------
14277: @cindex implementation-defined options, facility words
14278: @cindex facility words, implementation-defined options
14279:
14280: @table @i
14281: @item encoding of keyboard events (@code{EKEY}):
14282: @cindex keyboard events, encoding in @code{EKEY}
14283: @cindex @code{EKEY}, encoding of keyboard events
14284: Keys corresponding to ASCII characters are encoded as ASCII characters.
14285: Other keys are encoded with the constants @code{k-left}, @code{k-right},
14286: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
14287: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
14288: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
14289:
14290:
14291: @item duration of a system clock tick:
14292: @cindex duration of a system clock tick
14293: @cindex clock tick duration
14294: System dependent. With respect to @code{MS}, the time is specified in
14295: microseconds. How well the OS and the hardware implement this, is
14296: another question.
14297:
14298: @item repeatability to be expected from the execution of @code{MS}:
14299: @cindex repeatability to be expected from the execution of @code{MS}
14300: @cindex @code{MS}, repeatability to be expected
14301: System dependent. On Unix, a lot depends on load. If the system is
14302: lightly loaded, and the delay is short enough that Gforth does not get
14303: swapped out, the performance should be acceptable. Under MS-DOS and
14304: other single-tasking systems, it should be good.
14305:
14306: @end table
14307:
14308:
14309: @c ---------------------------------------------------------------------
14310: @node facility-ambcond, , facility-idef, The optional Facility word set
14311: @subsection Ambiguous conditions
14312: @c ---------------------------------------------------------------------
14313: @cindex facility words, ambiguous conditions
14314: @cindex ambiguous conditions, facility words
14315:
14316: @table @i
14317: @item @code{AT-XY} can't be performed on user output device:
14318: @cindex @code{AT-XY} can't be performed on user output device
14319: Largely terminal dependent. No range checks are done on the arguments.
14320: No errors are reported. You may see some garbage appearing, you may see
14321: simply nothing happen.
14322:
14323: @end table
14324:
14325:
14326: @c =====================================================================
14327: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
14328: @section The optional File-Access word set
14329: @c =====================================================================
14330: @cindex system documentation, file words
14331: @cindex file words, system documentation
14332:
14333: @menu
14334: * file-idef:: Implementation Defined Options
14335: * file-ambcond:: Ambiguous Conditions
14336: @end menu
14337:
14338: @c ---------------------------------------------------------------------
14339: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
14340: @subsection Implementation Defined Options
14341: @c ---------------------------------------------------------------------
14342: @cindex implementation-defined options, file words
14343: @cindex file words, implementation-defined options
14344:
14345: @table @i
14346: @item file access methods used:
14347: @cindex file access methods used
14348: @code{R/O}, @code{R/W} and @code{BIN} work as you would
14349: expect. @code{W/O} translates into the C file opening mode @code{w} (or
14350: @code{wb}): The file is cleared, if it exists, and created, if it does
14351: not (with both @code{open-file} and @code{create-file}). Under Unix
14352: @code{create-file} creates a file with 666 permissions modified by your
14353: umask.
14354:
14355: @item file exceptions:
14356: @cindex file exceptions
14357: The file words do not raise exceptions (except, perhaps, memory access
14358: faults when you pass illegal addresses or file-ids).
14359:
14360: @item file line terminator:
14361: @cindex file line terminator
14362: System-dependent. Gforth uses C's newline character as line
14363: terminator. What the actual character code(s) of this are is
14364: system-dependent.
14365:
14366: @item file name format:
14367: @cindex file name format
14368: System dependent. Gforth just uses the file name format of your OS.
14369:
14370: @item information returned by @code{FILE-STATUS}:
14371: @cindex @code{FILE-STATUS}, returned information
14372: @code{FILE-STATUS} returns the most powerful file access mode allowed
14373: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
14374: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
14375: along with the returned mode.
14376:
14377: @item input file state after an exception when including source:
14378: @cindex exception when including source
14379: All files that are left via the exception are closed.
14380:
14381: @item @i{ior} values and meaning:
14382: @cindex @i{ior} values and meaning
14383: @cindex @i{wior} values and meaning
14384: The @i{ior}s returned by the file and memory allocation words are
14385: intended as throw codes. They typically are in the range
14386: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
14387: @i{ior}s is -512@minus{}@i{errno}.
14388:
14389: @item maximum depth of file input nesting:
14390: @cindex maximum depth of file input nesting
14391: @cindex file input nesting, maximum depth
14392: limited by the amount of return stack, locals/TIB stack, and the number
14393: of open files available. This should not give you troubles.
14394:
14395: @item maximum size of input line:
14396: @cindex maximum size of input line
14397: @cindex input line size, maximum
14398: @code{/line}. Currently 255.
14399:
14400: @item methods of mapping block ranges to files:
14401: @cindex mapping block ranges to files
14402: @cindex files containing blocks
14403: @cindex blocks in files
14404: By default, blocks are accessed in the file @file{blocks.fb} in the
14405: current working directory. The file can be switched with @code{USE}.
14406:
14407: @item number of string buffers provided by @code{S"}:
14408: @cindex @code{S"}, number of string buffers
14409: 1
14410:
14411: @item size of string buffer used by @code{S"}:
14412: @cindex @code{S"}, size of string buffer
14413: @code{/line}. currently 255.
14414:
14415: @end table
14416:
14417: @c ---------------------------------------------------------------------
14418: @node file-ambcond, , file-idef, The optional File-Access word set
14419: @subsection Ambiguous conditions
14420: @c ---------------------------------------------------------------------
14421: @cindex file words, ambiguous conditions
14422: @cindex ambiguous conditions, file words
14423:
14424: @table @i
14425: @item attempting to position a file outside its boundaries:
14426: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
14427: @code{REPOSITION-FILE} is performed as usual: Afterwards,
14428: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
14429:
14430: @item attempting to read from file positions not yet written:
14431: @cindex reading from file positions not yet written
14432: End-of-file, i.e., zero characters are read and no error is reported.
14433:
14434: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
14435: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
14436: An appropriate exception may be thrown, but a memory fault or other
14437: problem is more probable.
14438:
14439: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
14440: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
14441: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
14442: The @i{ior} produced by the operation, that discovered the problem, is
14443: thrown.
14444:
14445: @item named file cannot be opened (@code{INCLUDED}):
14446: @cindex @code{INCLUDED}, named file cannot be opened
14447: The @i{ior} produced by @code{open-file} is thrown.
14448:
14449: @item requesting an unmapped block number:
14450: @cindex unmapped block numbers
14451: There are no unmapped legal block numbers. On some operating systems,
14452: writing a block with a large number may overflow the file system and
14453: have an error message as consequence.
14454:
14455: @item using @code{source-id} when @code{blk} is non-zero:
14456: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
14457: @code{source-id} performs its function. Typically it will give the id of
14458: the source which loaded the block. (Better ideas?)
14459:
14460: @end table
14461:
14462:
14463: @c =====================================================================
14464: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
14465: @section The optional Floating-Point word set
14466: @c =====================================================================
14467: @cindex system documentation, floating-point words
14468: @cindex floating-point words, system documentation
14469:
14470: @menu
14471: * floating-idef:: Implementation Defined Options
14472: * floating-ambcond:: Ambiguous Conditions
14473: @end menu
14474:
14475:
14476: @c ---------------------------------------------------------------------
14477: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
14478: @subsection Implementation Defined Options
14479: @c ---------------------------------------------------------------------
14480: @cindex implementation-defined options, floating-point words
14481: @cindex floating-point words, implementation-defined options
14482:
14483: @table @i
14484: @item format and range of floating point numbers:
14485: @cindex format and range of floating point numbers
14486: @cindex floating point numbers, format and range
14487: System-dependent; the @code{double} type of C.
14488:
14489: @item results of @code{REPRESENT} when @i{float} is out of range:
14490: @cindex @code{REPRESENT}, results when @i{float} is out of range
14491: System dependent; @code{REPRESENT} is implemented using the C library
14492: function @code{ecvt()} and inherits its behaviour in this respect.
14493:
14494: @item rounding or truncation of floating-point numbers:
14495: @cindex rounding of floating-point numbers
14496: @cindex truncation of floating-point numbers
14497: @cindex floating-point numbers, rounding or truncation
14498: System dependent; the rounding behaviour is inherited from the hosting C
14499: compiler. IEEE-FP-based (i.e., most) systems by default round to
14500: nearest, and break ties by rounding to even (i.e., such that the last
14501: bit of the mantissa is 0).
14502:
14503: @item size of floating-point stack:
14504: @cindex floating-point stack size
14505: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
14506: the floating-point stack (in floats). You can specify this on startup
14507: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
14508:
14509: @item width of floating-point stack:
14510: @cindex floating-point stack width
14511: @code{1 floats}.
14512:
14513: @end table
14514:
14515:
14516: @c ---------------------------------------------------------------------
14517: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
14518: @subsection Ambiguous conditions
14519: @c ---------------------------------------------------------------------
14520: @cindex floating-point words, ambiguous conditions
14521: @cindex ambiguous conditions, floating-point words
14522:
14523: @table @i
14524: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
14525: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
14526: System-dependent. Typically results in a @code{-23 THROW} like other
14527: alignment violations.
14528:
14529: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
14530: @cindex @code{f@@} used with an address that is not float aligned
14531: @cindex @code{f!} used with an address that is not float aligned
14532: System-dependent. Typically results in a @code{-23 THROW} like other
14533: alignment violations.
14534:
14535: @item floating-point result out of range:
14536: @cindex floating-point result out of range
14537: System-dependent. Can result in a @code{-43 throw} (floating point
14538: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
14539: (floating point inexact result), @code{-55 THROW} (Floating-point
14540: unidentified fault), or can produce a special value representing, e.g.,
14541: Infinity.
14542:
14543: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
14544: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
14545: System-dependent. Typically results in an alignment fault like other
14546: alignment violations.
14547:
14548: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
14549: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
14550: The floating-point number is converted into decimal nonetheless.
14551:
14552: @item Both arguments are equal to zero (@code{FATAN2}):
14553: @cindex @code{FATAN2}, both arguments are equal to zero
14554: System-dependent. @code{FATAN2} is implemented using the C library
14555: function @code{atan2()}.
14556:
14557: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14558: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14559: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
14560: because of small errors and the tan will be a very large (or very small)
14561: but finite number.
14562:
14563: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14564: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
14565: The result is rounded to the nearest float.
14566:
14567: @item dividing by zero:
14568: @cindex dividing by zero, floating-point
14569: @cindex floating-point dividing by zero
14570: @cindex floating-point unidentified fault, FP divide-by-zero
14571: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14572: (floating point divide by zero) or @code{-55 throw} (Floating-point
14573: unidentified fault).
14574:
14575: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14576: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14577: System dependent. On IEEE-FP based systems the number is converted into
14578: an infinity.
14579:
14580: @item @i{float}<1 (@code{FACOSH}):
14581: @cindex @code{FACOSH}, @i{float}<1
14582: @cindex floating-point unidentified fault, @code{FACOSH}
14583: Platform-dependent; on IEEE-FP systems typically produces a NaN.
14584:
14585: @item @i{float}=<-1 (@code{FLNP1}):
14586: @cindex @code{FLNP1}, @i{float}=<-1
14587: @cindex floating-point unidentified fault, @code{FLNP1}
14588: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14589: negative infinity for @i{float}=-1).
14590:
14591: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14592: @cindex @code{FLN}, @i{float}=<0
14593: @cindex @code{FLOG}, @i{float}=<0
14594: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
14595: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14596: negative infinity for @i{float}=0).
14597:
14598: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14599: @cindex @code{FASINH}, @i{float}<0
14600: @cindex @code{FSQRT}, @i{float}<0
14601: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
14602: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14603: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14604: C library?).
14605:
14606: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14607: @cindex @code{FACOS}, |@i{float}|>1
14608: @cindex @code{FASIN}, |@i{float}|>1
14609: @cindex @code{FATANH}, |@i{float}|>1
14610: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
14611: Platform-dependent; IEEE-FP systems typically produce a NaN.
14612:
14613: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14614: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
14615: @cindex floating-point unidentified fault, @code{F>D}
14616: Platform-dependent; typically, some double number is produced and no
14617: error is reported.
14618:
14619: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14620: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
14621: @code{Precision} characters of the numeric output area are used. If
14622: @code{precision} is too high, these words will smash the data or code
14623: close to @code{here}.
14624: @end table
14625:
14626: @c =====================================================================
14627: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14628: @section The optional Locals word set
14629: @c =====================================================================
14630: @cindex system documentation, locals words
14631: @cindex locals words, system documentation
14632:
14633: @menu
14634: * locals-idef:: Implementation Defined Options
14635: * locals-ambcond:: Ambiguous Conditions
14636: @end menu
14637:
14638:
14639: @c ---------------------------------------------------------------------
14640: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14641: @subsection Implementation Defined Options
14642: @c ---------------------------------------------------------------------
14643: @cindex implementation-defined options, locals words
14644: @cindex locals words, implementation-defined options
14645:
14646: @table @i
14647: @item maximum number of locals in a definition:
14648: @cindex maximum number of locals in a definition
14649: @cindex locals, maximum number in a definition
14650: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14651: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14652: characters. The number of locals in a definition is bounded by the size
14653: of locals-buffer, which contains the names of the locals.
14654:
14655: @end table
14656:
14657:
14658: @c ---------------------------------------------------------------------
14659: @node locals-ambcond, , locals-idef, The optional Locals word set
14660: @subsection Ambiguous conditions
14661: @c ---------------------------------------------------------------------
14662: @cindex locals words, ambiguous conditions
14663: @cindex ambiguous conditions, locals words
14664:
14665: @table @i
14666: @item executing a named local in interpretation state:
14667: @cindex local in interpretation state
14668: @cindex Interpreting a compile-only word, for a local
14669: Locals have no interpretation semantics. If you try to perform the
14670: interpretation semantics, you will get a @code{-14 throw} somewhere
14671: (Interpreting a compile-only word). If you perform the compilation
14672: semantics, the locals access will be compiled (irrespective of state).
14673:
14674: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
14675: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14676: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14677: @cindex Invalid name argument, @code{TO}
14678: @code{-32 throw} (Invalid name argument)
14679:
14680: @end table
14681:
14682:
14683: @c =====================================================================
14684: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14685: @section The optional Memory-Allocation word set
14686: @c =====================================================================
14687: @cindex system documentation, memory-allocation words
14688: @cindex memory-allocation words, system documentation
14689:
14690: @menu
14691: * memory-idef:: Implementation Defined Options
14692: @end menu
14693:
14694:
14695: @c ---------------------------------------------------------------------
14696: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14697: @subsection Implementation Defined Options
14698: @c ---------------------------------------------------------------------
14699: @cindex implementation-defined options, memory-allocation words
14700: @cindex memory-allocation words, implementation-defined options
14701:
14702: @table @i
14703: @item values and meaning of @i{ior}:
14704: @cindex @i{ior} values and meaning
14705: The @i{ior}s returned by the file and memory allocation words are
14706: intended as throw codes. They typically are in the range
14707: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
14708: @i{ior}s is -512@minus{}@i{errno}.
14709:
14710: @end table
14711:
14712: @c =====================================================================
14713: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14714: @section The optional Programming-Tools word set
14715: @c =====================================================================
14716: @cindex system documentation, programming-tools words
14717: @cindex programming-tools words, system documentation
14718:
14719: @menu
14720: * programming-idef:: Implementation Defined Options
14721: * programming-ambcond:: Ambiguous Conditions
14722: @end menu
14723:
14724:
14725: @c ---------------------------------------------------------------------
14726: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14727: @subsection Implementation Defined Options
14728: @c ---------------------------------------------------------------------
14729: @cindex implementation-defined options, programming-tools words
14730: @cindex programming-tools words, implementation-defined options
14731:
14732: @table @i
14733: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14734: @cindex @code{;CODE} ending sequence
14735: @cindex @code{CODE} ending sequence
14736: @code{END-CODE}
14737:
14738: @item manner of processing input following @code{;CODE} and @code{CODE}:
14739: @cindex @code{;CODE}, processing input
14740: @cindex @code{CODE}, processing input
14741: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14742: the input is processed by the text interpreter, (starting) in interpret
14743: state.
14744:
14745: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14746: @cindex @code{ASSEMBLER}, search order capability
14747: The ANS Forth search order word set.
14748:
14749: @item source and format of display by @code{SEE}:
14750: @cindex @code{SEE}, source and format of output
14751: The source for @code{see} is the executable code used by the inner
14752: interpreter. The current @code{see} tries to output Forth source code
14753: (and on some platforms, assembly code for primitives) as well as
14754: possible.
14755:
14756: @end table
14757:
14758: @c ---------------------------------------------------------------------
14759: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
14760: @subsection Ambiguous conditions
14761: @c ---------------------------------------------------------------------
14762: @cindex programming-tools words, ambiguous conditions
14763: @cindex ambiguous conditions, programming-tools words
14764:
14765: @table @i
14766:
14767: @item deleting the compilation word list (@code{FORGET}):
14768: @cindex @code{FORGET}, deleting the compilation word list
14769: Not implemented (yet).
14770:
14771: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14772: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14773: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
14774: @cindex control-flow stack underflow
14775: This typically results in an @code{abort"} with a descriptive error
14776: message (may change into a @code{-22 throw} (Control structure mismatch)
14777: in the future). You may also get a memory access error. If you are
14778: unlucky, this ambiguous condition is not caught.
14779:
14780: @item @i{name} can't be found (@code{FORGET}):
14781: @cindex @code{FORGET}, @i{name} can't be found
14782: Not implemented (yet).
14783:
14784: @item @i{name} not defined via @code{CREATE}:
14785: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
14786: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14787: the execution semantics of the last defined word no matter how it was
14788: defined.
14789:
14790: @item @code{POSTPONE} applied to @code{[IF]}:
14791: @cindex @code{POSTPONE} applied to @code{[IF]}
14792: @cindex @code{[IF]} and @code{POSTPONE}
14793: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14794: equivalent to @code{[IF]}.
14795:
14796: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14797: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14798: Continue in the same state of conditional compilation in the next outer
14799: input source. Currently there is no warning to the user about this.
14800:
14801: @item removing a needed definition (@code{FORGET}):
14802: @cindex @code{FORGET}, removing a needed definition
14803: Not implemented (yet).
14804:
14805: @end table
14806:
14807:
14808: @c =====================================================================
14809: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
14810: @section The optional Search-Order word set
14811: @c =====================================================================
14812: @cindex system documentation, search-order words
14813: @cindex search-order words, system documentation
14814:
14815: @menu
14816: * search-idef:: Implementation Defined Options
14817: * search-ambcond:: Ambiguous Conditions
14818: @end menu
14819:
14820:
14821: @c ---------------------------------------------------------------------
14822: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14823: @subsection Implementation Defined Options
14824: @c ---------------------------------------------------------------------
14825: @cindex implementation-defined options, search-order words
14826: @cindex search-order words, implementation-defined options
14827:
14828: @table @i
14829: @item maximum number of word lists in search order:
14830: @cindex maximum number of word lists in search order
14831: @cindex search order, maximum depth
14832: @code{s" wordlists" environment? drop .}. Currently 16.
14833:
14834: @item minimum search order:
14835: @cindex minimum search order
14836: @cindex search order, minimum
14837: @code{root root}.
14838:
14839: @end table
14840:
14841: @c ---------------------------------------------------------------------
14842: @node search-ambcond, , search-idef, The optional Search-Order word set
14843: @subsection Ambiguous conditions
14844: @c ---------------------------------------------------------------------
14845: @cindex search-order words, ambiguous conditions
14846: @cindex ambiguous conditions, search-order words
14847:
14848: @table @i
14849: @item changing the compilation word list (during compilation):
14850: @cindex changing the compilation word list (during compilation)
14851: @cindex compilation word list, change before definition ends
14852: The word is entered into the word list that was the compilation word list
14853: at the start of the definition. Any changes to the name field (e.g.,
14854: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
14855: are applied to the latest defined word (as reported by @code{latest} or
14856: @code{latestxt}), if possible, irrespective of the compilation word list.
14857:
14858: @item search order empty (@code{previous}):
14859: @cindex @code{previous}, search order empty
14860: @cindex vocstack empty, @code{previous}
14861: @code{abort" Vocstack empty"}.
14862:
14863: @item too many word lists in search order (@code{also}):
14864: @cindex @code{also}, too many word lists in search order
14865: @cindex vocstack full, @code{also}
14866: @code{abort" Vocstack full"}.
14867:
14868: @end table
14869:
14870: @c ***************************************************************
14871: @node Standard vs Extensions, Model, ANS conformance, Top
14872: @chapter Should I use Gforth extensions?
14873: @cindex Gforth extensions
14874:
14875: As you read through the rest of this manual, you will see documentation
14876: for @i{Standard} words, and documentation for some appealing Gforth
14877: @i{extensions}. You might ask yourself the question: @i{``Should I
14878: restrict myself to the standard, or should I use the extensions?''}
14879:
14880: The answer depends on the goals you have for the program you are working
14881: on:
14882:
14883: @itemize @bullet
14884:
14885: @item Is it just for yourself or do you want to share it with others?
14886:
14887: @item
14888: If you want to share it, do the others all use Gforth?
14889:
14890: @item
14891: If it is just for yourself, do you want to restrict yourself to Gforth?
14892:
14893: @end itemize
14894:
14895: If restricting the program to Gforth is ok, then there is no reason not
14896: to use extensions. It is still a good idea to keep to the standard
14897: where it is easy, in case you want to reuse these parts in another
14898: program that you want to be portable.
14899:
14900: If you want to be able to port the program to other Forth systems, there
14901: are the following points to consider:
14902:
14903: @itemize @bullet
14904:
14905: @item
14906: Most Forth systems that are being maintained support the ANS Forth
14907: standard. So if your program complies with the standard, it will be
14908: portable among many systems.
14909:
14910: @item
14911: A number of the Gforth extensions can be implemented in ANS Forth using
14912: public-domain files provided in the @file{compat/} directory. These are
14913: mentioned in the text in passing. There is no reason not to use these
14914: extensions, your program will still be ANS Forth compliant; just include
14915: the appropriate compat files with your program.
14916:
14917: @item
14918: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14919: analyse your program and determine what non-Standard words it relies
14920: upon. However, it does not check whether you use standard words in a
14921: non-standard way.
14922:
14923: @item
14924: Some techniques are not standardized by ANS Forth, and are hard or
14925: impossible to implement in a standard way, but can be implemented in
14926: most Forth systems easily, and usually in similar ways (e.g., accessing
14927: word headers). Forth has a rich historical precedent for programmers
14928: taking advantage of implementation-dependent features of their tools
14929: (for example, relying on a knowledge of the dictionary
14930: structure). Sometimes these techniques are necessary to extract every
14931: last bit of performance from the hardware, sometimes they are just a
14932: programming shorthand.
14933:
14934: @item
14935: Does using a Gforth extension save more work than the porting this part
14936: to other Forth systems (if any) will cost?
14937:
14938: @item
14939: Is the additional functionality worth the reduction in portability and
14940: the additional porting problems?
14941:
14942: @end itemize
14943:
14944: In order to perform these consideratios, you need to know what's
14945: standard and what's not. This manual generally states if something is
14946: non-standard, but the authoritative source is the
14947: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
14948: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14949: into the thought processes of the technical committee.
14950:
14951: Note also that portability between Forth systems is not the only
14952: portability issue; there is also the issue of portability between
14953: different platforms (processor/OS combinations).
14954:
14955: @c ***************************************************************
14956: @node Model, Integrating Gforth, Standard vs Extensions, Top
14957: @chapter Model
14958:
14959: This chapter has yet to be written. It will contain information, on
14960: which internal structures you can rely.
14961:
14962: @c ***************************************************************
14963: @node Integrating Gforth, Emacs and Gforth, Model, Top
14964: @chapter Integrating Gforth into C programs
14965:
14966: This is not yet implemented.
14967:
14968: Several people like to use Forth as scripting language for applications
14969: that are otherwise written in C, C++, or some other language.
14970:
14971: The Forth system ATLAST provides facilities for embedding it into
14972: applications; unfortunately it has several disadvantages: most
14973: importantly, it is not based on ANS Forth, and it is apparently dead
14974: (i.e., not developed further and not supported). The facilities
14975: provided by Gforth in this area are inspired by ATLAST's facilities, so
14976: making the switch should not be hard.
14977:
14978: We also tried to design the interface such that it can easily be
14979: implemented by other Forth systems, so that we may one day arrive at a
14980: standardized interface. Such a standard interface would allow you to
14981: replace the Forth system without having to rewrite C code.
14982:
14983: You embed the Gforth interpreter by linking with the library
14984: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
14985: global symbols in this library that belong to the interface, have the
14986: prefix @code{forth_}. (Global symbols that are used internally have the
14987: prefix @code{gforth_}).
14988:
14989: You can include the declarations of Forth types and the functions and
14990: variables of the interface with @code{#include <forth.h>}.
14991:
14992: Types.
14993:
14994: Variables.
14995:
14996: Data and FP Stack pointer. Area sizes.
14997:
14998: functions.
14999:
15000: forth_init(imagefile)
15001: forth_evaluate(string) exceptions?
15002: forth_goto(address) (or forth_execute(xt)?)
15003: forth_continue() (a corountining mechanism)
15004:
15005: Adding primitives.
15006:
15007: No checking.
15008:
15009: Signals?
15010:
15011: Accessing the Stacks
15012:
15013: @c ******************************************************************
15014: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
15015: @chapter Emacs and Gforth
15016: @cindex Emacs and Gforth
15017:
15018: @cindex @file{gforth.el}
15019: @cindex @file{forth.el}
15020: @cindex Rydqvist, Goran
15021: @cindex Kuehling, David
15022: @cindex comment editing commands
15023: @cindex @code{\}, editing with Emacs
15024: @cindex debug tracer editing commands
15025: @cindex @code{~~}, removal with Emacs
15026: @cindex Forth mode in Emacs
15027:
15028: Gforth comes with @file{gforth.el}, an improved version of
15029: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
15030: improvements are:
15031:
15032: @itemize @bullet
15033: @item
15034: A better handling of indentation.
15035: @item
15036: A custom hilighting engine for Forth-code.
15037: @item
15038: Comment paragraph filling (@kbd{M-q})
15039: @item
15040: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
15041: @item
15042: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
15043: @item
15044: Support of the @code{info-lookup} feature for looking up the
15045: documentation of a word.
15046: @item
15047: Support for reading and writing blocks files.
15048: @end itemize
15049:
15050: To get a basic description of these features, enter Forth mode and
15051: type @kbd{C-h m}.
15052:
15053: @cindex source location of error or debugging output in Emacs
15054: @cindex error output, finding the source location in Emacs
15055: @cindex debugging output, finding the source location in Emacs
15056: In addition, Gforth supports Emacs quite well: The source code locations
15057: given in error messages, debugging output (from @code{~~}) and failed
15058: assertion messages are in the right format for Emacs' compilation mode
15059: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
15060: Manual}) so the source location corresponding to an error or other
15061: message is only a few keystrokes away (@kbd{C-x `} for the next error,
15062: @kbd{C-c C-c} for the error under the cursor).
15063:
15064: @cindex viewing the documentation of a word in Emacs
15065: @cindex context-sensitive help
15066: Moreover, for words documented in this manual, you can look up the
15067: glossary entry quickly by using @kbd{C-h TAB}
15068: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
15069: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
15070: later and does not work for words containing @code{:}.
15071:
15072: @menu
15073: * Installing gforth.el:: Making Emacs aware of Forth.
15074: * Emacs Tags:: Viewing the source of a word in Emacs.
15075: * Hilighting:: Making Forth code look prettier.
15076: * Auto-Indentation:: Customizing auto-indentation.
15077: * Blocks Files:: Reading and writing blocks files.
15078: @end menu
15079:
15080: @c ----------------------------------
15081: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
15082: @section Installing gforth.el
15083: @cindex @file{.emacs}
15084: @cindex @file{gforth.el}, installation
15085: To make the features from @file{gforth.el} available in Emacs, add
15086: the following lines to your @file{.emacs} file:
15087:
15088: @example
15089: (autoload 'forth-mode "gforth.el")
15090: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
15091: auto-mode-alist))
15092: (autoload 'forth-block-mode "gforth.el")
15093: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
15094: auto-mode-alist))
15095: (add-hook 'forth-mode-hook (function (lambda ()
15096: ;; customize variables here:
15097: (setq forth-indent-level 4)
15098: (setq forth-minor-indent-level 2)
15099: (setq forth-hilight-level 3)
15100: ;;; ...
15101: )))
15102: @end example
15103:
15104: @c ----------------------------------
15105: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
15106: @section Emacs Tags
15107: @cindex @file{TAGS} file
15108: @cindex @file{etags.fs}
15109: @cindex viewing the source of a word in Emacs
15110: @cindex @code{require}, placement in files
15111: @cindex @code{include}, placement in files
15112: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
15113: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
15114: contains the definitions of all words defined afterwards. You can then
15115: find the source for a word using @kbd{M-.}. Note that Emacs can use
15116: several tags files at the same time (e.g., one for the Gforth sources
15117: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
15118: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
15119: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
15120: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
15121: with @file{etags.fs}, you should avoid putting definitions both before
15122: and after @code{require} etc., otherwise you will see the same file
15123: visited several times by commands like @code{tags-search}.
15124:
15125: @c ----------------------------------
15126: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
15127: @section Hilighting
15128: @cindex hilighting Forth code in Emacs
15129: @cindex highlighting Forth code in Emacs
15130: @file{gforth.el} comes with a custom source hilighting engine. When
15131: you open a file in @code{forth-mode}, it will be completely parsed,
15132: assigning faces to keywords, comments, strings etc. While you edit
15133: the file, modified regions get parsed and updated on-the-fly.
15134:
15135: Use the variable `forth-hilight-level' to change the level of
15136: decoration from 0 (no hilighting at all) to 3 (the default). Even if
15137: you set the hilighting level to 0, the parser will still work in the
15138: background, collecting information about whether regions of text are
15139: ``compiled'' or ``interpreted''. Those information are required for
15140: auto-indentation to work properly. Set `forth-disable-parser' to
15141: non-nil if your computer is too slow to handle parsing. This will
15142: have an impact on the smartness of the auto-indentation engine,
15143: though.
15144:
15145: Sometimes Forth sources define new features that should be hilighted,
15146: new control structures, defining-words etc. You can use the variable
15147: `forth-custom-words' to make @code{forth-mode} hilight additional
15148: words and constructs. See the docstring of `forth-words' for details
15149: (in Emacs, type @kbd{C-h v forth-words}).
15150:
15151: `forth-custom-words' is meant to be customized in your
15152: @file{.emacs} file. To customize hilighing in a file-specific manner,
15153: set `forth-local-words' in a local-variables section at the end of
15154: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
15155:
15156: Example:
15157: @example
15158: 0 [IF]
15159: Local Variables:
15160: forth-local-words:
15161: ((("t:") definition-starter (font-lock-keyword-face . 1)
15162: "[ \t\n]" t name (font-lock-function-name-face . 3))
15163: ((";t") definition-ender (font-lock-keyword-face . 1)))
15164: End:
15165: [THEN]
15166: @end example
15167:
15168: @c ----------------------------------
15169: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
15170: @section Auto-Indentation
15171: @cindex auto-indentation of Forth code in Emacs
15172: @cindex indentation of Forth code in Emacs
15173: @code{forth-mode} automatically tries to indent lines in a smart way,
15174: whenever you type @key{TAB} or break a line with @kbd{C-m}.
15175:
15176: Simple customization can be achieved by setting
15177: `forth-indent-level' and `forth-minor-indent-level' in your
15178: @file{.emacs} file. For historical reasons @file{gforth.el} indents
15179: per default by multiples of 4 columns. To use the more traditional
15180: 3-column indentation, add the following lines to your @file{.emacs}:
15181:
15182: @example
15183: (add-hook 'forth-mode-hook (function (lambda ()
15184: ;; customize variables here:
15185: (setq forth-indent-level 3)
15186: (setq forth-minor-indent-level 1)
15187: )))
15188: @end example
15189:
15190: If you want indentation to recognize non-default words, customize it
15191: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
15192: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
15193: v forth-indent-words}).
15194:
15195: To customize indentation in a file-specific manner, set
15196: `forth-local-indent-words' in a local-variables section at the end of
15197: your source file (@pxref{Local Variables in Files, Variables,,emacs,
15198: Emacs Manual}).
15199:
15200: Example:
15201: @example
15202: 0 [IF]
15203: Local Variables:
15204: forth-local-indent-words:
15205: ((("t:") (0 . 2) (0 . 2))
15206: ((";t") (-2 . 0) (0 . -2)))
15207: End:
15208: [THEN]
15209: @end example
15210:
15211: @c ----------------------------------
15212: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
15213: @section Blocks Files
15214: @cindex blocks files, use with Emacs
15215: @code{forth-mode} Autodetects blocks files by checking whether the
15216: length of the first line exceeds 1023 characters. It then tries to
15217: convert the file into normal text format. When you save the file, it
15218: will be written to disk as normal stream-source file.
15219:
15220: If you want to write blocks files, use @code{forth-blocks-mode}. It
15221: inherits all the features from @code{forth-mode}, plus some additions:
15222:
15223: @itemize @bullet
15224: @item
15225: Files are written to disk in blocks file format.
15226: @item
15227: Screen numbers are displayed in the mode line (enumerated beginning
15228: with the value of `forth-block-base')
15229: @item
15230: Warnings are displayed when lines exceed 64 characters.
15231: @item
15232: The beginning of the currently edited block is marked with an
15233: overlay-arrow.
15234: @end itemize
15235:
15236: There are some restrictions you should be aware of. When you open a
15237: blocks file that contains tabulator or newline characters, these
15238: characters will be translated into spaces when the file is written
15239: back to disk. If tabs or newlines are encountered during blocks file
15240: reading, an error is output to the echo area. So have a look at the
15241: `*Messages*' buffer, when Emacs' bell rings during reading.
15242:
15243: Please consult the docstring of @code{forth-blocks-mode} for more
15244: information by typing @kbd{C-h v forth-blocks-mode}).
15245:
15246: @c ******************************************************************
15247: @node Image Files, Engine, Emacs and Gforth, Top
15248: @chapter Image Files
15249: @cindex image file
15250: @cindex @file{.fi} files
15251: @cindex precompiled Forth code
15252: @cindex dictionary in persistent form
15253: @cindex persistent form of dictionary
15254:
15255: An image file is a file containing an image of the Forth dictionary,
15256: i.e., compiled Forth code and data residing in the dictionary. By
15257: convention, we use the extension @code{.fi} for image files.
15258:
15259: @menu
15260: * Image Licensing Issues:: Distribution terms for images.
15261: * Image File Background:: Why have image files?
15262: * Non-Relocatable Image Files:: don't always work.
15263: * Data-Relocatable Image Files:: are better.
15264: * Fully Relocatable Image Files:: better yet.
15265: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
15266: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
15267: * Modifying the Startup Sequence:: and turnkey applications.
15268: @end menu
15269:
15270: @node Image Licensing Issues, Image File Background, Image Files, Image Files
15271: @section Image Licensing Issues
15272: @cindex license for images
15273: @cindex image license
15274:
15275: An image created with @code{gforthmi} (@pxref{gforthmi}) or
15276: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
15277: original image; i.e., according to copyright law it is a derived work of
15278: the original image.
15279:
15280: Since Gforth is distributed under the GNU GPL, the newly created image
15281: falls under the GNU GPL, too. In particular, this means that if you
15282: distribute the image, you have to make all of the sources for the image
15283: available, including those you wrote. For details see @ref{Copying, ,
15284: GNU General Public License (Section 3)}.
15285:
15286: If you create an image with @code{cross} (@pxref{cross.fs}), the image
15287: contains only code compiled from the sources you gave it; if none of
15288: these sources is under the GPL, the terms discussed above do not apply
15289: to the image. However, if your image needs an engine (a gforth binary)
15290: that is under the GPL, you should make sure that you distribute both in
15291: a way that is at most a @emph{mere aggregation}, if you don't want the
15292: terms of the GPL to apply to the image.
15293:
15294: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
15295: @section Image File Background
15296: @cindex image file background
15297:
15298: Gforth consists not only of primitives (in the engine), but also of
15299: definitions written in Forth. Since the Forth compiler itself belongs to
15300: those definitions, it is not possible to start the system with the
15301: engine and the Forth source alone. Therefore we provide the Forth
15302: code as an image file in nearly executable form. When Gforth starts up,
15303: a C routine loads the image file into memory, optionally relocates the
15304: addresses, then sets up the memory (stacks etc.) according to
15305: information in the image file, and (finally) starts executing Forth
15306: code.
15307:
15308: The default image file is @file{gforth.fi} (in the @code{GFORTHPATH}).
15309: You can use a different image by using the @code{-i},
15310: @code{--image-file} or @code{--appl-image} options (@pxref{Invoking
15311: Gforth}), e.g.:
15312:
15313: @example
15314: gforth-fast -i myimage.fi
15315: @end example
15316:
15317: There are different variants of image files, and they represent
15318: different compromises between the goals of making it easy to generate
15319: image files and making them portable.
15320:
15321: @cindex relocation at run-time
15322: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
15323: run-time. This avoids many of the complications discussed below (image
15324: files are data relocatable without further ado), but costs performance
15325: (one addition per memory access) and makes it difficult to pass
15326: addresses between Forth and library calls or other programs.
15327:
15328: @cindex relocation at load-time
15329: By contrast, the Gforth loader performs relocation at image load time. The
15330: loader also has to replace tokens that represent primitive calls with the
15331: appropriate code-field addresses (or code addresses in the case of
15332: direct threading).
15333:
15334: There are three kinds of image files, with different degrees of
15335: relocatability: non-relocatable, data-relocatable, and fully relocatable
15336: image files.
15337:
15338: @cindex image file loader
15339: @cindex relocating loader
15340: @cindex loader for image files
15341: These image file variants have several restrictions in common; they are
15342: caused by the design of the image file loader:
15343:
15344: @itemize @bullet
15345: @item
15346: There is only one segment; in particular, this means, that an image file
15347: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
15348: them). The contents of the stacks are not represented, either.
15349:
15350: @item
15351: The only kinds of relocation supported are: adding the same offset to
15352: all cells that represent data addresses; and replacing special tokens
15353: with code addresses or with pieces of machine code.
15354:
15355: If any complex computations involving addresses are performed, the
15356: results cannot be represented in the image file. Several applications that
15357: use such computations come to mind:
15358:
15359: @itemize @minus
15360: @item
15361: Hashing addresses (or data structures which contain addresses) for table
15362: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
15363: purpose, you will have no problem, because the hash tables are
15364: recomputed automatically when the system is started. If you use your own
15365: hash tables, you will have to do something similar.
15366:
15367: @item
15368: There's a cute implementation of doubly-linked lists that uses
15369: @code{XOR}ed addresses. You could represent such lists as singly-linked
15370: in the image file, and restore the doubly-linked representation on
15371: startup.@footnote{In my opinion, though, you should think thrice before
15372: using a doubly-linked list (whatever implementation).}
15373:
15374: @item
15375: The code addresses of run-time routines like @code{docol:} cannot be
15376: represented in the image file (because their tokens would be replaced by
15377: machine code in direct threaded implementations). As a workaround,
15378: compute these addresses at run-time with @code{>code-address} from the
15379: executions tokens of appropriate words (see the definitions of
15380: @code{docol:} and friends in @file{kernel/getdoers.fs}).
15381:
15382: @item
15383: On many architectures addresses are represented in machine code in some
15384: shifted or mangled form. You cannot put @code{CODE} words that contain
15385: absolute addresses in this form in a relocatable image file. Workarounds
15386: are representing the address in some relative form (e.g., relative to
15387: the CFA, which is present in some register), or loading the address from
15388: a place where it is stored in a non-mangled form.
15389: @end itemize
15390: @end itemize
15391:
15392: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
15393: @section Non-Relocatable Image Files
15394: @cindex non-relocatable image files
15395: @cindex image file, non-relocatable
15396:
15397: These files are simple memory dumps of the dictionary. They are
15398: specific to the executable (i.e., @file{gforth} file) they were
15399: created with. What's worse, they are specific to the place on which
15400: the dictionary resided when the image was created. Now, there is no
15401: guarantee that the dictionary will reside at the same place the next
15402: time you start Gforth, so there's no guarantee that a non-relocatable
15403: image will work the next time (Gforth will complain instead of
15404: crashing, though). Indeed, on OSs with (enabled) address-space
15405: randomization non-relocatable images are unlikely to work.
15406:
15407: You can create a non-relocatable image file with @code{savesystem}, e.g.:
15408:
15409: @example
15410: gforth app.fs -e "savesystem app.fi bye"
15411: @end example
15412:
15413: doc-savesystem
15414:
15415:
15416: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
15417: @section Data-Relocatable Image Files
15418: @cindex data-relocatable image files
15419: @cindex image file, data-relocatable
15420:
15421: These files contain relocatable data addresses, but fixed code
15422: addresses (instead of tokens). They are specific to the executable
15423: (i.e., @file{gforth} file) they were created with. Also, they disable
15424: dynamic native code generation (typically a factor of 2 in speed).
15425: You get a data-relocatable image, if you pass the engine you want to
15426: use through the @code{GFORTHD} environment variable to @file{gforthmi}
15427: (@pxref{gforthmi}), e.g.
15428:
15429: @example
15430: GFORTHD="/usr/bin/gforth-fast --no-dynamic" gforthmi myimage.fi source.fs
15431: @end example
15432:
15433: Note that the @code{--no-dynamic} is required here for the image to
15434: work (otherwise it will contain references to dynamically generated
15435: code that is not saved in the image).
15436:
15437:
15438: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
15439: @section Fully Relocatable Image Files
15440: @cindex fully relocatable image files
15441: @cindex image file, fully relocatable
15442:
15443: @cindex @file{kern*.fi}, relocatability
15444: @cindex @file{gforth.fi}, relocatability
15445: These image files have relocatable data addresses, and tokens for code
15446: addresses. They can be used with different binaries (e.g., with and
15447: without debugging) on the same machine, and even across machines with
15448: the same data formats (byte order, cell size, floating point format),
15449: and they work with dynamic native code generation. However, they are
15450: usually specific to the version of Gforth they were created with. The
15451: files @file{gforth.fi} and @file{kernl*.fi} are fully relocatable.
15452:
15453: There are two ways to create a fully relocatable image file:
15454:
15455: @menu
15456: * gforthmi:: The normal way
15457: * cross.fs:: The hard way
15458: @end menu
15459:
15460: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
15461: @subsection @file{gforthmi}
15462: @cindex @file{comp-i.fs}
15463: @cindex @file{gforthmi}
15464:
15465: You will usually use @file{gforthmi}. If you want to create an
15466: image @i{file} that contains everything you would load by invoking
15467: Gforth with @code{gforth @i{options}}, you simply say:
15468: @example
15469: gforthmi @i{file} @i{options}
15470: @end example
15471:
15472: E.g., if you want to create an image @file{asm.fi} that has the file
15473: @file{asm.fs} loaded in addition to the usual stuff, you could do it
15474: like this:
15475:
15476: @example
15477: gforthmi asm.fi asm.fs
15478: @end example
15479:
15480: @file{gforthmi} is implemented as a sh script and works like this: It
15481: produces two non-relocatable images for different addresses and then
15482: compares them. Its output reflects this: first you see the output (if
15483: any) of the two Gforth invocations that produce the non-relocatable image
15484: files, then you see the output of the comparing program: It displays the
15485: offset used for data addresses and the offset used for code addresses;
15486: moreover, for each cell that cannot be represented correctly in the
15487: image files, it displays a line like this:
15488:
15489: @example
15490: 78DC BFFFFA50 BFFFFA40
15491: @end example
15492:
15493: This means that at offset $78dc from @code{forthstart}, one input image
15494: contains $bffffa50, and the other contains $bffffa40. Since these cells
15495: cannot be represented correctly in the output image, you should examine
15496: these places in the dictionary and verify that these cells are dead
15497: (i.e., not read before they are written).
15498:
15499: @cindex --application, @code{gforthmi} option
15500: If you insert the option @code{--application} in front of the image file
15501: name, you will get an image that uses the @code{--appl-image} option
15502: instead of the @code{--image-file} option (@pxref{Invoking
15503: Gforth}). When you execute such an image on Unix (by typing the image
15504: name as command), the Gforth engine will pass all options to the image
15505: instead of trying to interpret them as engine options.
15506:
15507: If you type @file{gforthmi} with no arguments, it prints some usage
15508: instructions.
15509:
15510: @cindex @code{savesystem} during @file{gforthmi}
15511: @cindex @code{bye} during @file{gforthmi}
15512: @cindex doubly indirect threaded code
15513: @cindex environment variables
15514: @cindex @code{GFORTHD} -- environment variable
15515: @cindex @code{GFORTH} -- environment variable
15516: @cindex @code{gforth-ditc}
15517: There are a few wrinkles: After processing the passed @i{options}, the
15518: words @code{savesystem} and @code{bye} must be visible. A special
15519: doubly indirect threaded version of the @file{gforth} executable is
15520: used for creating the non-relocatable images; you can pass the exact
15521: filename of this executable through the environment variable
15522: @code{GFORTHD} (default: @file{gforth-ditc}); if you pass a version
15523: that is not doubly indirect threaded, you will not get a fully
15524: relocatable image, but a data-relocatable image
15525: (@pxref{Data-Relocatable Image Files}), because there is no code
15526: address offset). The normal @file{gforth} executable is used for
15527: creating the relocatable image; you can pass the exact filename of
15528: this executable through the environment variable @code{GFORTH}.
15529:
15530: @node cross.fs, , gforthmi, Fully Relocatable Image Files
15531: @subsection @file{cross.fs}
15532: @cindex @file{cross.fs}
15533: @cindex cross-compiler
15534: @cindex metacompiler
15535: @cindex target compiler
15536:
15537: You can also use @code{cross}, a batch compiler that accepts a Forth-like
15538: programming language (@pxref{Cross Compiler}).
15539:
15540: @code{cross} allows you to create image files for machines with
15541: different data sizes and data formats than the one used for generating
15542: the image file. You can also use it to create an application image that
15543: does not contain a Forth compiler. These features are bought with
15544: restrictions and inconveniences in programming. E.g., addresses have to
15545: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
15546: order to make the code relocatable.
15547:
15548:
15549: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
15550: @section Stack and Dictionary Sizes
15551: @cindex image file, stack and dictionary sizes
15552: @cindex dictionary size default
15553: @cindex stack size default
15554:
15555: If you invoke Gforth with a command line flag for the size
15556: (@pxref{Invoking Gforth}), the size you specify is stored in the
15557: dictionary. If you save the dictionary with @code{savesystem} or create
15558: an image with @file{gforthmi}, this size will become the default
15559: for the resulting image file. E.g., the following will create a
15560: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
15561:
15562: @example
15563: gforthmi gforth.fi -m 1M
15564: @end example
15565:
15566: In other words, if you want to set the default size for the dictionary
15567: and the stacks of an image, just invoke @file{gforthmi} with the
15568: appropriate options when creating the image.
15569:
15570: @cindex stack size, cache-friendly
15571: Note: For cache-friendly behaviour (i.e., good performance), you should
15572: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
15573: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
15574: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
15575:
15576: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
15577: @section Running Image Files
15578: @cindex running image files
15579: @cindex invoking image files
15580: @cindex image file invocation
15581:
15582: @cindex -i, invoke image file
15583: @cindex --image file, invoke image file
15584: You can invoke Gforth with an image file @i{image} instead of the
15585: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
15586: @example
15587: gforth -i @i{image}
15588: @end example
15589:
15590: @cindex executable image file
15591: @cindex image file, executable
15592: If your operating system supports starting scripts with a line of the
15593: form @code{#! ...}, you just have to type the image file name to start
15594: Gforth with this image file (note that the file extension @code{.fi} is
15595: just a convention). I.e., to run Gforth with the image file @i{image},
15596: you can just type @i{image} instead of @code{gforth -i @i{image}}.
15597: This works because every @code{.fi} file starts with a line of this
15598: format:
15599:
15600: @example
15601: #! /usr/local/bin/gforth-0.4.0 -i
15602: @end example
15603:
15604: The file and pathname for the Gforth engine specified on this line is
15605: the specific Gforth executable that it was built against; i.e. the value
15606: of the environment variable @code{GFORTH} at the time that
15607: @file{gforthmi} was executed.
15608:
15609: You can make use of the same shell capability to make a Forth source
15610: file into an executable. For example, if you place this text in a file:
15611:
15612: @example
15613: #! /usr/local/bin/gforth
15614:
15615: ." Hello, world" CR
15616: bye
15617: @end example
15618:
15619: @noindent
15620: and then make the file executable (chmod +x in Unix), you can run it
15621: directly from the command line. The sequence @code{#!} is used in two
15622: ways; firstly, it is recognised as a ``magic sequence'' by the operating
15623: system@footnote{The Unix kernel actually recognises two types of files:
15624: executable files and files of data, where the data is processed by an
15625: interpreter that is specified on the ``interpreter line'' -- the first
15626: line of the file, starting with the sequence #!. There may be a small
15627: limit (e.g., 32) on the number of characters that may be specified on
15628: the interpreter line.} secondly it is treated as a comment character by
15629: Gforth. Because of the second usage, a space is required between
15630: @code{#!} and the path to the executable (moreover, some Unixes
15631: require the sequence @code{#! /}).
15632:
15633: The disadvantage of this latter technique, compared with using
15634: @file{gforthmi}, is that it is slightly slower; the Forth source code is
15635: compiled on-the-fly, each time the program is invoked.
15636:
15637: doc-#!
15638:
15639:
15640: @node Modifying the Startup Sequence, , Running Image Files, Image Files
15641: @section Modifying the Startup Sequence
15642: @cindex startup sequence for image file
15643: @cindex image file initialization sequence
15644: @cindex initialization sequence of image file
15645:
15646: You can add your own initialization to the startup sequence of an image
15647: through the deferred word @code{'cold}. @code{'cold} is invoked just
15648: before the image-specific command line processing (i.e., loading files
15649: and evaluating (@code{-e}) strings) starts.
15650:
15651: A sequence for adding your initialization usually looks like this:
15652:
15653: @example
15654: :noname
15655: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
15656: ... \ your stuff
15657: ; IS 'cold
15658: @end example
15659:
15660: After @code{'cold}, Gforth processes the image options
15661: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
15662: another deferred word. This normally prints Gforth's startup message
15663: and does nothing else.
15664:
15665: @cindex turnkey image files
15666: @cindex image file, turnkey applications
15667: So, if you want to make a turnkey image (i.e., an image for an
15668: application instead of an extended Forth system), you can do this in
15669: two ways:
15670:
15671: @itemize @bullet
15672:
15673: @item
15674: If you want to do your interpretation of the OS command-line
15675: arguments, hook into @code{'cold}. In that case you probably also
15676: want to build the image with @code{gforthmi --application}
15677: (@pxref{gforthmi}) to keep the engine from processing OS command line
15678: options. You can then do your own command-line processing with
15679: @code{next-arg}
15680:
15681: @item
15682: If you want to have the normal Gforth processing of OS command-line
15683: arguments, hook into @code{bootmessage}.
15684:
15685: @end itemize
15686:
15687: In either case, you probably do not want the word that you execute in
15688: these hooks to exit normally, but use @code{bye} or @code{throw}.
15689: Otherwise the Gforth startup process would continue and eventually
15690: present the Forth command line to the user.
15691:
15692: doc-'cold
15693: doc-bootmessage
15694:
15695: @c ******************************************************************
15696: @node Engine, Cross Compiler, Image Files, Top
15697: @chapter Engine
15698: @cindex engine
15699: @cindex virtual machine
15700:
15701: Reading this chapter is not necessary for programming with Gforth. It
15702: may be helpful for finding your way in the Gforth sources.
15703:
15704: The ideas in this section have also been published in the following
15705: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15706: Forth-Tagung '93; M. Anton Ertl,
15707: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15708: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15709: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15710: Threaded code variations and optimizations (extended version)}},
15711: Forth-Tagung '02.
15712:
15713: @menu
15714: * Portability::
15715: * Threading::
15716: * Primitives::
15717: * Performance::
15718: @end menu
15719:
15720: @node Portability, Threading, Engine, Engine
15721: @section Portability
15722: @cindex engine portability
15723:
15724: An important goal of the Gforth Project is availability across a wide
15725: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15726: achieved this goal by manually coding the engine in assembly language
15727: for several then-popular processors. This approach is very
15728: labor-intensive and the results are short-lived due to progress in
15729: computer architecture.
15730:
15731: @cindex C, using C for the engine
15732: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15733: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15734: particularly popular for UNIX-based Forths due to the large variety of
15735: architectures of UNIX machines. Unfortunately an implementation in C
15736: does not mix well with the goals of efficiency and with using
15737: traditional techniques: Indirect or direct threading cannot be expressed
15738: in C, and switch threading, the fastest technique available in C, is
15739: significantly slower. Another problem with C is that it is very
15740: cumbersome to express double integer arithmetic.
15741:
15742: @cindex GNU C for the engine
15743: @cindex long long
15744: Fortunately, there is a portable language that does not have these
15745: limitations: GNU C, the version of C processed by the GNU C compiler
15746: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15747: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15748: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15749: threading possible, its @code{long long} type (@pxref{Long Long, ,
15750: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
15751: double numbers on many systems. GNU C is freely available on all
15752: important (and many unimportant) UNIX machines, VMS, 80386s running
15753: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15754: on all these machines.
15755:
15756: Writing in a portable language has the reputation of producing code that
15757: is slower than assembly. For our Forth engine we repeatedly looked at
15758: the code produced by the compiler and eliminated most compiler-induced
15759: inefficiencies by appropriate changes in the source code.
15760:
15761: @cindex explicit register declarations
15762: @cindex --enable-force-reg, configuration flag
15763: @cindex -DFORCE_REG
15764: However, register allocation cannot be portably influenced by the
15765: programmer, leading to some inefficiencies on register-starved
15766: machines. We use explicit register declarations (@pxref{Explicit Reg
15767: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15768: improve the speed on some machines. They are turned on by using the
15769: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15770: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15771: machine, but also on the compiler version: On some machines some
15772: compiler versions produce incorrect code when certain explicit register
15773: declarations are used. So by default @code{-DFORCE_REG} is not used.
15774:
15775: @node Threading, Primitives, Portability, Engine
15776: @section Threading
15777: @cindex inner interpreter implementation
15778: @cindex threaded code implementation
15779:
15780: @cindex labels as values
15781: GNU C's labels as values extension (available since @code{gcc-2.0},
15782: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
15783: makes it possible to take the address of @i{label} by writing
15784: @code{&&@i{label}}. This address can then be used in a statement like
15785: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
15786: @code{goto x}.
15787:
15788: @cindex @code{NEXT}, indirect threaded
15789: @cindex indirect threaded inner interpreter
15790: @cindex inner interpreter, indirect threaded
15791: With this feature an indirect threaded @code{NEXT} looks like:
15792: @example
15793: cfa = *ip++;
15794: ca = *cfa;
15795: goto *ca;
15796: @end example
15797: @cindex instruction pointer
15798: For those unfamiliar with the names: @code{ip} is the Forth instruction
15799: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15800: execution token and points to the code field of the next word to be
15801: executed; The @code{ca} (code address) fetched from there points to some
15802: executable code, e.g., a primitive or the colon definition handler
15803: @code{docol}.
15804:
15805: @cindex @code{NEXT}, direct threaded
15806: @cindex direct threaded inner interpreter
15807: @cindex inner interpreter, direct threaded
15808: Direct threading is even simpler:
15809: @example
15810: ca = *ip++;
15811: goto *ca;
15812: @end example
15813:
15814: Of course we have packaged the whole thing neatly in macros called
15815: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
15816:
15817: @menu
15818: * Scheduling::
15819: * Direct or Indirect Threaded?::
15820: * Dynamic Superinstructions::
15821: * DOES>::
15822: @end menu
15823:
15824: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15825: @subsection Scheduling
15826: @cindex inner interpreter optimization
15827:
15828: There is a little complication: Pipelined and superscalar processors,
15829: i.e., RISC and some modern CISC machines can process independent
15830: instructions while waiting for the results of an instruction. The
15831: compiler usually reorders (schedules) the instructions in a way that
15832: achieves good usage of these delay slots. However, on our first tries
15833: the compiler did not do well on scheduling primitives. E.g., for
15834: @code{+} implemented as
15835: @example
15836: n=sp[0]+sp[1];
15837: sp++;
15838: sp[0]=n;
15839: NEXT;
15840: @end example
15841: the @code{NEXT} comes strictly after the other code, i.e., there is
15842: nearly no scheduling. After a little thought the problem becomes clear:
15843: The compiler cannot know that @code{sp} and @code{ip} point to different
15844: addresses (and the version of @code{gcc} we used would not know it even
15845: if it was possible), so it could not move the load of the cfa above the
15846: store to the TOS. Indeed the pointers could be the same, if code on or
15847: very near the top of stack were executed. In the interest of speed we
15848: chose to forbid this probably unused ``feature'' and helped the compiler
15849: in scheduling: @code{NEXT} is divided into several parts:
15850: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15851: like:
15852: @example
15853: NEXT_P0;
15854: n=sp[0]+sp[1];
15855: sp++;
15856: NEXT_P1;
15857: sp[0]=n;
15858: NEXT_P2;
15859: @end example
15860:
15861: There are various schemes that distribute the different operations of
15862: NEXT between these parts in several ways; in general, different schemes
15863: perform best on different processors. We use a scheme for most
15864: architectures that performs well for most processors of this
15865: architecture; in the future we may switch to benchmarking and chosing
15866: the scheme on installation time.
15867:
15868:
15869: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
15870: @subsection Direct or Indirect Threaded?
15871: @cindex threading, direct or indirect?
15872:
15873: Threaded forth code consists of references to primitives (simple machine
15874: code routines like @code{+}) and to non-primitives (e.g., colon
15875: definitions, variables, constants); for a specific class of
15876: non-primitives (e.g., variables) there is one code routine (e.g.,
15877: @code{dovar}), but each variable needs a separate reference to its data.
15878:
15879: Traditionally Forth has been implemented as indirect threaded code,
15880: because this allows to use only one cell to reference a non-primitive
15881: (basically you point to the data, and find the code address there).
15882:
15883: @cindex primitive-centric threaded code
15884: However, threaded code in Gforth (since 0.6.0) uses two cells for
15885: non-primitives, one for the code address, and one for the data address;
15886: the data pointer is an immediate argument for the virtual machine
15887: instruction represented by the code address. We call this
15888: @emph{primitive-centric} threaded code, because all code addresses point
15889: to simple primitives. E.g., for a variable, the code address is for
15890: @code{lit} (also used for integer literals like @code{99}).
15891:
15892: Primitive-centric threaded code allows us to use (faster) direct
15893: threading as dispatch method, completely portably (direct threaded code
15894: in Gforth before 0.6.0 required architecture-specific code). It also
15895: eliminates the performance problems related to I-cache consistency that
15896: 386 implementations have with direct threaded code, and allows
15897: additional optimizations.
15898:
15899: @cindex hybrid direct/indirect threaded code
15900: There is a catch, however: the @var{xt} parameter of @code{execute} can
15901: occupy only one cell, so how do we pass non-primitives with their code
15902: @emph{and} data addresses to them? Our answer is to use indirect
15903: threaded dispatch for @code{execute} and other words that use a
15904: single-cell xt. So, normal threaded code in colon definitions uses
15905: direct threading, and @code{execute} and similar words, which dispatch
15906: to xts on the data stack, use indirect threaded code. We call this
15907: @emph{hybrid direct/indirect} threaded code.
15908:
15909: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15910: @cindex gforth engine
15911: @cindex gforth-fast engine
15912: The engines @command{gforth} and @command{gforth-fast} use hybrid
15913: direct/indirect threaded code. This means that with these engines you
15914: cannot use @code{,} to compile an xt. Instead, you have to use
15915: @code{compile,}.
15916:
15917: @cindex gforth-itc engine
15918: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15919: This engine uses plain old indirect threaded code. It still compiles in
15920: a primitive-centric style, so you cannot use @code{compile,} instead of
15921: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
15922: ... [}). If you want to do that, you have to use @command{gforth-itc}
15923: and execute @code{' , is compile,}. Your program can check if it is
15924: running on a hybrid direct/indirect threaded engine or a pure indirect
15925: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15926:
15927:
15928: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15929: @subsection Dynamic Superinstructions
15930: @cindex Dynamic superinstructions with replication
15931: @cindex Superinstructions
15932: @cindex Replication
15933:
15934: The engines @command{gforth} and @command{gforth-fast} use another
15935: optimization: Dynamic superinstructions with replication. As an
15936: example, consider the following colon definition:
15937:
15938: @example
15939: : squared ( n1 -- n2 )
15940: dup * ;
15941: @end example
15942:
15943: Gforth compiles this into the threaded code sequence
15944:
15945: @example
15946: dup
15947: *
15948: ;s
15949: @end example
15950:
15951: In normal direct threaded code there is a code address occupying one
15952: cell for each of these primitives. Each code address points to a
15953: machine code routine, and the interpreter jumps to this machine code in
15954: order to execute the primitive. The routines for these three
15955: primitives are (in @command{gforth-fast} on the 386):
15956:
15957: @example
15958: Code dup
15959: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
15960: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
15961: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15962: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15963: end-code
15964: Code *
15965: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15966: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
15967: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
15968: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
15969: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15970: end-code
15971: Code ;s
15972: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
15973: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
15974: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15975: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15976: end-code
15977: @end example
15978:
15979: With dynamic superinstructions and replication the compiler does not
15980: just lay down the threaded code, but also copies the machine code
15981: fragments, usually without the jump at the end.
15982:
15983: @example
15984: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
15985: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
15986: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15987: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15988: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
15989: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
15990: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
15991: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
15992: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
15993: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15994: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15995: @end example
15996:
15997: Only when a threaded-code control-flow change happens (e.g., in
15998: @code{;s}), the jump is appended. This optimization eliminates many of
15999: these jumps and makes the rest much more predictable. The speedup
16000: depends on the processor and the application; on the Athlon and Pentium
16001: III this optimization typically produces a speedup by a factor of 2.
16002:
16003: The code addresses in the direct-threaded code are set to point to the
16004: appropriate points in the copied machine code, in this example like
16005: this:
16006:
16007: @example
16008: primitive code address
16009: dup $4057D27D
16010: * $4057D286
16011: ;s $4057D292
16012: @end example
16013:
16014: Thus there can be threaded-code jumps to any place in this piece of
16015: code. This also simplifies decompilation quite a bit.
16016:
16017: @cindex --no-dynamic command-line option
16018: @cindex --no-super command-line option
16019: You can disable this optimization with @option{--no-dynamic}. You can
16020: use the copying without eliminating the jumps (i.e., dynamic
16021: replication, but without superinstructions) with @option{--no-super};
16022: this gives the branch prediction benefit alone; the effect on
16023: performance depends on the CPU; on the Athlon and Pentium III the
16024: speedup is a little less than for dynamic superinstructions with
16025: replication.
16026:
16027: @cindex patching threaded code
16028: One use of these options is if you want to patch the threaded code.
16029: With superinstructions, many of the dispatch jumps are eliminated, so
16030: patching often has no effect. These options preserve all the dispatch
16031: jumps.
16032:
16033: @cindex --dynamic command-line option
16034: On some machines dynamic superinstructions are disabled by default,
16035: because it is unsafe on these machines. However, if you feel
16036: adventurous, you can enable it with @option{--dynamic}.
16037:
16038: @node DOES>, , Dynamic Superinstructions, Threading
16039: @subsection DOES>
16040: @cindex @code{DOES>} implementation
16041:
16042: @cindex @code{dodoes} routine
16043: @cindex @code{DOES>}-code
16044: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
16045: the chunk of code executed by every word defined by a
16046: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
16047: this is only needed if the xt of the word is @code{execute}d. The main
16048: problem here is: How to find the Forth code to be executed, i.e. the
16049: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
16050: solutions:
16051:
16052: In fig-Forth the code field points directly to the @code{dodoes} and the
16053: @code{DOES>}-code address is stored in the cell after the code address
16054: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
16055: illegal in the Forth-79 and all later standards, because in fig-Forth
16056: this address lies in the body (which is illegal in these
16057: standards). However, by making the code field larger for all words this
16058: solution becomes legal again. We use this approach. Leaving a cell
16059: unused in most words is a bit wasteful, but on the machines we are
16060: targeting this is hardly a problem.
16061:
16062:
16063: @node Primitives, Performance, Threading, Engine
16064: @section Primitives
16065: @cindex primitives, implementation
16066: @cindex virtual machine instructions, implementation
16067:
16068: @menu
16069: * Automatic Generation::
16070: * TOS Optimization::
16071: * Produced code::
16072: @end menu
16073:
16074: @node Automatic Generation, TOS Optimization, Primitives, Primitives
16075: @subsection Automatic Generation
16076: @cindex primitives, automatic generation
16077:
16078: @cindex @file{prims2x.fs}
16079:
16080: Since the primitives are implemented in a portable language, there is no
16081: longer any need to minimize the number of primitives. On the contrary,
16082: having many primitives has an advantage: speed. In order to reduce the
16083: number of errors in primitives and to make programming them easier, we
16084: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
16085: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
16086: generates most (and sometimes all) of the C code for a primitive from
16087: the stack effect notation. The source for a primitive has the following
16088: form:
16089:
16090: @cindex primitive source format
16091: @format
16092: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
16093: [@code{""}@i{glossary entry}@code{""}]
16094: @i{C code}
16095: [@code{:}
16096: @i{Forth code}]
16097: @end format
16098:
16099: The items in brackets are optional. The category and glossary fields
16100: are there for generating the documentation, the Forth code is there
16101: for manual implementations on machines without GNU C. E.g., the source
16102: for the primitive @code{+} is:
16103: @example
16104: + ( n1 n2 -- n ) core plus
16105: n = n1+n2;
16106: @end example
16107:
16108: This looks like a specification, but in fact @code{n = n1+n2} is C
16109: code. Our primitive generation tool extracts a lot of information from
16110: the stack effect notations@footnote{We use a one-stack notation, even
16111: though we have separate data and floating-point stacks; The separate
16112: notation can be generated easily from the unified notation.}: The number
16113: of items popped from and pushed on the stack, their type, and by what
16114: name they are referred to in the C code. It then generates a C code
16115: prelude and postlude for each primitive. The final C code for @code{+}
16116: looks like this:
16117:
16118: @example
16119: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
16120: /* */ /* documentation */
16121: NAME("+") /* debugging output (with -DDEBUG) */
16122: @{
16123: DEF_CA /* definition of variable ca (indirect threading) */
16124: Cell n1; /* definitions of variables */
16125: Cell n2;
16126: Cell n;
16127: NEXT_P0; /* NEXT part 0 */
16128: n1 = (Cell) sp[1]; /* input */
16129: n2 = (Cell) TOS;
16130: sp += 1; /* stack adjustment */
16131: @{
16132: n = n1+n2; /* C code taken from the source */
16133: @}
16134: NEXT_P1; /* NEXT part 1 */
16135: TOS = (Cell)n; /* output */
16136: NEXT_P2; /* NEXT part 2 */
16137: @}
16138: @end example
16139:
16140: This looks long and inefficient, but the GNU C compiler optimizes quite
16141: well and produces optimal code for @code{+} on, e.g., the R3000 and the
16142: HP RISC machines: Defining the @code{n}s does not produce any code, and
16143: using them as intermediate storage also adds no cost.
16144:
16145: There are also other optimizations that are not illustrated by this
16146: example: assignments between simple variables are usually for free (copy
16147: propagation). If one of the stack items is not used by the primitive
16148: (e.g. in @code{drop}), the compiler eliminates the load from the stack
16149: (dead code elimination). On the other hand, there are some things that
16150: the compiler does not do, therefore they are performed by
16151: @file{prims2x.fs}: The compiler does not optimize code away that stores
16152: a stack item to the place where it just came from (e.g., @code{over}).
16153:
16154: While programming a primitive is usually easy, there are a few cases
16155: where the programmer has to take the actions of the generator into
16156: account, most notably @code{?dup}, but also words that do not (always)
16157: fall through to @code{NEXT}.
16158:
16159: For more information
16160:
16161: @node TOS Optimization, Produced code, Automatic Generation, Primitives
16162: @subsection TOS Optimization
16163: @cindex TOS optimization for primitives
16164: @cindex primitives, keeping the TOS in a register
16165:
16166: An important optimization for stack machine emulators, e.g., Forth
16167: engines, is keeping one or more of the top stack items in
16168: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
16169: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
16170: @itemize @bullet
16171: @item
16172: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
16173: due to fewer loads from and stores to the stack.
16174: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
16175: @i{y<n}, due to additional moves between registers.
16176: @end itemize
16177:
16178: @cindex -DUSE_TOS
16179: @cindex -DUSE_NO_TOS
16180: In particular, keeping one item in a register is never a disadvantage,
16181: if there are enough registers. Keeping two items in registers is a
16182: disadvantage for frequent words like @code{?branch}, constants,
16183: variables, literals and @code{i}. Therefore our generator only produces
16184: code that keeps zero or one items in registers. The generated C code
16185: covers both cases; the selection between these alternatives is made at
16186: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
16187: code for @code{+} is just a simple variable name in the one-item case,
16188: otherwise it is a macro that expands into @code{sp[0]}. Note that the
16189: GNU C compiler tries to keep simple variables like @code{TOS} in
16190: registers, and it usually succeeds, if there are enough registers.
16191:
16192: @cindex -DUSE_FTOS
16193: @cindex -DUSE_NO_FTOS
16194: The primitive generator performs the TOS optimization for the
16195: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
16196: operations the benefit of this optimization is even larger:
16197: floating-point operations take quite long on most processors, but can be
16198: performed in parallel with other operations as long as their results are
16199: not used. If the FP-TOS is kept in a register, this works. If
16200: it is kept on the stack, i.e., in memory, the store into memory has to
16201: wait for the result of the floating-point operation, lengthening the
16202: execution time of the primitive considerably.
16203:
16204: The TOS optimization makes the automatic generation of primitives a
16205: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
16206: @code{TOS} is not sufficient. There are some special cases to
16207: consider:
16208: @itemize @bullet
16209: @item In the case of @code{dup ( w -- w w )} the generator must not
16210: eliminate the store to the original location of the item on the stack,
16211: if the TOS optimization is turned on.
16212: @item Primitives with stack effects of the form @code{--}
16213: @i{out1}...@i{outy} must store the TOS to the stack at the start.
16214: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
16215: must load the TOS from the stack at the end. But for the null stack
16216: effect @code{--} no stores or loads should be generated.
16217: @end itemize
16218:
16219: @node Produced code, , TOS Optimization, Primitives
16220: @subsection Produced code
16221: @cindex primitives, assembly code listing
16222:
16223: @cindex @file{engine.s}
16224: To see what assembly code is produced for the primitives on your machine
16225: with your compiler and your flag settings, type @code{make engine.s} and
16226: look at the resulting file @file{engine.s}. Alternatively, you can also
16227: disassemble the code of primitives with @code{see} on some architectures.
16228:
16229: @node Performance, , Primitives, Engine
16230: @section Performance
16231: @cindex performance of some Forth interpreters
16232: @cindex engine performance
16233: @cindex benchmarking Forth systems
16234: @cindex Gforth performance
16235:
16236: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
16237: impossible to write a significantly faster threaded-code engine.
16238:
16239: On register-starved machines like the 386 architecture processors
16240: improvements are possible, because @code{gcc} does not utilize the
16241: registers as well as a human, even with explicit register declarations;
16242: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
16243: and hand-tuned it for the 486; this system is 1.19 times faster on the
16244: Sieve benchmark on a 486DX2/66 than Gforth compiled with
16245: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
16246: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
16247: registers fit in real registers (and we can even afford to use the TOS
16248: optimization), resulting in a speedup of 1.14 on the sieve over the
16249: earlier results. And dynamic superinstructions provide another speedup
16250: (but only around a factor 1.2 on the 486).
16251:
16252: @cindex Win32Forth performance
16253: @cindex NT Forth performance
16254: @cindex eforth performance
16255: @cindex ThisForth performance
16256: @cindex PFE performance
16257: @cindex TILE performance
16258: The potential advantage of assembly language implementations is not
16259: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
16260: (direct threaded, compiled with @code{gcc-2.95.1} and
16261: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
16262: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
16263: (with and without peephole (aka pinhole) optimization of the threaded
16264: code); all these systems were written in assembly language. We also
16265: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
16266: with @code{gcc-2.6.3} with the default configuration for Linux:
16267: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
16268: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
16269: employs peephole optimization of the threaded code) and TILE (compiled
16270: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
16271: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
16272: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
16273: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
16274: then extended it to run the benchmarks, added the peephole optimizer,
16275: ran the benchmarks and reported the results.
16276:
16277: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
16278: matrix multiplication come from the Stanford integer benchmarks and have
16279: been translated into Forth by Martin Fraeman; we used the versions
16280: included in the TILE Forth package, but with bigger data set sizes; and
16281: a recursive Fibonacci number computation for benchmarking calling
16282: performance. The following table shows the time taken for the benchmarks
16283: scaled by the time taken by Gforth (in other words, it shows the speedup
16284: factor that Gforth achieved over the other systems).
16285:
16286: @example
16287: relative Win32- NT eforth This-
16288: time Gforth Forth Forth eforth +opt PFE Forth TILE
16289: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
16290: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
16291: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
16292: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
16293: @end example
16294:
16295: You may be quite surprised by the good performance of Gforth when
16296: compared with systems written in assembly language. One important reason
16297: for the disappointing performance of these other systems is probably
16298: that they are not written optimally for the 486 (e.g., they use the
16299: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
16300: but costly method for relocating the Forth image: like @code{cforth}, it
16301: computes the actual addresses at run time, resulting in two address
16302: computations per @code{NEXT} (@pxref{Image File Background}).
16303:
16304: The speedup of Gforth over PFE, ThisForth and TILE can be easily
16305: explained with the self-imposed restriction of the latter systems to
16306: standard C, which makes efficient threading impossible (however, the
16307: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
16308: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
16309: Moreover, current C compilers have a hard time optimizing other aspects
16310: of the ThisForth and the TILE source.
16311:
16312: The performance of Gforth on 386 architecture processors varies widely
16313: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
16314: allocate any of the virtual machine registers into real machine
16315: registers by itself and would not work correctly with explicit register
16316: declarations, giving a significantly slower engine (on a 486DX2/66
16317: running the Sieve) than the one measured above.
16318:
16319: Note that there have been several releases of Win32Forth since the
16320: release presented here, so the results presented above may have little
16321: predictive value for the performance of Win32Forth today (results for
16322: the current release on an i486DX2/66 are welcome).
16323:
16324: @cindex @file{Benchres}
16325: In
16326: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
16327: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
16328: Maierhofer (presented at EuroForth '95), an indirect threaded version of
16329: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
16330: several native code systems; that version of Gforth is slower on a 486
16331: than the version used here. You can find a newer version of these
16332: measurements at
16333: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
16334: find numbers for Gforth on various machines in @file{Benchres}.
16335:
16336: @c ******************************************************************
16337: @c @node Binding to System Library, Cross Compiler, Engine, Top
16338: @c @chapter Binding to System Library
16339:
16340: @c ****************************************************************
16341: @node Cross Compiler, Bugs, Engine, Top
16342: @chapter Cross Compiler
16343: @cindex @file{cross.fs}
16344: @cindex cross-compiler
16345: @cindex metacompiler
16346: @cindex target compiler
16347:
16348: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
16349: mostly written in Forth, including crucial parts like the outer
16350: interpreter and compiler, it needs compiled Forth code to get
16351: started. The cross compiler allows to create new images for other
16352: architectures, even running under another Forth system.
16353:
16354: @menu
16355: * Using the Cross Compiler::
16356: * How the Cross Compiler Works::
16357: @end menu
16358:
16359: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
16360: @section Using the Cross Compiler
16361:
16362: The cross compiler uses a language that resembles Forth, but isn't. The
16363: main difference is that you can execute Forth code after definition,
16364: while you usually can't execute the code compiled by cross, because the
16365: code you are compiling is typically for a different computer than the
16366: one you are compiling on.
16367:
16368: @c anton: This chapter is somewhat different from waht I would expect: I
16369: @c would expect an explanation of the cross language and how to create an
16370: @c application image with it. The section explains some aspects of
16371: @c creating a Gforth kernel.
16372:
16373: The Makefile is already set up to allow you to create kernels for new
16374: architectures with a simple make command. The generic kernels using the
16375: GCC compiled virtual machine are created in the normal build process
16376: with @code{make}. To create a embedded Gforth executable for e.g. the
16377: 8086 processor (running on a DOS machine), type
16378:
16379: @example
16380: make kernl-8086.fi
16381: @end example
16382:
16383: This will use the machine description from the @file{arch/8086}
16384: directory to create a new kernel. A machine file may look like that:
16385:
16386: @example
16387: \ Parameter for target systems 06oct92py
16388:
16389: 4 Constant cell \ cell size in bytes
16390: 2 Constant cell<< \ cell shift to bytes
16391: 5 Constant cell>bit \ cell shift to bits
16392: 8 Constant bits/char \ bits per character
16393: 8 Constant bits/byte \ bits per byte [default: 8]
16394: 8 Constant float \ bytes per float
16395: 8 Constant /maxalign \ maximum alignment in bytes
16396: false Constant bigendian \ byte order
16397: ( true=big, false=little )
16398:
16399: include machpc.fs \ feature list
16400: @end example
16401:
16402: This part is obligatory for the cross compiler itself, the feature list
16403: is used by the kernel to conditionally compile some features in and out,
16404: depending on whether the target supports these features.
16405:
16406: There are some optional features, if you define your own primitives,
16407: have an assembler, or need special, nonstandard preparation to make the
16408: boot process work. @code{asm-include} includes an assembler,
16409: @code{prims-include} includes primitives, and @code{>boot} prepares for
16410: booting.
16411:
16412: @example
16413: : asm-include ." Include assembler" cr
16414: s" arch/8086/asm.fs" included ;
16415:
16416: : prims-include ." Include primitives" cr
16417: s" arch/8086/prim.fs" included ;
16418:
16419: : >boot ." Prepare booting" cr
16420: s" ' boot >body into-forth 1+ !" evaluate ;
16421: @end example
16422:
16423: These words are used as sort of macro during the cross compilation in
16424: the file @file{kernel/main.fs}. Instead of using these macros, it would
16425: be possible --- but more complicated --- to write a new kernel project
16426: file, too.
16427:
16428: @file{kernel/main.fs} expects the machine description file name on the
16429: stack; the cross compiler itself (@file{cross.fs}) assumes that either
16430: @code{mach-file} leaves a counted string on the stack, or
16431: @code{machine-file} leaves an address, count pair of the filename on the
16432: stack.
16433:
16434: The feature list is typically controlled using @code{SetValue}, generic
16435: files that are used by several projects can use @code{DefaultValue}
16436: instead. Both functions work like @code{Value}, when the value isn't
16437: defined, but @code{SetValue} works like @code{to} if the value is
16438: defined, and @code{DefaultValue} doesn't set anything, if the value is
16439: defined.
16440:
16441: @example
16442: \ generic mach file for pc gforth 03sep97jaw
16443:
16444: true DefaultValue NIL \ relocating
16445:
16446: >ENVIRON
16447:
16448: true DefaultValue file \ controls the presence of the
16449: \ file access wordset
16450: true DefaultValue OS \ flag to indicate a operating system
16451:
16452: true DefaultValue prims \ true: primitives are c-code
16453:
16454: true DefaultValue floating \ floating point wordset is present
16455:
16456: true DefaultValue glocals \ gforth locals are present
16457: \ will be loaded
16458: true DefaultValue dcomps \ double number comparisons
16459:
16460: true DefaultValue hash \ hashing primitives are loaded/present
16461:
16462: true DefaultValue xconds \ used together with glocals,
16463: \ special conditionals supporting gforths'
16464: \ local variables
16465: true DefaultValue header \ save a header information
16466:
16467: true DefaultValue backtrace \ enables backtrace code
16468:
16469: false DefaultValue ec
16470: false DefaultValue crlf
16471:
16472: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
16473:
16474: &16 KB DefaultValue stack-size
16475: &15 KB &512 + DefaultValue fstack-size
16476: &15 KB DefaultValue rstack-size
16477: &14 KB &512 + DefaultValue lstack-size
16478: @end example
16479:
16480: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
16481: @section How the Cross Compiler Works
16482:
16483: @node Bugs, Origin, Cross Compiler, Top
16484: @appendix Bugs
16485: @cindex bug reporting
16486:
16487: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
16488:
16489: If you find a bug, please submit a bug report through
16490: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
16491:
16492: @itemize @bullet
16493: @item
16494: A program (or a sequence of keyboard commands) that reproduces the bug.
16495: @item
16496: A description of what you think constitutes the buggy behaviour.
16497: @item
16498: The Gforth version used (it is announced at the start of an
16499: interactive Gforth session).
16500: @item
16501: The machine and operating system (on Unix
16502: systems @code{uname -a} will report this information).
16503: @item
16504: The installation options (you can find the configure options at the
16505: start of @file{config.status}) and configuration (@code{configure}
16506: output or @file{config.cache}).
16507: @item
16508: A complete list of changes (if any) you (or your installer) have made to the
16509: Gforth sources.
16510: @end itemize
16511:
16512: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
16513: to Report Bugs, gcc.info, GNU C Manual}.
16514:
16515:
16516: @node Origin, Forth-related information, Bugs, Top
16517: @appendix Authors and Ancestors of Gforth
16518:
16519: @section Authors and Contributors
16520: @cindex authors of Gforth
16521: @cindex contributors to Gforth
16522:
16523: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
16524: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
16525: lot to the manual. Assemblers and disassemblers were contributed by
16526: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
16527: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
16528: and Stuart Ramsden inspired us with their continuous feedback. Lennart
16529: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
16530: working on automatic support for calling C libraries. Helpful comments
16531: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
16532: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
16533: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
16534: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
16535: comments from many others; thank you all, sorry for not listing you
16536: here (but digging through my mailbox to extract your names is on my
16537: to-do list).
16538:
16539: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
16540: and autoconf, among others), and to the creators of the Internet: Gforth
16541: was developed across the Internet, and its authors did not meet
16542: physically for the first 4 years of development.
16543:
16544: @section Pedigree
16545: @cindex pedigree of Gforth
16546:
16547: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
16548: significant part of the design of Gforth was prescribed by ANS Forth.
16549:
16550: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
16551: 32 bit native code version of VolksForth for the Atari ST, written
16552: mostly by Dietrich Weineck.
16553:
16554: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
16555: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
16556: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
16557:
16558: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
16559: @c Forth-83 standard. !! Pedigree? When?
16560:
16561: A team led by Bill Ragsdale implemented fig-Forth on many processors in
16562: 1979. Robert Selzer and Bill Ragsdale developed the original
16563: implementation of fig-Forth for the 6502 based on microForth.
16564:
16565: The principal architect of microForth was Dean Sanderson. microForth was
16566: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
16567: the 1802, and subsequently implemented on the 8080, the 6800 and the
16568: Z80.
16569:
16570: All earlier Forth systems were custom-made, usually by Charles Moore,
16571: who discovered (as he puts it) Forth during the late 60s. The first full
16572: Forth existed in 1971.
16573:
16574: A part of the information in this section comes from
16575: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
16576: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
16577: Charles H. Moore, presented at the HOPL-II conference and preprinted
16578: in SIGPLAN Notices 28(3), 1993. You can find more historical and
16579: genealogical information about Forth there. For a more general (and
16580: graphical) Forth family tree look see
16581: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
16582: Forth Family Tree and Timeline}.
16583:
16584: @c ------------------------------------------------------------------
16585: @node Forth-related information, Licenses, Origin, Top
16586: @appendix Other Forth-related information
16587: @cindex Forth-related information
16588:
16589: @c anton: I threw most of this stuff out, because it can be found through
16590: @c the FAQ and the FAQ is more likely to be up-to-date.
16591:
16592: @cindex comp.lang.forth
16593: @cindex frequently asked questions
16594: There is an active news group (comp.lang.forth) discussing Forth
16595: (including Gforth) and Forth-related issues. Its
16596: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
16597: (frequently asked questions and their answers) contains a lot of
16598: information on Forth. You should read it before posting to
16599: comp.lang.forth.
16600:
16601: The ANS Forth standard is most usable in its
16602: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
16603:
16604: @c ---------------------------------------------------
16605: @node Licenses, Word Index, Forth-related information, Top
16606: @appendix Licenses
16607:
16608: @menu
16609: * GNU Free Documentation License:: License for copying this manual.
16610: * Copying:: GPL (for copying this software).
16611: @end menu
16612:
16613: @node GNU Free Documentation License, Copying, Licenses, Licenses
16614: @appendixsec GNU Free Documentation License
16615: @include fdl.texi
16616:
16617: @node Copying, , GNU Free Documentation License, Licenses
16618: @appendixsec GNU GENERAL PUBLIC LICENSE
16619: @include gpl.texi
16620:
16621:
16622:
16623: @c ------------------------------------------------------------------
16624: @node Word Index, Concept Index, Licenses, Top
16625: @unnumbered Word Index
16626:
16627: This index is a list of Forth words that have ``glossary'' entries
16628: within this manual. Each word is listed with its stack effect and
16629: wordset.
16630:
16631: @printindex fn
16632:
16633: @c anton: the name index seems superfluous given the word and concept indices.
16634:
16635: @c @node Name Index, Concept Index, Word Index, Top
16636: @c @unnumbered Name Index
16637:
16638: @c This index is a list of Forth words that have ``glossary'' entries
16639: @c within this manual.
16640:
16641: @c @printindex ky
16642:
16643: @c -------------------------------------------------------
16644: @node Concept Index, , Word Index, Top
16645: @unnumbered Concept and Word Index
16646:
16647: Not all entries listed in this index are present verbatim in the
16648: text. This index also duplicates, in abbreviated form, all of the words
16649: listed in the Word Index (only the names are listed for the words here).
16650:
16651: @printindex cp
16652:
16653: @bye
16654:
16655:
16656:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>