Annotation of gforth/doc/gforth.ds, revision 1.149
1.1 anton 1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28 crook 3:
1.21 crook 4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28 crook 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.
1.36 anton 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
1.113 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
1.29 crook 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:
1.66 anton 24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
1.28 crook 25:
1.1 anton 26: @comment %**start of header (This is for running Texinfo on a region.)
27: @setfilename gforth.info
1.113 anton 28: @include version.texi
1.1 anton 29: @settitle Gforth Manual
1.113 anton 30: @c @syncodeindex pg cp
1.49 anton 31:
1.12 anton 32: @macro progstyle {}
33: Programming style note:
1.3 anton 34: @end macro
1.48 anton 35:
36: @macro assignment {}
37: @table @i
38: @item Assignment:
39: @end macro
40: @macro endassignment {}
41: @end table
42: @end macro
43:
1.29 crook 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:
1.113 anton 57: @comment %**end of header (This is for running Texinfo on a region.)
58: @copying
1.125 anton 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.
1.29 crook 63:
1.142 anton 64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005 Free Software Foundation, Inc.
1.29 crook 65:
1.113 anton 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
1.10 anton 80:
1.113 anton 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
1.1 anton 91:
92: @titlepage
1.113 anton 93: @title Gforth
94: @subtitle for version @value{VERSION}, @value{UPDATED}
95: @author Neal Crook
96: @author Anton Ertl
1.114 anton 97: @author David Kuehling
1.113 anton 98: @author Bernd Paysan
99: @author Jens Wilke
1.1 anton 100: @page
101: @vskip 0pt plus 1filll
1.113 anton 102: @insertcopying
103: @end titlepage
1.1 anton 104:
1.113 anton 105: @contents
1.1 anton 106:
1.113 anton 107: @ifnottex
108: @node Top, Goals, (dir), (dir)
109: @top Gforth
1.1 anton 110:
1.113 anton 111: @insertcopying
1.49 anton 112: @end ifnottex
1.1 anton 113:
114: @menu
1.26 crook 115: * Goals:: About the Gforth Project
1.29 crook 116: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 117: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 118: * Introduction:: An introduction to ANS Forth
1.1 anton 119: * Words:: Forth words available in Gforth
1.24 anton 120: * Error messages:: How to interpret them
1.1 anton 121: * Tools:: Programming tools
122: * ANS conformance:: Implementation-defined options etc.
1.65 anton 123: * Standard vs Extensions:: Should I use extensions?
1.1 anton 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
1.13 pazsan 129: * Cross Compiler:: The Cross Compiler
1.1 anton 130: * Bugs:: How to report them
131: * Origin:: Authors and ancestors of Gforth
1.21 crook 132: * Forth-related information:: Books and places to look on the WWW
1.113 anton 133: * Licenses::
1.1 anton 134: * Word Index:: An item for each Forth word
135: * Concept Index:: A menu covering many topics
1.12 anton 136:
1.91 anton 137: @detailmenu
138: --- The Detailed Node Listing ---
1.12 anton 139:
1.29 crook 140: Gforth Environment
141:
1.32 anton 142: * Invoking Gforth:: Getting in
143: * Leaving Gforth:: Getting out
144: * Command-line editing::
1.48 anton 145: * Environment variables:: that affect how Gforth starts up
1.32 anton 146: * Gforth Files:: What gets installed and where
1.112 anton 147: * Gforth in pipes::
1.48 anton 148: * Startup speed:: When 35ms is not fast enough ...
149:
150: Forth Tutorial
151:
152: * Starting Gforth Tutorial::
153: * Syntax Tutorial::
154: * Crash Course Tutorial::
155: * Stack Tutorial::
156: * Arithmetics Tutorial::
157: * Stack Manipulation Tutorial::
158: * Using files for Forth code Tutorial::
159: * Comments Tutorial::
160: * Colon Definitions Tutorial::
161: * Decompilation Tutorial::
162: * Stack-Effect Comments Tutorial::
163: * Types Tutorial::
164: * Factoring Tutorial::
165: * Designing the stack effect Tutorial::
166: * Local Variables Tutorial::
167: * Conditional execution Tutorial::
168: * Flags and Comparisons Tutorial::
169: * General Loops Tutorial::
170: * Counted loops Tutorial::
171: * Recursion Tutorial::
172: * Leaving definitions or loops Tutorial::
173: * Return Stack Tutorial::
174: * Memory Tutorial::
175: * Characters and Strings Tutorial::
176: * Alignment Tutorial::
1.87 anton 177: * Files Tutorial::
1.48 anton 178: * Interpretation and Compilation Semantics and Immediacy Tutorial::
179: * Execution Tokens Tutorial::
180: * Exceptions Tutorial::
181: * Defining Words Tutorial::
182: * Arrays and Records Tutorial::
183: * POSTPONE Tutorial::
184: * Literal Tutorial::
185: * Advanced macros Tutorial::
186: * Compilation Tokens Tutorial::
187: * Wordlists and Search Order Tutorial::
1.29 crook 188:
1.24 anton 189: An Introduction to ANS Forth
190:
1.67 anton 191: * Introducing the Text Interpreter::
192: * Stacks and Postfix notation::
193: * Your first definition::
194: * How does that work?::
195: * Forth is written in Forth::
196: * Review - elements of a Forth system::
197: * Where to go next::
198: * Exercises::
1.24 anton 199:
1.12 anton 200: Forth Words
201:
202: * Notation::
1.65 anton 203: * Case insensitivity::
204: * Comments::
205: * Boolean Flags::
1.12 anton 206: * Arithmetic::
207: * Stack Manipulation::
208: * Memory::
209: * Control Structures::
210: * Defining Words::
1.65 anton 211: * Interpretation and Compilation Semantics::
1.47 crook 212: * Tokens for Words::
1.81 anton 213: * Compiling words::
1.65 anton 214: * The Text Interpreter::
1.111 anton 215: * The Input Stream::
1.65 anton 216: * Word Lists::
217: * Environmental Queries::
1.12 anton 218: * Files::
219: * Blocks::
220: * Other I/O::
1.121 anton 221: * OS command line arguments::
1.78 anton 222: * Locals::
223: * Structures::
224: * Object-oriented Forth::
1.12 anton 225: * Programming Tools::
226: * Assembler and Code Words::
227: * Threading Words::
1.65 anton 228: * Passing Commands to the OS::
229: * Keeping track of Time::
230: * Miscellaneous Words::
1.12 anton 231:
232: Arithmetic
233:
234: * Single precision::
1.67 anton 235: * Double precision:: Double-cell integer arithmetic
1.12 anton 236: * Bitwise operations::
1.67 anton 237: * Numeric comparison::
1.32 anton 238: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 239: * Floating Point::
240:
241: Stack Manipulation
242:
243: * Data stack::
244: * Floating point stack::
245: * Return stack::
246: * Locals stack::
247: * Stack pointer manipulation::
248:
249: Memory
250:
1.32 anton 251: * Memory model::
252: * Dictionary allocation::
253: * Heap Allocation::
254: * Memory Access::
255: * Address arithmetic::
256: * Memory Blocks::
1.12 anton 257:
258: Control Structures
259:
1.41 anton 260: * Selection:: IF ... ELSE ... ENDIF
261: * Simple Loops:: BEGIN ...
1.32 anton 262: * Counted Loops:: DO
1.67 anton 263: * Arbitrary control structures::
264: * Calls and returns::
1.12 anton 265: * Exception Handling::
266:
267: Defining Words
268:
1.67 anton 269: * CREATE::
1.44 crook 270: * Variables:: Variables and user variables
1.67 anton 271: * Constants::
1.44 crook 272: * Values:: Initialised variables
1.67 anton 273: * Colon Definitions::
1.44 crook 274: * Anonymous Definitions:: Definitions without names
1.71 anton 275: * Supplying names:: Passing definition names as strings
1.67 anton 276: * User-defined Defining Words::
1.44 crook 277: * Deferred words:: Allow forward references
1.67 anton 278: * Aliases::
1.47 crook 279:
1.63 anton 280: User-defined Defining Words
281:
282: * CREATE..DOES> applications::
283: * CREATE..DOES> details::
284: * Advanced does> usage example::
1.91 anton 285: * @code{Const-does>}::
1.63 anton 286:
1.47 crook 287: Interpretation and Compilation Semantics
288:
1.67 anton 289: * Combined words::
1.12 anton 290:
1.71 anton 291: Tokens for Words
292:
293: * Execution token:: represents execution/interpretation semantics
294: * Compilation token:: represents compilation semantics
295: * Name token:: represents named words
296:
1.82 anton 297: Compiling words
298:
299: * Literals:: Compiling data values
300: * Macros:: Compiling words
301:
1.21 crook 302: The Text Interpreter
303:
1.67 anton 304: * Input Sources::
305: * Number Conversion::
306: * Interpret/Compile states::
307: * Interpreter Directives::
1.21 crook 308:
1.26 crook 309: Word Lists
310:
1.75 anton 311: * Vocabularies::
1.67 anton 312: * Why use word lists?::
1.75 anton 313: * Word list example::
1.26 crook 314:
315: Files
316:
1.48 anton 317: * Forth source files::
318: * General files::
319: * Search Paths::
320:
321: Search Paths
322:
1.75 anton 323: * Source Search Paths::
1.26 crook 324: * General Search Paths::
325:
326: Other I/O
327:
1.32 anton 328: * Simple numeric output:: Predefined formats
329: * Formatted numeric output:: Formatted (pictured) output
330: * String Formats:: How Forth stores strings in memory
1.67 anton 331: * Displaying characters and strings:: Other stuff
1.32 anton 332: * Input:: Input
1.112 anton 333: * Pipes:: How to create your own pipes
1.149 ! pazsan 334: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 335:
336: Locals
337:
338: * Gforth locals::
339: * ANS Forth locals::
340:
341: Gforth locals
342:
343: * Where are locals visible by name?::
344: * How long do locals live?::
1.78 anton 345: * Locals programming style::
346: * Locals implementation::
1.26 crook 347:
1.12 anton 348: Structures
349:
350: * Why explicit structure support?::
351: * Structure Usage::
352: * Structure Naming Convention::
353: * Structure Implementation::
354: * Structure Glossary::
355:
356: Object-oriented Forth
357:
1.48 anton 358: * Why object-oriented programming?::
359: * Object-Oriented Terminology::
360: * Objects::
361: * OOF::
362: * Mini-OOF::
1.23 crook 363: * Comparison with other object models::
1.12 anton 364:
1.24 anton 365: The @file{objects.fs} model
1.12 anton 366:
367: * Properties of the Objects model::
368: * Basic Objects Usage::
1.41 anton 369: * The Objects base class::
1.12 anton 370: * Creating objects::
371: * Object-Oriented Programming Style::
372: * Class Binding::
373: * Method conveniences::
374: * Classes and Scoping::
1.41 anton 375: * Dividing classes::
1.12 anton 376: * Object Interfaces::
377: * Objects Implementation::
378: * Objects Glossary::
379:
1.24 anton 380: The @file{oof.fs} model
1.12 anton 381:
1.67 anton 382: * Properties of the OOF model::
383: * Basic OOF Usage::
384: * The OOF base class::
385: * Class Declaration::
386: * Class Implementation::
1.12 anton 387:
1.24 anton 388: The @file{mini-oof.fs} model
1.23 crook 389:
1.48 anton 390: * Basic Mini-OOF Usage::
391: * Mini-OOF Example::
392: * Mini-OOF Implementation::
1.23 crook 393:
1.78 anton 394: Programming Tools
395:
396: * Examining::
397: * Forgetting words::
398: * Debugging:: Simple and quick.
399: * Assertions:: Making your programs self-checking.
400: * Singlestep Debugger:: Executing your program word by word.
401:
402: Assembler and Code Words
403:
404: * Code and ;code::
405: * Common Assembler:: Assembler Syntax
406: * Common Disassembler::
407: * 386 Assembler:: Deviations and special cases
408: * Alpha Assembler:: Deviations and special cases
409: * MIPS assembler:: Deviations and special cases
410: * Other assemblers:: How to write them
411:
1.12 anton 412: Tools
413:
414: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 415: * Stack depth changes:: Where does this stack item come from?
1.12 anton 416:
417: ANS conformance
418:
419: * The Core Words::
420: * The optional Block word set::
421: * The optional Double Number word set::
422: * The optional Exception word set::
423: * The optional Facility word set::
424: * The optional File-Access word set::
425: * The optional Floating-Point word set::
426: * The optional Locals word set::
427: * The optional Memory-Allocation word set::
428: * The optional Programming-Tools word set::
429: * The optional Search-Order word set::
430:
431: The Core Words
432:
433: * core-idef:: Implementation Defined Options
434: * core-ambcond:: Ambiguous Conditions
435: * core-other:: Other System Documentation
436:
437: The optional Block word set
438:
439: * block-idef:: Implementation Defined Options
440: * block-ambcond:: Ambiguous Conditions
441: * block-other:: Other System Documentation
442:
443: The optional Double Number word set
444:
445: * double-ambcond:: Ambiguous Conditions
446:
447: The optional Exception word set
448:
449: * exception-idef:: Implementation Defined Options
450:
451: The optional Facility word set
452:
453: * facility-idef:: Implementation Defined Options
454: * facility-ambcond:: Ambiguous Conditions
455:
456: The optional File-Access word set
457:
458: * file-idef:: Implementation Defined Options
459: * file-ambcond:: Ambiguous Conditions
460:
461: The optional Floating-Point word set
462:
463: * floating-idef:: Implementation Defined Options
464: * floating-ambcond:: Ambiguous Conditions
465:
466: The optional Locals word set
467:
468: * locals-idef:: Implementation Defined Options
469: * locals-ambcond:: Ambiguous Conditions
470:
471: The optional Memory-Allocation word set
472:
473: * memory-idef:: Implementation Defined Options
474:
475: The optional Programming-Tools word set
476:
477: * programming-idef:: Implementation Defined Options
478: * programming-ambcond:: Ambiguous Conditions
479:
480: The optional Search-Order word set
481:
482: * search-idef:: Implementation Defined Options
483: * search-ambcond:: Ambiguous Conditions
484:
1.109 anton 485: Emacs and Gforth
486:
487: * Installing gforth.el:: Making Emacs aware of Forth.
488: * Emacs Tags:: Viewing the source of a word in Emacs.
489: * Hilighting:: Making Forth code look prettier.
490: * Auto-Indentation:: Customizing auto-indentation.
491: * Blocks Files:: Reading and writing blocks files.
492:
1.12 anton 493: Image Files
494:
1.24 anton 495: * Image Licensing Issues:: Distribution terms for images.
496: * Image File Background:: Why have image files?
1.67 anton 497: * Non-Relocatable Image Files:: don't always work.
1.24 anton 498: * Data-Relocatable Image Files:: are better.
1.67 anton 499: * Fully Relocatable Image Files:: better yet.
1.24 anton 500: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 501: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 502: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 503:
504: Fully Relocatable Image Files
505:
1.27 crook 506: * gforthmi:: The normal way
1.12 anton 507: * cross.fs:: The hard way
508:
509: Engine
510:
511: * Portability::
512: * Threading::
513: * Primitives::
514: * Performance::
515:
516: Threading
517:
518: * Scheduling::
519: * Direct or Indirect Threaded?::
1.109 anton 520: * Dynamic Superinstructions::
1.12 anton 521: * DOES>::
522:
523: Primitives
524:
525: * Automatic Generation::
526: * TOS Optimization::
527: * Produced code::
1.13 pazsan 528:
529: Cross Compiler
530:
1.67 anton 531: * Using the Cross Compiler::
532: * How the Cross Compiler Works::
1.13 pazsan 533:
1.113 anton 534: Licenses
535:
536: * GNU Free Documentation License:: License for copying this manual.
537: * Copying:: GPL (for copying this software).
538:
1.24 anton 539: @end detailmenu
1.1 anton 540: @end menu
541:
1.113 anton 542: @c ----------------------------------------------------------
1.1 anton 543: @iftex
544: @unnumbered Preface
545: @cindex Preface
1.21 crook 546: This manual documents Gforth. Some introductory material is provided for
547: readers who are unfamiliar with Forth or who are migrating to Gforth
548: from other Forth compilers. However, this manual is primarily a
549: reference manual.
1.1 anton 550: @end iftex
551:
1.28 crook 552: @comment TODO much more blurb here.
1.26 crook 553:
554: @c ******************************************************************
1.113 anton 555: @node Goals, Gforth Environment, Top, Top
1.26 crook 556: @comment node-name, next, previous, up
557: @chapter Goals of Gforth
558: @cindex goals of the Gforth project
559: The goal of the Gforth Project is to develop a standard model for
560: ANS Forth. This can be split into several subgoals:
561:
562: @itemize @bullet
563: @item
564: Gforth should conform to the ANS Forth Standard.
565: @item
566: It should be a model, i.e. it should define all the
567: implementation-dependent things.
568: @item
569: It should become standard, i.e. widely accepted and used. This goal
570: is the most difficult one.
571: @end itemize
572:
573: To achieve these goals Gforth should be
574: @itemize @bullet
575: @item
576: Similar to previous models (fig-Forth, F83)
577: @item
578: Powerful. It should provide for all the things that are considered
579: necessary today and even some that are not yet considered necessary.
580: @item
581: Efficient. It should not get the reputation of being exceptionally
582: slow.
583: @item
584: Free.
585: @item
586: Available on many machines/easy to port.
587: @end itemize
588:
589: Have we achieved these goals? Gforth conforms to the ANS Forth
590: standard. It may be considered a model, but we have not yet documented
591: which parts of the model are stable and which parts we are likely to
592: change. It certainly has not yet become a de facto standard, but it
593: appears to be quite popular. It has some similarities to and some
594: differences from previous models. It has some powerful features, but not
595: yet everything that we envisioned. We certainly have achieved our
1.65 anton 596: execution speed goals (@pxref{Performance})@footnote{However, in 1998
597: the bar was raised when the major commercial Forth vendors switched to
598: native code compilers.}. It is free and available on many machines.
1.29 crook 599:
1.26 crook 600: @c ******************************************************************
1.48 anton 601: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 602: @chapter Gforth Environment
603: @cindex Gforth environment
1.21 crook 604:
1.45 crook 605: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 606: material in this chapter.
1.21 crook 607:
608: @menu
1.29 crook 609: * Invoking Gforth:: Getting in
610: * Leaving Gforth:: Getting out
611: * Command-line editing::
1.48 anton 612: * Environment variables:: that affect how Gforth starts up
1.29 crook 613: * Gforth Files:: What gets installed and where
1.112 anton 614: * Gforth in pipes::
1.48 anton 615: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 616: @end menu
617:
1.49 anton 618: For related information about the creation of images see @ref{Image Files}.
1.29 crook 619:
1.21 crook 620: @comment ----------------------------------------------
1.48 anton 621: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 622: @section Invoking Gforth
623: @cindex invoking Gforth
624: @cindex running Gforth
625: @cindex command-line options
626: @cindex options on the command line
627: @cindex flags on the command line
1.21 crook 628:
1.30 anton 629: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 630: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 631: will usually just say @code{gforth} -- this automatically loads the
632: default image file @file{gforth.fi}. In many other cases the default
633: Gforth image will be invoked like this:
1.21 crook 634: @example
1.30 anton 635: gforth [file | -e forth-code] ...
1.21 crook 636: @end example
1.29 crook 637: @noindent
638: This interprets the contents of the files and the Forth code in the order they
639: are given.
1.21 crook 640:
1.109 anton 641: In addition to the @command{gforth} engine, there is also an engine
642: called @command{gforth-fast}, which is faster, but gives less
643: informative error messages (@pxref{Error messages}) and may catch some
644: stack underflows later or not at all. You should use it for debugged,
645: performance-critical programs.
646:
647: Moreover, there is an engine called @command{gforth-itc}, which is
648: useful in some backwards-compatibility situations (@pxref{Direct or
649: Indirect Threaded?}).
1.30 anton 650:
1.29 crook 651: In general, the command line looks like this:
1.21 crook 652:
653: @example
1.30 anton 654: gforth[-fast] [engine options] [image options]
1.21 crook 655: @end example
656:
1.30 anton 657: The engine options must come before the rest of the command
1.29 crook 658: line. They are:
1.26 crook 659:
1.29 crook 660: @table @code
661: @cindex -i, command-line option
662: @cindex --image-file, command-line option
663: @item --image-file @i{file}
664: @itemx -i @i{file}
665: Loads the Forth image @i{file} instead of the default
666: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 667:
1.39 anton 668: @cindex --appl-image, command-line option
669: @item --appl-image @i{file}
670: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 671: to the image (instead of processing them as engine options). This is
672: useful for building executable application images on Unix, built with
1.39 anton 673: @code{gforthmi --application ...}.
674:
1.29 crook 675: @cindex --path, command-line option
676: @cindex -p, command-line option
677: @item --path @i{path}
678: @itemx -p @i{path}
679: Uses @i{path} for searching the image file and Forth source code files
680: instead of the default in the environment variable @code{GFORTHPATH} or
681: the path specified at installation time (e.g.,
682: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
683: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 684:
1.29 crook 685: @cindex --dictionary-size, command-line option
686: @cindex -m, command-line option
687: @cindex @i{size} parameters for command-line options
688: @cindex size of the dictionary and the stacks
689: @item --dictionary-size @i{size}
690: @itemx -m @i{size}
691: Allocate @i{size} space for the Forth dictionary space instead of
692: using the default specified in the image (typically 256K). The
693: @i{size} specification for this and subsequent options consists of
694: an integer and a unit (e.g.,
695: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
696: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
697: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
698: @code{e} is used.
1.21 crook 699:
1.29 crook 700: @cindex --data-stack-size, command-line option
701: @cindex -d, command-line option
702: @item --data-stack-size @i{size}
703: @itemx -d @i{size}
704: Allocate @i{size} space for the data stack instead of using the
705: default specified in the image (typically 16K).
1.21 crook 706:
1.29 crook 707: @cindex --return-stack-size, command-line option
708: @cindex -r, command-line option
709: @item --return-stack-size @i{size}
710: @itemx -r @i{size}
711: Allocate @i{size} space for the return stack instead of using the
712: default specified in the image (typically 15K).
1.21 crook 713:
1.29 crook 714: @cindex --fp-stack-size, command-line option
715: @cindex -f, command-line option
716: @item --fp-stack-size @i{size}
717: @itemx -f @i{size}
718: Allocate @i{size} space for the floating point stack instead of
719: using the default specified in the image (typically 15.5K). In this case
720: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 721:
1.48 anton 722: @cindex --locals-stack-size, command-line option
723: @cindex -l, command-line option
724: @item --locals-stack-size @i{size}
725: @itemx -l @i{size}
726: Allocate @i{size} space for the locals stack instead of using the
727: default specified in the image (typically 14.5K).
728:
729: @cindex -h, command-line option
730: @cindex --help, command-line option
731: @item --help
732: @itemx -h
733: Print a message about the command-line options
734:
735: @cindex -v, command-line option
736: @cindex --version, command-line option
737: @item --version
738: @itemx -v
739: Print version and exit
740:
741: @cindex --debug, command-line option
742: @item --debug
743: Print some information useful for debugging on startup.
744:
745: @cindex --offset-image, command-line option
746: @item --offset-image
747: Start the dictionary at a slightly different position than would be used
748: otherwise (useful for creating data-relocatable images,
749: @pxref{Data-Relocatable Image Files}).
750:
751: @cindex --no-offset-im, command-line option
752: @item --no-offset-im
753: Start the dictionary at the normal position.
754:
755: @cindex --clear-dictionary, command-line option
756: @item --clear-dictionary
757: Initialize all bytes in the dictionary to 0 before loading the image
758: (@pxref{Data-Relocatable Image Files}).
759:
760: @cindex --die-on-signal, command-line-option
761: @item --die-on-signal
762: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
763: or the segmentation violation SIGSEGV) by translating it into a Forth
764: @code{THROW}. With this option, Gforth exits if it receives such a
765: signal. This option is useful when the engine and/or the image might be
766: severely broken (such that it causes another signal before recovering
767: from the first); this option avoids endless loops in such cases.
1.109 anton 768:
1.119 anton 769: @cindex --no-dynamic, command-line option
770: @cindex --dynamic, command-line option
1.109 anton 771: @item --no-dynamic
772: @item --dynamic
773: Disable or enable dynamic superinstructions with replication
774: (@pxref{Dynamic Superinstructions}).
775:
1.119 anton 776: @cindex --no-super, command-line option
1.109 anton 777: @item --no-super
1.110 anton 778: Disable dynamic superinstructions, use just dynamic replication; this is
779: useful if you want to patch threaded code (@pxref{Dynamic
780: Superinstructions}).
1.119 anton 781:
782: @cindex --ss-number, command-line option
783: @item --ss-number=@var{N}
784: Use only the first @var{N} static superinstructions compiled into the
785: engine (default: use them all; note that only @code{gforth-fast} has
786: any). This option is useful for measuring the performance impact of
787: static superinstructions.
788:
789: @cindex --ss-min-..., command-line options
790: @item --ss-min-codesize
791: @item --ss-min-ls
792: @item --ss-min-lsu
793: @item --ss-min-nexts
794: Use specified metric for determining the cost of a primitive or static
795: superinstruction for static superinstruction selection. @code{Codesize}
796: is the native code size of the primive or static superinstruction,
797: @code{ls} is the number of loads and stores, @code{lsu} is the number of
798: loads, stores, and updates, and @code{nexts} is the number of dispatches
799: (not taking dynamic superinstructions into account), i.e. every
800: primitive or static superinstruction has cost 1. Default:
801: @code{codesize} if you use dynamic code generation, otherwise
802: @code{nexts}.
803:
804: @cindex --ss-greedy, command-line option
805: @item --ss-greedy
806: This option is useful for measuring the performance impact of static
807: superinstructions. By default, an optimal shortest-path algorithm is
808: used for selecting static superinstructions. With @option{--ss-greedy}
809: this algorithm is modified to assume that anything after the static
810: superinstruction currently under consideration is not combined into
811: static superinstructions. With @option{--ss-min-nexts} this produces
812: the same result as a greedy algorithm that always selects the longest
813: superinstruction available at the moment. E.g., if there are
814: superinstructions AB and BCD, then for the sequence A B C D the optimal
815: algorithm will select A BCD and the greedy algorithm will select AB C D.
816:
817: @cindex --print-metrics, command-line option
818: @item --print-metrics
819: Prints some metrics used during static superinstruction selection:
820: @code{code size} is the actual size of the dynamically generated code.
821: @code{Metric codesize} is the sum of the codesize metrics as seen by
822: static superinstruction selection; there is a difference from @code{code
823: size}, because not all primitives and static superinstructions are
824: compiled into dynamically generated code, and because of markers. The
825: other metrics correspond to the @option{ss-min-...} options. This
826: option is useful for evaluating the effects of the @option{--ss-...}
827: options.
1.109 anton 828:
1.48 anton 829: @end table
830:
831: @cindex loading files at startup
832: @cindex executing code on startup
833: @cindex batch processing with Gforth
834: As explained above, the image-specific command-line arguments for the
835: default image @file{gforth.fi} consist of a sequence of filenames and
836: @code{-e @var{forth-code}} options that are interpreted in the sequence
837: in which they are given. The @code{-e @var{forth-code}} or
1.121 anton 838: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
839: option takes only one argument; if you want to evaluate more Forth
840: words, you have to quote them or use @code{-e} several times. To exit
1.48 anton 841: after processing the command line (instead of entering interactive mode)
1.121 anton 842: append @code{-e bye} to the command line. You can also process the
843: command-line arguments with a Forth program (@pxref{OS command line
844: arguments}).
1.48 anton 845:
846: @cindex versions, invoking other versions of Gforth
847: If you have several versions of Gforth installed, @code{gforth} will
848: invoke the version that was installed last. @code{gforth-@i{version}}
849: invokes a specific version. If your environment contains the variable
850: @code{GFORTHPATH}, you may want to override it by using the
851: @code{--path} option.
852:
853: Not yet implemented:
854: On startup the system first executes the system initialization file
855: (unless the option @code{--no-init-file} is given; note that the system
856: resulting from using this option may not be ANS Forth conformant). Then
857: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 858: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 859: then in @file{~}, then in the normal path (see above).
860:
861:
862:
863: @comment ----------------------------------------------
864: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
865: @section Leaving Gforth
866: @cindex Gforth - leaving
867: @cindex leaving Gforth
868:
869: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
870: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
871: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 872: data are discarded. For ways of saving the state of the system before
873: leaving Gforth see @ref{Image Files}.
1.48 anton 874:
875: doc-bye
876:
877:
878: @comment ----------------------------------------------
1.65 anton 879: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 880: @section Command-line editing
881: @cindex command-line editing
882:
883: Gforth maintains a history file that records every line that you type to
884: the text interpreter. This file is preserved between sessions, and is
885: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
886: repeatedly you can recall successively older commands from this (or
887: previous) session(s). The full list of command-line editing facilities is:
888:
889: @itemize @bullet
890: @item
891: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
892: commands from the history buffer.
893: @item
894: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
895: from the history buffer.
896: @item
897: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
898: @item
899: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
900: @item
901: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
902: closing up the line.
903: @item
904: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
905: @item
906: @kbd{Ctrl-a} to move the cursor to the start of the line.
907: @item
908: @kbd{Ctrl-e} to move the cursor to the end of the line.
909: @item
910: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
911: line.
912: @item
913: @key{TAB} to step through all possible full-word completions of the word
914: currently being typed.
915: @item
1.65 anton 916: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
917: using @code{bye}).
918: @item
919: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
920: character under the cursor.
1.48 anton 921: @end itemize
922:
923: When editing, displayable characters are inserted to the left of the
924: cursor position; the line is always in ``insert'' (as opposed to
925: ``overstrike'') mode.
926:
927: @cindex history file
928: @cindex @file{.gforth-history}
929: On Unix systems, the history file is @file{~/.gforth-history} by
930: default@footnote{i.e. it is stored in the user's home directory.}. You
931: can find out the name and location of your history file using:
932:
933: @example
934: history-file type \ Unix-class systems
935:
936: history-file type \ Other systems
937: history-dir type
938: @end example
939:
940: If you enter long definitions by hand, you can use a text editor to
941: paste them out of the history file into a Forth source file for reuse at
942: a later time.
943:
944: Gforth never trims the size of the history file, so you should do this
945: periodically, if necessary.
946:
947: @comment this is all defined in history.fs
948: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
949: @comment chosen?
950:
951:
952: @comment ----------------------------------------------
1.65 anton 953: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 954: @section Environment variables
955: @cindex environment variables
956:
957: Gforth uses these environment variables:
958:
959: @itemize @bullet
960: @item
961: @cindex @code{GFORTHHIST} -- environment variable
962: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
963: open/create the history file, @file{.gforth-history}. Default:
964: @code{$HOME}.
965:
966: @item
967: @cindex @code{GFORTHPATH} -- environment variable
968: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
969: for Forth source-code files.
970:
971: @item
1.147 anton 972: @cindex @code{LANG} -- environment variable
973: @code{LANG} -- see @code{LC_CTYPE}
974:
975: @item
976: @cindex @code{LC_ALL} -- environment variable
977: @code{LC_ALL} -- see @code{LC_CTYPE}
978:
979: @item
980: @cindex @code{LC_CTYPE} -- environment variable
981: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
982: startup, Gforth uses the UTF-8 encoding for strings internally and
983: expects its input and produces its output in UTF-8 encoding, otherwise
984: the encoding is 8bit (see @pxref{Xchars and Unicode}). If this
985: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
986: that is unset, in @code{LANG}.
987:
988: @item
1.129 anton 989: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
990:
991: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
992: of @code{system} before passing it to C's @code{system()}. Default:
1.130 anton 993: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1.129 anton 994: and the command are directly concatenated, so if a space between them is
995: necessary, append it to the prefix.
996:
997: @item
1.48 anton 998: @cindex @code{GFORTH} -- environment variable
1.49 anton 999: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1000:
1001: @item
1002: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1003: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1004:
1005: @item
1006: @cindex @code{TMP}, @code{TEMP} - environment variable
1007: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1008: location for the history file.
1009: @end itemize
1010:
1011: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1012: @comment mentioning these.
1013:
1014: All the Gforth environment variables default to sensible values if they
1015: are not set.
1016:
1017:
1018: @comment ----------------------------------------------
1.112 anton 1019: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 1020: @section Gforth files
1021: @cindex Gforth files
1022:
1023: When you install Gforth on a Unix system, it installs files in these
1024: locations by default:
1025:
1026: @itemize @bullet
1027: @item
1028: @file{/usr/local/bin/gforth}
1029: @item
1030: @file{/usr/local/bin/gforthmi}
1031: @item
1032: @file{/usr/local/man/man1/gforth.1} - man page.
1033: @item
1034: @file{/usr/local/info} - the Info version of this manual.
1035: @item
1036: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1037: @item
1038: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1039: @item
1040: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1041: @item
1042: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1043: @end itemize
1044:
1045: You can select different places for installation by using
1046: @code{configure} options (listed with @code{configure --help}).
1047:
1048: @comment ----------------------------------------------
1.112 anton 1049: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1050: @section Gforth in pipes
1051: @cindex pipes, Gforth as part of
1052:
1053: Gforth can be used in pipes created elsewhere (described here). It can
1054: also create pipes on its own (@pxref{Pipes}).
1055:
1056: @cindex input from pipes
1057: If you pipe into Gforth, your program should read with @code{read-file}
1058: or @code{read-line} from @code{stdin} (@pxref{General files}).
1059: @code{Key} does not recognize the end of input. Words like
1060: @code{accept} echo the input and are therefore usually not useful for
1061: reading from a pipe. You have to invoke the Forth program with an OS
1062: command-line option, as you have no chance to use the Forth command line
1063: (the text interpreter would try to interpret the pipe input).
1064:
1065: @cindex output in pipes
1066: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1067:
1068: @cindex silent exiting from Gforth
1069: When you write to a pipe that has been closed at the other end, Gforth
1070: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1071: into the exception @code{broken-pipe-error}. If your application does
1072: not catch that exception, the system catches it and exits, usually
1073: silently (unless you were working on the Forth command line; then it
1074: prints an error message and exits). This is usually the desired
1075: behaviour.
1076:
1077: If you do not like this behaviour, you have to catch the exception
1078: yourself, and react to it.
1079:
1080: Here's an example of an invocation of Gforth that is usable in a pipe:
1081:
1082: @example
1083: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1084: type repeat ; foo bye"
1085: @end example
1086:
1087: This example just copies the input verbatim to the output. A very
1088: simple pipe containing this example looks like this:
1089:
1090: @example
1091: cat startup.fs |
1092: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1093: type repeat ; foo bye"|
1094: head
1095: @end example
1096:
1097: @cindex stderr and pipes
1098: Pipes involving Gforth's @code{stderr} output do not work.
1099:
1100: @comment ----------------------------------------------
1101: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1102: @section Startup speed
1103: @cindex Startup speed
1104: @cindex speed, startup
1105:
1106: If Gforth is used for CGI scripts or in shell scripts, its startup
1107: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1108: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1109: system time.
1110:
1111: If startup speed is a problem, you may consider the following ways to
1112: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1113: (for example, by using Fast-CGI).
1.48 anton 1114:
1.112 anton 1115: An easy step that influences Gforth startup speed is the use of the
1116: @option{--no-dynamic} option; this decreases image loading speed, but
1117: increases compile-time and run-time.
1118:
1119: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1120: building it with @code{XLDFLAGS=-static}. This requires more memory for
1121: the code and will therefore slow down the first invocation, but
1122: subsequent invocations avoid the dynamic linking overhead. Another
1123: disadvantage is that Gforth won't profit from library upgrades. As a
1124: result, @code{gforth-static -e bye} takes about 17.1ms user and
1125: 8.2ms system time.
1126:
1127: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1128: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1129: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1130: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1131: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1132: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1133: address for the dictionary, for whatever reason; so you better provide a
1134: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1135: bye} takes about 15.3ms user and 7.5ms system time.
1136:
1137: The final step is to disable dictionary hashing in Gforth. Gforth
1138: builds the hash table on startup, which takes much of the startup
1139: overhead. You can do this by commenting out the @code{include hash.fs}
1140: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1141: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1142: The disadvantages are that functionality like @code{table} and
1143: @code{ekey} is missing and that text interpretation (e.g., compiling)
1144: now takes much longer. So, you should only use this method if there is
1145: no significant text interpretation to perform (the script should be
1.62 crook 1146: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1147: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1148:
1149: @c ******************************************************************
1150: @node Tutorial, Introduction, Gforth Environment, Top
1151: @chapter Forth Tutorial
1152: @cindex Tutorial
1153: @cindex Forth Tutorial
1154:
1.67 anton 1155: @c Topics from nac's Introduction that could be mentioned:
1156: @c press <ret> after each line
1157: @c Prompt
1158: @c numbers vs. words in dictionary on text interpretation
1159: @c what happens on redefinition
1160: @c parsing words (in particular, defining words)
1161:
1.83 anton 1162: The difference of this chapter from the Introduction
1163: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1164: be used while sitting in front of a computer, and covers much more
1165: material, but does not explain how the Forth system works.
1166:
1.62 crook 1167: This tutorial can be used with any ANS-compliant Forth; any
1168: Gforth-specific features are marked as such and you can skip them if you
1169: work with another Forth. This tutorial does not explain all features of
1170: Forth, just enough to get you started and give you some ideas about the
1171: facilities available in Forth. Read the rest of the manual and the
1172: standard when you are through this.
1.48 anton 1173:
1174: The intended way to use this tutorial is that you work through it while
1175: sitting in front of the console, take a look at the examples and predict
1176: what they will do, then try them out; if the outcome is not as expected,
1177: find out why (e.g., by trying out variations of the example), so you
1178: understand what's going on. There are also some assignments that you
1179: should solve.
1180:
1181: This tutorial assumes that you have programmed before and know what,
1182: e.g., a loop is.
1183:
1184: @c !! explain compat library
1185:
1186: @menu
1187: * Starting Gforth Tutorial::
1188: * Syntax Tutorial::
1189: * Crash Course Tutorial::
1190: * Stack Tutorial::
1191: * Arithmetics Tutorial::
1192: * Stack Manipulation Tutorial::
1193: * Using files for Forth code Tutorial::
1194: * Comments Tutorial::
1195: * Colon Definitions Tutorial::
1196: * Decompilation Tutorial::
1197: * Stack-Effect Comments Tutorial::
1198: * Types Tutorial::
1199: * Factoring Tutorial::
1200: * Designing the stack effect Tutorial::
1201: * Local Variables Tutorial::
1202: * Conditional execution Tutorial::
1203: * Flags and Comparisons Tutorial::
1204: * General Loops Tutorial::
1205: * Counted loops Tutorial::
1206: * Recursion Tutorial::
1207: * Leaving definitions or loops Tutorial::
1208: * Return Stack Tutorial::
1209: * Memory Tutorial::
1210: * Characters and Strings Tutorial::
1211: * Alignment Tutorial::
1.87 anton 1212: * Files Tutorial::
1.48 anton 1213: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1214: * Execution Tokens Tutorial::
1215: * Exceptions Tutorial::
1216: * Defining Words Tutorial::
1217: * Arrays and Records Tutorial::
1218: * POSTPONE Tutorial::
1219: * Literal Tutorial::
1220: * Advanced macros Tutorial::
1221: * Compilation Tokens Tutorial::
1222: * Wordlists and Search Order Tutorial::
1223: @end menu
1224:
1225: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1226: @section Starting Gforth
1.66 anton 1227: @cindex starting Gforth tutorial
1.48 anton 1228: You can start Gforth by typing its name:
1229:
1230: @example
1231: gforth
1232: @end example
1233:
1234: That puts you into interactive mode; you can leave Gforth by typing
1235: @code{bye}. While in Gforth, you can edit the command line and access
1236: the command line history with cursor keys, similar to bash.
1237:
1238:
1239: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1240: @section Syntax
1.66 anton 1241: @cindex syntax tutorial
1.48 anton 1242:
1243: A @dfn{word} is a sequence of arbitrary characters (expcept white
1244: space). Words are separated by white space. E.g., each of the
1245: following lines contains exactly one word:
1246:
1247: @example
1248: word
1249: !@@#$%^&*()
1250: 1234567890
1251: 5!a
1252: @end example
1253:
1254: A frequent beginner's error is to leave away necessary white space,
1255: resulting in an error like @samp{Undefined word}; so if you see such an
1256: error, check if you have put spaces wherever necessary.
1257:
1258: @example
1259: ." hello, world" \ correct
1260: ."hello, world" \ gives an "Undefined word" error
1261: @end example
1262:
1.65 anton 1263: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1264: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1265: your system is case-sensitive, you may have to type all the examples
1266: given here in upper case.
1267:
1268:
1269: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1270: @section Crash Course
1271:
1272: Type
1273:
1274: @example
1275: 0 0 !
1276: here execute
1277: ' catch >body 20 erase abort
1278: ' (quit) >body 20 erase
1279: @end example
1280:
1281: The last two examples are guaranteed to destroy parts of Gforth (and
1282: most other systems), so you better leave Gforth afterwards (if it has
1283: not finished by itself). On some systems you may have to kill gforth
1284: from outside (e.g., in Unix with @code{kill}).
1285:
1286: Now that you know how to produce crashes (and that there's not much to
1287: them), let's learn how to produce meaningful programs.
1288:
1289:
1290: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1291: @section Stack
1.66 anton 1292: @cindex stack tutorial
1.48 anton 1293:
1294: The most obvious feature of Forth is the stack. When you type in a
1295: number, it is pushed on the stack. You can display the content of the
1296: stack with @code{.s}.
1297:
1298: @example
1299: 1 2 .s
1300: 3 .s
1301: @end example
1302:
1303: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1304: appear in @code{.s} output as they appeared in the input.
1305:
1306: You can print the top of stack element with @code{.}.
1307:
1308: @example
1309: 1 2 3 . . .
1310: @end example
1311:
1312: In general, words consume their stack arguments (@code{.s} is an
1313: exception).
1314:
1.141 anton 1315: @quotation Assignment
1.48 anton 1316: What does the stack contain after @code{5 6 7 .}?
1.141 anton 1317: @end quotation
1.48 anton 1318:
1319:
1320: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1321: @section Arithmetics
1.66 anton 1322: @cindex arithmetics tutorial
1.48 anton 1323:
1324: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1325: operate on the top two stack items:
1326:
1327: @example
1.67 anton 1328: 2 2 .s
1329: + .s
1330: .
1.48 anton 1331: 2 1 - .
1332: 7 3 mod .
1333: @end example
1334:
1335: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1336: as in the corresponding infix expression (this is generally the case in
1337: Forth).
1338:
1339: Parentheses are superfluous (and not available), because the order of
1340: the words unambiguously determines the order of evaluation and the
1341: operands:
1342:
1343: @example
1344: 3 4 + 5 * .
1345: 3 4 5 * + .
1346: @end example
1347:
1.141 anton 1348: @quotation Assignment
1.48 anton 1349: What are the infix expressions corresponding to the Forth code above?
1350: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1351: known as Postfix or RPN (Reverse Polish Notation).}.
1.141 anton 1352: @end quotation
1.48 anton 1353:
1354: To change the sign, use @code{negate}:
1355:
1356: @example
1357: 2 negate .
1358: @end example
1359:
1.141 anton 1360: @quotation Assignment
1.48 anton 1361: Convert -(-3)*4-5 to Forth.
1.141 anton 1362: @end quotation
1.48 anton 1363:
1364: @code{/mod} performs both @code{/} and @code{mod}.
1365:
1366: @example
1367: 7 3 /mod . .
1368: @end example
1369:
1.66 anton 1370: Reference: @ref{Arithmetic}.
1371:
1372:
1.48 anton 1373: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1374: @section Stack Manipulation
1.66 anton 1375: @cindex stack manipulation tutorial
1.48 anton 1376:
1377: Stack manipulation words rearrange the data on the stack.
1378:
1379: @example
1380: 1 .s drop .s
1381: 1 .s dup .s drop drop .s
1382: 1 2 .s over .s drop drop drop
1383: 1 2 .s swap .s drop drop
1384: 1 2 3 .s rot .s drop drop drop
1385: @end example
1386:
1387: These are the most important stack manipulation words. There are also
1388: variants that manipulate twice as many stack items:
1389:
1390: @example
1391: 1 2 3 4 .s 2swap .s 2drop 2drop
1392: @end example
1393:
1394: Two more stack manipulation words are:
1395:
1396: @example
1397: 1 2 .s nip .s drop
1398: 1 2 .s tuck .s 2drop drop
1399: @end example
1400:
1.141 anton 1401: @quotation Assignment
1.48 anton 1402: Replace @code{nip} and @code{tuck} with combinations of other stack
1403: manipulation words.
1404:
1405: @example
1406: Given: How do you get:
1407: 1 2 3 3 2 1
1408: 1 2 3 1 2 3 2
1409: 1 2 3 1 2 3 3
1410: 1 2 3 1 3 3
1411: 1 2 3 2 1 3
1412: 1 2 3 4 4 3 2 1
1413: 1 2 3 1 2 3 1 2 3
1414: 1 2 3 4 1 2 3 4 1 2
1415: 1 2 3
1416: 1 2 3 1 2 3 4
1417: 1 2 3 1 3
1418: @end example
1.141 anton 1419: @end quotation
1.48 anton 1420:
1421: @example
1422: 5 dup * .
1423: @end example
1424:
1.141 anton 1425: @quotation Assignment
1.48 anton 1426: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1427: Write a piece of Forth code that expects two numbers on the stack
1428: (@var{a} and @var{b}, with @var{b} on top) and computes
1429: @code{(a-b)(a+1)}.
1.141 anton 1430: @end quotation
1.48 anton 1431:
1.66 anton 1432: Reference: @ref{Stack Manipulation}.
1433:
1434:
1.48 anton 1435: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1436: @section Using files for Forth code
1.66 anton 1437: @cindex loading Forth code, tutorial
1438: @cindex files containing Forth code, tutorial
1.48 anton 1439:
1440: While working at the Forth command line is convenient for one-line
1441: examples and short one-off code, you probably want to store your source
1442: code in files for convenient editing and persistence. You can use your
1443: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1444: Gforth}) to create @var{file.fs} and use
1.48 anton 1445:
1446: @example
1.102 anton 1447: s" @var{file.fs}" included
1.48 anton 1448: @end example
1449:
1450: to load it into your Forth system. The file name extension I use for
1451: Forth files is @samp{.fs}.
1452:
1453: You can easily start Gforth with some files loaded like this:
1454:
1455: @example
1.102 anton 1456: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1457: @end example
1458:
1459: If an error occurs during loading these files, Gforth terminates,
1460: whereas an error during @code{INCLUDED} within Gforth usually gives you
1461: a Gforth command line. Starting the Forth system every time gives you a
1462: clean start every time, without interference from the results of earlier
1463: tries.
1464:
1465: I often put all the tests in a file, then load the code and run the
1466: tests with
1467:
1468: @example
1.102 anton 1469: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1470: @end example
1471:
1472: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1473: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1474: restart this command without ado.
1475:
1476: The advantage of this approach is that the tests can be repeated easily
1477: every time the program ist changed, making it easy to catch bugs
1478: introduced by the change.
1479:
1.66 anton 1480: Reference: @ref{Forth source files}.
1481:
1.48 anton 1482:
1483: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1484: @section Comments
1.66 anton 1485: @cindex comments tutorial
1.48 anton 1486:
1487: @example
1488: \ That's a comment; it ends at the end of the line
1489: ( Another comment; it ends here: ) .s
1490: @end example
1491:
1492: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1493: separated with white space from the following text.
1494:
1495: @example
1496: \This gives an "Undefined word" error
1497: @end example
1498:
1499: The first @code{)} ends a comment started with @code{(}, so you cannot
1500: nest @code{(}-comments; and you cannot comment out text containing a
1501: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1502: avoid @code{)} in word names.}.
1503:
1504: I use @code{\}-comments for descriptive text and for commenting out code
1505: of one or more line; I use @code{(}-comments for describing the stack
1506: effect, the stack contents, or for commenting out sub-line pieces of
1507: code.
1508:
1509: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1510: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1511: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1512: with @kbd{M-q}.
1513:
1.66 anton 1514: Reference: @ref{Comments}.
1515:
1.48 anton 1516:
1517: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1518: @section Colon Definitions
1.66 anton 1519: @cindex colon definitions, tutorial
1520: @cindex definitions, tutorial
1521: @cindex procedures, tutorial
1522: @cindex functions, tutorial
1.48 anton 1523:
1524: are similar to procedures and functions in other programming languages.
1525:
1526: @example
1527: : squared ( n -- n^2 )
1528: dup * ;
1529: 5 squared .
1530: 7 squared .
1531: @end example
1532:
1533: @code{:} starts the colon definition; its name is @code{squared}. The
1534: following comment describes its stack effect. The words @code{dup *}
1535: are not executed, but compiled into the definition. @code{;} ends the
1536: colon definition.
1537:
1538: The newly-defined word can be used like any other word, including using
1539: it in other definitions:
1540:
1541: @example
1542: : cubed ( n -- n^3 )
1543: dup squared * ;
1544: -5 cubed .
1545: : fourth-power ( n -- n^4 )
1546: squared squared ;
1547: 3 fourth-power .
1548: @end example
1549:
1.141 anton 1550: @quotation Assignment
1.48 anton 1551: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1552: @code{/mod} in terms of other Forth words, and check if they work (hint:
1553: test your tests on the originals first). Don't let the
1554: @samp{redefined}-Messages spook you, they are just warnings.
1.141 anton 1555: @end quotation
1.48 anton 1556:
1.66 anton 1557: Reference: @ref{Colon Definitions}.
1558:
1.48 anton 1559:
1560: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1561: @section Decompilation
1.66 anton 1562: @cindex decompilation tutorial
1563: @cindex see tutorial
1.48 anton 1564:
1565: You can decompile colon definitions with @code{see}:
1566:
1567: @example
1568: see squared
1569: see cubed
1570: @end example
1571:
1572: In Gforth @code{see} shows you a reconstruction of the source code from
1573: the executable code. Informations that were present in the source, but
1574: not in the executable code, are lost (e.g., comments).
1575:
1.65 anton 1576: You can also decompile the predefined words:
1577:
1578: @example
1579: see .
1580: see +
1581: @end example
1582:
1583:
1.48 anton 1584: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1585: @section Stack-Effect Comments
1.66 anton 1586: @cindex stack-effect comments, tutorial
1587: @cindex --, tutorial
1.48 anton 1588: By convention the comment after the name of a definition describes the
1589: stack effect: The part in from of the @samp{--} describes the state of
1590: the stack before the execution of the definition, i.e., the parameters
1591: that are passed into the colon definition; the part behind the @samp{--}
1592: is the state of the stack after the execution of the definition, i.e.,
1593: the results of the definition. The stack comment only shows the top
1594: stack items that the definition accesses and/or changes.
1595:
1596: You should put a correct stack effect on every definition, even if it is
1597: just @code{( -- )}. You should also add some descriptive comment to
1598: more complicated words (I usually do this in the lines following
1599: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1600: you have to work through every definition before you can understand
1.48 anton 1601: any).
1602:
1.141 anton 1603: @quotation Assignment
1.48 anton 1604: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1605: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1606: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1607: are done, you can compare your stack effects to those in this manual
1.48 anton 1608: (@pxref{Word Index}).
1.141 anton 1609: @end quotation
1.48 anton 1610:
1611: Sometimes programmers put comments at various places in colon
1612: definitions that describe the contents of the stack at that place (stack
1613: comments); i.e., they are like the first part of a stack-effect
1614: comment. E.g.,
1615:
1616: @example
1617: : cubed ( n -- n^3 )
1618: dup squared ( n n^2 ) * ;
1619: @end example
1620:
1621: In this case the stack comment is pretty superfluous, because the word
1622: is simple enough. If you think it would be a good idea to add such a
1623: comment to increase readability, you should also consider factoring the
1624: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1625: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1626: however, if you decide not to refactor it, then having such a comment is
1627: better than not having it.
1628:
1629: The names of the stack items in stack-effect and stack comments in the
1630: standard, in this manual, and in many programs specify the type through
1631: a type prefix, similar to Fortran and Hungarian notation. The most
1632: frequent prefixes are:
1633:
1634: @table @code
1635: @item n
1636: signed integer
1637: @item u
1638: unsigned integer
1639: @item c
1640: character
1641: @item f
1642: Boolean flags, i.e. @code{false} or @code{true}.
1643: @item a-addr,a-
1644: Cell-aligned address
1645: @item c-addr,c-
1646: Char-aligned address (note that a Char may have two bytes in Windows NT)
1647: @item xt
1648: Execution token, same size as Cell
1649: @item w,x
1650: Cell, can contain an integer or an address. It usually takes 32, 64 or
1651: 16 bits (depending on your platform and Forth system). A cell is more
1652: commonly known as machine word, but the term @emph{word} already means
1653: something different in Forth.
1654: @item d
1655: signed double-cell integer
1656: @item ud
1657: unsigned double-cell integer
1658: @item r
1659: Float (on the FP stack)
1660: @end table
1661:
1662: You can find a more complete list in @ref{Notation}.
1663:
1.141 anton 1664: @quotation Assignment
1.48 anton 1665: Write stack-effect comments for all definitions you have written up to
1666: now.
1.141 anton 1667: @end quotation
1.48 anton 1668:
1669:
1670: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1671: @section Types
1.66 anton 1672: @cindex types tutorial
1.48 anton 1673:
1674: In Forth the names of the operations are not overloaded; so similar
1675: operations on different types need different names; e.g., @code{+} adds
1676: integers, and you have to use @code{f+} to add floating-point numbers.
1677: The following prefixes are often used for related operations on
1678: different types:
1679:
1680: @table @code
1681: @item (none)
1682: signed integer
1683: @item u
1684: unsigned integer
1685: @item c
1686: character
1687: @item d
1688: signed double-cell integer
1689: @item ud, du
1690: unsigned double-cell integer
1691: @item 2
1692: two cells (not-necessarily double-cell numbers)
1693: @item m, um
1694: mixed single-cell and double-cell operations
1695: @item f
1696: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1697: and @samp{r} represents FP numbers).
1.48 anton 1698: @end table
1699:
1700: If there are no differences between the signed and the unsigned variant
1701: (e.g., for @code{+}), there is only the prefix-less variant.
1702:
1703: Forth does not perform type checking, neither at compile time, nor at
1704: run time. If you use the wrong oeration, the data are interpreted
1705: incorrectly:
1706:
1707: @example
1708: -1 u.
1709: @end example
1710:
1711: If you have only experience with type-checked languages until now, and
1712: have heard how important type-checking is, don't panic! In my
1713: experience (and that of other Forthers), type errors in Forth code are
1714: usually easy to find (once you get used to it), the increased vigilance
1715: of the programmer tends to catch some harder errors in addition to most
1716: type errors, and you never have to work around the type system, so in
1717: most situations the lack of type-checking seems to be a win (projects to
1718: add type checking to Forth have not caught on).
1719:
1720:
1721: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1722: @section Factoring
1.66 anton 1723: @cindex factoring tutorial
1.48 anton 1724:
1725: If you try to write longer definitions, you will soon find it hard to
1726: keep track of the stack contents. Therefore, good Forth programmers
1727: tend to write only short definitions (e.g., three lines). The art of
1728: finding meaningful short definitions is known as factoring (as in
1729: factoring polynomials).
1730:
1731: Well-factored programs offer additional advantages: smaller, more
1732: general words, are easier to test and debug and can be reused more and
1733: better than larger, specialized words.
1734:
1735: So, if you run into difficulties with stack management, when writing
1736: code, try to define meaningful factors for the word, and define the word
1737: in terms of those. Even if a factor contains only two words, it is
1738: often helpful.
1739:
1.65 anton 1740: Good factoring is not easy, and it takes some practice to get the knack
1741: for it; but even experienced Forth programmers often don't find the
1742: right solution right away, but only when rewriting the program. So, if
1743: you don't come up with a good solution immediately, keep trying, don't
1744: despair.
1.48 anton 1745:
1746: @c example !!
1747:
1748:
1749: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1750: @section Designing the stack effect
1.66 anton 1751: @cindex Stack effect design, tutorial
1752: @cindex design of stack effects, tutorial
1.48 anton 1753:
1754: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1755: function; and since there is only one result, you don't have to deal with
1.48 anton 1756: the order of results, either.
1757:
1.117 anton 1758: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1759: parameter and result order of a definition is important and should be
1760: designed well. The general guideline is to design the stack effect such
1761: that the word is simple to use in most cases, even if that complicates
1762: the implementation of the word. Some concrete rules are:
1763:
1764: @itemize @bullet
1765:
1766: @item
1767: Words consume all of their parameters (e.g., @code{.}).
1768:
1769: @item
1770: If there is a convention on the order of parameters (e.g., from
1771: mathematics or another programming language), stick with it (e.g.,
1772: @code{-}).
1773:
1774: @item
1775: If one parameter usually requires only a short computation (e.g., it is
1776: a constant), pass it on the top of the stack. Conversely, parameters
1777: that usually require a long sequence of code to compute should be passed
1778: as the bottom (i.e., first) parameter. This makes the code easier to
1779: read, because reader does not need to keep track of the bottom item
1780: through a long sequence of code (or, alternatively, through stack
1.49 anton 1781: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1782: address on top of the stack because it is usually simpler to compute
1783: than the stored value (often the address is just a variable).
1784:
1785: @item
1786: Similarly, results that are usually consumed quickly should be returned
1787: on the top of stack, whereas a result that is often used in long
1788: computations should be passed as bottom result. E.g., the file words
1789: like @code{open-file} return the error code on the top of stack, because
1790: it is usually consumed quickly by @code{throw}; moreover, the error code
1791: has to be checked before doing anything with the other results.
1792:
1793: @end itemize
1794:
1795: These rules are just general guidelines, don't lose sight of the overall
1796: goal to make the words easy to use. E.g., if the convention rule
1797: conflicts with the computation-length rule, you might decide in favour
1798: of the convention if the word will be used rarely, and in favour of the
1799: computation-length rule if the word will be used frequently (because
1800: with frequent use the cost of breaking the computation-length rule would
1801: be quite high, and frequent use makes it easier to remember an
1802: unconventional order).
1803:
1804: @c example !! structure package
1805:
1.65 anton 1806:
1.48 anton 1807: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1808: @section Local Variables
1.66 anton 1809: @cindex local variables, tutorial
1.48 anton 1810:
1811: You can define local variables (@emph{locals}) in a colon definition:
1812:
1813: @example
1814: : swap @{ a b -- b a @}
1815: b a ;
1816: 1 2 swap .s 2drop
1817: @end example
1818:
1819: (If your Forth system does not support this syntax, include
1820: @file{compat/anslocals.fs} first).
1821:
1822: In this example @code{@{ a b -- b a @}} is the locals definition; it
1823: takes two cells from the stack, puts the top of stack in @code{b} and
1824: the next stack element in @code{a}. @code{--} starts a comment ending
1825: with @code{@}}. After the locals definition, using the name of the
1826: local will push its value on the stack. You can leave the comment
1827: part (@code{-- b a}) away:
1828:
1829: @example
1830: : swap ( x1 x2 -- x2 x1 )
1831: @{ a b @} b a ;
1832: @end example
1833:
1834: In Gforth you can have several locals definitions, anywhere in a colon
1835: definition; in contrast, in a standard program you can have only one
1836: locals definition per colon definition, and that locals definition must
1837: be outside any controll structure.
1838:
1839: With locals you can write slightly longer definitions without running
1840: into stack trouble. However, I recommend trying to write colon
1841: definitions without locals for exercise purposes to help you gain the
1842: essential factoring skills.
1843:
1.141 anton 1844: @quotation Assignment
1.48 anton 1845: Rewrite your definitions until now with locals
1.141 anton 1846: @end quotation
1.48 anton 1847:
1.66 anton 1848: Reference: @ref{Locals}.
1849:
1.48 anton 1850:
1851: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1852: @section Conditional execution
1.66 anton 1853: @cindex conditionals, tutorial
1854: @cindex if, tutorial
1.48 anton 1855:
1856: In Forth you can use control structures only inside colon definitions.
1857: An @code{if}-structure looks like this:
1858:
1859: @example
1860: : abs ( n1 -- +n2 )
1861: dup 0 < if
1862: negate
1863: endif ;
1864: 5 abs .
1865: -5 abs .
1866: @end example
1867:
1868: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1869: the following code is performed, otherwise execution continues after the
1.51 pazsan 1870: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 1871: elements and prioduces a flag:
1872:
1873: @example
1874: 1 2 < .
1875: 2 1 < .
1876: 1 1 < .
1877: @end example
1878:
1879: Actually the standard name for @code{endif} is @code{then}. This
1880: tutorial presents the examples using @code{endif}, because this is often
1881: less confusing for people familiar with other programming languages
1882: where @code{then} has a different meaning. If your system does not have
1883: @code{endif}, define it with
1884:
1885: @example
1886: : endif postpone then ; immediate
1887: @end example
1888:
1889: You can optionally use an @code{else}-part:
1890:
1891: @example
1892: : min ( n1 n2 -- n )
1893: 2dup < if
1894: drop
1895: else
1896: nip
1897: endif ;
1898: 2 3 min .
1899: 3 2 min .
1900: @end example
1901:
1.141 anton 1902: @quotation Assignment
1.48 anton 1903: Write @code{min} without @code{else}-part (hint: what's the definition
1904: of @code{nip}?).
1.141 anton 1905: @end quotation
1.48 anton 1906:
1.66 anton 1907: Reference: @ref{Selection}.
1908:
1.48 anton 1909:
1910: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1911: @section Flags and Comparisons
1.66 anton 1912: @cindex flags tutorial
1913: @cindex comparison tutorial
1.48 anton 1914:
1915: In a false-flag all bits are clear (0 when interpreted as integer). In
1916: a canonical true-flag all bits are set (-1 as a twos-complement signed
1917: integer); in many contexts (e.g., @code{if}) any non-zero value is
1918: treated as true flag.
1919:
1920: @example
1921: false .
1922: true .
1923: true hex u. decimal
1924: @end example
1925:
1926: Comparison words produce canonical flags:
1927:
1928: @example
1929: 1 1 = .
1930: 1 0= .
1931: 0 1 < .
1932: 0 0 < .
1933: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1934: -1 1 < .
1935: @end example
1936:
1.66 anton 1937: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1938: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1939: these combinations are standard (for details see the standard,
1940: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1941:
1942: You can use @code{and or xor invert} can be used as operations on
1943: canonical flags. Actually they are bitwise operations:
1944:
1945: @example
1946: 1 2 and .
1947: 1 2 or .
1948: 1 3 xor .
1949: 1 invert .
1950: @end example
1951:
1952: You can convert a zero/non-zero flag into a canonical flag with
1953: @code{0<>} (and complement it on the way with @code{0=}).
1954:
1955: @example
1956: 1 0= .
1957: 1 0<> .
1958: @end example
1959:
1.65 anton 1960: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 1961: operation of the Boolean operations to avoid @code{if}s:
1962:
1963: @example
1964: : foo ( n1 -- n2 )
1965: 0= if
1966: 14
1967: else
1968: 0
1969: endif ;
1970: 0 foo .
1971: 1 foo .
1972:
1973: : foo ( n1 -- n2 )
1974: 0= 14 and ;
1975: 0 foo .
1976: 1 foo .
1977: @end example
1978:
1.141 anton 1979: @quotation Assignment
1.48 anton 1980: Write @code{min} without @code{if}.
1.141 anton 1981: @end quotation
1.48 anton 1982:
1.66 anton 1983: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
1984: @ref{Bitwise operations}.
1985:
1.48 anton 1986:
1987: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
1988: @section General Loops
1.66 anton 1989: @cindex loops, indefinite, tutorial
1.48 anton 1990:
1991: The endless loop is the most simple one:
1992:
1993: @example
1994: : endless ( -- )
1995: 0 begin
1996: dup . 1+
1997: again ;
1998: endless
1999: @end example
2000:
2001: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2002: does nothing at run-time, @code{again} jumps back to @code{begin}.
2003:
2004: A loop with one exit at any place looks like this:
2005:
2006: @example
2007: : log2 ( +n1 -- n2 )
2008: \ logarithmus dualis of n1>0, rounded down to the next integer
2009: assert( dup 0> )
2010: 2/ 0 begin
2011: over 0> while
2012: 1+ swap 2/ swap
2013: repeat
2014: nip ;
2015: 7 log2 .
2016: 8 log2 .
2017: @end example
2018:
2019: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2020: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2021: continues behind the @code{while}. @code{Repeat} jumps back to
2022: @code{begin}, just like @code{again}.
2023:
2024: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2025: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2026: one bit (arithmetic shift right):
2027:
2028: @example
2029: -5 2 / .
2030: -5 2/ .
2031: @end example
2032:
2033: @code{assert(} is no standard word, but you can get it on systems other
2034: then Gforth by including @file{compat/assert.fs}. You can see what it
2035: does by trying
2036:
2037: @example
2038: 0 log2 .
2039: @end example
2040:
2041: Here's a loop with an exit at the end:
2042:
2043: @example
2044: : log2 ( +n1 -- n2 )
2045: \ logarithmus dualis of n1>0, rounded down to the next integer
2046: assert( dup 0 > )
2047: -1 begin
2048: 1+ swap 2/ swap
2049: over 0 <=
2050: until
2051: nip ;
2052: @end example
2053:
2054: @code{Until} consumes a flag; if it is non-zero, execution continues at
2055: the @code{begin}, otherwise after the @code{until}.
2056:
1.141 anton 2057: @quotation Assignment
1.48 anton 2058: Write a definition for computing the greatest common divisor.
1.141 anton 2059: @end quotation
1.48 anton 2060:
1.66 anton 2061: Reference: @ref{Simple Loops}.
2062:
1.48 anton 2063:
2064: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2065: @section Counted loops
1.66 anton 2066: @cindex loops, counted, tutorial
1.48 anton 2067:
2068: @example
2069: : ^ ( n1 u -- n )
2070: \ n = the uth power of u1
2071: 1 swap 0 u+do
2072: over *
2073: loop
2074: nip ;
2075: 3 2 ^ .
2076: 4 3 ^ .
2077: @end example
2078:
2079: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2080: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2081: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2082: times (or not at all, if @code{u3-u4<0}).
2083:
2084: You can see the stack effect design rules at work in the stack effect of
2085: the loop start words: Since the start value of the loop is more
2086: frequently constant than the end value, the start value is passed on
2087: the top-of-stack.
2088:
2089: You can access the counter of a counted loop with @code{i}:
2090:
2091: @example
2092: : fac ( u -- u! )
2093: 1 swap 1+ 1 u+do
2094: i *
2095: loop ;
2096: 5 fac .
2097: 7 fac .
2098: @end example
2099:
2100: There is also @code{+do}, which expects signed numbers (important for
2101: deciding whether to enter the loop).
2102:
1.141 anton 2103: @quotation Assignment
1.48 anton 2104: Write a definition for computing the nth Fibonacci number.
1.141 anton 2105: @end quotation
1.48 anton 2106:
1.65 anton 2107: You can also use increments other than 1:
2108:
2109: @example
2110: : up2 ( n1 n2 -- )
2111: +do
2112: i .
2113: 2 +loop ;
2114: 10 0 up2
2115:
2116: : down2 ( n1 n2 -- )
2117: -do
2118: i .
2119: 2 -loop ;
2120: 0 10 down2
2121: @end example
1.48 anton 2122:
1.66 anton 2123: Reference: @ref{Counted Loops}.
2124:
1.48 anton 2125:
2126: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2127: @section Recursion
1.66 anton 2128: @cindex recursion tutorial
1.48 anton 2129:
2130: Usually the name of a definition is not visible in the definition; but
2131: earlier definitions are usually visible:
2132:
2133: @example
2134: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2135: : / ( n1 n2 -- n )
2136: dup 0= if
2137: -10 throw \ report division by zero
2138: endif
2139: / \ old version
2140: ;
2141: 1 0 /
2142: @end example
2143:
2144: For recursive definitions you can use @code{recursive} (non-standard) or
2145: @code{recurse}:
2146:
2147: @example
2148: : fac1 ( n -- n! ) recursive
2149: dup 0> if
2150: dup 1- fac1 *
2151: else
2152: drop 1
2153: endif ;
2154: 7 fac1 .
2155:
2156: : fac2 ( n -- n! )
2157: dup 0> if
2158: dup 1- recurse *
2159: else
2160: drop 1
2161: endif ;
2162: 8 fac2 .
2163: @end example
2164:
1.141 anton 2165: @quotation Assignment
1.48 anton 2166: Write a recursive definition for computing the nth Fibonacci number.
1.141 anton 2167: @end quotation
1.48 anton 2168:
1.66 anton 2169: Reference (including indirect recursion): @xref{Calls and returns}.
2170:
1.48 anton 2171:
2172: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2173: @section Leaving definitions or loops
1.66 anton 2174: @cindex leaving definitions, tutorial
2175: @cindex leaving loops, tutorial
1.48 anton 2176:
2177: @code{EXIT} exits the current definition right away. For every counted
2178: loop that is left in this way, an @code{UNLOOP} has to be performed
2179: before the @code{EXIT}:
2180:
2181: @c !! real examples
2182: @example
2183: : ...
2184: ... u+do
2185: ... if
2186: ... unloop exit
2187: endif
2188: ...
2189: loop
2190: ... ;
2191: @end example
2192:
2193: @code{LEAVE} leaves the innermost counted loop right away:
2194:
2195: @example
2196: : ...
2197: ... u+do
2198: ... if
2199: ... leave
2200: endif
2201: ...
2202: loop
2203: ... ;
2204: @end example
2205:
1.65 anton 2206: @c !! example
1.48 anton 2207:
1.66 anton 2208: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2209:
2210:
1.48 anton 2211: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2212: @section Return Stack
1.66 anton 2213: @cindex return stack tutorial
1.48 anton 2214:
2215: In addition to the data stack Forth also has a second stack, the return
2216: stack; most Forth systems store the return addresses of procedure calls
2217: there (thus its name). Programmers can also use this stack:
2218:
2219: @example
2220: : foo ( n1 n2 -- )
2221: .s
2222: >r .s
1.50 anton 2223: r@@ .
1.48 anton 2224: >r .s
1.50 anton 2225: r@@ .
1.48 anton 2226: r> .
1.50 anton 2227: r@@ .
1.48 anton 2228: r> . ;
2229: 1 2 foo
2230: @end example
2231:
2232: @code{>r} takes an element from the data stack and pushes it onto the
2233: return stack; conversely, @code{r>} moves an elementm from the return to
2234: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148 anton 2235: on the data stack.
1.48 anton 2236:
2237: Forth programmers usually use the return stack for storing data
2238: temporarily, if using the data stack alone would be too complex, and
2239: factoring and locals are not an option:
2240:
2241: @example
2242: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2243: rot >r rot r> ;
2244: @end example
2245:
2246: The return address of the definition and the loop control parameters of
2247: counted loops usually reside on the return stack, so you have to take
2248: all items, that you have pushed on the return stack in a colon
2249: definition or counted loop, from the return stack before the definition
2250: or loop ends. You cannot access items that you pushed on the return
2251: stack outside some definition or loop within the definition of loop.
2252:
2253: If you miscount the return stack items, this usually ends in a crash:
2254:
2255: @example
2256: : crash ( n -- )
2257: >r ;
2258: 5 crash
2259: @end example
2260:
2261: You cannot mix using locals and using the return stack (according to the
2262: standard; Gforth has no problem). However, they solve the same
2263: problems, so this shouldn't be an issue.
2264:
1.141 anton 2265: @quotation Assignment
1.48 anton 2266: Can you rewrite any of the definitions you wrote until now in a better
2267: way using the return stack?
1.141 anton 2268: @end quotation
1.48 anton 2269:
1.66 anton 2270: Reference: @ref{Return stack}.
2271:
1.48 anton 2272:
2273: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2274: @section Memory
1.66 anton 2275: @cindex memory access/allocation tutorial
1.48 anton 2276:
2277: You can create a global variable @code{v} with
2278:
2279: @example
2280: variable v ( -- addr )
2281: @end example
2282:
2283: @code{v} pushes the address of a cell in memory on the stack. This cell
2284: was reserved by @code{variable}. You can use @code{!} (store) to store
2285: values into this cell and @code{@@} (fetch) to load the value from the
2286: stack into memory:
2287:
2288: @example
2289: v .
2290: 5 v ! .s
1.50 anton 2291: v @@ .
1.48 anton 2292: @end example
2293:
1.65 anton 2294: You can see a raw dump of memory with @code{dump}:
2295:
2296: @example
2297: v 1 cells .s dump
2298: @end example
2299:
2300: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2301: generally, address units (aus)) that @code{n1 cells} occupy. You can
2302: also reserve more memory:
1.48 anton 2303:
2304: @example
2305: create v2 20 cells allot
1.65 anton 2306: v2 20 cells dump
1.48 anton 2307: @end example
2308:
1.65 anton 2309: creates a word @code{v2} and reserves 20 uninitialized cells; the
2310: address pushed by @code{v2} points to the start of these 20 cells. You
2311: can use address arithmetic to access these cells:
1.48 anton 2312:
2313: @example
2314: 3 v2 5 cells + !
1.65 anton 2315: v2 20 cells dump
1.48 anton 2316: @end example
2317:
2318: You can reserve and initialize memory with @code{,}:
2319:
2320: @example
2321: create v3
2322: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2323: v3 @@ .
2324: v3 cell+ @@ .
2325: v3 2 cells + @@ .
1.65 anton 2326: v3 5 cells dump
1.48 anton 2327: @end example
2328:
1.141 anton 2329: @quotation Assignment
1.48 anton 2330: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2331: @code{u} cells, with the first of these cells at @code{addr}, the next
2332: one at @code{addr cell+} etc.
1.141 anton 2333: @end quotation
1.48 anton 2334:
2335: You can also reserve memory without creating a new word:
2336:
2337: @example
1.60 anton 2338: here 10 cells allot .
2339: here .
1.48 anton 2340: @end example
2341:
2342: @code{Here} pushes the start address of the memory area. You should
2343: store it somewhere, or you will have a hard time finding the memory area
2344: again.
2345:
2346: @code{Allot} manages dictionary memory. The dictionary memory contains
2347: the system's data structures for words etc. on Gforth and most other
2348: Forth systems. It is managed like a stack: You can free the memory that
2349: you have just @code{allot}ed with
2350:
2351: @example
2352: -10 cells allot
1.60 anton 2353: here .
1.48 anton 2354: @end example
2355:
2356: Note that you cannot do this if you have created a new word in the
2357: meantime (because then your @code{allot}ed memory is no longer on the
2358: top of the dictionary ``stack'').
2359:
2360: Alternatively, you can use @code{allocate} and @code{free} which allow
2361: freeing memory in any order:
2362:
2363: @example
2364: 10 cells allocate throw .s
2365: 20 cells allocate throw .s
2366: swap
2367: free throw
2368: free throw
2369: @end example
2370:
2371: The @code{throw}s deal with errors (e.g., out of memory).
2372:
1.65 anton 2373: And there is also a
2374: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2375: garbage collector}, which eliminates the need to @code{free} memory
2376: explicitly.
1.48 anton 2377:
1.66 anton 2378: Reference: @ref{Memory}.
2379:
1.48 anton 2380:
2381: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2382: @section Characters and Strings
1.66 anton 2383: @cindex strings tutorial
2384: @cindex characters tutorial
1.48 anton 2385:
2386: On the stack characters take up a cell, like numbers. In memory they
2387: have their own size (one 8-bit byte on most systems), and therefore
2388: require their own words for memory access:
2389:
2390: @example
2391: create v4
2392: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2393: v4 4 chars + c@@ .
1.65 anton 2394: v4 5 chars dump
1.48 anton 2395: @end example
2396:
2397: The preferred representation of strings on the stack is @code{addr
2398: u-count}, where @code{addr} is the address of the first character and
2399: @code{u-count} is the number of characters in the string.
2400:
2401: @example
2402: v4 5 type
2403: @end example
2404:
2405: You get a string constant with
2406:
2407: @example
2408: s" hello, world" .s
2409: type
2410: @end example
2411:
2412: Make sure you have a space between @code{s"} and the string; @code{s"}
2413: is a normal Forth word and must be delimited with white space (try what
2414: happens when you remove the space).
2415:
2416: However, this interpretive use of @code{s"} is quite restricted: the
2417: string exists only until the next call of @code{s"} (some Forth systems
2418: keep more than one of these strings, but usually they still have a
1.62 crook 2419: limited lifetime).
1.48 anton 2420:
2421: @example
2422: s" hello," s" world" .s
2423: type
2424: type
2425: @end example
2426:
1.62 crook 2427: You can also use @code{s"} in a definition, and the resulting
2428: strings then live forever (well, for as long as the definition):
1.48 anton 2429:
2430: @example
2431: : foo s" hello," s" world" ;
2432: foo .s
2433: type
2434: type
2435: @end example
2436:
1.141 anton 2437: @quotation Assignment
1.48 anton 2438: @code{Emit ( c -- )} types @code{c} as character (not a number).
2439: Implement @code{type ( addr u -- )}.
1.141 anton 2440: @end quotation
1.48 anton 2441:
1.66 anton 2442: Reference: @ref{Memory Blocks}.
2443:
2444:
1.84 pazsan 2445: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2446: @section Alignment
1.66 anton 2447: @cindex alignment tutorial
2448: @cindex memory alignment tutorial
1.48 anton 2449:
2450: On many processors cells have to be aligned in memory, if you want to
2451: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2452: not require alignment, access to aligned cells is faster).
1.48 anton 2453:
2454: @code{Create} aligns @code{here} (i.e., the place where the next
2455: allocation will occur, and that the @code{create}d word points to).
2456: Likewise, the memory produced by @code{allocate} starts at an aligned
2457: address. Adding a number of @code{cells} to an aligned address produces
2458: another aligned address.
2459:
2460: However, address arithmetic involving @code{char+} and @code{chars} can
2461: create an address that is not cell-aligned. @code{Aligned ( addr --
2462: a-addr )} produces the next aligned address:
2463:
2464: @example
1.50 anton 2465: v3 char+ aligned .s @@ .
2466: v3 char+ .s @@ .
1.48 anton 2467: @end example
2468:
2469: Similarly, @code{align} advances @code{here} to the next aligned
2470: address:
2471:
2472: @example
2473: create v5 97 c,
2474: here .
2475: align here .
2476: 1000 ,
2477: @end example
2478:
2479: Note that you should use aligned addresses even if your processor does
2480: not require them, if you want your program to be portable.
2481:
1.66 anton 2482: Reference: @ref{Address arithmetic}.
2483:
1.48 anton 2484:
1.84 pazsan 2485: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2486: @section Files
2487: @cindex files tutorial
2488:
2489: This section gives a short introduction into how to use files inside
2490: Forth. It's broken up into five easy steps:
2491:
2492: @enumerate 1
2493: @item Opened an ASCII text file for input
2494: @item Opened a file for output
2495: @item Read input file until string matched (or some other condition matched)
2496: @item Wrote some lines from input ( modified or not) to output
2497: @item Closed the files.
2498: @end enumerate
2499:
2500: @subsection Open file for input
2501:
2502: @example
2503: s" foo.in" r/o open-file throw Value fd-in
2504: @end example
2505:
2506: @subsection Create file for output
2507:
2508: @example
2509: s" foo.out" w/o create-file throw Value fd-out
2510: @end example
2511:
2512: The available file modes are r/o for read-only access, r/w for
2513: read-write access, and w/o for write-only access. You could open both
2514: files with r/w, too, if you like. All file words return error codes; for
2515: most applications, it's best to pass there error codes with @code{throw}
2516: to the outer error handler.
2517:
2518: If you want words for opening and assigning, define them as follows:
2519:
2520: @example
2521: 0 Value fd-in
2522: 0 Value fd-out
2523: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2524: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2525: @end example
2526:
2527: Usage example:
2528:
2529: @example
2530: s" foo.in" open-input
2531: s" foo.out" open-output
2532: @end example
2533:
2534: @subsection Scan file for a particular line
2535:
2536: @example
2537: 256 Constant max-line
2538: Create line-buffer max-line 2 + allot
2539:
2540: : scan-file ( addr u -- )
2541: begin
2542: line-buffer max-line fd-in read-line throw
2543: while
2544: >r 2dup line-buffer r> compare 0=
2545: until
2546: else
2547: drop
2548: then
2549: 2drop ;
2550: @end example
2551:
2552: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2553: the buffer at addr, and returns the number of bytes read, a flag that is
2554: false when the end of file is reached, and an error code.
1.84 pazsan 2555:
2556: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2557: returns zero if both strings are equal. It returns a positive number if
2558: the first string is lexically greater, a negative if the second string
2559: is lexically greater.
2560:
2561: We haven't seen this loop here; it has two exits. Since the @code{while}
2562: exits with the number of bytes read on the stack, we have to clean up
2563: that separately; that's after the @code{else}.
2564:
2565: Usage example:
2566:
2567: @example
2568: s" The text I search is here" scan-file
2569: @end example
2570:
2571: @subsection Copy input to output
2572:
2573: @example
2574: : copy-file ( -- )
2575: begin
2576: line-buffer max-line fd-in read-line throw
2577: while
2578: line-buffer swap fd-out write-file throw
2579: repeat ;
2580: @end example
2581:
2582: @subsection Close files
2583:
2584: @example
2585: fd-in close-file throw
2586: fd-out close-file throw
2587: @end example
2588:
2589: Likewise, you can put that into definitions, too:
2590:
2591: @example
2592: : close-input ( -- ) fd-in close-file throw ;
2593: : close-output ( -- ) fd-out close-file throw ;
2594: @end example
2595:
1.141 anton 2596: @quotation Assignment
1.84 pazsan 2597: How could you modify @code{copy-file} so that it copies until a second line is
2598: matched? Can you write a program that extracts a section of a text file,
2599: given the line that starts and the line that terminates that section?
1.141 anton 2600: @end quotation
1.84 pazsan 2601:
2602: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2603: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2604: @cindex semantics tutorial
2605: @cindex interpretation semantics tutorial
2606: @cindex compilation semantics tutorial
2607: @cindex immediate, tutorial
1.48 anton 2608:
2609: When a word is compiled, it behaves differently from being interpreted.
2610: E.g., consider @code{+}:
2611:
2612: @example
2613: 1 2 + .
2614: : foo + ;
2615: @end example
2616:
2617: These two behaviours are known as compilation and interpretation
2618: semantics. For normal words (e.g., @code{+}), the compilation semantics
2619: is to append the interpretation semantics to the currently defined word
2620: (@code{foo} in the example above). I.e., when @code{foo} is executed
2621: later, the interpretation semantics of @code{+} (i.e., adding two
2622: numbers) will be performed.
2623:
2624: However, there are words with non-default compilation semantics, e.g.,
2625: the control-flow words like @code{if}. You can use @code{immediate} to
2626: change the compilation semantics of the last defined word to be equal to
2627: the interpretation semantics:
2628:
2629: @example
2630: : [FOO] ( -- )
2631: 5 . ; immediate
2632:
2633: [FOO]
2634: : bar ( -- )
2635: [FOO] ;
2636: bar
2637: see bar
2638: @end example
2639:
2640: Two conventions to mark words with non-default compilation semnatics are
2641: names with brackets (more frequently used) and to write them all in
2642: upper case (less frequently used).
2643:
2644: In Gforth (and many other systems) you can also remove the
2645: interpretation semantics with @code{compile-only} (the compilation
2646: semantics is derived from the original interpretation semantics):
2647:
2648: @example
2649: : flip ( -- )
2650: 6 . ; compile-only \ but not immediate
2651: flip
2652:
2653: : flop ( -- )
2654: flip ;
2655: flop
2656: @end example
2657:
2658: In this example the interpretation semantics of @code{flop} is equal to
2659: the original interpretation semantics of @code{flip}.
2660:
2661: The text interpreter has two states: in interpret state, it performs the
2662: interpretation semantics of words it encounters; in compile state, it
2663: performs the compilation semantics of these words.
2664:
2665: Among other things, @code{:} switches into compile state, and @code{;}
2666: switches back to interpret state. They contain the factors @code{]}
2667: (switch to compile state) and @code{[} (switch to interpret state), that
2668: do nothing but switch the state.
2669:
2670: @example
2671: : xxx ( -- )
2672: [ 5 . ]
2673: ;
2674:
2675: xxx
2676: see xxx
2677: @end example
2678:
2679: These brackets are also the source of the naming convention mentioned
2680: above.
2681:
1.66 anton 2682: Reference: @ref{Interpretation and Compilation Semantics}.
2683:
1.48 anton 2684:
2685: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2686: @section Execution Tokens
1.66 anton 2687: @cindex execution tokens tutorial
2688: @cindex XT tutorial
1.48 anton 2689:
2690: @code{' word} gives you the execution token (XT) of a word. The XT is a
2691: cell representing the interpretation semantics of a word. You can
2692: execute this semantics with @code{execute}:
2693:
2694: @example
2695: ' + .s
2696: 1 2 rot execute .
2697: @end example
2698:
2699: The XT is similar to a function pointer in C. However, parameter
2700: passing through the stack makes it a little more flexible:
2701:
2702: @example
2703: : map-array ( ... addr u xt -- ... )
1.50 anton 2704: \ executes xt ( ... x -- ... ) for every element of the array starting
2705: \ at addr and containing u elements
1.48 anton 2706: @{ xt @}
2707: cells over + swap ?do
1.50 anton 2708: i @@ xt execute
1.48 anton 2709: 1 cells +loop ;
2710:
2711: create a 3 , 4 , 2 , -1 , 4 ,
2712: a 5 ' . map-array .s
2713: 0 a 5 ' + map-array .
2714: s" max-n" environment? drop .s
2715: a 5 ' min map-array .
2716: @end example
2717:
2718: You can use map-array with the XTs of words that consume one element
2719: more than they produce. In theory you can also use it with other XTs,
2720: but the stack effect then depends on the size of the array, which is
2721: hard to understand.
2722:
1.51 pazsan 2723: Since XTs are cell-sized, you can store them in memory and manipulate
2724: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2725: word with @code{compile,}:
2726:
2727: @example
2728: : foo1 ( n1 n2 -- n )
2729: [ ' + compile, ] ;
2730: see foo
2731: @end example
2732:
2733: This is non-standard, because @code{compile,} has no compilation
2734: semantics in the standard, but it works in good Forth systems. For the
2735: broken ones, use
2736:
2737: @example
2738: : [compile,] compile, ; immediate
2739:
2740: : foo1 ( n1 n2 -- n )
2741: [ ' + ] [compile,] ;
2742: see foo
2743: @end example
2744:
2745: @code{'} is a word with default compilation semantics; it parses the
2746: next word when its interpretation semantics are executed, not during
2747: compilation:
2748:
2749: @example
2750: : foo ( -- xt )
2751: ' ;
2752: see foo
2753: : bar ( ... "word" -- ... )
2754: ' execute ;
2755: see bar
1.60 anton 2756: 1 2 bar + .
1.48 anton 2757: @end example
2758:
2759: You often want to parse a word during compilation and compile its XT so
2760: it will be pushed on the stack at run-time. @code{[']} does this:
2761:
2762: @example
2763: : xt-+ ( -- xt )
2764: ['] + ;
2765: see xt-+
2766: 1 2 xt-+ execute .
2767: @end example
2768:
2769: Many programmers tend to see @code{'} and the word it parses as one
2770: unit, and expect it to behave like @code{[']} when compiled, and are
2771: confused by the actual behaviour. If you are, just remember that the
2772: Forth system just takes @code{'} as one unit and has no idea that it is
2773: a parsing word (attempts to convenience programmers in this issue have
2774: usually resulted in even worse pitfalls, see
1.66 anton 2775: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2776: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2777:
2778: Note that the state of the interpreter does not come into play when
1.51 pazsan 2779: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2780: compile state, it still gives you the interpretation semantics. And
2781: whatever that state is, @code{execute} performs the semantics
1.66 anton 2782: represented by the XT (i.e., for XTs produced with @code{'} the
2783: interpretation semantics).
2784:
2785: Reference: @ref{Tokens for Words}.
1.48 anton 2786:
2787:
2788: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2789: @section Exceptions
1.66 anton 2790: @cindex exceptions tutorial
1.48 anton 2791:
2792: @code{throw ( n -- )} causes an exception unless n is zero.
2793:
2794: @example
2795: 100 throw .s
2796: 0 throw .s
2797: @end example
2798:
2799: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2800: it catches exceptions and pushes the number of the exception on the
2801: stack (or 0, if the xt executed without exception). If there was an
2802: exception, the stacks have the same depth as when entering @code{catch}:
2803:
2804: @example
2805: .s
2806: 3 0 ' / catch .s
2807: 3 2 ' / catch .s
2808: @end example
2809:
1.141 anton 2810: @quotation Assignment
1.48 anton 2811: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2812: @end quotation
1.48 anton 2813:
2814: @code{Throw} always jumps to the dynamically next enclosing
2815: @code{catch}, even if it has to leave several call levels to achieve
2816: this:
2817:
2818: @example
2819: : foo 100 throw ;
2820: : foo1 foo ." after foo" ;
1.51 pazsan 2821: : bar ['] foo1 catch ;
1.60 anton 2822: bar .
1.48 anton 2823: @end example
2824:
2825: It is often important to restore a value upon leaving a definition, even
2826: if the definition is left through an exception. You can ensure this
2827: like this:
2828:
2829: @example
2830: : ...
2831: save-x
1.51 pazsan 2832: ['] word-changing-x catch ( ... n )
1.48 anton 2833: restore-x
2834: ( ... n ) throw ;
2835: @end example
2836:
1.55 anton 2837: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 2838: @code{try ... recover ... endtry}. If the code between @code{try} and
2839: @code{recover} has an exception, the stack depths are restored, the
2840: exception number is pushed on the stack, and the code between
2841: @code{recover} and @code{endtry} is performed. E.g., the definition for
2842: @code{catch} is
2843:
2844: @example
2845: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
2846: try
2847: execute 0
2848: recover
2849: nip
2850: endtry ;
2851: @end example
2852:
2853: The equivalent to the restoration code above is
2854:
2855: @example
2856: : ...
2857: save-x
2858: try
1.92 anton 2859: word-changing-x 0
2860: recover endtry
1.48 anton 2861: restore-x
2862: throw ;
2863: @end example
2864:
1.92 anton 2865: This works if @code{word-changing-x} does not change the stack depth,
2866: otherwise you should add some code between @code{recover} and
2867: @code{endtry} to balance the stack.
1.48 anton 2868:
1.66 anton 2869: Reference: @ref{Exception Handling}.
2870:
1.48 anton 2871:
2872: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2873: @section Defining Words
1.66 anton 2874: @cindex defining words tutorial
2875: @cindex does> tutorial
2876: @cindex create...does> tutorial
2877:
2878: @c before semantics?
1.48 anton 2879:
2880: @code{:}, @code{create}, and @code{variable} are definition words: They
2881: define other words. @code{Constant} is another definition word:
2882:
2883: @example
2884: 5 constant foo
2885: foo .
2886: @end example
2887:
2888: You can also use the prefixes @code{2} (double-cell) and @code{f}
2889: (floating point) with @code{variable} and @code{constant}.
2890:
2891: You can also define your own defining words. E.g.:
2892:
2893: @example
2894: : variable ( "name" -- )
2895: create 0 , ;
2896: @end example
2897:
2898: You can also define defining words that create words that do something
2899: other than just producing their address:
2900:
2901: @example
2902: : constant ( n "name" -- )
2903: create ,
2904: does> ( -- n )
1.50 anton 2905: ( addr ) @@ ;
1.48 anton 2906:
2907: 5 constant foo
2908: foo .
2909: @end example
2910:
2911: The definition of @code{constant} above ends at the @code{does>}; i.e.,
2912: @code{does>} replaces @code{;}, but it also does something else: It
2913: changes the last defined word such that it pushes the address of the
2914: body of the word and then performs the code after the @code{does>}
2915: whenever it is called.
2916:
2917: In the example above, @code{constant} uses @code{,} to store 5 into the
2918: body of @code{foo}. When @code{foo} executes, it pushes the address of
2919: the body onto the stack, then (in the code after the @code{does>})
2920: fetches the 5 from there.
2921:
2922: The stack comment near the @code{does>} reflects the stack effect of the
2923: defined word, not the stack effect of the code after the @code{does>}
2924: (the difference is that the code expects the address of the body that
2925: the stack comment does not show).
2926:
2927: You can use these definition words to do factoring in cases that involve
2928: (other) definition words. E.g., a field offset is always added to an
2929: address. Instead of defining
2930:
2931: @example
2932: 2 cells constant offset-field1
2933: @end example
2934:
2935: and using this like
2936:
2937: @example
2938: ( addr ) offset-field1 +
2939: @end example
2940:
2941: you can define a definition word
2942:
2943: @example
2944: : simple-field ( n "name" -- )
2945: create ,
2946: does> ( n1 -- n1+n )
1.50 anton 2947: ( addr ) @@ + ;
1.48 anton 2948: @end example
1.21 crook 2949:
1.48 anton 2950: Definition and use of field offsets now look like this:
1.21 crook 2951:
1.48 anton 2952: @example
2953: 2 cells simple-field field1
1.60 anton 2954: create mystruct 4 cells allot
2955: mystruct .s field1 .s drop
1.48 anton 2956: @end example
1.21 crook 2957:
1.48 anton 2958: If you want to do something with the word without performing the code
2959: after the @code{does>}, you can access the body of a @code{create}d word
2960: with @code{>body ( xt -- addr )}:
1.21 crook 2961:
1.48 anton 2962: @example
2963: : value ( n "name" -- )
2964: create ,
2965: does> ( -- n1 )
1.50 anton 2966: @@ ;
1.48 anton 2967: : to ( n "name" -- )
2968: ' >body ! ;
1.21 crook 2969:
1.48 anton 2970: 5 value foo
2971: foo .
2972: 7 to foo
2973: foo .
2974: @end example
1.21 crook 2975:
1.141 anton 2976: @quotation Assignment
1.48 anton 2977: Define @code{defer ( "name" -- )}, which creates a word that stores an
2978: XT (at the start the XT of @code{abort}), and upon execution
2979: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
2980: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
2981: recursion is one application of @code{defer}.
1.141 anton 2982: @end quotation
1.29 crook 2983:
1.66 anton 2984: Reference: @ref{User-defined Defining Words}.
2985:
2986:
1.48 anton 2987: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
2988: @section Arrays and Records
1.66 anton 2989: @cindex arrays tutorial
2990: @cindex records tutorial
2991: @cindex structs tutorial
1.29 crook 2992:
1.48 anton 2993: Forth has no standard words for defining data structures such as arrays
2994: and records (structs in C terminology), but you can build them yourself
2995: based on address arithmetic. You can also define words for defining
2996: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 2997:
1.48 anton 2998: One of the first projects a Forth newcomer sets out upon when learning
2999: about defining words is an array defining word (possibly for
3000: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3001: learn something from it. However, don't be disappointed when you later
3002: learn that you have little use for these words (inappropriate use would
3003: be even worse). I have not yet found a set of useful array words yet;
3004: the needs are just too diverse, and named, global arrays (the result of
3005: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3006: consider how to pass them as parameters). Another such project is a set
3007: of words to help dealing with strings.
1.29 crook 3008:
1.48 anton 3009: On the other hand, there is a useful set of record words, and it has
3010: been defined in @file{compat/struct.fs}; these words are predefined in
3011: Gforth. They are explained in depth elsewhere in this manual (see
3012: @pxref{Structures}). The @code{simple-field} example above is
3013: simplified variant of fields in this package.
1.21 crook 3014:
3015:
1.48 anton 3016: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3017: @section @code{POSTPONE}
1.66 anton 3018: @cindex postpone tutorial
1.21 crook 3019:
1.48 anton 3020: You can compile the compilation semantics (instead of compiling the
3021: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3022:
1.48 anton 3023: @example
3024: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3025: POSTPONE + ; immediate
1.48 anton 3026: : foo ( n1 n2 -- n )
3027: MY-+ ;
3028: 1 2 foo .
3029: see foo
3030: @end example
1.21 crook 3031:
1.48 anton 3032: During the definition of @code{foo} the text interpreter performs the
3033: compilation semantics of @code{MY-+}, which performs the compilation
3034: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3035:
3036: This example also displays separate stack comments for the compilation
3037: semantics and for the stack effect of the compiled code. For words with
3038: default compilation semantics these stack effects are usually not
3039: displayed; the stack effect of the compilation semantics is always
3040: @code{( -- )} for these words, the stack effect for the compiled code is
3041: the stack effect of the interpretation semantics.
3042:
3043: Note that the state of the interpreter does not come into play when
3044: performing the compilation semantics in this way. You can also perform
3045: it interpretively, e.g.:
3046:
3047: @example
3048: : foo2 ( n1 n2 -- n )
3049: [ MY-+ ] ;
3050: 1 2 foo .
3051: see foo
3052: @end example
1.21 crook 3053:
1.48 anton 3054: However, there are some broken Forth systems where this does not always
1.62 crook 3055: work, and therefore this practice was been declared non-standard in
1.48 anton 3056: 1999.
3057: @c !! repair.fs
3058:
3059: Here is another example for using @code{POSTPONE}:
1.44 crook 3060:
1.48 anton 3061: @example
3062: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3063: POSTPONE negate POSTPONE + ; immediate compile-only
3064: : bar ( n1 n2 -- n )
3065: MY-- ;
3066: 2 1 bar .
3067: see bar
3068: @end example
1.21 crook 3069:
1.48 anton 3070: You can define @code{ENDIF} in this way:
1.21 crook 3071:
1.48 anton 3072: @example
3073: : ENDIF ( Compilation: orig -- )
3074: POSTPONE then ; immediate
3075: @end example
1.21 crook 3076:
1.141 anton 3077: @quotation Assignment
1.48 anton 3078: Write @code{MY-2DUP} that has compilation semantics equivalent to
3079: @code{2dup}, but compiles @code{over over}.
1.141 anton 3080: @end quotation
1.29 crook 3081:
1.66 anton 3082: @c !! @xref{Macros} for reference
3083:
3084:
1.48 anton 3085: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3086: @section @code{Literal}
1.66 anton 3087: @cindex literal tutorial
1.29 crook 3088:
1.48 anton 3089: You cannot @code{POSTPONE} numbers:
1.21 crook 3090:
1.48 anton 3091: @example
3092: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3093: @end example
3094:
1.48 anton 3095: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3096:
1.48 anton 3097: @example
3098: : [FOO] ( compilation: --; run-time: -- n )
3099: 500 POSTPONE literal ; immediate
1.29 crook 3100:
1.60 anton 3101: : flip [FOO] ;
1.48 anton 3102: flip .
3103: see flip
3104: @end example
1.29 crook 3105:
1.48 anton 3106: @code{LITERAL} consumes a number at compile-time (when it's compilation
3107: semantics are executed) and pushes it at run-time (when the code it
3108: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3109: number computed at compile time into the current word:
1.29 crook 3110:
1.48 anton 3111: @example
3112: : bar ( -- n )
3113: [ 2 2 + ] literal ;
3114: see bar
3115: @end example
1.29 crook 3116:
1.141 anton 3117: @quotation Assignment
1.48 anton 3118: Write @code{]L} which allows writing the example above as @code{: bar (
3119: -- n ) [ 2 2 + ]L ;}
1.141 anton 3120: @end quotation
1.48 anton 3121:
1.66 anton 3122: @c !! @xref{Macros} for reference
3123:
1.48 anton 3124:
3125: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3126: @section Advanced macros
1.66 anton 3127: @cindex macros, advanced tutorial
3128: @cindex run-time code generation, tutorial
1.48 anton 3129:
1.66 anton 3130: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3131: Execution Tokens}. It frequently performs @code{execute}, a relatively
3132: expensive operation in some Forth implementations. You can use
1.48 anton 3133: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3134: and produce a word that contains the word to be performed directly:
3135:
3136: @c use ]] ... [[
3137: @example
3138: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3139: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3140: \ array beginning at addr and containing u elements
3141: @{ xt @}
3142: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3143: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3144: 1 cells POSTPONE literal POSTPONE +loop ;
3145:
3146: : sum-array ( addr u -- n )
3147: 0 rot rot [ ' + compile-map-array ] ;
3148: see sum-array
3149: a 5 sum-array .
3150: @end example
3151:
3152: You can use the full power of Forth for generating the code; here's an
3153: example where the code is generated in a loop:
3154:
3155: @example
3156: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3157: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3158: POSTPONE tuck POSTPONE @@
1.48 anton 3159: POSTPONE literal POSTPONE * POSTPONE +
3160: POSTPONE swap POSTPONE cell+ ;
3161:
3162: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3163: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3164: 0 postpone literal postpone swap
3165: [ ' compile-vmul-step compile-map-array ]
3166: postpone drop ;
3167: see compile-vmul
3168:
3169: : a-vmul ( addr -- n )
1.51 pazsan 3170: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3171: [ a 5 compile-vmul ] ;
3172: see a-vmul
3173: a a-vmul .
3174: @end example
3175:
3176: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3177: also use @code{map-array} instead (try it now!).
1.48 anton 3178:
3179: You can use this technique for efficient multiplication of large
3180: matrices. In matrix multiplication, you multiply every line of one
3181: matrix with every column of the other matrix. You can generate the code
3182: for one line once, and use it for every column. The only downside of
3183: this technique is that it is cumbersome to recover the memory consumed
3184: by the generated code when you are done (and in more complicated cases
3185: it is not possible portably).
3186:
1.66 anton 3187: @c !! @xref{Macros} for reference
3188:
3189:
1.48 anton 3190: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3191: @section Compilation Tokens
1.66 anton 3192: @cindex compilation tokens, tutorial
3193: @cindex CT, tutorial
1.48 anton 3194:
3195: This section is Gforth-specific. You can skip it.
3196:
3197: @code{' word compile,} compiles the interpretation semantics. For words
3198: with default compilation semantics this is the same as performing the
3199: compilation semantics. To represent the compilation semantics of other
3200: words (e.g., words like @code{if} that have no interpretation
3201: semantics), Gforth has the concept of a compilation token (CT,
3202: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3203: You can perform the compilation semantics represented by a CT with
3204: @code{execute}:
1.29 crook 3205:
1.48 anton 3206: @example
3207: : foo2 ( n1 n2 -- n )
3208: [ comp' + execute ] ;
3209: see foo
3210: @end example
1.29 crook 3211:
1.48 anton 3212: You can compile the compilation semantics represented by a CT with
3213: @code{postpone,}:
1.30 anton 3214:
1.48 anton 3215: @example
3216: : foo3 ( -- )
3217: [ comp' + postpone, ] ;
3218: see foo3
3219: @end example
1.30 anton 3220:
1.51 pazsan 3221: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3222: @code{comp'} is particularly useful for words that have no
3223: interpretation semantics:
1.29 crook 3224:
1.30 anton 3225: @example
1.48 anton 3226: ' if
1.60 anton 3227: comp' if .s 2drop
1.30 anton 3228: @end example
3229:
1.66 anton 3230: Reference: @ref{Tokens for Words}.
3231:
1.29 crook 3232:
1.48 anton 3233: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3234: @section Wordlists and Search Order
1.66 anton 3235: @cindex wordlists tutorial
3236: @cindex search order, tutorial
1.48 anton 3237:
3238: The dictionary is not just a memory area that allows you to allocate
3239: memory with @code{allot}, it also contains the Forth words, arranged in
3240: several wordlists. When searching for a word in a wordlist,
3241: conceptually you start searching at the youngest and proceed towards
3242: older words (in reality most systems nowadays use hash-tables); i.e., if
3243: you define a word with the same name as an older word, the new word
3244: shadows the older word.
3245:
3246: Which wordlists are searched in which order is determined by the search
3247: order. You can display the search order with @code{order}. It displays
3248: first the search order, starting with the wordlist searched first, then
3249: it displays the wordlist that will contain newly defined words.
1.21 crook 3250:
1.48 anton 3251: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3252:
1.48 anton 3253: @example
3254: wordlist constant mywords
3255: @end example
1.21 crook 3256:
1.48 anton 3257: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3258: defined words (the @emph{current} wordlist):
1.21 crook 3259:
1.48 anton 3260: @example
3261: mywords set-current
3262: order
3263: @end example
1.26 crook 3264:
1.48 anton 3265: Gforth does not display a name for the wordlist in @code{mywords}
3266: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3267:
1.48 anton 3268: You can get the current wordlist with @code{get-current ( -- wid)}. If
3269: you want to put something into a specific wordlist without overall
3270: effect on the current wordlist, this typically looks like this:
1.21 crook 3271:
1.48 anton 3272: @example
3273: get-current mywords set-current ( wid )
3274: create someword
3275: ( wid ) set-current
3276: @end example
1.21 crook 3277:
1.48 anton 3278: You can write the search order with @code{set-order ( wid1 .. widn n --
3279: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3280: searched wordlist is topmost.
1.21 crook 3281:
1.48 anton 3282: @example
3283: get-order mywords swap 1+ set-order
3284: order
3285: @end example
1.21 crook 3286:
1.48 anton 3287: Yes, the order of wordlists in the output of @code{order} is reversed
3288: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3289:
1.141 anton 3290: @quotation Assignment
1.48 anton 3291: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3292: wordlist to the search order. Define @code{previous ( -- )}, which
3293: removes the first searched wordlist from the search order. Experiment
3294: with boundary conditions (you will see some crashes or situations that
3295: are hard or impossible to leave).
1.141 anton 3296: @end quotation
1.21 crook 3297:
1.48 anton 3298: The search order is a powerful foundation for providing features similar
3299: to Modula-2 modules and C++ namespaces. However, trying to modularize
3300: programs in this way has disadvantages for debugging and reuse/factoring
3301: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3302: though). These disadvantages are not so clear in other
1.82 anton 3303: languages/programming environments, because these languages are not so
1.48 anton 3304: strong in debugging and reuse.
1.21 crook 3305:
1.66 anton 3306: @c !! example
3307:
3308: Reference: @ref{Word Lists}.
1.21 crook 3309:
1.29 crook 3310: @c ******************************************************************
1.48 anton 3311: @node Introduction, Words, Tutorial, Top
1.29 crook 3312: @comment node-name, next, previous, up
3313: @chapter An Introduction to ANS Forth
3314: @cindex Forth - an introduction
1.21 crook 3315:
1.83 anton 3316: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3317: that it is slower-paced in its examples, but uses them to dive deep into
3318: explaining Forth internals (not covered by the Tutorial). Apart from
3319: that, this chapter covers far less material. It is suitable for reading
3320: without using a computer.
3321:
1.29 crook 3322: The primary purpose of this manual is to document Gforth. However, since
3323: Forth is not a widely-known language and there is a lack of up-to-date
3324: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3325: material. For other sources of Forth-related
3326: information, see @ref{Forth-related information}.
1.21 crook 3327:
1.29 crook 3328: The examples in this section should work on any ANS Forth; the
3329: output shown was produced using Gforth. Each example attempts to
3330: reproduce the exact output that Gforth produces. If you try out the
3331: examples (and you should), what you should type is shown @kbd{like this}
3332: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3333: that, where the example shows @key{RET} it means that you should
1.29 crook 3334: press the ``carriage return'' key. Unfortunately, some output formats for
3335: this manual cannot show the difference between @kbd{this} and
3336: @code{this} which will make trying out the examples harder (but not
3337: impossible).
1.21 crook 3338:
1.29 crook 3339: Forth is an unusual language. It provides an interactive development
3340: environment which includes both an interpreter and compiler. Forth
3341: programming style encourages you to break a problem down into many
3342: @cindex factoring
3343: small fragments (@dfn{factoring}), and then to develop and test each
3344: fragment interactively. Forth advocates assert that breaking the
3345: edit-compile-test cycle used by conventional programming languages can
3346: lead to great productivity improvements.
1.21 crook 3347:
1.29 crook 3348: @menu
1.67 anton 3349: * Introducing the Text Interpreter::
3350: * Stacks and Postfix notation::
3351: * Your first definition::
3352: * How does that work?::
3353: * Forth is written in Forth::
3354: * Review - elements of a Forth system::
3355: * Where to go next::
3356: * Exercises::
1.29 crook 3357: @end menu
1.21 crook 3358:
1.29 crook 3359: @comment ----------------------------------------------
3360: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3361: @section Introducing the Text Interpreter
3362: @cindex text interpreter
3363: @cindex outer interpreter
1.21 crook 3364:
1.30 anton 3365: @c IMO this is too detailed and the pace is too slow for
3366: @c an introduction. If you know German, take a look at
3367: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3368: @c to see how I do it - anton
3369:
1.44 crook 3370: @c nac-> Where I have accepted your comments 100% and modified the text
3371: @c accordingly, I have deleted your comments. Elsewhere I have added a
3372: @c response like this to attempt to rationalise what I have done. Of
3373: @c course, this is a very clumsy mechanism for something that would be
3374: @c done far more efficiently over a beer. Please delete any dialogue
3375: @c you consider closed.
3376:
1.29 crook 3377: When you invoke the Forth image, you will see a startup banner printed
3378: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3379: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3380: its command line interpreter, which is called the @dfn{Text Interpreter}
3381: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3382: about the text interpreter as you read through this chapter, for more
3383: detail @pxref{The Text Interpreter}).
1.21 crook 3384:
1.29 crook 3385: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3386: input. Type a number and press the @key{RET} key:
1.21 crook 3387:
1.26 crook 3388: @example
1.30 anton 3389: @kbd{45@key{RET}} ok
1.26 crook 3390: @end example
1.21 crook 3391:
1.29 crook 3392: Rather than give you a prompt to invite you to input something, the text
3393: interpreter prints a status message @i{after} it has processed a line
3394: of input. The status message in this case (``@code{ ok}'' followed by
3395: carriage-return) indicates that the text interpreter was able to process
3396: all of your input successfully. Now type something illegal:
3397:
3398: @example
1.30 anton 3399: @kbd{qwer341@key{RET}}
1.134 anton 3400: *the terminal*:2: Undefined word
3401: >>>qwer341<<<
3402: Backtrace:
3403: $2A95B42A20 throw
3404: $2A95B57FB8 no.extensions
1.29 crook 3405: @end example
1.23 crook 3406:
1.134 anton 3407: The exact text, other than the ``Undefined word'' may differ slightly
3408: on your system, but the effect is the same; when the text interpreter
1.29 crook 3409: detects an error, it discards any remaining text on a line, resets
1.134 anton 3410: certain internal state and prints an error message. For a detailed
3411: description of error messages see @ref{Error messages}.
1.23 crook 3412:
1.29 crook 3413: The text interpreter waits for you to press carriage-return, and then
3414: processes your input line. Starting at the beginning of the line, it
3415: breaks the line into groups of characters separated by spaces. For each
3416: group of characters in turn, it makes two attempts to do something:
1.23 crook 3417:
1.29 crook 3418: @itemize @bullet
3419: @item
1.44 crook 3420: @cindex name dictionary
1.29 crook 3421: It tries to treat it as a command. It does this by searching a @dfn{name
3422: dictionary}. If the group of characters matches an entry in the name
3423: dictionary, the name dictionary provides the text interpreter with
3424: information that allows the text interpreter perform some actions. In
3425: Forth jargon, we say that the group
3426: @cindex word
3427: @cindex definition
3428: @cindex execution token
3429: @cindex xt
3430: of characters names a @dfn{word}, that the dictionary search returns an
3431: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3432: word, and that the text interpreter executes the xt. Often, the terms
3433: @dfn{word} and @dfn{definition} are used interchangeably.
3434: @item
3435: If the text interpreter fails to find a match in the name dictionary, it
3436: tries to treat the group of characters as a number in the current number
3437: base (when you start up Forth, the current number base is base 10). If
3438: the group of characters legitimately represents a number, the text
3439: interpreter pushes the number onto a stack (we'll learn more about that
3440: in the next section).
3441: @end itemize
1.23 crook 3442:
1.29 crook 3443: If the text interpreter is unable to do either of these things with any
3444: group of characters, it discards the group of characters and the rest of
3445: the line, then prints an error message. If the text interpreter reaches
3446: the end of the line without error, it prints the status message ``@code{ ok}''
3447: followed by carriage-return.
1.21 crook 3448:
1.29 crook 3449: This is the simplest command we can give to the text interpreter:
1.23 crook 3450:
3451: @example
1.30 anton 3452: @key{RET} ok
1.23 crook 3453: @end example
1.21 crook 3454:
1.29 crook 3455: The text interpreter did everything we asked it to do (nothing) without
3456: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3457: command:
1.21 crook 3458:
1.23 crook 3459: @example
1.30 anton 3460: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3461: *the terminal*:3: Undefined word
3462: 12 dup >>>fred<<< dup
3463: Backtrace:
3464: $2A95B42A20 throw
3465: $2A95B57FB8 no.extensions
1.23 crook 3466: @end example
1.21 crook 3467:
1.29 crook 3468: When you press the carriage-return key, the text interpreter starts to
3469: work its way along the line:
1.21 crook 3470:
1.29 crook 3471: @itemize @bullet
3472: @item
3473: When it gets to the space after the @code{2}, it takes the group of
3474: characters @code{12} and looks them up in the name
3475: dictionary@footnote{We can't tell if it found them or not, but assume
3476: for now that it did not}. There is no match for this group of characters
3477: in the name dictionary, so it tries to treat them as a number. It is
3478: able to do this successfully, so it puts the number, 12, ``on the stack''
3479: (whatever that means).
3480: @item
3481: The text interpreter resumes scanning the line and gets the next group
3482: of characters, @code{dup}. It looks it up in the name dictionary and
3483: (you'll have to take my word for this) finds it, and executes the word
3484: @code{dup} (whatever that means).
3485: @item
3486: Once again, the text interpreter resumes scanning the line and gets the
3487: group of characters @code{fred}. It looks them up in the name
3488: dictionary, but can't find them. It tries to treat them as a number, but
3489: they don't represent any legal number.
3490: @end itemize
1.21 crook 3491:
1.29 crook 3492: At this point, the text interpreter gives up and prints an error
3493: message. The error message shows exactly how far the text interpreter
3494: got in processing the line. In particular, it shows that the text
3495: interpreter made no attempt to do anything with the final character
3496: group, @code{dup}, even though we have good reason to believe that the
3497: text interpreter would have no problem looking that word up and
3498: executing it a second time.
1.21 crook 3499:
3500:
1.29 crook 3501: @comment ----------------------------------------------
3502: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3503: @section Stacks, postfix notation and parameter passing
3504: @cindex text interpreter
3505: @cindex outer interpreter
1.21 crook 3506:
1.29 crook 3507: In procedural programming languages (like C and Pascal), the
3508: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3509: functions or procedures are called with @dfn{explicit parameters}. For
3510: example, in C we might write:
1.21 crook 3511:
1.23 crook 3512: @example
1.29 crook 3513: total = total + new_volume(length,height,depth);
1.23 crook 3514: @end example
1.21 crook 3515:
1.23 crook 3516: @noindent
1.29 crook 3517: where new_volume is a function-call to another piece of code, and total,
3518: length, height and depth are all variables. length, height and depth are
3519: parameters to the function-call.
1.21 crook 3520:
1.29 crook 3521: In Forth, the equivalent of the function or procedure is the
3522: @dfn{definition} and parameters are implicitly passed between
3523: definitions using a shared stack that is visible to the
3524: programmer. Although Forth does support variables, the existence of the
3525: stack means that they are used far less often than in most other
3526: programming languages. When the text interpreter encounters a number, it
3527: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3528: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3529: used for any operation is implied unambiguously by the operation being
3530: performed. The stack used for all integer operations is called the @dfn{data
3531: stack} and, since this is the stack used most commonly, references to
3532: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3533:
1.29 crook 3534: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3535:
1.23 crook 3536: @example
1.30 anton 3537: @kbd{1 2 3@key{RET}} ok
1.23 crook 3538: @end example
1.21 crook 3539:
1.29 crook 3540: Then this instructs the text interpreter to placed three numbers on the
3541: (data) stack. An analogy for the behaviour of the stack is to take a
3542: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3543: the table. The 3 was the last card onto the pile (``last-in'') and if
3544: you take a card off the pile then, unless you're prepared to fiddle a
3545: bit, the card that you take off will be the 3 (``first-out''). The
3546: number that will be first-out of the stack is called the @dfn{top of
3547: stack}, which
3548: @cindex TOS definition
3549: is often abbreviated to @dfn{TOS}.
1.21 crook 3550:
1.29 crook 3551: To understand how parameters are passed in Forth, consider the
3552: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3553: be surprised to learn that this definition performs addition. More
3554: precisely, it adds two number together and produces a result. Where does
3555: it get the two numbers from? It takes the top two numbers off the
3556: stack. Where does it place the result? On the stack. You can act-out the
3557: behaviour of @code{+} with your playing cards like this:
1.21 crook 3558:
3559: @itemize @bullet
3560: @item
1.29 crook 3561: Pick up two cards from the stack on the table
1.21 crook 3562: @item
1.29 crook 3563: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3564: numbers''
1.21 crook 3565: @item
1.29 crook 3566: Decide that the answer is 5
1.21 crook 3567: @item
1.29 crook 3568: Shuffle the two cards back into the pack and find a 5
1.21 crook 3569: @item
1.29 crook 3570: Put a 5 on the remaining ace that's on the table.
1.21 crook 3571: @end itemize
3572:
1.29 crook 3573: If you don't have a pack of cards handy but you do have Forth running,
3574: you can use the definition @code{.s} to show the current state of the stack,
3575: without affecting the stack. Type:
1.21 crook 3576:
3577: @example
1.124 anton 3578: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3579: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3580: @end example
3581:
1.124 anton 3582: The text interpreter looks up the word @code{clearstacks} and executes
3583: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3584: left on it by earlier examples. The text interpreter pushes each of the
3585: three numbers in turn onto the stack. Finally, the text interpreter
3586: looks up the word @code{.s} and executes it. The effect of executing
3587: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3588: followed by a list of all the items on the stack; the item on the far
3589: right-hand side is the TOS.
1.21 crook 3590:
1.29 crook 3591: You can now type:
1.21 crook 3592:
1.29 crook 3593: @example
1.30 anton 3594: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3595: @end example
1.21 crook 3596:
1.29 crook 3597: @noindent
3598: which is correct; there are now 2 items on the stack and the result of
3599: the addition is 5.
1.23 crook 3600:
1.29 crook 3601: If you're playing with cards, try doing a second addition: pick up the
3602: two cards, work out that their sum is 6, shuffle them into the pack,
3603: look for a 6 and place that on the table. You now have just one item on
3604: the stack. What happens if you try to do a third addition? Pick up the
3605: first card, pick up the second card -- ah! There is no second card. This
3606: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3607: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3608: Underflow or an Invalid Memory Address error).
1.23 crook 3609:
1.29 crook 3610: The opposite situation to a stack underflow is a @dfn{stack overflow},
3611: which simply accepts that there is a finite amount of storage space
3612: reserved for the stack. To stretch the playing card analogy, if you had
3613: enough packs of cards and you piled the cards up on the table, you would
3614: eventually be unable to add another card; you'd hit the ceiling. Gforth
3615: allows you to set the maximum size of the stacks. In general, the only
3616: time that you will get a stack overflow is because a definition has a
3617: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3618:
1.29 crook 3619: There's one final use for the playing card analogy. If you model your
3620: stack using a pack of playing cards, the maximum number of items on
3621: your stack will be 52 (I assume you didn't use the Joker). The maximum
3622: @i{value} of any item on the stack is 13 (the King). In fact, the only
3623: possible numbers are positive integer numbers 1 through 13; you can't
3624: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3625: think about some of the cards, you can accommodate different
3626: numbers. For example, you could think of the Jack as representing 0,
3627: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3628: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3629: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3630:
1.29 crook 3631: In that analogy, the limit was the amount of information that a single
3632: stack entry could hold, and Forth has a similar limit. In Forth, the
3633: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3634: implementation dependent and affects the maximum value that a stack
3635: entry can hold. A Standard Forth provides a cell size of at least
3636: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3637:
1.29 crook 3638: Forth does not do any type checking for you, so you are free to
3639: manipulate and combine stack items in any way you wish. A convenient way
3640: of treating stack items is as 2's complement signed integers, and that
3641: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3642:
1.29 crook 3643: @example
1.30 anton 3644: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3645: @end example
1.21 crook 3646:
1.29 crook 3647: If you use numbers and definitions like @code{+} in order to turn Forth
3648: into a great big pocket calculator, you will realise that it's rather
3649: different from a normal calculator. Rather than typing 2 + 3 = you had
3650: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3651: result). The terminology used to describe this difference is to say that
3652: your calculator uses @dfn{Infix Notation} (parameters and operators are
3653: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3654: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3655:
1.29 crook 3656: Whilst postfix notation might look confusing to begin with, it has
3657: several important advantages:
1.21 crook 3658:
1.23 crook 3659: @itemize @bullet
3660: @item
1.29 crook 3661: it is unambiguous
1.23 crook 3662: @item
1.29 crook 3663: it is more concise
1.23 crook 3664: @item
1.29 crook 3665: it fits naturally with a stack-based system
1.23 crook 3666: @end itemize
1.21 crook 3667:
1.29 crook 3668: To examine these claims in more detail, consider these sums:
1.21 crook 3669:
1.29 crook 3670: @example
3671: 6 + 5 * 4 =
3672: 4 * 5 + 6 =
3673: @end example
1.21 crook 3674:
1.29 crook 3675: If you're just learning maths or your maths is very rusty, you will
3676: probably come up with the answer 44 for the first and 26 for the
3677: second. If you are a bit of a whizz at maths you will remember the
3678: @i{convention} that multiplication takes precendence over addition, and
3679: you'd come up with the answer 26 both times. To explain the answer 26
3680: to someone who got the answer 44, you'd probably rewrite the first sum
3681: like this:
1.21 crook 3682:
1.29 crook 3683: @example
3684: 6 + (5 * 4) =
3685: @end example
1.21 crook 3686:
1.29 crook 3687: If what you really wanted was to perform the addition before the
3688: multiplication, you would have to use parentheses to force it.
1.21 crook 3689:
1.29 crook 3690: If you did the first two sums on a pocket calculator you would probably
3691: get the right answers, unless you were very cautious and entered them using
3692: these keystroke sequences:
1.21 crook 3693:
1.29 crook 3694: 6 + 5 = * 4 =
3695: 4 * 5 = + 6 =
1.21 crook 3696:
1.29 crook 3697: Postfix notation is unambiguous because the order that the operators
3698: are applied is always explicit; that also means that parentheses are
3699: never required. The operators are @i{active} (the act of quoting the
3700: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3701:
1.29 crook 3702: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3703: equivalent ways:
1.26 crook 3704:
3705: @example
1.29 crook 3706: 6 5 4 * + or:
3707: 5 4 * 6 +
1.26 crook 3708: @end example
1.23 crook 3709:
1.29 crook 3710: An important thing that you should notice about this notation is that
3711: the @i{order} of the numbers does not change; if you want to subtract
3712: 2 from 10 you type @code{10 2 -}.
1.1 anton 3713:
1.29 crook 3714: The reason that Forth uses postfix notation is very simple to explain: it
3715: makes the implementation extremely simple, and it follows naturally from
3716: using the stack as a mechanism for passing parameters. Another way of
3717: thinking about this is to realise that all Forth definitions are
3718: @i{active}; they execute as they are encountered by the text
3719: interpreter. The result of this is that the syntax of Forth is trivially
3720: simple.
1.1 anton 3721:
3722:
3723:
1.29 crook 3724: @comment ----------------------------------------------
3725: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3726: @section Your first Forth definition
3727: @cindex first definition
1.1 anton 3728:
1.29 crook 3729: Until now, the examples we've seen have been trivial; we've just been
3730: using Forth as a bigger-than-pocket calculator. Also, each calculation
3731: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3732: again@footnote{That's not quite true. If you press the up-arrow key on
3733: your keyboard you should be able to scroll back to any earlier command,
3734: edit it and re-enter it.} In this section we'll see how to add new
3735: words to Forth's vocabulary.
1.1 anton 3736:
1.29 crook 3737: The easiest way to create a new word is to use a @dfn{colon
3738: definition}. We'll define a few and try them out before worrying too
3739: much about how they work. Try typing in these examples; be careful to
3740: copy the spaces accurately:
1.1 anton 3741:
1.29 crook 3742: @example
3743: : add-two 2 + . ;
3744: : greet ." Hello and welcome" ;
3745: : demo 5 add-two ;
3746: @end example
1.1 anton 3747:
1.29 crook 3748: @noindent
3749: Now try them out:
1.1 anton 3750:
1.29 crook 3751: @example
1.30 anton 3752: @kbd{greet@key{RET}} Hello and welcome ok
3753: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3754: @kbd{4 add-two@key{RET}} 6 ok
3755: @kbd{demo@key{RET}} 7 ok
3756: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3757: @end example
1.1 anton 3758:
1.29 crook 3759: The first new thing that we've introduced here is the pair of words
3760: @code{:} and @code{;}. These are used to start and terminate a new
3761: definition, respectively. The first word after the @code{:} is the name
3762: for the new definition.
1.1 anton 3763:
1.29 crook 3764: As you can see from the examples, a definition is built up of words that
3765: have already been defined; Forth makes no distinction between
3766: definitions that existed when you started the system up, and those that
3767: you define yourself.
1.1 anton 3768:
1.29 crook 3769: The examples also introduce the words @code{.} (dot), @code{."}
3770: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3771: the stack and displays it. It's like @code{.s} except that it only
3772: displays the top item of the stack and it is destructive; after it has
3773: executed, the number is no longer on the stack. There is always one
3774: space printed after the number, and no spaces before it. Dot-quote
3775: defines a string (a sequence of characters) that will be printed when
3776: the word is executed. The string can contain any printable characters
3777: except @code{"}. A @code{"} has a special function; it is not a Forth
3778: word but it acts as a delimiter (the way that delimiters work is
3779: described in the next section). Finally, @code{dup} duplicates the value
3780: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3781:
1.29 crook 3782: We already know that the text interpreter searches through the
3783: dictionary to locate names. If you've followed the examples earlier, you
3784: will already have a definition called @code{add-two}. Lets try modifying
3785: it by typing in a new definition:
1.1 anton 3786:
1.29 crook 3787: @example
1.30 anton 3788: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3789: @end example
1.5 anton 3790:
1.29 crook 3791: Forth recognised that we were defining a word that already exists, and
3792: printed a message to warn us of that fact. Let's try out the new
3793: definition:
1.5 anton 3794:
1.29 crook 3795: @example
1.30 anton 3796: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3797: @end example
1.1 anton 3798:
1.29 crook 3799: @noindent
3800: All that we've actually done here, though, is to create a new
3801: definition, with a particular name. The fact that there was already a
3802: definition with the same name did not make any difference to the way
3803: that the new definition was created (except that Forth printed a warning
3804: message). The old definition of add-two still exists (try @code{demo}
3805: again to see that this is true). Any new definition will use the new
3806: definition of @code{add-two}, but old definitions continue to use the
3807: version that already existed at the time that they were @code{compiled}.
1.1 anton 3808:
1.29 crook 3809: Before you go on to the next section, try defining and redefining some
3810: words of your own.
1.1 anton 3811:
1.29 crook 3812: @comment ----------------------------------------------
3813: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3814: @section How does that work?
3815: @cindex parsing words
1.1 anton 3816:
1.30 anton 3817: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3818:
3819: @c Is it a good idea to talk about the interpretation semantics of a
3820: @c number? We don't have an xt to go along with it. - anton
3821:
3822: @c Now that I have eliminated execution semantics, I wonder if it would not
3823: @c be better to keep them (or add run-time semantics), to make it easier to
3824: @c explain what compilation semantics usually does. - anton
3825:
1.44 crook 3826: @c nac-> I removed the term ``default compilation sematics'' from the
3827: @c introductory chapter. Removing ``execution semantics'' was making
3828: @c everything simpler to explain, then I think the use of this term made
3829: @c everything more complex again. I replaced it with ``default
3830: @c semantics'' (which is used elsewhere in the manual) by which I mean
3831: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3832: @c flag set''.
3833:
3834: @c anton: I have eliminated default semantics (except in one place where it
3835: @c means "default interpretation and compilation semantics"), because it
3836: @c makes no sense in the presence of combined words. I reverted to
3837: @c "execution semantics" where necessary.
3838:
3839: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3840: @c section (and, unusually for me, I think I even made it shorter!). See
3841: @c what you think -- I know I have not addressed your primary concern
3842: @c that it is too heavy-going for an introduction. From what I understood
3843: @c of your course notes it looks as though they might be a good framework.
3844: @c Things that I've tried to capture here are some things that came as a
3845: @c great revelation here when I first understood them. Also, I like the
3846: @c fact that a very simple code example shows up almost all of the issues
3847: @c that you need to understand to see how Forth works. That's unique and
3848: @c worthwhile to emphasise.
3849:
1.83 anton 3850: @c anton: I think it's a good idea to present the details, especially those
3851: @c that you found to be a revelation, and probably the tutorial tries to be
3852: @c too superficial and does not get some of the things across that make
3853: @c Forth special. I do believe that most of the time these things should
3854: @c be discussed at the end of a section or in separate sections instead of
3855: @c in the middle of a section (e.g., the stuff you added in "User-defined
3856: @c defining words" leads in a completely different direction from the rest
3857: @c of the section).
3858:
1.29 crook 3859: Now we're going to take another look at the definition of @code{add-two}
3860: from the previous section. From our knowledge of the way that the text
3861: interpreter works, we would have expected this result when we tried to
3862: define @code{add-two}:
1.21 crook 3863:
1.29 crook 3864: @example
1.44 crook 3865: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 3866: *the terminal*:4: Undefined word
3867: : >>>add-two<<< 2 + . ;
1.29 crook 3868: @end example
1.28 crook 3869:
1.29 crook 3870: The reason that this didn't happen is bound up in the way that @code{:}
3871: works. The word @code{:} does two special things. The first special
3872: thing that it does prevents the text interpreter from ever seeing the
3873: characters @code{add-two}. The text interpreter uses a variable called
3874: @cindex modifying >IN
1.44 crook 3875: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3876: input line. When it encounters the word @code{:} it behaves in exactly
3877: the same way as it does for any other word; it looks it up in the name
3878: dictionary, finds its xt and executes it. When @code{:} executes, it
3879: looks at the input buffer, finds the word @code{add-two} and advances the
3880: value of @code{>IN} to point past it. It then does some other stuff
3881: associated with creating the new definition (including creating an entry
3882: for @code{add-two} in the name dictionary). When the execution of @code{:}
3883: completes, control returns to the text interpreter, which is oblivious
3884: to the fact that it has been tricked into ignoring part of the input
3885: line.
1.21 crook 3886:
1.29 crook 3887: @cindex parsing words
3888: Words like @code{:} -- words that advance the value of @code{>IN} and so
3889: prevent the text interpreter from acting on the whole of the input line
3890: -- are called @dfn{parsing words}.
1.21 crook 3891:
1.29 crook 3892: @cindex @code{state} - effect on the text interpreter
3893: @cindex text interpreter - effect of state
3894: The second special thing that @code{:} does is change the value of a
3895: variable called @code{state}, which affects the way that the text
3896: interpreter behaves. When Gforth starts up, @code{state} has the value
3897: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3898: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 3899: the text interpreter is said to be @dfn{compiling}.
3900:
3901: In this example, the text interpreter is compiling when it processes the
3902: string ``@code{2 + . ;}''. It still breaks the string down into
3903: character sequences in the same way. However, instead of pushing the
3904: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
3905: into the definition of @code{add-two} that will make the number @code{2} get
3906: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
3907: the behaviours of @code{+} and @code{.} are also compiled into the
3908: definition.
3909:
3910: One category of words don't get compiled. These so-called @dfn{immediate
3911: words} get executed (performed @i{now}) regardless of whether the text
3912: interpreter is interpreting or compiling. The word @code{;} is an
3913: immediate word. Rather than being compiled into the definition, it
3914: executes. Its effect is to terminate the current definition, which
3915: includes changing the value of @code{state} back to 0.
3916:
3917: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
3918: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
3919: definition.
1.28 crook 3920:
1.30 anton 3921: In Forth, every word or number can be described in terms of two
1.29 crook 3922: properties:
1.28 crook 3923:
3924: @itemize @bullet
3925: @item
1.29 crook 3926: @cindex interpretation semantics
1.44 crook 3927: Its @dfn{interpretation semantics} describe how it will behave when the
3928: text interpreter encounters it in @dfn{interpret} state. The
3929: interpretation semantics of a word are represented by an @dfn{execution
3930: token}.
1.28 crook 3931: @item
1.29 crook 3932: @cindex compilation semantics
1.44 crook 3933: Its @dfn{compilation semantics} describe how it will behave when the
3934: text interpreter encounters it in @dfn{compile} state. The compilation
3935: semantics of a word are represented in an implementation-dependent way;
3936: Gforth uses a @dfn{compilation token}.
1.29 crook 3937: @end itemize
3938:
3939: @noindent
3940: Numbers are always treated in a fixed way:
3941:
3942: @itemize @bullet
1.28 crook 3943: @item
1.44 crook 3944: When the number is @dfn{interpreted}, its behaviour is to push the
3945: number onto the stack.
1.28 crook 3946: @item
1.30 anton 3947: When the number is @dfn{compiled}, a piece of code is appended to the
3948: current definition that pushes the number when it runs. (In other words,
3949: the compilation semantics of a number are to postpone its interpretation
3950: semantics until the run-time of the definition that it is being compiled
3951: into.)
1.29 crook 3952: @end itemize
3953:
1.44 crook 3954: Words don't behave in such a regular way, but most have @i{default
3955: semantics} which means that they behave like this:
1.29 crook 3956:
3957: @itemize @bullet
1.28 crook 3958: @item
1.30 anton 3959: The @dfn{interpretation semantics} of the word are to do something useful.
3960: @item
1.29 crook 3961: The @dfn{compilation semantics} of the word are to append its
1.30 anton 3962: @dfn{interpretation semantics} to the current definition (so that its
3963: run-time behaviour is to do something useful).
1.28 crook 3964: @end itemize
3965:
1.30 anton 3966: @cindex immediate words
1.44 crook 3967: The actual behaviour of any particular word can be controlled by using
3968: the words @code{immediate} and @code{compile-only} when the word is
3969: defined. These words set flags in the name dictionary entry of the most
3970: recently defined word, and these flags are retrieved by the text
3971: interpreter when it finds the word in the name dictionary.
3972:
3973: A word that is marked as @dfn{immediate} has compilation semantics that
3974: are identical to its interpretation semantics. In other words, it
3975: behaves like this:
1.29 crook 3976:
3977: @itemize @bullet
3978: @item
1.30 anton 3979: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 3980: @item
1.30 anton 3981: The @dfn{compilation semantics} of the word are to do something useful
3982: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 3983: @end itemize
1.28 crook 3984:
1.44 crook 3985: Marking a word as @dfn{compile-only} prohibits the text interpreter from
3986: performing the interpretation semantics of the word directly; an attempt
3987: to do so will generate an error. It is never necessary to use
3988: @code{compile-only} (and it is not even part of ANS Forth, though it is
3989: provided by many implementations) but it is good etiquette to apply it
3990: to a word that will not behave correctly (and might have unexpected
3991: side-effects) in interpret state. For example, it is only legal to use
3992: the conditional word @code{IF} within a definition. If you forget this
3993: and try to use it elsewhere, the fact that (in Gforth) it is marked as
3994: @code{compile-only} allows the text interpreter to generate a helpful
3995: error message rather than subjecting you to the consequences of your
3996: folly.
3997:
1.29 crook 3998: This example shows the difference between an immediate and a
3999: non-immediate word:
1.28 crook 4000:
1.29 crook 4001: @example
4002: : show-state state @@ . ;
4003: : show-state-now show-state ; immediate
4004: : word1 show-state ;
4005: : word2 show-state-now ;
1.28 crook 4006: @end example
1.23 crook 4007:
1.29 crook 4008: The word @code{immediate} after the definition of @code{show-state-now}
4009: makes that word an immediate word. These definitions introduce a new
4010: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4011: variable, and leaves it on the stack. Therefore, the behaviour of
4012: @code{show-state} is to print a number that represents the current value
4013: of @code{state}.
1.28 crook 4014:
1.29 crook 4015: When you execute @code{word1}, it prints the number 0, indicating that
4016: the system is interpreting. When the text interpreter compiled the
4017: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4018: compilation semantics are to append its interpretation semantics to the
1.29 crook 4019: current definition. When you execute @code{word1}, it performs the
1.30 anton 4020: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4021: (and therefore @code{show-state}) are executed, the system is
4022: interpreting.
1.28 crook 4023:
1.30 anton 4024: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4025: you should have seen the number -1 printed, followed by ``@code{
4026: ok}''. When the text interpreter compiled the definition of
4027: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4028: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4029: semantics. It is executed straight away (even before the text
4030: interpreter has moved on to process another group of characters; the
4031: @code{;} in this example). The effect of executing it are to display the
4032: value of @code{state} @i{at the time that the definition of}
4033: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4034: system is compiling at this time. If you execute @code{word2} it does
4035: nothing at all.
1.28 crook 4036:
1.29 crook 4037: @cindex @code{."}, how it works
4038: Before leaving the subject of immediate words, consider the behaviour of
4039: @code{."} in the definition of @code{greet}, in the previous
4040: section. This word is both a parsing word and an immediate word. Notice
4041: that there is a space between @code{."} and the start of the text
4042: @code{Hello and welcome}, but that there is no space between the last
4043: letter of @code{welcome} and the @code{"} character. The reason for this
4044: is that @code{."} is a Forth word; it must have a space after it so that
4045: the text interpreter can identify it. The @code{"} is not a Forth word;
4046: it is a @dfn{delimiter}. The examples earlier show that, when the string
4047: is displayed, there is neither a space before the @code{H} nor after the
4048: @code{e}. Since @code{."} is an immediate word, it executes at the time
4049: that @code{greet} is defined. When it executes, its behaviour is to
4050: search forward in the input line looking for the delimiter. When it
4051: finds the delimiter, it updates @code{>IN} to point past the
4052: delimiter. It also compiles some magic code into the definition of
4053: @code{greet}; the xt of a run-time routine that prints a text string. It
4054: compiles the string @code{Hello and welcome} into memory so that it is
4055: available to be printed later. When the text interpreter gains control,
4056: the next word it finds in the input stream is @code{;} and so it
4057: terminates the definition of @code{greet}.
1.28 crook 4058:
4059:
4060: @comment ----------------------------------------------
1.29 crook 4061: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4062: @section Forth is written in Forth
4063: @cindex structure of Forth programs
4064:
4065: When you start up a Forth compiler, a large number of definitions
4066: already exist. In Forth, you develop a new application using bottom-up
4067: programming techniques to create new definitions that are defined in
4068: terms of existing definitions. As you create each definition you can
4069: test and debug it interactively.
4070:
4071: If you have tried out the examples in this section, you will probably
4072: have typed them in by hand; when you leave Gforth, your definitions will
4073: be lost. You can avoid this by using a text editor to enter Forth source
4074: code into a file, and then loading code from the file using
1.49 anton 4075: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4076: processed by the text interpreter, just as though you had typed it in by
4077: hand@footnote{Actually, there are some subtle differences -- see
4078: @ref{The Text Interpreter}.}.
4079:
4080: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4081: files for program entry (@pxref{Blocks}).
1.28 crook 4082:
1.29 crook 4083: In common with many, if not most, Forth compilers, most of Gforth is
4084: actually written in Forth. All of the @file{.fs} files in the
4085: installation directory@footnote{For example,
1.30 anton 4086: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4087: study to see examples of Forth programming.
1.28 crook 4088:
1.29 crook 4089: Gforth maintains a history file that records every line that you type to
4090: the text interpreter. This file is preserved between sessions, and is
4091: used to provide a command-line recall facility. If you enter long
4092: definitions by hand, you can use a text editor to paste them out of the
4093: history file into a Forth source file for reuse at a later time
1.49 anton 4094: (for more information @pxref{Command-line editing}).
1.28 crook 4095:
4096:
4097: @comment ----------------------------------------------
1.29 crook 4098: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4099: @section Review - elements of a Forth system
4100: @cindex elements of a Forth system
1.28 crook 4101:
1.29 crook 4102: To summarise this chapter:
1.28 crook 4103:
4104: @itemize @bullet
4105: @item
1.29 crook 4106: Forth programs use @dfn{factoring} to break a problem down into small
4107: fragments called @dfn{words} or @dfn{definitions}.
4108: @item
4109: Forth program development is an interactive process.
4110: @item
4111: The main command loop that accepts input, and controls both
4112: interpretation and compilation, is called the @dfn{text interpreter}
4113: (also known as the @dfn{outer interpreter}).
4114: @item
4115: Forth has a very simple syntax, consisting of words and numbers
4116: separated by spaces or carriage-return characters. Any additional syntax
4117: is imposed by @dfn{parsing words}.
4118: @item
4119: Forth uses a stack to pass parameters between words. As a result, it
4120: uses postfix notation.
4121: @item
4122: To use a word that has previously been defined, the text interpreter
4123: searches for the word in the @dfn{name dictionary}.
4124: @item
1.30 anton 4125: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4126: @item
1.29 crook 4127: The text interpreter uses the value of @code{state} to select between
4128: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4129: semantics} of a word that it encounters.
1.28 crook 4130: @item
1.30 anton 4131: The relationship between the @dfn{interpretation semantics} and
4132: @dfn{compilation semantics} for a word
1.29 crook 4133: depend upon the way in which the word was defined (for example, whether
4134: it is an @dfn{immediate} word).
1.28 crook 4135: @item
1.29 crook 4136: Forth definitions can be implemented in Forth (called @dfn{high-level
4137: definitions}) or in some other way (usually a lower-level language and
4138: as a result often called @dfn{low-level definitions}, @dfn{code
4139: definitions} or @dfn{primitives}).
1.28 crook 4140: @item
1.29 crook 4141: Many Forth systems are implemented mainly in Forth.
1.28 crook 4142: @end itemize
4143:
4144:
1.29 crook 4145: @comment ----------------------------------------------
1.48 anton 4146: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4147: @section Where To Go Next
4148: @cindex where to go next
1.28 crook 4149:
1.29 crook 4150: Amazing as it may seem, if you have read (and understood) this far, you
4151: know almost all the fundamentals about the inner workings of a Forth
4152: system. You certainly know enough to be able to read and understand the
4153: rest of this manual and the ANS Forth document, to learn more about the
4154: facilities that Forth in general and Gforth in particular provide. Even
4155: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4156: However, that's not a good idea just yet... better to try writing some
1.29 crook 4157: programs in Gforth.
1.28 crook 4158:
1.29 crook 4159: Forth has such a rich vocabulary that it can be hard to know where to
4160: start in learning it. This section suggests a few sets of words that are
4161: enough to write small but useful programs. Use the word index in this
4162: document to learn more about each word, then try it out and try to write
4163: small definitions using it. Start by experimenting with these words:
1.28 crook 4164:
4165: @itemize @bullet
4166: @item
1.29 crook 4167: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4168: @item
4169: Comparison: @code{MIN MAX =}
4170: @item
4171: Logic: @code{AND OR XOR NOT}
4172: @item
4173: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4174: @item
1.29 crook 4175: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4176: @item
1.29 crook 4177: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4178: @item
1.29 crook 4179: Defining words: @code{: ; CREATE}
1.28 crook 4180: @item
1.29 crook 4181: Memory allocation words: @code{ALLOT ,}
1.28 crook 4182: @item
1.29 crook 4183: Tools: @code{SEE WORDS .S MARKER}
4184: @end itemize
4185:
4186: When you have mastered those, go on to:
4187:
4188: @itemize @bullet
1.28 crook 4189: @item
1.29 crook 4190: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4191: @item
1.29 crook 4192: Memory access: @code{@@ !}
1.28 crook 4193: @end itemize
1.23 crook 4194:
1.29 crook 4195: When you have mastered these, there's nothing for it but to read through
4196: the whole of this manual and find out what you've missed.
4197:
4198: @comment ----------------------------------------------
1.48 anton 4199: @node Exercises, , Where to go next, Introduction
1.29 crook 4200: @section Exercises
4201: @cindex exercises
4202:
4203: TODO: provide a set of programming excercises linked into the stuff done
4204: already and into other sections of the manual. Provide solutions to all
4205: the exercises in a .fs file in the distribution.
4206:
4207: @c Get some inspiration from Starting Forth and Kelly&Spies.
4208:
4209: @c excercises:
4210: @c 1. take inches and convert to feet and inches.
4211: @c 2. take temperature and convert from fahrenheight to celcius;
4212: @c may need to care about symmetric vs floored??
4213: @c 3. take input line and do character substitution
4214: @c to encipher or decipher
4215: @c 4. as above but work on a file for in and out
4216: @c 5. take input line and convert to pig-latin
4217: @c
4218: @c thing of sets of things to exercise then come up with
4219: @c problems that need those things.
4220:
4221:
1.26 crook 4222: @c ******************************************************************
1.29 crook 4223: @node Words, Error messages, Introduction, Top
1.1 anton 4224: @chapter Forth Words
1.26 crook 4225: @cindex words
1.1 anton 4226:
4227: @menu
4228: * Notation::
1.65 anton 4229: * Case insensitivity::
4230: * Comments::
4231: * Boolean Flags::
1.1 anton 4232: * Arithmetic::
4233: * Stack Manipulation::
1.5 anton 4234: * Memory::
1.1 anton 4235: * Control Structures::
4236: * Defining Words::
1.65 anton 4237: * Interpretation and Compilation Semantics::
1.47 crook 4238: * Tokens for Words::
1.81 anton 4239: * Compiling words::
1.65 anton 4240: * The Text Interpreter::
1.111 anton 4241: * The Input Stream::
1.65 anton 4242: * Word Lists::
4243: * Environmental Queries::
1.12 anton 4244: * Files::
4245: * Blocks::
4246: * Other I/O::
1.121 anton 4247: * OS command line arguments::
1.78 anton 4248: * Locals::
4249: * Structures::
4250: * Object-oriented Forth::
1.12 anton 4251: * Programming Tools::
4252: * Assembler and Code Words::
4253: * Threading Words::
1.65 anton 4254: * Passing Commands to the OS::
4255: * Keeping track of Time::
4256: * Miscellaneous Words::
1.1 anton 4257: @end menu
4258:
1.65 anton 4259: @node Notation, Case insensitivity, Words, Words
1.1 anton 4260: @section Notation
4261: @cindex notation of glossary entries
4262: @cindex format of glossary entries
4263: @cindex glossary notation format
4264: @cindex word glossary entry format
4265:
4266: The Forth words are described in this section in the glossary notation
1.67 anton 4267: that has become a de-facto standard for Forth texts:
1.1 anton 4268:
4269: @format
1.29 crook 4270: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4271: @end format
1.29 crook 4272: @i{Description}
1.1 anton 4273:
4274: @table @var
4275: @item word
1.28 crook 4276: The name of the word.
1.1 anton 4277:
4278: @item Stack effect
4279: @cindex stack effect
1.29 crook 4280: The stack effect is written in the notation @code{@i{before} --
4281: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4282: stack entries before and after the execution of the word. The rest of
4283: the stack is not touched by the word. The top of stack is rightmost,
4284: i.e., a stack sequence is written as it is typed in. Note that Gforth
4285: uses a separate floating point stack, but a unified stack
1.29 crook 4286: notation. Also, return stack effects are not shown in @i{stack
4287: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4288: the type and/or the function of the item. See below for a discussion of
4289: the types.
4290:
4291: All words have two stack effects: A compile-time stack effect and a
4292: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4293: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4294: this standard behaviour, or the word does other unusual things at
4295: compile time, both stack effects are shown; otherwise only the run-time
4296: stack effect is shown.
4297:
4298: @cindex pronounciation of words
4299: @item pronunciation
4300: How the word is pronounced.
4301:
4302: @cindex wordset
1.67 anton 4303: @cindex environment wordset
1.1 anton 4304: @item wordset
1.21 crook 4305: The ANS Forth standard is divided into several word sets. A standard
4306: system need not support all of them. Therefore, in theory, the fewer
4307: word sets your program uses the more portable it will be. However, we
4308: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4309: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4310: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4311: describes words that will work in future releases of Gforth;
4312: @code{gforth-internal} words are more volatile. Environmental query
4313: strings are also displayed like words; you can recognize them by the
1.21 crook 4314: @code{environment} in the word set field.
1.1 anton 4315:
4316: @item Description
4317: A description of the behaviour of the word.
4318: @end table
4319:
4320: @cindex types of stack items
4321: @cindex stack item types
4322: The type of a stack item is specified by the character(s) the name
4323: starts with:
4324:
4325: @table @code
4326: @item f
4327: @cindex @code{f}, stack item type
4328: Boolean flags, i.e. @code{false} or @code{true}.
4329: @item c
4330: @cindex @code{c}, stack item type
4331: Char
4332: @item w
4333: @cindex @code{w}, stack item type
4334: Cell, can contain an integer or an address
4335: @item n
4336: @cindex @code{n}, stack item type
4337: signed integer
4338: @item u
4339: @cindex @code{u}, stack item type
4340: unsigned integer
4341: @item d
4342: @cindex @code{d}, stack item type
4343: double sized signed integer
4344: @item ud
4345: @cindex @code{ud}, stack item type
4346: double sized unsigned integer
4347: @item r
4348: @cindex @code{r}, stack item type
4349: Float (on the FP stack)
1.21 crook 4350: @item a-
1.1 anton 4351: @cindex @code{a_}, stack item type
4352: Cell-aligned address
1.21 crook 4353: @item c-
1.1 anton 4354: @cindex @code{c_}, stack item type
4355: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4356: @item f-
1.1 anton 4357: @cindex @code{f_}, stack item type
4358: Float-aligned address
1.21 crook 4359: @item df-
1.1 anton 4360: @cindex @code{df_}, stack item type
4361: Address aligned for IEEE double precision float
1.21 crook 4362: @item sf-
1.1 anton 4363: @cindex @code{sf_}, stack item type
4364: Address aligned for IEEE single precision float
4365: @item xt
4366: @cindex @code{xt}, stack item type
4367: Execution token, same size as Cell
4368: @item wid
4369: @cindex @code{wid}, stack item type
1.21 crook 4370: Word list ID, same size as Cell
1.68 anton 4371: @item ior, wior
4372: @cindex ior type description
4373: @cindex wior type description
4374: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4375: @item f83name
4376: @cindex @code{f83name}, stack item type
4377: Pointer to a name structure
4378: @item "
4379: @cindex @code{"}, stack item type
1.12 anton 4380: string in the input stream (not on the stack). The terminating character
4381: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4382: quotes.
4383: @end table
4384:
1.65 anton 4385: @comment ----------------------------------------------
4386: @node Case insensitivity, Comments, Notation, Words
4387: @section Case insensitivity
4388: @cindex case sensitivity
4389: @cindex upper and lower case
4390:
4391: Gforth is case-insensitive; you can enter definitions and invoke
4392: Standard words using upper, lower or mixed case (however,
4393: @pxref{core-idef, Implementation-defined options, Implementation-defined
4394: options}).
4395:
4396: ANS Forth only @i{requires} implementations to recognise Standard words
4397: when they are typed entirely in upper case. Therefore, a Standard
4398: program must use upper case for all Standard words. You can use whatever
4399: case you like for words that you define, but in a Standard program you
4400: have to use the words in the same case that you defined them.
4401:
4402: Gforth supports case sensitivity through @code{table}s (case-sensitive
4403: wordlists, @pxref{Word Lists}).
4404:
4405: Two people have asked how to convert Gforth to be case-sensitive; while
4406: we think this is a bad idea, you can change all wordlists into tables
4407: like this:
4408:
4409: @example
4410: ' table-find forth-wordlist wordlist-map @ !
4411: @end example
4412:
4413: Note that you now have to type the predefined words in the same case
4414: that we defined them, which are varying. You may want to convert them
4415: to your favourite case before doing this operation (I won't explain how,
4416: because if you are even contemplating doing this, you'd better have
4417: enough knowledge of Forth systems to know this already).
4418:
4419: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4420: @section Comments
1.26 crook 4421: @cindex comments
1.21 crook 4422:
1.29 crook 4423: Forth supports two styles of comment; the traditional @i{in-line} comment,
4424: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4425:
1.44 crook 4426:
1.23 crook 4427: doc-(
1.21 crook 4428: doc-\
1.23 crook 4429: doc-\G
1.21 crook 4430:
1.44 crook 4431:
1.21 crook 4432: @node Boolean Flags, Arithmetic, Comments, Words
4433: @section Boolean Flags
1.26 crook 4434: @cindex Boolean flags
1.21 crook 4435:
4436: A Boolean flag is cell-sized. A cell with all bits clear represents the
4437: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4438: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4439: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4440: @c on and off to Memory?
4441: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4442:
1.21 crook 4443: doc-true
4444: doc-false
1.29 crook 4445: doc-on
4446: doc-off
1.21 crook 4447:
1.44 crook 4448:
1.21 crook 4449: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4450: @section Arithmetic
4451: @cindex arithmetic words
4452:
4453: @cindex division with potentially negative operands
4454: Forth arithmetic is not checked, i.e., you will not hear about integer
4455: overflow on addition or multiplication, you may hear about division by
4456: zero if you are lucky. The operator is written after the operands, but
4457: the operands are still in the original order. I.e., the infix @code{2-1}
4458: corresponds to @code{2 1 -}. Forth offers a variety of division
4459: operators. If you perform division with potentially negative operands,
4460: you do not want to use @code{/} or @code{/mod} with its undefined
4461: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4462: former, @pxref{Mixed precision}).
1.26 crook 4463: @comment TODO discuss the different division forms and the std approach
1.1 anton 4464:
4465: @menu
4466: * Single precision::
1.67 anton 4467: * Double precision:: Double-cell integer arithmetic
1.1 anton 4468: * Bitwise operations::
1.67 anton 4469: * Numeric comparison::
1.29 crook 4470: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4471: * Floating Point::
4472: @end menu
4473:
1.67 anton 4474: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4475: @subsection Single precision
4476: @cindex single precision arithmetic words
4477:
1.67 anton 4478: @c !! cell undefined
4479:
4480: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4481: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4482: treat them. For the rules used by the text interpreter for recognising
4483: single-precision integers see @ref{Number Conversion}.
1.21 crook 4484:
1.67 anton 4485: These words are all defined for signed operands, but some of them also
4486: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4487: @code{*}.
1.44 crook 4488:
1.1 anton 4489: doc-+
1.21 crook 4490: doc-1+
1.128 anton 4491: doc-under+
1.1 anton 4492: doc--
1.21 crook 4493: doc-1-
1.1 anton 4494: doc-*
4495: doc-/
4496: doc-mod
4497: doc-/mod
4498: doc-negate
4499: doc-abs
4500: doc-min
4501: doc-max
1.27 crook 4502: doc-floored
1.1 anton 4503:
1.44 crook 4504:
1.67 anton 4505: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4506: @subsection Double precision
4507: @cindex double precision arithmetic words
4508:
1.49 anton 4509: For the rules used by the text interpreter for
4510: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4511:
4512: A double precision number is represented by a cell pair, with the most
1.67 anton 4513: significant cell at the TOS. It is trivial to convert an unsigned single
4514: to a double: simply push a @code{0} onto the TOS. Since numbers are
4515: represented by Gforth using 2's complement arithmetic, converting a
4516: signed single to a (signed) double requires sign-extension across the
4517: most significant cell. This can be achieved using @code{s>d}. The moral
4518: of the story is that you cannot convert a number without knowing whether
4519: it represents an unsigned or a signed number.
1.21 crook 4520:
1.67 anton 4521: These words are all defined for signed operands, but some of them also
4522: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4523:
1.21 crook 4524: doc-s>d
1.67 anton 4525: doc-d>s
1.21 crook 4526: doc-d+
4527: doc-d-
4528: doc-dnegate
4529: doc-dabs
4530: doc-dmin
4531: doc-dmax
4532:
1.44 crook 4533:
1.67 anton 4534: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4535: @subsection Bitwise operations
4536: @cindex bitwise operation words
4537:
4538:
4539: doc-and
4540: doc-or
4541: doc-xor
4542: doc-invert
4543: doc-lshift
4544: doc-rshift
4545: doc-2*
4546: doc-d2*
4547: doc-2/
4548: doc-d2/
4549:
4550:
4551: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4552: @subsection Numeric comparison
4553: @cindex numeric comparison words
4554:
1.67 anton 4555: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4556: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4557:
1.28 crook 4558: doc-<
4559: doc-<=
4560: doc-<>
4561: doc-=
4562: doc->
4563: doc->=
4564:
1.21 crook 4565: doc-0<
1.23 crook 4566: doc-0<=
1.21 crook 4567: doc-0<>
4568: doc-0=
1.23 crook 4569: doc-0>
4570: doc-0>=
1.28 crook 4571:
4572: doc-u<
4573: doc-u<=
1.44 crook 4574: @c u<> and u= exist but are the same as <> and =
1.31 anton 4575: @c doc-u<>
4576: @c doc-u=
1.28 crook 4577: doc-u>
4578: doc-u>=
4579:
4580: doc-within
4581:
4582: doc-d<
4583: doc-d<=
4584: doc-d<>
4585: doc-d=
4586: doc-d>
4587: doc-d>=
1.23 crook 4588:
1.21 crook 4589: doc-d0<
1.23 crook 4590: doc-d0<=
4591: doc-d0<>
1.21 crook 4592: doc-d0=
1.23 crook 4593: doc-d0>
4594: doc-d0>=
4595:
1.21 crook 4596: doc-du<
1.28 crook 4597: doc-du<=
1.44 crook 4598: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4599: @c doc-du<>
4600: @c doc-du=
1.28 crook 4601: doc-du>
4602: doc-du>=
1.1 anton 4603:
1.44 crook 4604:
1.21 crook 4605: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4606: @subsection Mixed precision
4607: @cindex mixed precision arithmetic words
4608:
1.44 crook 4609:
1.1 anton 4610: doc-m+
4611: doc-*/
4612: doc-*/mod
4613: doc-m*
4614: doc-um*
4615: doc-m*/
4616: doc-um/mod
4617: doc-fm/mod
4618: doc-sm/rem
4619:
1.44 crook 4620:
1.21 crook 4621: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4622: @subsection Floating Point
4623: @cindex floating point arithmetic words
4624:
1.49 anton 4625: For the rules used by the text interpreter for
4626: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4627:
1.67 anton 4628: Gforth has a separate floating point stack, but the documentation uses
4629: the unified notation.@footnote{It's easy to generate the separate
4630: notation from that by just separating the floating-point numbers out:
4631: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4632: r3 )}.}
1.1 anton 4633:
4634: @cindex floating-point arithmetic, pitfalls
4635: Floating point numbers have a number of unpleasant surprises for the
4636: unwary (e.g., floating point addition is not associative) and even a few
4637: for the wary. You should not use them unless you know what you are doing
4638: or you don't care that the results you get are totally bogus. If you
4639: want to learn about the problems of floating point numbers (and how to
1.66 anton 4640: avoid them), you might start with @cite{David Goldberg,
4641: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4642: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4643: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4644:
1.44 crook 4645:
1.21 crook 4646: doc-d>f
4647: doc-f>d
1.1 anton 4648: doc-f+
4649: doc-f-
4650: doc-f*
4651: doc-f/
4652: doc-fnegate
4653: doc-fabs
4654: doc-fmax
4655: doc-fmin
4656: doc-floor
4657: doc-fround
4658: doc-f**
4659: doc-fsqrt
4660: doc-fexp
4661: doc-fexpm1
4662: doc-fln
4663: doc-flnp1
4664: doc-flog
4665: doc-falog
1.32 anton 4666: doc-f2*
4667: doc-f2/
4668: doc-1/f
4669: doc-precision
4670: doc-set-precision
4671:
4672: @cindex angles in trigonometric operations
4673: @cindex trigonometric operations
4674: Angles in floating point operations are given in radians (a full circle
4675: has 2 pi radians).
4676:
1.1 anton 4677: doc-fsin
4678: doc-fcos
4679: doc-fsincos
4680: doc-ftan
4681: doc-fasin
4682: doc-facos
4683: doc-fatan
4684: doc-fatan2
4685: doc-fsinh
4686: doc-fcosh
4687: doc-ftanh
4688: doc-fasinh
4689: doc-facosh
4690: doc-fatanh
1.21 crook 4691: doc-pi
1.28 crook 4692:
1.32 anton 4693: @cindex equality of floats
4694: @cindex floating-point comparisons
1.31 anton 4695: One particular problem with floating-point arithmetic is that comparison
4696: for equality often fails when you would expect it to succeed. For this
4697: reason approximate equality is often preferred (but you still have to
1.67 anton 4698: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4699: differently from what you might expect. The comparison words are:
1.31 anton 4700:
4701: doc-f~rel
4702: doc-f~abs
1.68 anton 4703: doc-f~
1.31 anton 4704: doc-f=
4705: doc-f<>
4706:
4707: doc-f<
4708: doc-f<=
4709: doc-f>
4710: doc-f>=
4711:
1.21 crook 4712: doc-f0<
1.28 crook 4713: doc-f0<=
4714: doc-f0<>
1.21 crook 4715: doc-f0=
1.28 crook 4716: doc-f0>
4717: doc-f0>=
4718:
1.1 anton 4719:
4720: @node Stack Manipulation, Memory, Arithmetic, Words
4721: @section Stack Manipulation
4722: @cindex stack manipulation words
4723:
4724: @cindex floating-point stack in the standard
1.21 crook 4725: Gforth maintains a number of separate stacks:
4726:
1.29 crook 4727: @cindex data stack
4728: @cindex parameter stack
1.21 crook 4729: @itemize @bullet
4730: @item
1.29 crook 4731: A data stack (also known as the @dfn{parameter stack}) -- for
4732: characters, cells, addresses, and double cells.
1.21 crook 4733:
1.29 crook 4734: @cindex floating-point stack
1.21 crook 4735: @item
1.44 crook 4736: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4737:
1.29 crook 4738: @cindex return stack
1.21 crook 4739: @item
1.44 crook 4740: A return stack -- for holding the return addresses of colon
1.32 anton 4741: definitions and other (non-FP) data.
1.21 crook 4742:
1.29 crook 4743: @cindex locals stack
1.21 crook 4744: @item
1.44 crook 4745: A locals stack -- for holding local variables.
1.21 crook 4746: @end itemize
4747:
1.1 anton 4748: @menu
4749: * Data stack::
4750: * Floating point stack::
4751: * Return stack::
4752: * Locals stack::
4753: * Stack pointer manipulation::
4754: @end menu
4755:
4756: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4757: @subsection Data stack
4758: @cindex data stack manipulation words
4759: @cindex stack manipulations words, data stack
4760:
1.44 crook 4761:
1.1 anton 4762: doc-drop
4763: doc-nip
4764: doc-dup
4765: doc-over
4766: doc-tuck
4767: doc-swap
1.21 crook 4768: doc-pick
1.1 anton 4769: doc-rot
4770: doc--rot
4771: doc-?dup
4772: doc-roll
4773: doc-2drop
4774: doc-2nip
4775: doc-2dup
4776: doc-2over
4777: doc-2tuck
4778: doc-2swap
4779: doc-2rot
4780:
1.44 crook 4781:
1.1 anton 4782: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4783: @subsection Floating point stack
4784: @cindex floating-point stack manipulation words
4785: @cindex stack manipulation words, floating-point stack
4786:
1.32 anton 4787: Whilst every sane Forth has a separate floating-point stack, it is not
4788: strictly required; an ANS Forth system could theoretically keep
4789: floating-point numbers on the data stack. As an additional difficulty,
4790: you don't know how many cells a floating-point number takes. It is
4791: reportedly possible to write words in a way that they work also for a
4792: unified stack model, but we do not recommend trying it. Instead, just
4793: say that your program has an environmental dependency on a separate
4794: floating-point stack.
4795:
4796: doc-floating-stack
4797:
1.1 anton 4798: doc-fdrop
4799: doc-fnip
4800: doc-fdup
4801: doc-fover
4802: doc-ftuck
4803: doc-fswap
1.21 crook 4804: doc-fpick
1.1 anton 4805: doc-frot
4806:
1.44 crook 4807:
1.1 anton 4808: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4809: @subsection Return stack
4810: @cindex return stack manipulation words
4811: @cindex stack manipulation words, return stack
4812:
1.32 anton 4813: @cindex return stack and locals
4814: @cindex locals and return stack
4815: A Forth system is allowed to keep local variables on the
4816: return stack. This is reasonable, as local variables usually eliminate
4817: the need to use the return stack explicitly. So, if you want to produce
4818: a standard compliant program and you are using local variables in a
4819: word, forget about return stack manipulations in that word (refer to the
4820: standard document for the exact rules).
4821:
1.1 anton 4822: doc->r
4823: doc-r>
4824: doc-r@
4825: doc-rdrop
4826: doc-2>r
4827: doc-2r>
4828: doc-2r@
4829: doc-2rdrop
4830:
1.44 crook 4831:
1.1 anton 4832: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4833: @subsection Locals stack
4834:
1.78 anton 4835: Gforth uses an extra locals stack. It is described, along with the
4836: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4837:
1.1 anton 4838: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4839: @subsection Stack pointer manipulation
4840: @cindex stack pointer manipulation words
4841:
1.44 crook 4842: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4843: doc-sp0
1.1 anton 4844: doc-sp@
4845: doc-sp!
1.21 crook 4846: doc-fp0
1.1 anton 4847: doc-fp@
4848: doc-fp!
1.21 crook 4849: doc-rp0
1.1 anton 4850: doc-rp@
4851: doc-rp!
1.21 crook 4852: doc-lp0
1.1 anton 4853: doc-lp@
4854: doc-lp!
4855:
1.44 crook 4856:
1.1 anton 4857: @node Memory, Control Structures, Stack Manipulation, Words
4858: @section Memory
1.26 crook 4859: @cindex memory words
1.1 anton 4860:
1.32 anton 4861: @menu
4862: * Memory model::
4863: * Dictionary allocation::
4864: * Heap Allocation::
4865: * Memory Access::
4866: * Address arithmetic::
4867: * Memory Blocks::
4868: @end menu
4869:
1.67 anton 4870: In addition to the standard Forth memory allocation words, there is also
4871: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4872: garbage collector}.
4873:
1.32 anton 4874: @node Memory model, Dictionary allocation, Memory, Memory
4875: @subsection ANS Forth and Gforth memory models
4876:
4877: @c The ANS Forth description is a mess (e.g., is the heap part of
4878: @c the dictionary?), so let's not stick to closely with it.
4879:
1.67 anton 4880: ANS Forth considers a Forth system as consisting of several address
4881: spaces, of which only @dfn{data space} is managed and accessible with
4882: the memory words. Memory not necessarily in data space includes the
4883: stacks, the code (called code space) and the headers (called name
4884: space). In Gforth everything is in data space, but the code for the
4885: primitives is usually read-only.
1.32 anton 4886:
4887: Data space is divided into a number of areas: The (data space portion of
4888: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4889: refer to the search data structure embodied in word lists and headers,
4890: because it is used for looking up names, just as you would in a
4891: conventional dictionary.}, the heap, and a number of system-allocated
4892: buffers.
4893:
1.68 anton 4894: @cindex address arithmetic restrictions, ANS vs. Gforth
4895: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 4896: In ANS Forth data space is also divided into contiguous regions. You
4897: can only use address arithmetic within a contiguous region, not between
4898: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 4899: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 4900: allocation}).
4901:
4902: Gforth provides one big address space, and address arithmetic can be
4903: performed between any addresses. However, in the dictionary headers or
4904: code are interleaved with data, so almost the only contiguous data space
4905: regions there are those described by ANS Forth as contiguous; but you
4906: can be sure that the dictionary is allocated towards increasing
4907: addresses even between contiguous regions. The memory order of
4908: allocations in the heap is platform-dependent (and possibly different
4909: from one run to the next).
4910:
1.27 crook 4911:
1.32 anton 4912: @node Dictionary allocation, Heap Allocation, Memory model, Memory
4913: @subsection Dictionary allocation
1.27 crook 4914: @cindex reserving data space
4915: @cindex data space - reserving some
4916:
1.32 anton 4917: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
4918: you want to deallocate X, you also deallocate everything
4919: allocated after X.
4920:
1.68 anton 4921: @cindex contiguous regions in dictionary allocation
1.32 anton 4922: The allocations using the words below are contiguous and grow the region
4923: towards increasing addresses. Other words that allocate dictionary
4924: memory of any kind (i.e., defining words including @code{:noname}) end
4925: the contiguous region and start a new one.
4926:
4927: In ANS Forth only @code{create}d words are guaranteed to produce an
4928: address that is the start of the following contiguous region. In
4929: particular, the cell allocated by @code{variable} is not guaranteed to
4930: be contiguous with following @code{allot}ed memory.
4931:
4932: You can deallocate memory by using @code{allot} with a negative argument
4933: (with some restrictions, see @code{allot}). For larger deallocations use
4934: @code{marker}.
1.27 crook 4935:
1.29 crook 4936:
1.27 crook 4937: doc-here
4938: doc-unused
4939: doc-allot
4940: doc-c,
1.29 crook 4941: doc-f,
1.27 crook 4942: doc-,
4943: doc-2,
4944:
1.32 anton 4945: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
4946: course you should allocate memory in an aligned way, too. I.e., before
4947: allocating allocating a cell, @code{here} must be cell-aligned, etc.
4948: The words below align @code{here} if it is not already. Basically it is
4949: only already aligned for a type, if the last allocation was a multiple
4950: of the size of this type and if @code{here} was aligned for this type
4951: before.
4952:
4953: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
4954: ANS Forth (@code{maxalign}ed in Gforth).
4955:
4956: doc-align
4957: doc-falign
4958: doc-sfalign
4959: doc-dfalign
4960: doc-maxalign
4961: doc-cfalign
4962:
4963:
4964: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
4965: @subsection Heap allocation
4966: @cindex heap allocation
4967: @cindex dynamic allocation of memory
4968: @cindex memory-allocation word set
4969:
1.68 anton 4970: @cindex contiguous regions and heap allocation
1.32 anton 4971: Heap allocation supports deallocation of allocated memory in any
4972: order. Dictionary allocation is not affected by it (i.e., it does not
4973: end a contiguous region). In Gforth, these words are implemented using
4974: the standard C library calls malloc(), free() and resize().
4975:
1.68 anton 4976: The memory region produced by one invocation of @code{allocate} or
4977: @code{resize} is internally contiguous. There is no contiguity between
4978: such a region and any other region (including others allocated from the
4979: heap).
4980:
1.32 anton 4981: doc-allocate
4982: doc-free
4983: doc-resize
4984:
1.27 crook 4985:
1.32 anton 4986: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 4987: @subsection Memory Access
4988: @cindex memory access words
4989:
4990: doc-@
4991: doc-!
4992: doc-+!
4993: doc-c@
4994: doc-c!
4995: doc-2@
4996: doc-2!
4997: doc-f@
4998: doc-f!
4999: doc-sf@
5000: doc-sf!
5001: doc-df@
5002: doc-df!
1.144 anton 5003: doc-sw@
5004: doc-uw@
5005: doc-w!
5006: doc-sl@
5007: doc-ul@
5008: doc-l!
1.68 anton 5009:
1.32 anton 5010: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5011: @subsection Address arithmetic
1.1 anton 5012: @cindex address arithmetic words
5013:
1.67 anton 5014: Address arithmetic is the foundation on which you can build data
5015: structures like arrays, records (@pxref{Structures}) and objects
5016: (@pxref{Object-oriented Forth}).
1.32 anton 5017:
1.68 anton 5018: @cindex address unit
5019: @cindex au (address unit)
1.1 anton 5020: ANS Forth does not specify the sizes of the data types. Instead, it
5021: offers a number of words for computing sizes and doing address
1.29 crook 5022: arithmetic. Address arithmetic is performed in terms of address units
5023: (aus); on most systems the address unit is one byte. Note that a
5024: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5025: platforms where it is a noop, it compiles to nothing).
1.1 anton 5026:
1.67 anton 5027: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5028: you have the address of a cell, perform @code{1 cells +}, and you will
5029: have the address of the next cell.
5030:
1.68 anton 5031: @cindex contiguous regions and address arithmetic
1.67 anton 5032: In ANS Forth you can perform address arithmetic only within a contiguous
5033: region, i.e., if you have an address into one region, you can only add
5034: and subtract such that the result is still within the region; you can
5035: only subtract or compare addresses from within the same contiguous
5036: region. Reasons: several contiguous regions can be arranged in memory
5037: in any way; on segmented systems addresses may have unusual
5038: representations, such that address arithmetic only works within a
5039: region. Gforth provides a few more guarantees (linear address space,
5040: dictionary grows upwards), but in general I have found it easy to stay
5041: within contiguous regions (exception: computing and comparing to the
5042: address just beyond the end of an array).
5043:
1.1 anton 5044: @cindex alignment of addresses for types
5045: ANS Forth also defines words for aligning addresses for specific
5046: types. Many computers require that accesses to specific data types
5047: must only occur at specific addresses; e.g., that cells may only be
5048: accessed at addresses divisible by 4. Even if a machine allows unaligned
5049: accesses, it can usually perform aligned accesses faster.
5050:
5051: For the performance-conscious: alignment operations are usually only
5052: necessary during the definition of a data structure, not during the
5053: (more frequent) accesses to it.
5054:
5055: ANS Forth defines no words for character-aligning addresses. This is not
5056: an oversight, but reflects the fact that addresses that are not
5057: char-aligned have no use in the standard and therefore will not be
5058: created.
5059:
5060: @cindex @code{CREATE} and alignment
1.29 crook 5061: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5062: are cell-aligned; in addition, Gforth guarantees that these addresses
5063: are aligned for all purposes.
5064:
1.26 crook 5065: Note that the ANS Forth word @code{char} has nothing to do with address
5066: arithmetic.
1.1 anton 5067:
1.44 crook 5068:
1.1 anton 5069: doc-chars
5070: doc-char+
5071: doc-cells
5072: doc-cell+
5073: doc-cell
5074: doc-aligned
5075: doc-floats
5076: doc-float+
5077: doc-float
5078: doc-faligned
5079: doc-sfloats
5080: doc-sfloat+
5081: doc-sfaligned
5082: doc-dfloats
5083: doc-dfloat+
5084: doc-dfaligned
5085: doc-maxaligned
5086: doc-cfaligned
5087: doc-address-unit-bits
1.145 anton 5088: doc-/w
5089: doc-/l
1.44 crook 5090:
1.32 anton 5091: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5092: @subsection Memory Blocks
5093: @cindex memory block words
1.27 crook 5094: @cindex character strings - moving and copying
5095:
1.49 anton 5096: Memory blocks often represent character strings; For ways of storing
5097: character strings in memory see @ref{String Formats}. For other
5098: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5099:
1.67 anton 5100: A few of these words work on address unit blocks. In that case, you
5101: usually have to insert @code{CHARS} before the word when working on
5102: character strings. Most words work on character blocks, and expect a
5103: char-aligned address.
5104:
5105: When copying characters between overlapping memory regions, use
5106: @code{chars move} or choose carefully between @code{cmove} and
5107: @code{cmove>}.
1.44 crook 5108:
1.1 anton 5109: doc-move
5110: doc-erase
5111: doc-cmove
5112: doc-cmove>
5113: doc-fill
5114: doc-blank
1.21 crook 5115: doc-compare
1.111 anton 5116: doc-str=
5117: doc-str<
5118: doc-string-prefix?
1.21 crook 5119: doc-search
1.27 crook 5120: doc--trailing
5121: doc-/string
1.82 anton 5122: doc-bounds
1.141 anton 5123: doc-pad
1.111 anton 5124:
1.27 crook 5125: @comment TODO examples
5126:
1.1 anton 5127:
1.26 crook 5128: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5129: @section Control Structures
5130: @cindex control structures
5131:
1.33 anton 5132: Control structures in Forth cannot be used interpretively, only in a
5133: colon definition@footnote{To be precise, they have no interpretation
5134: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5135: not like this limitation, but have not seen a satisfying way around it
5136: yet, although many schemes have been proposed.
1.1 anton 5137:
5138: @menu
1.33 anton 5139: * Selection:: IF ... ELSE ... ENDIF
5140: * Simple Loops:: BEGIN ...
1.29 crook 5141: * Counted Loops:: DO
1.67 anton 5142: * Arbitrary control structures::
5143: * Calls and returns::
1.1 anton 5144: * Exception Handling::
5145: @end menu
5146:
5147: @node Selection, Simple Loops, Control Structures, Control Structures
5148: @subsection Selection
5149: @cindex selection control structures
5150: @cindex control structures for selection
5151:
5152: @cindex @code{IF} control structure
5153: @example
1.29 crook 5154: @i{flag}
1.1 anton 5155: IF
1.29 crook 5156: @i{code}
1.1 anton 5157: ENDIF
5158: @end example
1.21 crook 5159: @noindent
1.33 anton 5160:
1.44 crook 5161: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5162: with any bit set represents truth) @i{code} is executed.
1.33 anton 5163:
1.1 anton 5164: @example
1.29 crook 5165: @i{flag}
1.1 anton 5166: IF
1.29 crook 5167: @i{code1}
1.1 anton 5168: ELSE
1.29 crook 5169: @i{code2}
1.1 anton 5170: ENDIF
5171: @end example
5172:
1.44 crook 5173: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5174: executed.
1.33 anton 5175:
1.1 anton 5176: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5177: standard, and @code{ENDIF} is not, although it is quite popular. We
5178: recommend using @code{ENDIF}, because it is less confusing for people
5179: who also know other languages (and is not prone to reinforcing negative
5180: prejudices against Forth in these people). Adding @code{ENDIF} to a
5181: system that only supplies @code{THEN} is simple:
5182: @example
1.82 anton 5183: : ENDIF POSTPONE then ; immediate
1.1 anton 5184: @end example
5185:
5186: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5187: (adv.)} has the following meanings:
5188: @quotation
5189: ... 2b: following next after in order ... 3d: as a necessary consequence
5190: (if you were there, then you saw them).
5191: @end quotation
5192: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5193: and many other programming languages has the meaning 3d.]
5194:
1.21 crook 5195: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5196: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5197: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5198: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5199: @file{compat/control.fs}.
5200:
5201: @cindex @code{CASE} control structure
5202: @example
1.29 crook 5203: @i{n}
1.1 anton 5204: CASE
1.29 crook 5205: @i{n1} OF @i{code1} ENDOF
5206: @i{n2} OF @i{code2} ENDOF
1.1 anton 5207: @dots{}
1.68 anton 5208: ( n ) @i{default-code} ( n )
1.131 anton 5209: ENDCASE ( )
1.1 anton 5210: @end example
5211:
1.131 anton 5212: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5213: no @i{ni} matches, the optional @i{default-code} is executed. The
5214: optional default case can be added by simply writing the code after
5215: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5216: but must not consume it. The value @i{n} is consumed by this
5217: construction (either by a OF that matches, or by the ENDCASE, if no OF
5218: matches).
1.1 anton 5219:
1.69 anton 5220: @progstyle
1.131 anton 5221: To keep the code understandable, you should ensure that you change the
5222: stack in the same way (wrt. number and types of stack items consumed
5223: and pushed) on all paths through a selection construct.
1.69 anton 5224:
1.1 anton 5225: @node Simple Loops, Counted Loops, Selection, Control Structures
5226: @subsection Simple Loops
5227: @cindex simple loops
5228: @cindex loops without count
5229:
5230: @cindex @code{WHILE} loop
5231: @example
5232: BEGIN
1.29 crook 5233: @i{code1}
5234: @i{flag}
1.1 anton 5235: WHILE
1.29 crook 5236: @i{code2}
1.1 anton 5237: REPEAT
5238: @end example
5239:
1.29 crook 5240: @i{code1} is executed and @i{flag} is computed. If it is true,
5241: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5242: false, execution continues after the @code{REPEAT}.
5243:
5244: @cindex @code{UNTIL} loop
5245: @example
5246: BEGIN
1.29 crook 5247: @i{code}
5248: @i{flag}
1.1 anton 5249: UNTIL
5250: @end example
5251:
1.29 crook 5252: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5253:
1.69 anton 5254: @progstyle
5255: To keep the code understandable, a complete iteration of the loop should
5256: not change the number and types of the items on the stacks.
5257:
1.1 anton 5258: @cindex endless loop
5259: @cindex loops, endless
5260: @example
5261: BEGIN
1.29 crook 5262: @i{code}
1.1 anton 5263: AGAIN
5264: @end example
5265:
5266: This is an endless loop.
5267:
5268: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5269: @subsection Counted Loops
5270: @cindex counted loops
5271: @cindex loops, counted
5272: @cindex @code{DO} loops
5273:
5274: The basic counted loop is:
5275: @example
1.29 crook 5276: @i{limit} @i{start}
1.1 anton 5277: ?DO
1.29 crook 5278: @i{body}
1.1 anton 5279: LOOP
5280: @end example
5281:
1.29 crook 5282: This performs one iteration for every integer, starting from @i{start}
5283: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5284: accessed with @code{i}. For example, the loop:
1.1 anton 5285: @example
5286: 10 0 ?DO
5287: i .
5288: LOOP
5289: @end example
1.21 crook 5290: @noindent
5291: prints @code{0 1 2 3 4 5 6 7 8 9}
5292:
1.1 anton 5293: The index of the innermost loop can be accessed with @code{i}, the index
5294: of the next loop with @code{j}, and the index of the third loop with
5295: @code{k}.
5296:
1.44 crook 5297:
1.1 anton 5298: doc-i
5299: doc-j
5300: doc-k
5301:
1.44 crook 5302:
1.1 anton 5303: The loop control data are kept on the return stack, so there are some
1.21 crook 5304: restrictions on mixing return stack accesses and counted loop words. In
5305: particuler, if you put values on the return stack outside the loop, you
5306: cannot read them inside the loop@footnote{well, not in a way that is
5307: portable.}. If you put values on the return stack within a loop, you
5308: have to remove them before the end of the loop and before accessing the
5309: index of the loop.
1.1 anton 5310:
5311: There are several variations on the counted loop:
5312:
1.21 crook 5313: @itemize @bullet
5314: @item
5315: @code{LEAVE} leaves the innermost counted loop immediately; execution
5316: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5317:
5318: @example
5319: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5320: @end example
5321: prints @code{0 1 2 3}
5322:
1.1 anton 5323:
1.21 crook 5324: @item
5325: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5326: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5327: return stack so @code{EXIT} can get to its return address. For example:
5328:
5329: @example
5330: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5331: @end example
5332: prints @code{0 1 2 3}
5333:
5334:
5335: @item
1.29 crook 5336: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5337: (and @code{LOOP} iterates until they become equal by wrap-around
5338: arithmetic). This behaviour is usually not what you want. Therefore,
5339: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5340: @code{?DO}), which do not enter the loop if @i{start} is greater than
5341: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5342: unsigned loop parameters.
5343:
1.21 crook 5344: @item
5345: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5346: the loop, independent of the loop parameters. Do not use @code{DO}, even
5347: if you know that the loop is entered in any case. Such knowledge tends
5348: to become invalid during maintenance of a program, and then the
5349: @code{DO} will make trouble.
5350:
5351: @item
1.29 crook 5352: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5353: index by @i{n} instead of by 1. The loop is terminated when the border
5354: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5355:
1.21 crook 5356: @example
5357: 4 0 +DO i . 2 +LOOP
5358: @end example
5359: @noindent
5360: prints @code{0 2}
5361:
5362: @example
5363: 4 1 +DO i . 2 +LOOP
5364: @end example
5365: @noindent
5366: prints @code{1 3}
1.1 anton 5367:
1.68 anton 5368: @item
1.1 anton 5369: @cindex negative increment for counted loops
5370: @cindex counted loops with negative increment
1.29 crook 5371: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5372:
1.21 crook 5373: @example
5374: -1 0 ?DO i . -1 +LOOP
5375: @end example
5376: @noindent
5377: prints @code{0 -1}
1.1 anton 5378:
1.21 crook 5379: @example
5380: 0 0 ?DO i . -1 +LOOP
5381: @end example
5382: prints nothing.
1.1 anton 5383:
1.29 crook 5384: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5385: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5386: index by @i{u} each iteration. The loop is terminated when the border
5387: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5388: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5389:
1.21 crook 5390: @example
5391: -2 0 -DO i . 1 -LOOP
5392: @end example
5393: @noindent
5394: prints @code{0 -1}
1.1 anton 5395:
1.21 crook 5396: @example
5397: -1 0 -DO i . 1 -LOOP
5398: @end example
5399: @noindent
5400: prints @code{0}
5401:
5402: @example
5403: 0 0 -DO i . 1 -LOOP
5404: @end example
5405: @noindent
5406: prints nothing.
1.1 anton 5407:
1.21 crook 5408: @end itemize
1.1 anton 5409:
5410: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5411: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5412: for these words that uses only standard words is provided in
5413: @file{compat/loops.fs}.
1.1 anton 5414:
5415:
5416: @cindex @code{FOR} loops
1.26 crook 5417: Another counted loop is:
1.1 anton 5418: @example
1.29 crook 5419: @i{n}
1.1 anton 5420: FOR
1.29 crook 5421: @i{body}
1.1 anton 5422: NEXT
5423: @end example
5424: This is the preferred loop of native code compiler writers who are too
1.26 crook 5425: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5426: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5427: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5428: Forth systems may behave differently, even if they support @code{FOR}
5429: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5430:
5431: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5432: @subsection Arbitrary control structures
5433: @cindex control structures, user-defined
5434:
5435: @cindex control-flow stack
5436: ANS Forth permits and supports using control structures in a non-nested
5437: way. Information about incomplete control structures is stored on the
5438: control-flow stack. This stack may be implemented on the Forth data
5439: stack, and this is what we have done in Gforth.
5440:
5441: @cindex @code{orig}, control-flow stack item
5442: @cindex @code{dest}, control-flow stack item
5443: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5444: entry represents a backward branch target. A few words are the basis for
5445: building any control structure possible (except control structures that
5446: need storage, like calls, coroutines, and backtracking).
5447:
1.44 crook 5448:
1.1 anton 5449: doc-if
5450: doc-ahead
5451: doc-then
5452: doc-begin
5453: doc-until
5454: doc-again
5455: doc-cs-pick
5456: doc-cs-roll
5457:
1.44 crook 5458:
1.21 crook 5459: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5460: manipulate the control-flow stack in a portable way. Without them, you
5461: would need to know how many stack items are occupied by a control-flow
5462: entry (many systems use one cell. In Gforth they currently take three,
5463: but this may change in the future).
5464:
1.1 anton 5465: Some standard control structure words are built from these words:
5466:
1.44 crook 5467:
1.1 anton 5468: doc-else
5469: doc-while
5470: doc-repeat
5471:
1.44 crook 5472:
5473: @noindent
1.1 anton 5474: Gforth adds some more control-structure words:
5475:
1.44 crook 5476:
1.1 anton 5477: doc-endif
5478: doc-?dup-if
5479: doc-?dup-0=-if
5480:
1.44 crook 5481:
5482: @noindent
1.1 anton 5483: Counted loop words constitute a separate group of words:
5484:
1.44 crook 5485:
1.1 anton 5486: doc-?do
5487: doc-+do
5488: doc-u+do
5489: doc--do
5490: doc-u-do
5491: doc-do
5492: doc-for
5493: doc-loop
5494: doc-+loop
5495: doc--loop
5496: doc-next
5497: doc-leave
5498: doc-?leave
5499: doc-unloop
5500: doc-done
5501:
1.44 crook 5502:
1.21 crook 5503: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5504: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5505: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5506: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5507: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5508: resolved (by using one of the loop-ending words or @code{DONE}).
5509:
1.44 crook 5510: @noindent
1.26 crook 5511: Another group of control structure words are:
1.1 anton 5512:
1.44 crook 5513:
1.1 anton 5514: doc-case
5515: doc-endcase
5516: doc-of
5517: doc-endof
5518:
1.44 crook 5519:
1.21 crook 5520: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5521: @code{CS-ROLL}.
1.1 anton 5522:
5523: @subsubsection Programming Style
1.47 crook 5524: @cindex control structures programming style
5525: @cindex programming style, arbitrary control structures
1.1 anton 5526:
5527: In order to ensure readability we recommend that you do not create
5528: arbitrary control structures directly, but define new control structure
5529: words for the control structure you want and use these words in your
1.26 crook 5530: program. For example, instead of writing:
1.1 anton 5531:
5532: @example
1.26 crook 5533: BEGIN
1.1 anton 5534: ...
1.26 crook 5535: IF [ 1 CS-ROLL ]
1.1 anton 5536: ...
1.26 crook 5537: AGAIN THEN
1.1 anton 5538: @end example
5539:
1.21 crook 5540: @noindent
1.1 anton 5541: we recommend defining control structure words, e.g.,
5542:
5543: @example
1.26 crook 5544: : WHILE ( DEST -- ORIG DEST )
5545: POSTPONE IF
5546: 1 CS-ROLL ; immediate
5547:
5548: : REPEAT ( orig dest -- )
5549: POSTPONE AGAIN
5550: POSTPONE THEN ; immediate
1.1 anton 5551: @end example
5552:
1.21 crook 5553: @noindent
1.1 anton 5554: and then using these to create the control structure:
5555:
5556: @example
1.26 crook 5557: BEGIN
1.1 anton 5558: ...
1.26 crook 5559: WHILE
1.1 anton 5560: ...
1.26 crook 5561: REPEAT
1.1 anton 5562: @end example
5563:
5564: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5565: @code{WHILE} are predefined, so in this example it would not be
5566: necessary to define them.
5567:
5568: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5569: @subsection Calls and returns
5570: @cindex calling a definition
5571: @cindex returning from a definition
5572:
1.3 anton 5573: @cindex recursive definitions
5574: A definition can be called simply be writing the name of the definition
1.26 crook 5575: to be called. Normally a definition is invisible during its own
1.3 anton 5576: definition. If you want to write a directly recursive definition, you
1.26 crook 5577: can use @code{recursive} to make the current definition visible, or
5578: @code{recurse} to call the current definition directly.
1.3 anton 5579:
1.44 crook 5580:
1.3 anton 5581: doc-recursive
5582: doc-recurse
5583:
1.44 crook 5584:
1.21 crook 5585: @comment TODO add example of the two recursion methods
1.12 anton 5586: @quotation
5587: @progstyle
5588: I prefer using @code{recursive} to @code{recurse}, because calling the
5589: definition by name is more descriptive (if the name is well-chosen) than
5590: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5591: implementation, it is much better to read (and think) ``now sort the
5592: partitions'' than to read ``now do a recursive call''.
5593: @end quotation
1.3 anton 5594:
1.29 crook 5595: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5596:
5597: @example
1.28 crook 5598: Defer foo
1.3 anton 5599:
5600: : bar ( ... -- ... )
5601: ... foo ... ;
5602:
5603: :noname ( ... -- ... )
5604: ... bar ... ;
5605: IS foo
5606: @end example
5607:
1.44 crook 5608: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5609:
1.26 crook 5610: The current definition returns control to the calling definition when
1.33 anton 5611: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5612:
5613: doc-exit
5614: doc-;s
5615:
1.44 crook 5616:
1.1 anton 5617: @node Exception Handling, , Calls and returns, Control Structures
5618: @subsection Exception Handling
1.26 crook 5619: @cindex exceptions
1.1 anton 5620:
1.68 anton 5621: @c quit is a very bad idea for error handling,
5622: @c because it does not translate into a THROW
5623: @c it also does not belong into this chapter
5624:
5625: If a word detects an error condition that it cannot handle, it can
5626: @code{throw} an exception. In the simplest case, this will terminate
5627: your program, and report an appropriate error.
1.21 crook 5628:
1.68 anton 5629: doc-throw
1.1 anton 5630:
1.69 anton 5631: @code{Throw} consumes a cell-sized error number on the stack. There are
5632: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5633: Gforth (and most other systems) you can use the iors produced by various
5634: words as error numbers (e.g., a typical use of @code{allocate} is
5635: @code{allocate throw}). Gforth also provides the word @code{exception}
5636: to define your own error numbers (with decent error reporting); an ANS
5637: Forth version of this word (but without the error messages) is available
5638: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5639: numbers (anything outside the range -4095..0), but won't get nice error
5640: messages, only numbers. For example, try:
5641:
5642: @example
1.69 anton 5643: -10 throw \ ANS defined
5644: -267 throw \ system defined
5645: s" my error" exception throw \ user defined
5646: 7 throw \ arbitrary number
1.68 anton 5647: @end example
5648:
5649: doc---exception-exception
1.1 anton 5650:
1.69 anton 5651: A common idiom to @code{THROW} a specific error if a flag is true is
5652: this:
5653:
5654: @example
5655: @code{( flag ) 0<> @i{errno} and throw}
5656: @end example
5657:
5658: Your program can provide exception handlers to catch exceptions. An
5659: exception handler can be used to correct the problem, or to clean up
5660: some data structures and just throw the exception to the next exception
5661: handler. Note that @code{throw} jumps to the dynamically innermost
5662: exception handler. The system's exception handler is outermost, and just
5663: prints an error and restarts command-line interpretation (or, in batch
5664: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5665:
1.68 anton 5666: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5667:
1.68 anton 5668: doc-catch
5669:
5670: The most common use of exception handlers is to clean up the state when
5671: an error happens. E.g.,
1.1 anton 5672:
1.26 crook 5673: @example
1.68 anton 5674: base @ >r hex \ actually the hex should be inside foo, or we h
5675: ['] foo catch ( nerror|0 )
5676: r> base !
1.69 anton 5677: ( nerror|0 ) throw \ pass it on
1.26 crook 5678: @end example
1.1 anton 5679:
1.69 anton 5680: A use of @code{catch} for handling the error @code{myerror} might look
5681: like this:
1.44 crook 5682:
1.68 anton 5683: @example
1.69 anton 5684: ['] foo catch
5685: CASE
5686: myerror OF ... ( do something about it ) ENDOF
5687: dup throw \ default: pass other errors on, do nothing on non-errors
5688: ENDCASE
1.68 anton 5689: @end example
1.44 crook 5690:
1.68 anton 5691: Having to wrap the code into a separate word is often cumbersome,
5692: therefore Gforth provides an alternative syntax:
1.1 anton 5693:
5694: @example
1.69 anton 5695: TRY
1.68 anton 5696: @i{code1}
1.69 anton 5697: RECOVER \ optional
1.68 anton 5698: @i{code2} \ optional
1.69 anton 5699: ENDTRY
1.1 anton 5700: @end example
5701:
1.68 anton 5702: This performs @i{Code1}. If @i{code1} completes normally, execution
5703: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5704: reset to the state during @code{try}, the throw value is pushed on the
5705: data stack, and execution constinues at @i{code2}, and finally falls
1.92 anton 5706: through the @code{endtry} into the following code.
1.26 crook 5707:
1.68 anton 5708: doc-try
5709: doc-recover
5710: doc-endtry
1.26 crook 5711:
1.69 anton 5712: The cleanup example from above in this syntax:
1.26 crook 5713:
1.68 anton 5714: @example
1.69 anton 5715: base @ >r TRY
1.68 anton 5716: hex foo \ now the hex is placed correctly
1.69 anton 5717: 0 \ value for throw
1.92 anton 5718: RECOVER ENDTRY
1.68 anton 5719: r> base ! throw
1.1 anton 5720: @end example
5721:
1.69 anton 5722: And here's the error handling example:
1.1 anton 5723:
1.68 anton 5724: @example
1.69 anton 5725: TRY
1.68 anton 5726: foo
1.69 anton 5727: RECOVER
5728: CASE
5729: myerror OF ... ( do something about it ) ENDOF
5730: throw \ pass other errors on
5731: ENDCASE
5732: ENDTRY
1.68 anton 5733: @end example
1.1 anton 5734:
1.69 anton 5735: @progstyle
5736: As usual, you should ensure that the stack depth is statically known at
5737: the end: either after the @code{throw} for passing on errors, or after
5738: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5739: selection construct for handling the error).
5740:
1.68 anton 5741: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5742: and you can provide an error message. @code{Abort} just produces an
5743: ``Aborted'' error.
1.1 anton 5744:
1.68 anton 5745: The problem with these words is that exception handlers cannot
5746: differentiate between different @code{abort"}s; they just look like
5747: @code{-2 throw} to them (the error message cannot be accessed by
5748: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5749: exception handlers.
1.44 crook 5750:
1.68 anton 5751: doc-abort"
1.26 crook 5752: doc-abort
1.29 crook 5753:
5754:
1.44 crook 5755:
1.29 crook 5756: @c -------------------------------------------------------------
1.47 crook 5757: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5758: @section Defining Words
5759: @cindex defining words
5760:
1.47 crook 5761: Defining words are used to extend Forth by creating new entries in the dictionary.
5762:
1.29 crook 5763: @menu
1.67 anton 5764: * CREATE::
1.44 crook 5765: * Variables:: Variables and user variables
1.67 anton 5766: * Constants::
1.44 crook 5767: * Values:: Initialised variables
1.67 anton 5768: * Colon Definitions::
1.44 crook 5769: * Anonymous Definitions:: Definitions without names
1.69 anton 5770: * Supplying names:: Passing definition names as strings
1.67 anton 5771: * User-defined Defining Words::
1.44 crook 5772: * Deferred words:: Allow forward references
1.67 anton 5773: * Aliases::
1.29 crook 5774: @end menu
5775:
1.44 crook 5776: @node CREATE, Variables, Defining Words, Defining Words
5777: @subsection @code{CREATE}
1.29 crook 5778: @cindex simple defining words
5779: @cindex defining words, simple
5780:
5781: Defining words are used to create new entries in the dictionary. The
5782: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5783: this:
5784:
5785: @example
5786: CREATE new-word1
5787: @end example
5788:
1.69 anton 5789: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5790: input stream (@code{new-word1} in our example). It generates a
5791: dictionary entry for @code{new-word1}. When @code{new-word1} is
5792: executed, all that it does is leave an address on the stack. The address
5793: represents the value of the data space pointer (@code{HERE}) at the time
5794: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5795: associating a name with the address of a region of memory.
1.29 crook 5796:
1.34 anton 5797: doc-create
5798:
1.69 anton 5799: Note that in ANS Forth guarantees only for @code{create} that its body
5800: is in dictionary data space (i.e., where @code{here}, @code{allot}
5801: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5802: @code{create}d words can be modified with @code{does>}
5803: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5804: can only be applied to @code{create}d words.
5805:
1.29 crook 5806: By extending this example to reserve some memory in data space, we end
1.69 anton 5807: up with something like a @i{variable}. Here are two different ways to do
5808: it:
1.29 crook 5809:
5810: @example
5811: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5812: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5813: @end example
5814:
5815: The variable can be examined and modified using @code{@@} (``fetch'') and
5816: @code{!} (``store'') like this:
5817:
5818: @example
5819: new-word2 @@ . \ get address, fetch from it and display
5820: 1234 new-word2 ! \ new value, get address, store to it
5821: @end example
5822:
1.44 crook 5823: @cindex arrays
5824: A similar mechanism can be used to create arrays. For example, an
5825: 80-character text input buffer:
1.29 crook 5826:
5827: @example
1.44 crook 5828: CREATE text-buf 80 chars allot
5829:
5830: text-buf 0 chars c@@ \ the 1st character (offset 0)
5831: text-buf 3 chars c@@ \ the 4th character (offset 3)
5832: @end example
1.29 crook 5833:
1.44 crook 5834: You can build arbitrarily complex data structures by allocating
1.49 anton 5835: appropriate areas of memory. For further discussions of this, and to
1.66 anton 5836: learn about some Gforth tools that make it easier,
1.49 anton 5837: @xref{Structures}.
1.44 crook 5838:
5839:
5840: @node Variables, Constants, CREATE, Defining Words
5841: @subsection Variables
5842: @cindex variables
5843:
5844: The previous section showed how a sequence of commands could be used to
5845: generate a variable. As a final refinement, the whole code sequence can
5846: be wrapped up in a defining word (pre-empting the subject of the next
5847: section), making it easier to create new variables:
5848:
5849: @example
5850: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5851: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5852:
5853: myvariableX foo \ variable foo starts off with an unknown value
5854: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5855:
5856: 45 3 * foo ! \ set foo to 135
5857: 1234 joe ! \ set joe to 1234
5858: 3 joe +! \ increment joe by 3.. to 1237
5859: @end example
5860:
5861: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5862: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 5863: guarantee that a @code{Variable} is initialised when it is created
5864: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5865: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5866: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5867: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 5868: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 5869: store a boolean, you can use @code{on} and @code{off} to toggle its
5870: state.
1.29 crook 5871:
1.34 anton 5872: doc-variable
5873: doc-2variable
5874: doc-fvariable
5875:
1.29 crook 5876: @cindex user variables
5877: @cindex user space
5878: The defining word @code{User} behaves in the same way as @code{Variable}.
5879: The difference is that it reserves space in @i{user (data) space} rather
5880: than normal data space. In a Forth system that has a multi-tasker, each
5881: task has its own set of user variables.
5882:
1.34 anton 5883: doc-user
1.67 anton 5884: @c doc-udp
5885: @c doc-uallot
1.34 anton 5886:
1.29 crook 5887: @comment TODO is that stuff about user variables strictly correct? Is it
5888: @comment just terminal tasks that have user variables?
5889: @comment should document tasker.fs (with some examples) elsewhere
5890: @comment in this manual, then expand on user space and user variables.
5891:
1.44 crook 5892: @node Constants, Values, Variables, Defining Words
5893: @subsection Constants
5894: @cindex constants
5895:
5896: @code{Constant} allows you to declare a fixed value and refer to it by
5897: name. For example:
1.29 crook 5898:
5899: @example
5900: 12 Constant INCHES-PER-FOOT
5901: 3E+08 fconstant SPEED-O-LIGHT
5902: @end example
5903:
5904: A @code{Variable} can be both read and written, so its run-time
5905: behaviour is to supply an address through which its current value can be
5906: manipulated. In contrast, the value of a @code{Constant} cannot be
5907: changed once it has been declared@footnote{Well, often it can be -- but
5908: not in a Standard, portable way. It's safer to use a @code{Value} (read
5909: on).} so it's not necessary to supply the address -- it is more
5910: efficient to return the value of the constant directly. That's exactly
5911: what happens; the run-time effect of a constant is to put its value on
1.49 anton 5912: the top of the stack (You can find one
5913: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 5914:
1.69 anton 5915: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 5916: double and floating-point constants, respectively.
5917:
1.34 anton 5918: doc-constant
5919: doc-2constant
5920: doc-fconstant
5921:
5922: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 5923: @c nac-> How could that not be true in an ANS Forth? You can't define a
5924: @c constant, use it and then delete the definition of the constant..
1.69 anton 5925:
5926: @c anton->An ANS Forth system can compile a constant to a literal; On
5927: @c decompilation you would see only the number, just as if it had been used
5928: @c in the first place. The word will stay, of course, but it will only be
5929: @c used by the text interpreter (no run-time duties, except when it is
5930: @c POSTPONEd or somesuch).
5931:
5932: @c nac:
1.44 crook 5933: @c I agree that it's rather deep, but IMO it is an important difference
5934: @c relative to other programming languages.. often it's annoying: it
5935: @c certainly changes my programming style relative to C.
5936:
1.69 anton 5937: @c anton: In what way?
5938:
1.29 crook 5939: Constants in Forth behave differently from their equivalents in other
5940: programming languages. In other languages, a constant (such as an EQU in
5941: assembler or a #define in C) only exists at compile-time; in the
5942: executable program the constant has been translated into an absolute
5943: number and, unless you are using a symbolic debugger, it's impossible to
5944: know what abstract thing that number represents. In Forth a constant has
1.44 crook 5945: an entry in the header space and remains there after the code that uses
5946: it has been defined. In fact, it must remain in the dictionary since it
5947: has run-time duties to perform. For example:
1.29 crook 5948:
5949: @example
5950: 12 Constant INCHES-PER-FOOT
5951: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
5952: @end example
5953:
5954: @cindex in-lining of constants
5955: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
5956: associated with the constant @code{INCHES-PER-FOOT}. If you use
5957: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
5958: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
5959: attempt to optimise constants by in-lining them where they are used. You
5960: can force Gforth to in-line a constant like this:
5961:
5962: @example
5963: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
5964: @end example
5965:
5966: If you use @code{see} to decompile @i{this} version of
5967: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 5968: longer present. To understand how this works, read
5969: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 5970:
5971: In-lining constants in this way might improve execution time
5972: fractionally, and can ensure that a constant is now only referenced at
5973: compile-time. However, the definition of the constant still remains in
5974: the dictionary. Some Forth compilers provide a mechanism for controlling
5975: a second dictionary for holding transient words such that this second
5976: dictionary can be deleted later in order to recover memory
5977: space. However, there is no standard way of doing this.
5978:
5979:
1.44 crook 5980: @node Values, Colon Definitions, Constants, Defining Words
5981: @subsection Values
5982: @cindex values
1.34 anton 5983:
1.69 anton 5984: A @code{Value} behaves like a @code{Constant}, but it can be changed.
5985: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
5986: (not in ANS Forth) you can access (and change) a @code{value} also with
5987: @code{>body}.
5988:
5989: Here are some
5990: examples:
1.29 crook 5991:
5992: @example
1.69 anton 5993: 12 Value APPLES \ Define APPLES with an initial value of 12
5994: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
5995: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
5996: APPLES \ puts 35 on the top of the stack.
1.29 crook 5997: @end example
5998:
1.44 crook 5999: doc-value
6000: doc-to
1.29 crook 6001:
1.35 anton 6002:
1.69 anton 6003:
1.44 crook 6004: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6005: @subsection Colon Definitions
6006: @cindex colon definitions
1.35 anton 6007:
6008: @example
1.44 crook 6009: : name ( ... -- ... )
6010: word1 word2 word3 ;
1.29 crook 6011: @end example
6012:
1.44 crook 6013: @noindent
6014: Creates a word called @code{name} that, upon execution, executes
6015: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6016:
1.49 anton 6017: The explanation above is somewhat superficial. For simple examples of
6018: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6019: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6020: Compilation Semantics}.
1.29 crook 6021:
1.44 crook 6022: doc-:
6023: doc-;
1.1 anton 6024:
1.34 anton 6025:
1.69 anton 6026: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6027: @subsection Anonymous Definitions
6028: @cindex colon definitions
6029: @cindex defining words without name
1.34 anton 6030:
1.44 crook 6031: Sometimes you want to define an @dfn{anonymous word}; a word without a
6032: name. You can do this with:
1.1 anton 6033:
1.44 crook 6034: doc-:noname
1.1 anton 6035:
1.44 crook 6036: This leaves the execution token for the word on the stack after the
6037: closing @code{;}. Here's an example in which a deferred word is
6038: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6039:
1.29 crook 6040: @example
1.44 crook 6041: Defer deferred
6042: :noname ( ... -- ... )
6043: ... ;
6044: IS deferred
1.29 crook 6045: @end example
1.26 crook 6046:
1.44 crook 6047: @noindent
6048: Gforth provides an alternative way of doing this, using two separate
6049: words:
1.27 crook 6050:
1.44 crook 6051: doc-noname
6052: @cindex execution token of last defined word
1.116 anton 6053: doc-latestxt
1.1 anton 6054:
1.44 crook 6055: @noindent
6056: The previous example can be rewritten using @code{noname} and
1.116 anton 6057: @code{latestxt}:
1.1 anton 6058:
1.26 crook 6059: @example
1.44 crook 6060: Defer deferred
6061: noname : ( ... -- ... )
6062: ... ;
1.116 anton 6063: latestxt IS deferred
1.26 crook 6064: @end example
1.1 anton 6065:
1.29 crook 6066: @noindent
1.44 crook 6067: @code{noname} works with any defining word, not just @code{:}.
6068:
1.116 anton 6069: @code{latestxt} also works when the last word was not defined as
1.71 anton 6070: @code{noname}. It does not work for combined words, though. It also has
6071: the useful property that is is valid as soon as the header for a
6072: definition has been built. Thus:
1.44 crook 6073:
6074: @example
1.116 anton 6075: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6076: @end example
1.1 anton 6077:
1.44 crook 6078: @noindent
6079: prints 3 numbers; the last two are the same.
1.26 crook 6080:
1.69 anton 6081: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6082: @subsection Supplying the name of a defined word
6083: @cindex names for defined words
6084: @cindex defining words, name given in a string
6085:
6086: By default, a defining word takes the name for the defined word from the
6087: input stream. Sometimes you want to supply the name from a string. You
6088: can do this with:
6089:
6090: doc-nextname
6091:
6092: For example:
6093:
6094: @example
6095: s" foo" nextname create
6096: @end example
6097:
6098: @noindent
6099: is equivalent to:
6100:
6101: @example
6102: create foo
6103: @end example
6104:
6105: @noindent
6106: @code{nextname} works with any defining word.
6107:
1.1 anton 6108:
1.69 anton 6109: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26 crook 6110: @subsection User-defined Defining Words
6111: @cindex user-defined defining words
6112: @cindex defining words, user-defined
1.1 anton 6113:
1.29 crook 6114: You can create a new defining word by wrapping defining-time code around
6115: an existing defining word and putting the sequence in a colon
1.69 anton 6116: definition.
6117:
6118: @c anton: This example is very complex and leads in a quite different
6119: @c direction from the CREATE-DOES> stuff that follows. It should probably
6120: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6121: @c subsection of Defining Words)
6122:
6123: For example, suppose that you have a word @code{stats} that
1.29 crook 6124: gathers statistics about colon definitions given the @i{xt} of the
6125: definition, and you want every colon definition in your application to
6126: make a call to @code{stats}. You can define and use a new version of
6127: @code{:} like this:
6128:
6129: @example
6130: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6131: ... ; \ other code
6132:
1.116 anton 6133: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6134:
6135: my: foo + - ;
6136: @end example
6137:
6138: When @code{foo} is defined using @code{my:} these steps occur:
6139:
6140: @itemize @bullet
6141: @item
6142: @code{my:} is executed.
6143: @item
6144: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6145: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6146: the input stream for a name, builds a dictionary header for the name
6147: @code{foo} and switches @code{state} from interpret to compile.
6148: @item
1.116 anton 6149: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6150: being defined -- @code{foo} -- onto the stack.
6151: @item
6152: The code that was produced by @code{postpone literal} is executed; this
6153: causes the value on the stack to be compiled as a literal in the code
6154: area of @code{foo}.
6155: @item
6156: The code @code{['] stats} compiles a literal into the definition of
6157: @code{my:}. When @code{compile,} is executed, that literal -- the
6158: execution token for @code{stats} -- is layed down in the code area of
6159: @code{foo} , following the literal@footnote{Strictly speaking, the
6160: mechanism that @code{compile,} uses to convert an @i{xt} into something
6161: in the code area is implementation-dependent. A threaded implementation
6162: might spit out the execution token directly whilst another
6163: implementation might spit out a native code sequence.}.
6164: @item
6165: At this point, the execution of @code{my:} is complete, and control
6166: returns to the text interpreter. The text interpreter is in compile
6167: state, so subsequent text @code{+ -} is compiled into the definition of
6168: @code{foo} and the @code{;} terminates the definition as always.
6169: @end itemize
6170:
6171: You can use @code{see} to decompile a word that was defined using
6172: @code{my:} and see how it is different from a normal @code{:}
6173: definition. For example:
6174:
6175: @example
6176: : bar + - ; \ like foo but using : rather than my:
6177: see bar
6178: : bar
6179: + - ;
6180: see foo
6181: : foo
6182: 107645672 stats + - ;
6183:
1.140 anton 6184: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6185: @end example
6186:
6187: You can use techniques like this to make new defining words in terms of
6188: @i{any} existing defining word.
1.1 anton 6189:
6190:
1.29 crook 6191: @cindex defining defining words
1.26 crook 6192: @cindex @code{CREATE} ... @code{DOES>}
6193: If you want the words defined with your defining words to behave
6194: differently from words defined with standard defining words, you can
6195: write your defining word like this:
1.1 anton 6196:
6197: @example
1.26 crook 6198: : def-word ( "name" -- )
1.29 crook 6199: CREATE @i{code1}
1.26 crook 6200: DOES> ( ... -- ... )
1.29 crook 6201: @i{code2} ;
1.26 crook 6202:
6203: def-word name
1.1 anton 6204: @end example
6205:
1.29 crook 6206: @cindex child words
6207: This fragment defines a @dfn{defining word} @code{def-word} and then
6208: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6209: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6210: is not executed at this time. The word @code{name} is sometimes called a
6211: @dfn{child} of @code{def-word}.
6212:
6213: When you execute @code{name}, the address of the body of @code{name} is
6214: put on the data stack and @i{code2} is executed (the address of the body
6215: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6216: @code{CREATE}, i.e., the address a @code{create}d word returns by
6217: default).
6218:
6219: @c anton:
6220: @c www.dictionary.com says:
6221: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6222: @c several generations of absence, usually caused by the chance
6223: @c recombination of genes. 2.An individual or a part that exhibits
6224: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6225: @c of previous behavior after a period of absence.
6226: @c
6227: @c Doesn't seem to fit.
1.29 crook 6228:
1.69 anton 6229: @c @cindex atavism in child words
1.33 anton 6230: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6231: similarly; they all have a common run-time behaviour determined by
6232: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6233: body of the child word. The structure of the data is common to all
6234: children of @code{def-word}, but the data values are specific -- and
6235: private -- to each child word. When a child word is executed, the
6236: address of its private data area is passed as a parameter on TOS to be
6237: used and manipulated@footnote{It is legitimate both to read and write to
6238: this data area.} by @i{code2}.
1.29 crook 6239:
6240: The two fragments of code that make up the defining words act (are
6241: executed) at two completely separate times:
1.1 anton 6242:
1.29 crook 6243: @itemize @bullet
6244: @item
6245: At @i{define time}, the defining word executes @i{code1} to generate a
6246: child word
6247: @item
6248: At @i{child execution time}, when a child word is invoked, @i{code2}
6249: is executed, using parameters (data) that are private and specific to
6250: the child word.
6251: @end itemize
6252:
1.44 crook 6253: Another way of understanding the behaviour of @code{def-word} and
6254: @code{name} is to say that, if you make the following definitions:
1.33 anton 6255: @example
6256: : def-word1 ( "name" -- )
6257: CREATE @i{code1} ;
6258:
6259: : action1 ( ... -- ... )
6260: @i{code2} ;
6261:
6262: def-word1 name1
6263: @end example
6264:
1.44 crook 6265: @noindent
6266: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6267:
1.29 crook 6268: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6269:
1.1 anton 6270: @example
1.29 crook 6271: : CONSTANT ( w "name" -- )
6272: CREATE ,
1.26 crook 6273: DOES> ( -- w )
6274: @@ ;
1.1 anton 6275: @end example
6276:
1.29 crook 6277: @comment There is a beautiful description of how this works and what
6278: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6279: @comment commentary on the Counting Fruits problem.
6280:
6281: When you create a constant with @code{5 CONSTANT five}, a set of
6282: define-time actions take place; first a new word @code{five} is created,
6283: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6284: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6285: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6286: no code of its own; it simply contains a data field and a pointer to the
6287: code that follows @code{DOES>} in its defining word. That makes words
6288: created in this way very compact.
6289:
6290: The final example in this section is intended to remind you that space
6291: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6292: both read and written by a Standard program@footnote{Exercise: use this
6293: example as a starting point for your own implementation of @code{Value}
6294: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6295: @code{[']}.}:
6296:
6297: @example
6298: : foo ( "name" -- )
6299: CREATE -1 ,
6300: DOES> ( -- )
1.33 anton 6301: @@ . ;
1.29 crook 6302:
6303: foo first-word
6304: foo second-word
6305:
6306: 123 ' first-word >BODY !
6307: @end example
6308:
6309: If @code{first-word} had been a @code{CREATE}d word, we could simply
6310: have executed it to get the address of its data field. However, since it
6311: was defined to have @code{DOES>} actions, its execution semantics are to
6312: perform those @code{DOES>} actions. To get the address of its data field
6313: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6314: translate the xt into the address of the data field. When you execute
6315: @code{first-word}, it will display @code{123}. When you execute
6316: @code{second-word} it will display @code{-1}.
1.26 crook 6317:
6318: @cindex stack effect of @code{DOES>}-parts
6319: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6320: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6321: the stack effect of the defined words, not the stack effect of the
6322: following code (the following code expects the address of the body on
6323: the top of stack, which is not reflected in the stack comment). This is
6324: the convention that I use and recommend (it clashes a bit with using
6325: locals declarations for stack effect specification, though).
1.1 anton 6326:
1.53 anton 6327: @menu
6328: * CREATE..DOES> applications::
6329: * CREATE..DOES> details::
1.63 anton 6330: * Advanced does> usage example::
1.91 anton 6331: * @code{Const-does>}::
1.53 anton 6332: @end menu
6333:
6334: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6335: @subsubsection Applications of @code{CREATE..DOES>}
6336: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6337:
1.26 crook 6338: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6339:
1.26 crook 6340: @cindex factoring similar colon definitions
6341: When you see a sequence of code occurring several times, and you can
6342: identify a meaning, you will factor it out as a colon definition. When
6343: you see similar colon definitions, you can factor them using
6344: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6345: that look very similar:
1.1 anton 6346: @example
1.26 crook 6347: : ori, ( reg-target reg-source n -- )
6348: 0 asm-reg-reg-imm ;
6349: : andi, ( reg-target reg-source n -- )
6350: 1 asm-reg-reg-imm ;
1.1 anton 6351: @end example
6352:
1.26 crook 6353: @noindent
6354: This could be factored with:
6355: @example
6356: : reg-reg-imm ( op-code -- )
6357: CREATE ,
6358: DOES> ( reg-target reg-source n -- )
6359: @@ asm-reg-reg-imm ;
6360:
6361: 0 reg-reg-imm ori,
6362: 1 reg-reg-imm andi,
6363: @end example
1.1 anton 6364:
1.26 crook 6365: @cindex currying
6366: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6367: supply a part of the parameters for a word (known as @dfn{currying} in
6368: the functional language community). E.g., @code{+} needs two
6369: parameters. Creating versions of @code{+} with one parameter fixed can
6370: be done like this:
1.82 anton 6371:
1.1 anton 6372: @example
1.82 anton 6373: : curry+ ( n1 "name" -- )
1.26 crook 6374: CREATE ,
6375: DOES> ( n2 -- n1+n2 )
6376: @@ + ;
6377:
6378: 3 curry+ 3+
6379: -2 curry+ 2-
1.1 anton 6380: @end example
6381:
1.91 anton 6382:
1.63 anton 6383: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6384: @subsubsection The gory details of @code{CREATE..DOES>}
6385: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6386:
1.26 crook 6387: doc-does>
1.1 anton 6388:
1.26 crook 6389: @cindex @code{DOES>} in a separate definition
6390: This means that you need not use @code{CREATE} and @code{DOES>} in the
6391: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6392: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6393: @example
6394: : does1
6395: DOES> ( ... -- ... )
1.44 crook 6396: ... ;
6397:
6398: : does2
6399: DOES> ( ... -- ... )
6400: ... ;
6401:
6402: : def-word ( ... -- ... )
6403: create ...
6404: IF
6405: does1
6406: ELSE
6407: does2
6408: ENDIF ;
6409: @end example
6410:
6411: In this example, the selection of whether to use @code{does1} or
1.69 anton 6412: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6413: @code{CREATE}d.
6414:
6415: @cindex @code{DOES>} in interpretation state
6416: In a standard program you can apply a @code{DOES>}-part only if the last
6417: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6418: will override the behaviour of the last word defined in any case. In a
6419: standard program, you can use @code{DOES>} only in a colon
6420: definition. In Gforth, you can also use it in interpretation state, in a
6421: kind of one-shot mode; for example:
6422: @example
6423: CREATE name ( ... -- ... )
6424: @i{initialization}
6425: DOES>
6426: @i{code} ;
6427: @end example
6428:
6429: @noindent
6430: is equivalent to the standard:
6431: @example
6432: :noname
6433: DOES>
6434: @i{code} ;
6435: CREATE name EXECUTE ( ... -- ... )
6436: @i{initialization}
6437: @end example
6438:
1.53 anton 6439: doc->body
6440:
1.91 anton 6441: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6442: @subsubsection Advanced does> usage example
6443:
6444: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6445: for disassembling instructions, that follow a very repetetive scheme:
6446:
6447: @example
6448: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6449: @var{entry-num} cells @var{table} + !
6450: @end example
6451:
6452: Of course, this inspires the idea to factor out the commonalities to
6453: allow a definition like
6454:
6455: @example
6456: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6457: @end example
6458:
6459: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6460: correlated. Moreover, before I wrote the disassembler, there already
6461: existed code that defines instructions like this:
1.63 anton 6462:
6463: @example
6464: @var{entry-num} @var{inst-format} @var{inst-name}
6465: @end example
6466:
6467: This code comes from the assembler and resides in
6468: @file{arch/mips/insts.fs}.
6469:
6470: So I had to define the @var{inst-format} words that performed the scheme
6471: above when executed. At first I chose to use run-time code-generation:
6472:
6473: @example
6474: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6475: :noname Postpone @var{disasm-operands}
6476: name Postpone sliteral Postpone type Postpone ;
6477: swap cells @var{table} + ! ;
6478: @end example
6479:
6480: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6481:
1.63 anton 6482: An alternative would have been to write this using
6483: @code{create}/@code{does>}:
6484:
6485: @example
6486: : @var{inst-format} ( entry-num "name" -- )
6487: here name string, ( entry-num c-addr ) \ parse and save "name"
6488: noname create , ( entry-num )
1.116 anton 6489: latestxt swap cells @var{table} + !
1.63 anton 6490: does> ( addr w -- )
6491: \ disassemble instruction w at addr
6492: @@ >r
6493: @var{disasm-operands}
6494: r> count type ;
6495: @end example
6496:
6497: Somehow the first solution is simpler, mainly because it's simpler to
6498: shift a string from definition-time to use-time with @code{sliteral}
6499: than with @code{string,} and friends.
6500:
6501: I wrote a lot of words following this scheme and soon thought about
6502: factoring out the commonalities among them. Note that this uses a
6503: two-level defining word, i.e., a word that defines ordinary defining
6504: words.
6505:
6506: This time a solution involving @code{postpone} and friends seemed more
6507: difficult (try it as an exercise), so I decided to use a
6508: @code{create}/@code{does>} word; since I was already at it, I also used
6509: @code{create}/@code{does>} for the lower level (try using
6510: @code{postpone} etc. as an exercise), resulting in the following
6511: definition:
6512:
6513: @example
6514: : define-format ( disasm-xt table-xt -- )
6515: \ define an instruction format that uses disasm-xt for
6516: \ disassembling and enters the defined instructions into table
6517: \ table-xt
6518: create 2,
6519: does> ( u "inst" -- )
6520: \ defines an anonymous word for disassembling instruction inst,
6521: \ and enters it as u-th entry into table-xt
6522: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6523: noname create 2, \ define anonymous word
1.116 anton 6524: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6525: does> ( addr w -- )
6526: \ disassemble instruction w at addr
6527: 2@@ >r ( addr w disasm-xt R: c-addr )
6528: execute ( R: c-addr ) \ disassemble operands
6529: r> count type ; \ print name
6530: @end example
6531:
6532: Note that the tables here (in contrast to above) do the @code{cells +}
6533: by themselves (that's why you have to pass an xt). This word is used in
6534: the following way:
6535:
6536: @example
6537: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6538: @end example
6539:
1.71 anton 6540: As shown above, the defined instruction format is then used like this:
6541:
6542: @example
6543: @var{entry-num} @var{inst-format} @var{inst-name}
6544: @end example
6545:
1.63 anton 6546: In terms of currying, this kind of two-level defining word provides the
6547: parameters in three stages: first @var{disasm-operands} and @var{table},
6548: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6549: the instruction to be disassembled.
6550:
6551: Of course this did not quite fit all the instruction format names used
6552: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6553: the parameters into the right form.
6554:
6555: If you have trouble following this section, don't worry. First, this is
6556: involved and takes time (and probably some playing around) to
6557: understand; second, this is the first two-level
6558: @code{create}/@code{does>} word I have written in seventeen years of
6559: Forth; and if I did not have @file{insts.fs} to start with, I may well
6560: have elected to use just a one-level defining word (with some repeating
6561: of parameters when using the defining word). So it is not necessary to
6562: understand this, but it may improve your understanding of Forth.
1.44 crook 6563:
6564:
1.91 anton 6565: @node @code{Const-does>}, , Advanced does> usage example, User-defined Defining Words
6566: @subsubsection @code{Const-does>}
6567:
6568: A frequent use of @code{create}...@code{does>} is for transferring some
6569: values from definition-time to run-time. Gforth supports this use with
6570:
6571: doc-const-does>
6572:
6573: A typical use of this word is:
6574:
6575: @example
6576: : curry+ ( n1 "name" -- )
6577: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6578: + ;
6579:
6580: 3 curry+ 3+
6581: @end example
6582:
6583: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6584: definition to run-time.
6585:
6586: The advantages of using @code{const-does>} are:
6587:
6588: @itemize
6589:
6590: @item
6591: You don't have to deal with storing and retrieving the values, i.e.,
6592: your program becomes more writable and readable.
6593:
6594: @item
6595: When using @code{does>}, you have to introduce a @code{@@} that cannot
6596: be optimized away (because you could change the data using
6597: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6598:
6599: @end itemize
6600:
6601: An ANS Forth implementation of @code{const-does>} is available in
6602: @file{compat/const-does.fs}.
6603:
6604:
1.44 crook 6605: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6606: @subsection Deferred words
6607: @cindex deferred words
6608:
6609: The defining word @code{Defer} allows you to define a word by name
6610: without defining its behaviour; the definition of its behaviour is
6611: deferred. Here are two situation where this can be useful:
6612:
6613: @itemize @bullet
6614: @item
6615: Where you want to allow the behaviour of a word to be altered later, and
6616: for all precompiled references to the word to change when its behaviour
6617: is changed.
6618: @item
6619: For mutual recursion; @xref{Calls and returns}.
6620: @end itemize
6621:
6622: In the following example, @code{foo} always invokes the version of
6623: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6624: always invokes the version that prints ``@code{Hello}''. There is no way
6625: of getting @code{foo} to use the later version without re-ordering the
6626: source code and recompiling it.
6627:
6628: @example
6629: : greet ." Good morning" ;
6630: : foo ... greet ... ;
6631: : greet ." Hello" ;
6632: : bar ... greet ... ;
6633: @end example
6634:
6635: This problem can be solved by defining @code{greet} as a @code{Defer}red
6636: word. The behaviour of a @code{Defer}red word can be defined and
6637: redefined at any time by using @code{IS} to associate the xt of a
6638: previously-defined word with it. The previous example becomes:
6639:
6640: @example
1.69 anton 6641: Defer greet ( -- )
1.44 crook 6642: : foo ... greet ... ;
6643: : bar ... greet ... ;
1.69 anton 6644: : greet1 ( -- ) ." Good morning" ;
6645: : greet2 ( -- ) ." Hello" ;
1.132 anton 6646: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6647: @end example
6648:
1.69 anton 6649: @progstyle
6650: You should write a stack comment for every deferred word, and put only
6651: XTs into deferred words that conform to this stack effect. Otherwise
6652: it's too difficult to use the deferred word.
6653:
1.44 crook 6654: A deferred word can be used to improve the statistics-gathering example
6655: from @ref{User-defined Defining Words}; rather than edit the
6656: application's source code to change every @code{:} to a @code{my:}, do
6657: this:
6658:
6659: @example
6660: : real: : ; \ retain access to the original
6661: defer : \ redefine as a deferred word
1.132 anton 6662: ' my: IS : \ use special version of :
1.44 crook 6663: \
6664: \ load application here
6665: \
1.132 anton 6666: ' real: IS : \ go back to the original
1.44 crook 6667: @end example
6668:
6669:
1.132 anton 6670: One thing to note is that @code{IS} has special compilation semantics,
6671: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6672:
6673: @example
6674: : set-greet ( xt -- )
1.132 anton 6675: IS greet ;
1.44 crook 6676:
6677: ' greet1 set-greet
6678: @end example
6679:
1.132 anton 6680: In situations where @code{IS} does not fit, use @code{defer!} instead.
6681:
1.69 anton 6682: A deferred word can only inherit execution semantics from the xt
6683: (because that is all that an xt can represent -- for more discussion of
6684: this @pxref{Tokens for Words}); by default it will have default
6685: interpretation and compilation semantics deriving from this execution
6686: semantics. However, you can change the interpretation and compilation
6687: semantics of the deferred word in the usual ways:
1.44 crook 6688:
6689: @example
1.132 anton 6690: : bar .... ; immediate
1.44 crook 6691: Defer fred immediate
6692: Defer jim
6693:
1.132 anton 6694: ' bar IS jim \ jim has default semantics
6695: ' bar IS fred \ fred is immediate
1.44 crook 6696: @end example
6697:
6698: doc-defer
1.132 anton 6699: doc-defer!
1.44 crook 6700: doc-is
1.132 anton 6701: doc-defer@
6702: doc-action-of
1.44 crook 6703: @comment TODO document these: what's defers [is]
6704: doc-defers
6705:
6706: @c Use @code{words-deferred} to see a list of deferred words.
6707:
1.132 anton 6708: Definitions of these words (except @code{defers}) in ANS Forth are
6709: provided in @file{compat/defer.fs}.
1.44 crook 6710:
6711:
1.69 anton 6712: @node Aliases, , Deferred words, Defining Words
1.44 crook 6713: @subsection Aliases
6714: @cindex aliases
1.1 anton 6715:
1.44 crook 6716: The defining word @code{Alias} allows you to define a word by name that
6717: has the same behaviour as some other word. Here are two situation where
6718: this can be useful:
1.1 anton 6719:
1.44 crook 6720: @itemize @bullet
6721: @item
6722: When you want access to a word's definition from a different word list
6723: (for an example of this, see the definition of the @code{Root} word list
6724: in the Gforth source).
6725: @item
6726: When you want to create a synonym; a definition that can be known by
6727: either of two names (for example, @code{THEN} and @code{ENDIF} are
6728: aliases).
6729: @end itemize
1.1 anton 6730:
1.69 anton 6731: Like deferred words, an alias has default compilation and interpretation
6732: semantics at the beginning (not the modifications of the other word),
6733: but you can change them in the usual ways (@code{immediate},
6734: @code{compile-only}). For example:
1.1 anton 6735:
6736: @example
1.44 crook 6737: : foo ... ; immediate
6738:
6739: ' foo Alias bar \ bar is not an immediate word
6740: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6741: @end example
6742:
1.44 crook 6743: Words that are aliases have the same xt, different headers in the
6744: dictionary, and consequently different name tokens (@pxref{Tokens for
6745: Words}) and possibly different immediate flags. An alias can only have
6746: default or immediate compilation semantics; you can define aliases for
6747: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6748:
1.44 crook 6749: doc-alias
1.1 anton 6750:
6751:
1.47 crook 6752: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6753: @section Interpretation and Compilation Semantics
1.26 crook 6754: @cindex semantics, interpretation and compilation
1.1 anton 6755:
1.71 anton 6756: @c !! state and ' are used without explanation
6757: @c example for immediate/compile-only? or is the tutorial enough
6758:
1.26 crook 6759: @cindex interpretation semantics
1.71 anton 6760: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6761: interpreter does when it encounters the word in interpret state. It also
6762: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6763: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6764: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6765: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6766:
1.26 crook 6767: @cindex compilation semantics
1.71 anton 6768: The @dfn{compilation semantics} of a (named) word are what the text
6769: interpreter does when it encounters the word in compile state. It also
6770: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6771: compiles@footnote{In standard terminology, ``appends to the current
6772: definition''.} the compilation semantics of @i{word}.
1.1 anton 6773:
1.26 crook 6774: @cindex execution semantics
6775: The standard also talks about @dfn{execution semantics}. They are used
6776: only for defining the interpretation and compilation semantics of many
6777: words. By default, the interpretation semantics of a word are to
6778: @code{execute} its execution semantics, and the compilation semantics of
6779: a word are to @code{compile,} its execution semantics.@footnote{In
6780: standard terminology: The default interpretation semantics are its
6781: execution semantics; the default compilation semantics are to append its
6782: execution semantics to the execution semantics of the current
6783: definition.}
6784:
1.71 anton 6785: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6786: the text interpreter, ticked, or @code{postpone}d, so they have no
6787: interpretation or compilation semantics. Their behaviour is represented
6788: by their XT (@pxref{Tokens for Words}), and we call it execution
6789: semantics, too.
6790:
1.26 crook 6791: @comment TODO expand, make it co-operate with new sections on text interpreter.
6792:
6793: @cindex immediate words
6794: @cindex compile-only words
6795: You can change the semantics of the most-recently defined word:
6796:
1.44 crook 6797:
1.26 crook 6798: doc-immediate
6799: doc-compile-only
6800: doc-restrict
6801:
1.82 anton 6802: By convention, words with non-default compilation semantics (e.g.,
6803: immediate words) often have names surrounded with brackets (e.g.,
6804: @code{[']}, @pxref{Execution token}).
1.44 crook 6805:
1.26 crook 6806: Note that ticking (@code{'}) a compile-only word gives an error
6807: (``Interpreting a compile-only word'').
1.1 anton 6808:
1.47 crook 6809: @menu
1.67 anton 6810: * Combined words::
1.47 crook 6811: @end menu
1.44 crook 6812:
1.71 anton 6813:
1.48 anton 6814: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6815: @subsection Combined Words
6816: @cindex combined words
6817:
6818: Gforth allows you to define @dfn{combined words} -- words that have an
6819: arbitrary combination of interpretation and compilation semantics.
6820:
1.26 crook 6821: doc-interpret/compile:
1.1 anton 6822:
1.26 crook 6823: This feature was introduced for implementing @code{TO} and @code{S"}. I
6824: recommend that you do not define such words, as cute as they may be:
6825: they make it hard to get at both parts of the word in some contexts.
6826: E.g., assume you want to get an execution token for the compilation
6827: part. Instead, define two words, one that embodies the interpretation
6828: part, and one that embodies the compilation part. Once you have done
6829: that, you can define a combined word with @code{interpret/compile:} for
6830: the convenience of your users.
1.1 anton 6831:
1.26 crook 6832: You might try to use this feature to provide an optimizing
6833: implementation of the default compilation semantics of a word. For
6834: example, by defining:
1.1 anton 6835: @example
1.26 crook 6836: :noname
6837: foo bar ;
6838: :noname
6839: POSTPONE foo POSTPONE bar ;
1.29 crook 6840: interpret/compile: opti-foobar
1.1 anton 6841: @end example
1.26 crook 6842:
1.23 crook 6843: @noindent
1.26 crook 6844: as an optimizing version of:
6845:
1.1 anton 6846: @example
1.26 crook 6847: : foobar
6848: foo bar ;
1.1 anton 6849: @end example
6850:
1.26 crook 6851: Unfortunately, this does not work correctly with @code{[compile]},
6852: because @code{[compile]} assumes that the compilation semantics of all
6853: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6854: opti-foobar} would compile compilation semantics, whereas
6855: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6856:
1.26 crook 6857: @cindex state-smart words (are a bad idea)
1.82 anton 6858: @anchor{state-smartness}
1.29 crook 6859: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6860: by @code{interpret/compile:} (words are state-smart if they check
6861: @code{STATE} during execution). E.g., they would try to code
6862: @code{foobar} like this:
1.1 anton 6863:
1.26 crook 6864: @example
6865: : foobar
6866: STATE @@
6867: IF ( compilation state )
6868: POSTPONE foo POSTPONE bar
6869: ELSE
6870: foo bar
6871: ENDIF ; immediate
6872: @end example
1.1 anton 6873:
1.26 crook 6874: Although this works if @code{foobar} is only processed by the text
6875: interpreter, it does not work in other contexts (like @code{'} or
6876: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6877: for a state-smart word, not for the interpretation semantics of the
6878: original @code{foobar}; when you execute this execution token (directly
6879: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6880: state, the result will not be what you expected (i.e., it will not
6881: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6882: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6883: M. Anton Ertl,
6884: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6885: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6886:
1.26 crook 6887: @cindex defining words with arbitrary semantics combinations
6888: It is also possible to write defining words that define words with
6889: arbitrary combinations of interpretation and compilation semantics. In
6890: general, they look like this:
1.1 anton 6891:
1.26 crook 6892: @example
6893: : def-word
6894: create-interpret/compile
1.29 crook 6895: @i{code1}
1.26 crook 6896: interpretation>
1.29 crook 6897: @i{code2}
1.26 crook 6898: <interpretation
6899: compilation>
1.29 crook 6900: @i{code3}
1.26 crook 6901: <compilation ;
6902: @end example
1.1 anton 6903:
1.29 crook 6904: For a @i{word} defined with @code{def-word}, the interpretation
6905: semantics are to push the address of the body of @i{word} and perform
6906: @i{code2}, and the compilation semantics are to push the address of
6907: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 6908: can also be defined like this (except that the defined constants don't
6909: behave correctly when @code{[compile]}d):
1.1 anton 6910:
1.26 crook 6911: @example
6912: : constant ( n "name" -- )
6913: create-interpret/compile
6914: ,
6915: interpretation> ( -- n )
6916: @@
6917: <interpretation
6918: compilation> ( compilation. -- ; run-time. -- n )
6919: @@ postpone literal
6920: <compilation ;
6921: @end example
1.1 anton 6922:
1.44 crook 6923:
1.26 crook 6924: doc-create-interpret/compile
6925: doc-interpretation>
6926: doc-<interpretation
6927: doc-compilation>
6928: doc-<compilation
1.1 anton 6929:
1.44 crook 6930:
1.29 crook 6931: Words defined with @code{interpret/compile:} and
1.26 crook 6932: @code{create-interpret/compile} have an extended header structure that
6933: differs from other words; however, unless you try to access them with
6934: plain address arithmetic, you should not notice this. Words for
6935: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 6936: @code{'} @i{word} @code{>body} also gives you the body of a word created
6937: with @code{create-interpret/compile}.
1.1 anton 6938:
1.44 crook 6939:
1.47 crook 6940: @c -------------------------------------------------------------
1.81 anton 6941: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 6942: @section Tokens for Words
6943: @cindex tokens for words
6944:
6945: This section describes the creation and use of tokens that represent
6946: words.
6947:
1.71 anton 6948: @menu
6949: * Execution token:: represents execution/interpretation semantics
6950: * Compilation token:: represents compilation semantics
6951: * Name token:: represents named words
6952: @end menu
1.47 crook 6953:
1.71 anton 6954: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
6955: @subsection Execution token
1.47 crook 6956:
6957: @cindex xt
6958: @cindex execution token
1.71 anton 6959: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
6960: You can use @code{execute} to invoke this behaviour.
1.47 crook 6961:
1.71 anton 6962: @cindex tick (')
6963: You can use @code{'} to get an execution token that represents the
6964: interpretation semantics of a named word:
1.47 crook 6965:
6966: @example
1.97 anton 6967: 5 ' . ( n xt )
6968: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 6969: @end example
1.47 crook 6970:
1.71 anton 6971: doc-'
6972:
6973: @code{'} parses at run-time; there is also a word @code{[']} that parses
6974: when it is compiled, and compiles the resulting XT:
6975:
6976: @example
6977: : foo ['] . execute ;
6978: 5 foo
6979: : bar ' execute ; \ by contrast,
6980: 5 bar . \ ' parses "." when bar executes
6981: @end example
6982:
6983: doc-[']
6984:
6985: If you want the execution token of @i{word}, write @code{['] @i{word}}
6986: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
6987: @code{'} and @code{[']} behave somewhat unusually by complaining about
6988: compile-only words (because these words have no interpretation
6989: semantics). You might get what you want by using @code{COMP' @i{word}
6990: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
6991: token}).
6992:
1.116 anton 6993: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 6994: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
6995: for the only behaviour the word has (the execution semantics). For
1.116 anton 6996: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 6997: would produce if the word was defined anonymously.
6998:
6999: @example
7000: :noname ." hello" ;
7001: execute
1.47 crook 7002: @end example
7003:
1.71 anton 7004: An XT occupies one cell and can be manipulated like any other cell.
7005:
1.47 crook 7006: @cindex code field address
7007: @cindex CFA
1.71 anton 7008: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7009: operations that produce or consume it). For old hands: In Gforth, the
7010: XT is implemented as a code field address (CFA).
7011:
7012: doc-execute
7013: doc-perform
7014:
7015: @node Compilation token, Name token, Execution token, Tokens for Words
7016: @subsection Compilation token
1.47 crook 7017:
7018: @cindex compilation token
1.71 anton 7019: @cindex CT (compilation token)
7020: Gforth represents the compilation semantics of a named word by a
1.47 crook 7021: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7022: @i{xt} is an execution token. The compilation semantics represented by
7023: the compilation token can be performed with @code{execute}, which
7024: consumes the whole compilation token, with an additional stack effect
7025: determined by the represented compilation semantics.
7026:
7027: At present, the @i{w} part of a compilation token is an execution token,
7028: and the @i{xt} part represents either @code{execute} or
7029: @code{compile,}@footnote{Depending upon the compilation semantics of the
7030: word. If the word has default compilation semantics, the @i{xt} will
7031: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7032: @i{xt} will represent @code{execute}.}. However, don't rely on that
7033: knowledge, unless necessary; future versions of Gforth may introduce
7034: unusual compilation tokens (e.g., a compilation token that represents
7035: the compilation semantics of a literal).
7036:
1.71 anton 7037: You can perform the compilation semantics represented by the compilation
7038: token with @code{execute}. You can compile the compilation semantics
7039: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7040: equivalent to @code{postpone @i{word}}.
7041:
7042: doc-[comp']
7043: doc-comp'
7044: doc-postpone,
7045:
7046: @node Name token, , Compilation token, Tokens for Words
7047: @subsection Name token
1.47 crook 7048:
7049: @cindex name token
1.116 anton 7050: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7051: token is an abstract data type that occurs as argument or result of the
7052: words below.
7053:
7054: @c !! put this elswhere?
1.47 crook 7055: @cindex name field address
7056: @cindex NFA
1.116 anton 7057: The closest thing to the nt in older Forth systems is the name field
7058: address (NFA), but there are significant differences: in older Forth
7059: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7060: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7061: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7062: is a link field in the structure identified by the name token, but
7063: searching usually uses a hash table external to these structures; the
7064: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7065: implemented as the address of that count field.
1.47 crook 7066:
7067: doc-find-name
1.116 anton 7068: doc-latest
7069: doc->name
1.47 crook 7070: doc-name>int
7071: doc-name?int
7072: doc-name>comp
7073: doc-name>string
1.109 anton 7074: doc-id.
7075: doc-.name
7076: doc-.id
1.47 crook 7077:
1.81 anton 7078: @c ----------------------------------------------------------
7079: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7080: @section Compiling words
7081: @cindex compiling words
7082: @cindex macros
7083:
7084: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7085: between compilation and run-time. E.g., you can run arbitrary code
7086: between defining words (or for computing data used by defining words
7087: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7088: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7089: running arbitrary code while compiling a colon definition (exception:
7090: you must not allot dictionary space).
7091:
7092: @menu
7093: * Literals:: Compiling data values
7094: * Macros:: Compiling words
7095: @end menu
7096:
7097: @node Literals, Macros, Compiling words, Compiling words
7098: @subsection Literals
7099: @cindex Literals
7100:
7101: The simplest and most frequent example is to compute a literal during
7102: compilation. E.g., the following definition prints an array of strings,
7103: one string per line:
7104:
7105: @example
7106: : .strings ( addr u -- ) \ gforth
7107: 2* cells bounds U+DO
7108: cr i 2@@ type
7109: 2 cells +LOOP ;
7110: @end example
1.81 anton 7111:
1.82 anton 7112: With a simple-minded compiler like Gforth's, this computes @code{2
7113: cells} on every loop iteration. You can compute this value once and for
7114: all at compile time and compile it into the definition like this:
7115:
7116: @example
7117: : .strings ( addr u -- ) \ gforth
7118: 2* cells bounds U+DO
7119: cr i 2@@ type
7120: [ 2 cells ] literal +LOOP ;
7121: @end example
7122:
7123: @code{[} switches the text interpreter to interpret state (you will get
7124: an @code{ok} prompt if you type this example interactively and insert a
7125: newline between @code{[} and @code{]}), so it performs the
7126: interpretation semantics of @code{2 cells}; this computes a number.
7127: @code{]} switches the text interpreter back into compile state. It then
7128: performs @code{Literal}'s compilation semantics, which are to compile
7129: this number into the current word. You can decompile the word with
7130: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7131:
1.82 anton 7132: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7133: *} in this way.
1.81 anton 7134:
1.82 anton 7135: doc-[
7136: doc-]
1.81 anton 7137: doc-literal
7138: doc-]L
1.82 anton 7139:
7140: There are also words for compiling other data types than single cells as
7141: literals:
7142:
1.81 anton 7143: doc-2literal
7144: doc-fliteral
1.82 anton 7145: doc-sliteral
7146:
7147: @cindex colon-sys, passing data across @code{:}
7148: @cindex @code{:}, passing data across
7149: You might be tempted to pass data from outside a colon definition to the
7150: inside on the data stack. This does not work, because @code{:} puhes a
7151: colon-sys, making stuff below unaccessible. E.g., this does not work:
7152:
7153: @example
7154: 5 : foo literal ; \ error: "unstructured"
7155: @end example
7156:
7157: Instead, you have to pass the value in some other way, e.g., through a
7158: variable:
7159:
7160: @example
7161: variable temp
7162: 5 temp !
7163: : foo [ temp @@ ] literal ;
7164: @end example
7165:
7166:
7167: @node Macros, , Literals, Compiling words
7168: @subsection Macros
7169: @cindex Macros
7170: @cindex compiling compilation semantics
7171:
7172: @code{Literal} and friends compile data values into the current
7173: definition. You can also write words that compile other words into the
7174: current definition. E.g.,
7175:
7176: @example
7177: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7178: POSTPONE + ;
7179:
7180: : foo ( n1 n2 -- n )
7181: [ compile-+ ] ;
7182: 1 2 foo .
7183: @end example
7184:
7185: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7186: What happens in this example? @code{Postpone} compiles the compilation
7187: semantics of @code{+} into @code{compile-+}; later the text interpreter
7188: executes @code{compile-+} and thus the compilation semantics of +, which
7189: compile (the execution semantics of) @code{+} into
7190: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7191: should only be executed in compile state, so this example is not
7192: guaranteed to work on all standard systems, but on any decent system it
7193: will work.}
7194:
7195: doc-postpone
7196: doc-[compile]
7197:
7198: Compiling words like @code{compile-+} are usually immediate (or similar)
7199: so you do not have to switch to interpret state to execute them;
7200: mopifying the last example accordingly produces:
7201:
7202: @example
7203: : [compile-+] ( compilation: --; interpretation: -- )
7204: \ compiled code: ( n1 n2 -- n )
7205: POSTPONE + ; immediate
7206:
7207: : foo ( n1 n2 -- n )
7208: [compile-+] ;
7209: 1 2 foo .
7210: @end example
7211:
7212: Immediate compiling words are similar to macros in other languages (in
7213: particular, Lisp). The important differences to macros in, e.g., C are:
7214:
7215: @itemize @bullet
7216:
7217: @item
7218: You use the same language for defining and processing macros, not a
7219: separate preprocessing language and processor.
7220:
7221: @item
7222: Consequently, the full power of Forth is available in macro definitions.
7223: E.g., you can perform arbitrarily complex computations, or generate
7224: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7225: Tutorial}). This power is very useful when writing a parser generators
7226: or other code-generating software.
7227:
7228: @item
7229: Macros defined using @code{postpone} etc. deal with the language at a
7230: higher level than strings; name binding happens at macro definition
7231: time, so you can avoid the pitfalls of name collisions that can happen
7232: in C macros. Of course, Forth is a liberal language and also allows to
7233: shoot yourself in the foot with text-interpreted macros like
7234:
7235: @example
7236: : [compile-+] s" +" evaluate ; immediate
7237: @end example
7238:
7239: Apart from binding the name at macro use time, using @code{evaluate}
7240: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7241: @end itemize
7242:
7243: You may want the macro to compile a number into a word. The word to do
7244: it is @code{literal}, but you have to @code{postpone} it, so its
7245: compilation semantics take effect when the macro is executed, not when
7246: it is compiled:
7247:
7248: @example
7249: : [compile-5] ( -- ) \ compiled code: ( -- n )
7250: 5 POSTPONE literal ; immediate
7251:
7252: : foo [compile-5] ;
7253: foo .
7254: @end example
7255:
7256: You may want to pass parameters to a macro, that the macro should
7257: compile into the current definition. If the parameter is a number, then
7258: you can use @code{postpone literal} (similar for other values).
7259:
7260: If you want to pass a word that is to be compiled, the usual way is to
7261: pass an execution token and @code{compile,} it:
7262:
7263: @example
7264: : twice1 ( xt -- ) \ compiled code: ... -- ...
7265: dup compile, compile, ;
7266:
7267: : 2+ ( n1 -- n2 )
7268: [ ' 1+ twice1 ] ;
7269: @end example
7270:
7271: doc-compile,
7272:
7273: An alternative available in Gforth, that allows you to pass compile-only
7274: words as parameters is to use the compilation token (@pxref{Compilation
7275: token}). The same example in this technique:
7276:
7277: @example
7278: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7279: 2dup 2>r execute 2r> execute ;
7280:
7281: : 2+ ( n1 -- n2 )
7282: [ comp' 1+ twice ] ;
7283: @end example
7284:
7285: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7286: works even if the executed compilation semantics has an effect on the
7287: data stack.
7288:
7289: You can also define complete definitions with these words; this provides
7290: an alternative to using @code{does>} (@pxref{User-defined Defining
7291: Words}). E.g., instead of
7292:
7293: @example
7294: : curry+ ( n1 "name" -- )
7295: CREATE ,
7296: DOES> ( n2 -- n1+n2 )
7297: @@ + ;
7298: @end example
7299:
7300: you could define
7301:
7302: @example
7303: : curry+ ( n1 "name" -- )
7304: \ name execution: ( n2 -- n1+n2 )
7305: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7306:
1.82 anton 7307: -3 curry+ 3-
7308: see 3-
7309: @end example
1.81 anton 7310:
1.82 anton 7311: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7312: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7313:
1.82 anton 7314: This way of writing defining words is sometimes more, sometimes less
7315: convenient than using @code{does>} (@pxref{Advanced does> usage
7316: example}). One advantage of this method is that it can be optimized
7317: better, because the compiler knows that the value compiled with
7318: @code{literal} is fixed, whereas the data associated with a
7319: @code{create}d word can be changed.
1.47 crook 7320:
1.26 crook 7321: @c ----------------------------------------------------------
1.111 anton 7322: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7323: @section The Text Interpreter
7324: @cindex interpreter - outer
7325: @cindex text interpreter
7326: @cindex outer interpreter
1.1 anton 7327:
1.34 anton 7328: @c Should we really describe all these ugly details? IMO the text
7329: @c interpreter should be much cleaner, but that may not be possible within
7330: @c ANS Forth. - anton
1.44 crook 7331: @c nac-> I wanted to explain how it works to show how you can exploit
7332: @c it in your own programs. When I was writing a cross-compiler, figuring out
7333: @c some of these gory details was very helpful to me. None of the textbooks
7334: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7335: @c seems to positively avoid going into too much detail for some of
7336: @c the internals.
1.34 anton 7337:
1.71 anton 7338: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7339: @c it is; for the ugly details, I would prefer another place. I wonder
7340: @c whether we should have a chapter before "Words" that describes some
7341: @c basic concepts referred to in words, and a chapter after "Words" that
7342: @c describes implementation details.
7343:
1.29 crook 7344: The text interpreter@footnote{This is an expanded version of the
7345: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7346: that processes input from the current input device. It is also called
7347: the outer interpreter, in contrast to the inner interpreter
7348: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7349: implementations.
1.27 crook 7350:
1.29 crook 7351: @cindex interpret state
7352: @cindex compile state
7353: The text interpreter operates in one of two states: @dfn{interpret
7354: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7355: aptly-named variable @code{state}.
1.29 crook 7356:
7357: This section starts by describing how the text interpreter behaves when
7358: it is in interpret state, processing input from the user input device --
7359: the keyboard. This is the mode that a Forth system is in after it starts
7360: up.
7361:
7362: @cindex input buffer
7363: @cindex terminal input buffer
7364: The text interpreter works from an area of memory called the @dfn{input
7365: buffer}@footnote{When the text interpreter is processing input from the
7366: keyboard, this area of memory is called the @dfn{terminal input buffer}
7367: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7368: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7369: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7370: leading spaces (called @dfn{delimiters}) then parses a string (a
7371: sequence of non-space characters) until it reaches either a space
7372: character or the end of the buffer. Having parsed a string, it makes two
7373: attempts to process it:
1.27 crook 7374:
1.29 crook 7375: @cindex dictionary
1.27 crook 7376: @itemize @bullet
7377: @item
1.29 crook 7378: It looks for the string in a @dfn{dictionary} of definitions. If the
7379: string is found, the string names a @dfn{definition} (also known as a
7380: @dfn{word}) and the dictionary search returns information that allows
7381: the text interpreter to perform the word's @dfn{interpretation
7382: semantics}. In most cases, this simply means that the word will be
7383: executed.
1.27 crook 7384: @item
7385: If the string is not found in the dictionary, the text interpreter
1.29 crook 7386: attempts to treat it as a number, using the rules described in
7387: @ref{Number Conversion}. If the string represents a legal number in the
7388: current radix, the number is pushed onto a parameter stack (the data
7389: stack for integers, the floating-point stack for floating-point
7390: numbers).
7391: @end itemize
7392:
7393: If both attempts fail, or if the word is found in the dictionary but has
7394: no interpretation semantics@footnote{This happens if the word was
7395: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7396: remainder of the input buffer, issues an error message and waits for
7397: more input. If one of the attempts succeeds, the text interpreter
7398: repeats the parsing process until the whole of the input buffer has been
7399: processed, at which point it prints the status message ``@code{ ok}''
7400: and waits for more input.
7401:
1.71 anton 7402: @c anton: this should be in the input stream subsection (or below it)
7403:
1.29 crook 7404: @cindex parse area
7405: The text interpreter keeps track of its position in the input buffer by
7406: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7407: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7408: of the input buffer. The region from offset @code{>IN @@} to the end of
7409: the input buffer is called the @dfn{parse area}@footnote{In other words,
7410: the text interpreter processes the contents of the input buffer by
7411: parsing strings from the parse area until the parse area is empty.}.
7412: This example shows how @code{>IN} changes as the text interpreter parses
7413: the input buffer:
7414:
7415: @example
7416: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7417: CR ." ->" TYPE ." <-" ; IMMEDIATE
7418:
7419: 1 2 3 remaining + remaining .
7420:
7421: : foo 1 2 3 remaining SWAP remaining ;
7422: @end example
7423:
7424: @noindent
7425: The result is:
7426:
7427: @example
7428: ->+ remaining .<-
7429: ->.<-5 ok
7430:
7431: ->SWAP remaining ;-<
7432: ->;<- ok
7433: @end example
7434:
7435: @cindex parsing words
7436: The value of @code{>IN} can also be modified by a word in the input
7437: buffer that is executed by the text interpreter. This means that a word
7438: can ``trick'' the text interpreter into either skipping a section of the
7439: input buffer@footnote{This is how parsing words work.} or into parsing a
7440: section twice. For example:
1.27 crook 7441:
1.29 crook 7442: @example
1.71 anton 7443: : lat ." <<foo>>" ;
7444: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7445: @end example
7446:
7447: @noindent
7448: When @code{flat} is executed, this output is produced@footnote{Exercise
7449: for the reader: what would happen if the @code{3} were replaced with
7450: @code{4}?}:
7451:
7452: @example
1.71 anton 7453: <<bar>><<foo>>
1.29 crook 7454: @end example
7455:
1.71 anton 7456: This technique can be used to work around some of the interoperability
7457: problems of parsing words. Of course, it's better to avoid parsing
7458: words where possible.
7459:
1.29 crook 7460: @noindent
7461: Two important notes about the behaviour of the text interpreter:
1.27 crook 7462:
7463: @itemize @bullet
7464: @item
7465: It processes each input string to completion before parsing additional
1.29 crook 7466: characters from the input buffer.
7467: @item
7468: It treats the input buffer as a read-only region (and so must your code).
7469: @end itemize
7470:
7471: @noindent
7472: When the text interpreter is in compile state, its behaviour changes in
7473: these ways:
7474:
7475: @itemize @bullet
7476: @item
7477: If a parsed string is found in the dictionary, the text interpreter will
7478: perform the word's @dfn{compilation semantics}. In most cases, this
7479: simply means that the execution semantics of the word will be appended
7480: to the current definition.
1.27 crook 7481: @item
1.29 crook 7482: When a number is encountered, it is compiled into the current definition
7483: (as a literal) rather than being pushed onto a parameter stack.
7484: @item
7485: If an error occurs, @code{state} is modified to put the text interpreter
7486: back into interpret state.
7487: @item
7488: Each time a line is entered from the keyboard, Gforth prints
7489: ``@code{ compiled}'' rather than `` @code{ok}''.
7490: @end itemize
7491:
7492: @cindex text interpreter - input sources
7493: When the text interpreter is using an input device other than the
7494: keyboard, its behaviour changes in these ways:
7495:
7496: @itemize @bullet
7497: @item
7498: When the parse area is empty, the text interpreter attempts to refill
7499: the input buffer from the input source. When the input source is
1.71 anton 7500: exhausted, the input source is set back to the previous input source.
1.29 crook 7501: @item
7502: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7503: time the parse area is emptied.
7504: @item
7505: If an error occurs, the input source is set back to the user input
7506: device.
1.27 crook 7507: @end itemize
1.21 crook 7508:
1.49 anton 7509: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7510:
1.26 crook 7511: doc->in
1.27 crook 7512: doc-source
7513:
1.26 crook 7514: doc-tib
7515: doc-#tib
1.1 anton 7516:
1.44 crook 7517:
1.26 crook 7518: @menu
1.67 anton 7519: * Input Sources::
7520: * Number Conversion::
7521: * Interpret/Compile states::
7522: * Interpreter Directives::
1.26 crook 7523: @end menu
1.1 anton 7524:
1.29 crook 7525: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7526: @subsection Input Sources
7527: @cindex input sources
7528: @cindex text interpreter - input sources
7529:
1.44 crook 7530: By default, the text interpreter processes input from the user input
1.29 crook 7531: device (the keyboard) when Forth starts up. The text interpreter can
7532: process input from any of these sources:
7533:
7534: @itemize @bullet
7535: @item
7536: The user input device -- the keyboard.
7537: @item
7538: A file, using the words described in @ref{Forth source files}.
7539: @item
7540: A block, using the words described in @ref{Blocks}.
7541: @item
7542: A text string, using @code{evaluate}.
7543: @end itemize
7544:
7545: A program can identify the current input device from the values of
7546: @code{source-id} and @code{blk}.
7547:
1.44 crook 7548:
1.29 crook 7549: doc-source-id
7550: doc-blk
7551:
7552: doc-save-input
7553: doc-restore-input
7554:
7555: doc-evaluate
1.111 anton 7556: doc-query
1.1 anton 7557:
1.29 crook 7558:
1.44 crook 7559:
1.29 crook 7560: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7561: @subsection Number Conversion
7562: @cindex number conversion
7563: @cindex double-cell numbers, input format
7564: @cindex input format for double-cell numbers
7565: @cindex single-cell numbers, input format
7566: @cindex input format for single-cell numbers
7567: @cindex floating-point numbers, input format
7568: @cindex input format for floating-point numbers
1.1 anton 7569:
1.29 crook 7570: This section describes the rules that the text interpreter uses when it
7571: tries to convert a string into a number.
1.1 anton 7572:
1.26 crook 7573: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7574: number base@footnote{For example, 0-9 when the number base is decimal or
7575: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7576:
1.26 crook 7577: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7578:
1.29 crook 7579: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7580: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7581:
1.26 crook 7582: Let * represent any number of instances of the previous character
7583: (including none).
1.1 anton 7584:
1.26 crook 7585: Let any other character represent itself.
1.1 anton 7586:
1.29 crook 7587: @noindent
1.26 crook 7588: Now, the conversion rules are:
1.21 crook 7589:
1.26 crook 7590: @itemize @bullet
7591: @item
7592: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7593: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7594: @item
7595: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7596: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7597: arithmetic. Examples are -45 -5681 -0
7598: @item
7599: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7600: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7601: (all three of these represent the same number).
1.26 crook 7602: @item
7603: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7604: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7605: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7606: -34.65 (all three of these represent the same number).
1.26 crook 7607: @item
1.29 crook 7608: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7609: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7610: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7611: number) +12.E-4
1.26 crook 7612: @end itemize
1.1 anton 7613:
1.26 crook 7614: By default, the number base used for integer number conversion is given
1.35 anton 7615: by the contents of the variable @code{base}. Note that a lot of
7616: confusion can result from unexpected values of @code{base}. If you
7617: change @code{base} anywhere, make sure to save the old value and restore
7618: it afterwards. In general I recommend keeping @code{base} decimal, and
7619: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7620:
1.29 crook 7621: doc-dpl
1.26 crook 7622: doc-base
7623: doc-hex
7624: doc-decimal
1.1 anton 7625:
1.26 crook 7626: @cindex '-prefix for character strings
7627: @cindex &-prefix for decimal numbers
1.133 anton 7628: @cindex #-prefix for decimal numbers
1.26 crook 7629: @cindex %-prefix for binary numbers
7630: @cindex $-prefix for hexadecimal numbers
1.133 anton 7631: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7632: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7633: prefix@footnote{Some Forth implementations provide a similar scheme by
7634: implementing @code{$} etc. as parsing words that process the subsequent
7635: number in the input stream and push it onto the stack. For example, see
7636: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7637: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7638: is required between the prefix and the number.} before the first digit
1.133 anton 7639: of an (integer) number. The following prefixes are supported:
1.1 anton 7640:
1.26 crook 7641: @itemize @bullet
7642: @item
1.35 anton 7643: @code{&} -- decimal
1.26 crook 7644: @item
1.133 anton 7645: @code{#} -- decimal
7646: @item
1.35 anton 7647: @code{%} -- binary
1.26 crook 7648: @item
1.35 anton 7649: @code{$} -- hexadecimal
1.26 crook 7650: @item
1.133 anton 7651: @code{0x} -- hexadecimal, if base<33.
7652: @item
7653: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7654: optional @code{'} may be present after the character.
1.26 crook 7655: @end itemize
1.1 anton 7656:
1.26 crook 7657: Here are some examples, with the equivalent decimal number shown after
7658: in braces:
1.1 anton 7659:
1.26 crook 7660: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7661: 'A (65),
7662: -'a' (-97),
1.26 crook 7663: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7664:
1.26 crook 7665: @cindex number conversion - traps for the unwary
1.29 crook 7666: @noindent
1.26 crook 7667: Number conversion has a number of traps for the unwary:
1.1 anton 7668:
1.26 crook 7669: @itemize @bullet
7670: @item
7671: You cannot determine the current number base using the code sequence
1.35 anton 7672: @code{base @@ .} -- the number base is always 10 in the current number
7673: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7674: @item
7675: If the number base is set to a value greater than 14 (for example,
7676: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7677: it to be intepreted as either a single-precision integer or a
7678: floating-point number (Gforth treats it as an integer). The ambiguity
7679: can be resolved by explicitly stating the sign of the mantissa and/or
7680: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7681: ambiguity arises; either representation will be treated as a
7682: floating-point number.
7683: @item
1.29 crook 7684: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7685: It is used to specify file types.
7686: @item
1.72 anton 7687: ANS Forth requires the @code{.} of a double-precision number to be the
7688: final character in the string. Gforth allows the @code{.} to be
7689: anywhere after the first digit.
1.26 crook 7690: @item
7691: The number conversion process does not check for overflow.
7692: @item
1.72 anton 7693: In an ANS Forth program @code{base} is required to be decimal when
7694: converting floating-point numbers. In Gforth, number conversion to
7695: floating-point numbers always uses base &10, irrespective of the value
7696: of @code{base}.
1.26 crook 7697: @end itemize
1.1 anton 7698:
1.49 anton 7699: You can read numbers into your programs with the words described in
7700: @ref{Input}.
1.1 anton 7701:
1.82 anton 7702: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7703: @subsection Interpret/Compile states
7704: @cindex Interpret/Compile states
1.1 anton 7705:
1.29 crook 7706: A standard program is not permitted to change @code{state}
7707: explicitly. However, it can change @code{state} implicitly, using the
7708: words @code{[} and @code{]}. When @code{[} is executed it switches
7709: @code{state} to interpret state, and therefore the text interpreter
7710: starts interpreting. When @code{]} is executed it switches @code{state}
7711: to compile state and therefore the text interpreter starts
1.44 crook 7712: compiling. The most common usage for these words is for switching into
7713: interpret state and back from within a colon definition; this technique
1.49 anton 7714: can be used to compile a literal (for an example, @pxref{Literals}) or
7715: for conditional compilation (for an example, @pxref{Interpreter
7716: Directives}).
1.44 crook 7717:
1.35 anton 7718:
7719: @c This is a bad example: It's non-standard, and it's not necessary.
7720: @c However, I can't think of a good example for switching into compile
7721: @c state when there is no current word (@code{state}-smart words are not a
7722: @c good reason). So maybe we should use an example for switching into
7723: @c interpret @code{state} in a colon def. - anton
1.44 crook 7724: @c nac-> I agree. I started out by putting in the example, then realised
7725: @c that it was non-ANS, so wrote more words around it. I hope this
7726: @c re-written version is acceptable to you. I do want to keep the example
7727: @c as it is helpful for showing what is and what is not portable, particularly
7728: @c where it outlaws a style in common use.
7729:
1.72 anton 7730: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7731: @c that, we can also show what's not. In any case, I have written a
7732: @c section Compiling Words which also deals with [ ].
1.35 anton 7733:
1.95 anton 7734: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7735:
1.95 anton 7736: @c @code{[} and @code{]} also give you the ability to switch into compile
7737: @c state and back, but we cannot think of any useful Standard application
7738: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7739:
7740: @c @example
7741: @c : AA ." this is A" ;
7742: @c : BB ." this is B" ;
7743: @c : CC ." this is C" ;
7744:
7745: @c create table ] aa bb cc [
7746:
7747: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7748: @c cells table + @@ execute ;
7749: @c @end example
7750:
7751: @c This example builds a jump table; @code{0 go} will display ``@code{this
7752: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7753: @c defining @code{table} like this:
7754:
7755: @c @example
7756: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7757: @c @end example
7758:
7759: @c The problem with this code is that the definition of @code{table} is not
7760: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7761: @c @i{may} work on systems where code space and data space co-incide, the
7762: @c Standard only allows data space to be assigned for a @code{CREATE}d
7763: @c word. In addition, the Standard only allows @code{@@} to access data
7764: @c space, whilst this example is using it to access code space. The only
7765: @c portable, Standard way to build this table is to build it in data space,
7766: @c like this:
7767:
7768: @c @example
7769: @c create table ' aa , ' bb , ' cc ,
7770: @c @end example
1.29 crook 7771:
1.95 anton 7772: @c doc-state
1.44 crook 7773:
1.29 crook 7774:
1.82 anton 7775: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7776: @subsection Interpreter Directives
7777: @cindex interpreter directives
1.72 anton 7778: @cindex conditional compilation
1.1 anton 7779:
1.29 crook 7780: These words are usually used in interpret state; typically to control
7781: which parts of a source file are processed by the text
1.26 crook 7782: interpreter. There are only a few ANS Forth Standard words, but Gforth
7783: supplements these with a rich set of immediate control structure words
7784: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7785: used in compile state (@pxref{Control Structures}). Typical usages:
7786:
7787: @example
1.72 anton 7788: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7789: .
7790: .
1.72 anton 7791: HAVE-ASSEMBLER [IF]
1.29 crook 7792: : ASSEMBLER-FEATURE
7793: ...
7794: ;
7795: [ENDIF]
7796: .
7797: .
7798: : SEE
7799: ... \ general-purpose SEE code
1.72 anton 7800: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7801: ... \ assembler-specific SEE code
7802: [ [ENDIF] ]
7803: ;
7804: @end example
1.1 anton 7805:
1.44 crook 7806:
1.26 crook 7807: doc-[IF]
7808: doc-[ELSE]
7809: doc-[THEN]
7810: doc-[ENDIF]
1.1 anton 7811:
1.26 crook 7812: doc-[IFDEF]
7813: doc-[IFUNDEF]
1.1 anton 7814:
1.26 crook 7815: doc-[?DO]
7816: doc-[DO]
7817: doc-[FOR]
7818: doc-[LOOP]
7819: doc-[+LOOP]
7820: doc-[NEXT]
1.1 anton 7821:
1.26 crook 7822: doc-[BEGIN]
7823: doc-[UNTIL]
7824: doc-[AGAIN]
7825: doc-[WHILE]
7826: doc-[REPEAT]
1.1 anton 7827:
1.27 crook 7828:
1.26 crook 7829: @c -------------------------------------------------------------
1.111 anton 7830: @node The Input Stream, Word Lists, The Text Interpreter, Words
7831: @section The Input Stream
7832: @cindex input stream
7833:
7834: @c !! integrate this better with the "Text Interpreter" section
7835: The text interpreter reads from the input stream, which can come from
7836: several sources (@pxref{Input Sources}). Some words, in particular
7837: defining words, but also words like @code{'}, read parameters from the
7838: input stream instead of from the stack.
7839:
7840: Such words are called parsing words, because they parse the input
7841: stream. Parsing words are hard to use in other words, because it is
7842: hard to pass program-generated parameters through the input stream.
7843: They also usually have an unintuitive combination of interpretation and
7844: compilation semantics when implemented naively, leading to various
7845: approaches that try to produce a more intuitive behaviour
7846: (@pxref{Combined words}).
7847:
7848: It should be obvious by now that parsing words are a bad idea. If you
7849: want to implement a parsing word for convenience, also provide a factor
7850: of the word that does not parse, but takes the parameters on the stack.
7851: To implement the parsing word on top if it, you can use the following
7852: words:
7853:
7854: @c anton: these belong in the input stream section
7855: doc-parse
1.138 anton 7856: doc-parse-name
1.111 anton 7857: doc-parse-word
7858: doc-name
7859: doc-word
7860: doc-\"-parse
7861: doc-refill
7862:
7863: Conversely, if you have the bad luck (or lack of foresight) to have to
7864: deal with parsing words without having such factors, how do you pass a
7865: string that is not in the input stream to it?
7866:
7867: doc-execute-parsing
7868:
1.146 anton 7869: A definition of this word in ANS Forth is provided in
7870: @file{compat/execute-parsing.fs}.
7871:
1.111 anton 7872: If you want to run a parsing word on a file, the following word should
7873: help:
7874:
7875: doc-execute-parsing-file
7876:
7877: @c -------------------------------------------------------------
7878: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 7879: @section Word Lists
7880: @cindex word lists
1.32 anton 7881: @cindex header space
1.1 anton 7882:
1.36 anton 7883: A wordlist is a list of named words; you can add new words and look up
7884: words by name (and you can remove words in a restricted way with
7885: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7886:
7887: @cindex search order stack
7888: The text interpreter searches the wordlists present in the search order
7889: (a stack of wordlists), from the top to the bottom. Within each
7890: wordlist, the search starts conceptually at the newest word; i.e., if
7891: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7892:
1.26 crook 7893: @cindex compilation word list
1.36 anton 7894: New words are added to the @dfn{compilation wordlist} (aka current
7895: wordlist).
1.1 anton 7896:
1.36 anton 7897: @cindex wid
7898: A word list is identified by a cell-sized word list identifier (@i{wid})
7899: in much the same way as a file is identified by a file handle. The
7900: numerical value of the wid has no (portable) meaning, and might change
7901: from session to session.
1.1 anton 7902:
1.29 crook 7903: The ANS Forth ``Search order'' word set is intended to provide a set of
7904: low-level tools that allow various different schemes to be
1.74 anton 7905: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 7906: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 7907: Forth.
1.1 anton 7908:
1.27 crook 7909: @comment TODO: locals section refers to here, saying that every word list (aka
7910: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 7911: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 7912:
1.45 crook 7913: @comment TODO: document markers, reveal, tables, mappedwordlist
7914:
7915: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 7916: @comment word from the source files, rather than some alias.
1.44 crook 7917:
1.26 crook 7918: doc-forth-wordlist
7919: doc-definitions
7920: doc-get-current
7921: doc-set-current
7922: doc-get-order
1.45 crook 7923: doc---gforthman-set-order
1.26 crook 7924: doc-wordlist
1.30 anton 7925: doc-table
1.79 anton 7926: doc->order
1.36 anton 7927: doc-previous
1.26 crook 7928: doc-also
1.45 crook 7929: doc---gforthman-forth
1.26 crook 7930: doc-only
1.45 crook 7931: doc---gforthman-order
1.15 anton 7932:
1.26 crook 7933: doc-find
7934: doc-search-wordlist
1.15 anton 7935:
1.26 crook 7936: doc-words
7937: doc-vlist
1.44 crook 7938: @c doc-words-deferred
1.1 anton 7939:
1.74 anton 7940: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 7941: doc-root
7942: doc-vocabulary
7943: doc-seal
7944: doc-vocs
7945: doc-current
7946: doc-context
1.1 anton 7947:
1.44 crook 7948:
1.26 crook 7949: @menu
1.75 anton 7950: * Vocabularies::
1.67 anton 7951: * Why use word lists?::
1.75 anton 7952: * Word list example::
1.26 crook 7953: @end menu
7954:
1.75 anton 7955: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
7956: @subsection Vocabularies
7957: @cindex Vocabularies, detailed explanation
7958:
7959: Here is an example of creating and using a new wordlist using ANS
7960: Forth words:
7961:
7962: @example
7963: wordlist constant my-new-words-wordlist
7964: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
7965:
7966: \ add it to the search order
7967: also my-new-words
7968:
7969: \ alternatively, add it to the search order and make it
7970: \ the compilation word list
7971: also my-new-words definitions
7972: \ type "order" to see the problem
7973: @end example
7974:
7975: The problem with this example is that @code{order} has no way to
7976: associate the name @code{my-new-words} with the wid of the word list (in
7977: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7978: that has no associated name). There is no Standard way of associating a
7979: name with a wid.
7980:
7981: In Gforth, this example can be re-coded using @code{vocabulary}, which
7982: associates a name with a wid:
7983:
7984: @example
7985: vocabulary my-new-words
7986:
7987: \ add it to the search order
7988: also my-new-words
7989:
7990: \ alternatively, add it to the search order and make it
7991: \ the compilation word list
7992: my-new-words definitions
7993: \ type "order" to see that the problem is solved
7994: @end example
7995:
7996:
7997: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 7998: @subsection Why use word lists?
7999: @cindex word lists - why use them?
8000:
1.74 anton 8001: Here are some reasons why people use wordlists:
1.26 crook 8002:
8003: @itemize @bullet
1.74 anton 8004:
8005: @c anton: Gforth's hashing implementation makes the search speed
8006: @c independent from the number of words. But it is linear with the number
8007: @c of wordlists that have to be searched, so in effect using more wordlists
8008: @c actually slows down compilation.
8009:
8010: @c @item
8011: @c To improve compilation speed by reducing the number of header space
8012: @c entries that must be searched. This is achieved by creating a new
8013: @c word list that contains all of the definitions that are used in the
8014: @c definition of a Forth system but which would not usually be used by
8015: @c programs running on that system. That word list would be on the search
8016: @c list when the Forth system was compiled but would be removed from the
8017: @c search list for normal operation. This can be a useful technique for
8018: @c low-performance systems (for example, 8-bit processors in embedded
8019: @c systems) but is unlikely to be necessary in high-performance desktop
8020: @c systems.
8021:
1.26 crook 8022: @item
8023: To prevent a set of words from being used outside the context in which
8024: they are valid. Two classic examples of this are an integrated editor
8025: (all of the edit commands are defined in a separate word list; the
8026: search order is set to the editor word list when the editor is invoked;
8027: the old search order is restored when the editor is terminated) and an
8028: integrated assembler (the op-codes for the machine are defined in a
8029: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8030:
8031: @item
8032: To organize the words of an application or library into a user-visible
8033: set (in @code{forth-wordlist} or some other common wordlist) and a set
8034: of helper words used just for the implementation (hidden in a separate
1.75 anton 8035: wordlist). This keeps @code{words}' output smaller, separates
8036: implementation and interface, and reduces the chance of name conflicts
8037: within the common wordlist.
1.74 anton 8038:
1.26 crook 8039: @item
8040: To prevent a name-space clash between multiple definitions with the same
8041: name. For example, when building a cross-compiler you might have a word
8042: @code{IF} that generates conditional code for your target system. By
8043: placing this definition in a different word list you can control whether
8044: the host system's @code{IF} or the target system's @code{IF} get used in
8045: any particular context by controlling the order of the word lists on the
8046: search order stack.
1.74 anton 8047:
1.26 crook 8048: @end itemize
1.1 anton 8049:
1.74 anton 8050: The downsides of using wordlists are:
8051:
8052: @itemize
8053:
8054: @item
8055: Debugging becomes more cumbersome.
8056:
8057: @item
8058: Name conflicts worked around with wordlists are still there, and you
8059: have to arrange the search order carefully to get the desired results;
8060: if you forget to do that, you get hard-to-find errors (as in any case
8061: where you read the code differently from the compiler; @code{see} can
1.75 anton 8062: help seeing which of several possible words the name resolves to in such
8063: cases). @code{See} displays just the name of the words, not what
8064: wordlist they belong to, so it might be misleading. Using unique names
8065: is a better approach to avoid name conflicts.
1.74 anton 8066:
8067: @item
8068: You have to explicitly undo any changes to the search order. In many
8069: cases it would be more convenient if this happened implicitly. Gforth
8070: currently does not provide such a feature, but it may do so in the
8071: future.
8072: @end itemize
8073:
8074:
1.75 anton 8075: @node Word list example, , Why use word lists?, Word Lists
8076: @subsection Word list example
8077: @cindex word lists - example
1.1 anton 8078:
1.74 anton 8079: The following example is from the
8080: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8081: garbage collector} and uses wordlists to separate public words from
8082: helper words:
8083:
8084: @example
8085: get-current ( wid )
8086: vocabulary garbage-collector also garbage-collector definitions
8087: ... \ define helper words
8088: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8089: ... \ define the public (i.e., API) words
8090: \ they can refer to the helper words
8091: previous \ restore original search order (helper words become invisible)
8092: @end example
8093:
1.26 crook 8094: @c -------------------------------------------------------------
8095: @node Environmental Queries, Files, Word Lists, Words
8096: @section Environmental Queries
8097: @cindex environmental queries
1.21 crook 8098:
1.26 crook 8099: ANS Forth introduced the idea of ``environmental queries'' as a way
8100: for a program running on a system to determine certain characteristics of the system.
8101: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8102:
1.32 anton 8103: The Standard requires that the header space used for environmental queries
8104: be distinct from the header space used for definitions.
1.21 crook 8105:
1.26 crook 8106: Typically, environmental queries are supported by creating a set of
1.29 crook 8107: definitions in a word list that is @i{only} used during environmental
1.26 crook 8108: queries; that is what Gforth does. There is no Standard way of adding
8109: definitions to the set of recognised environmental queries, but any
8110: implementation that supports the loading of optional word sets must have
8111: some mechanism for doing this (after loading the word set, the
8112: associated environmental query string must return @code{true}). In
8113: Gforth, the word list used to honour environmental queries can be
8114: manipulated just like any other word list.
1.21 crook 8115:
1.44 crook 8116:
1.26 crook 8117: doc-environment?
8118: doc-environment-wordlist
1.21 crook 8119:
1.26 crook 8120: doc-gforth
8121: doc-os-class
1.21 crook 8122:
1.44 crook 8123:
1.26 crook 8124: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8125: returning two items on the stack, querying it using @code{environment?}
8126: will return an additional item; the @code{true} flag that shows that the
8127: string was recognised.
1.21 crook 8128:
1.26 crook 8129: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8130:
1.26 crook 8131: Here are some examples of using environmental queries:
1.21 crook 8132:
1.26 crook 8133: @example
8134: s" address-unit-bits" environment? 0=
8135: [IF]
8136: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8137: [ELSE]
8138: drop \ ensure balanced stack effect
1.26 crook 8139: [THEN]
1.21 crook 8140:
1.75 anton 8141: \ this might occur in the prelude of a standard program that uses THROW
8142: s" exception" environment? [IF]
8143: 0= [IF]
8144: : throw abort" exception thrown" ;
8145: [THEN]
8146: [ELSE] \ we don't know, so make sure
8147: : throw abort" exception thrown" ;
8148: [THEN]
1.21 crook 8149:
1.26 crook 8150: s" gforth" environment? [IF] .( Gforth version ) TYPE
8151: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8152:
8153: \ a program using v*
8154: s" gforth" environment? [IF]
8155: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8156: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8157: >r swap 2swap swap 0e r> 0 ?DO
8158: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8159: LOOP
8160: 2drop 2drop ;
8161: [THEN]
8162: [ELSE] \
8163: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8164: ...
8165: [THEN]
1.26 crook 8166: @end example
1.21 crook 8167:
1.26 crook 8168: Here is an example of adding a definition to the environment word list:
1.21 crook 8169:
1.26 crook 8170: @example
8171: get-current environment-wordlist set-current
8172: true constant block
8173: true constant block-ext
8174: set-current
8175: @end example
1.21 crook 8176:
1.26 crook 8177: You can see what definitions are in the environment word list like this:
1.21 crook 8178:
1.26 crook 8179: @example
1.79 anton 8180: environment-wordlist >order words previous
1.26 crook 8181: @end example
1.21 crook 8182:
8183:
1.26 crook 8184: @c -------------------------------------------------------------
8185: @node Files, Blocks, Environmental Queries, Words
8186: @section Files
1.28 crook 8187: @cindex files
8188: @cindex I/O - file-handling
1.21 crook 8189:
1.26 crook 8190: Gforth provides facilities for accessing files that are stored in the
8191: host operating system's file-system. Files that are processed by Gforth
8192: can be divided into two categories:
1.21 crook 8193:
1.23 crook 8194: @itemize @bullet
8195: @item
1.29 crook 8196: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8197: @item
1.29 crook 8198: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8199: @end itemize
8200:
8201: @menu
1.48 anton 8202: * Forth source files::
8203: * General files::
8204: * Search Paths::
1.26 crook 8205: @end menu
8206:
8207: @c -------------------------------------------------------------
8208: @node Forth source files, General files, Files, Files
8209: @subsection Forth source files
8210: @cindex including files
8211: @cindex Forth source files
1.21 crook 8212:
1.26 crook 8213: The simplest way to interpret the contents of a file is to use one of
8214: these two formats:
1.21 crook 8215:
1.26 crook 8216: @example
8217: include mysource.fs
8218: s" mysource.fs" included
8219: @end example
1.21 crook 8220:
1.75 anton 8221: You usually want to include a file only if it is not included already
1.26 crook 8222: (by, say, another source file). In that case, you can use one of these
1.45 crook 8223: three formats:
1.21 crook 8224:
1.26 crook 8225: @example
8226: require mysource.fs
8227: needs mysource.fs
8228: s" mysource.fs" required
8229: @end example
1.21 crook 8230:
1.26 crook 8231: @cindex stack effect of included files
8232: @cindex including files, stack effect
1.45 crook 8233: It is good practice to write your source files such that interpreting them
8234: does not change the stack. Source files designed in this way can be used with
1.26 crook 8235: @code{required} and friends without complications. For example:
1.21 crook 8236:
1.26 crook 8237: @example
1.75 anton 8238: 1024 require foo.fs drop
1.26 crook 8239: @end example
1.21 crook 8240:
1.75 anton 8241: Here you want to pass the argument 1024 (e.g., a buffer size) to
8242: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8243: ), which allows its use with @code{require}. Of course with such
8244: parameters to required files, you have to ensure that the first
8245: @code{require} fits for all uses (i.e., @code{require} it early in the
8246: master load file).
1.44 crook 8247:
1.26 crook 8248: doc-include-file
8249: doc-included
1.28 crook 8250: doc-included?
1.26 crook 8251: doc-include
8252: doc-required
8253: doc-require
8254: doc-needs
1.75 anton 8255: @c doc-init-included-files @c internal
8256: doc-sourcefilename
8257: doc-sourceline#
1.44 crook 8258:
1.26 crook 8259: A definition in ANS Forth for @code{required} is provided in
8260: @file{compat/required.fs}.
1.21 crook 8261:
1.26 crook 8262: @c -------------------------------------------------------------
8263: @node General files, Search Paths, Forth source files, Files
8264: @subsection General files
8265: @cindex general files
8266: @cindex file-handling
1.21 crook 8267:
1.75 anton 8268: Files are opened/created by name and type. The following file access
8269: methods (FAMs) are recognised:
1.44 crook 8270:
1.75 anton 8271: @cindex fam (file access method)
1.26 crook 8272: doc-r/o
8273: doc-r/w
8274: doc-w/o
8275: doc-bin
1.1 anton 8276:
1.44 crook 8277:
1.26 crook 8278: When a file is opened/created, it returns a file identifier,
1.29 crook 8279: @i{wfileid} that is used for all other file commands. All file
8280: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8281: successful operation and an implementation-defined non-zero value in the
8282: case of an error.
1.21 crook 8283:
1.44 crook 8284:
1.26 crook 8285: doc-open-file
8286: doc-create-file
1.21 crook 8287:
1.26 crook 8288: doc-close-file
8289: doc-delete-file
8290: doc-rename-file
8291: doc-read-file
8292: doc-read-line
8293: doc-write-file
8294: doc-write-line
8295: doc-emit-file
8296: doc-flush-file
1.21 crook 8297:
1.26 crook 8298: doc-file-status
8299: doc-file-position
8300: doc-reposition-file
8301: doc-file-size
8302: doc-resize-file
1.21 crook 8303:
1.93 anton 8304: doc-slurp-file
8305: doc-slurp-fid
1.112 anton 8306: doc-stdin
8307: doc-stdout
8308: doc-stderr
1.44 crook 8309:
1.26 crook 8310: @c ---------------------------------------------------------
1.48 anton 8311: @node Search Paths, , General files, Files
1.26 crook 8312: @subsection Search Paths
8313: @cindex path for @code{included}
8314: @cindex file search path
8315: @cindex @code{include} search path
8316: @cindex search path for files
1.21 crook 8317:
1.26 crook 8318: If you specify an absolute filename (i.e., a filename starting with
8319: @file{/} or @file{~}, or with @file{:} in the second position (as in
8320: @samp{C:...})) for @code{included} and friends, that file is included
8321: just as you would expect.
1.21 crook 8322:
1.75 anton 8323: If the filename starts with @file{./}, this refers to the directory that
8324: the present file was @code{included} from. This allows files to include
8325: other files relative to their own position (irrespective of the current
8326: working directory or the absolute position). This feature is essential
8327: for libraries consisting of several files, where a file may include
8328: other files from the library. It corresponds to @code{#include "..."}
8329: in C. If the current input source is not a file, @file{.} refers to the
8330: directory of the innermost file being included, or, if there is no file
8331: being included, to the current working directory.
8332:
8333: For relative filenames (not starting with @file{./}), Gforth uses a
8334: search path similar to Forth's search order (@pxref{Word Lists}). It
8335: tries to find the given filename in the directories present in the path,
8336: and includes the first one it finds. There are separate search paths for
8337: Forth source files and general files. If the search path contains the
8338: directory @file{.}, this refers to the directory of the current file, or
8339: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8340:
1.26 crook 8341: Use @file{~+} to refer to the current working directory (as in the
8342: @code{bash}).
1.1 anton 8343:
1.75 anton 8344: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8345:
1.48 anton 8346: @menu
1.75 anton 8347: * Source Search Paths::
1.48 anton 8348: * General Search Paths::
8349: @end menu
8350:
1.26 crook 8351: @c ---------------------------------------------------------
1.75 anton 8352: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8353: @subsubsection Source Search Paths
8354: @cindex search path control, source files
1.5 anton 8355:
1.26 crook 8356: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8357: Gforth}). You can display it and change it using @code{fpath} in
8358: combination with the general path handling words.
1.5 anton 8359:
1.75 anton 8360: doc-fpath
8361: @c the functionality of the following words is easily available through
8362: @c fpath and the general path words. The may go away.
8363: @c doc-.fpath
8364: @c doc-fpath+
8365: @c doc-fpath=
8366: @c doc-open-fpath-file
1.44 crook 8367:
8368: @noindent
1.26 crook 8369: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8370:
1.26 crook 8371: @example
1.75 anton 8372: fpath path= /usr/lib/forth/|./
1.26 crook 8373: require timer.fs
8374: @end example
1.5 anton 8375:
1.75 anton 8376:
1.26 crook 8377: @c ---------------------------------------------------------
1.75 anton 8378: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8379: @subsubsection General Search Paths
1.75 anton 8380: @cindex search path control, source files
1.5 anton 8381:
1.26 crook 8382: Your application may need to search files in several directories, like
8383: @code{included} does. To facilitate this, Gforth allows you to define
8384: and use your own search paths, by providing generic equivalents of the
8385: Forth search path words:
1.5 anton 8386:
1.75 anton 8387: doc-open-path-file
8388: doc-path-allot
8389: doc-clear-path
8390: doc-also-path
1.26 crook 8391: doc-.path
8392: doc-path+
8393: doc-path=
1.5 anton 8394:
1.75 anton 8395: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8396:
1.75 anton 8397: Here's an example of creating an empty search path:
8398: @c
1.26 crook 8399: @example
1.75 anton 8400: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8401: @end example
1.5 anton 8402:
1.26 crook 8403: @c -------------------------------------------------------------
8404: @node Blocks, Other I/O, Files, Words
8405: @section Blocks
1.28 crook 8406: @cindex I/O - blocks
8407: @cindex blocks
8408:
8409: When you run Gforth on a modern desk-top computer, it runs under the
8410: control of an operating system which provides certain services. One of
8411: these services is @var{file services}, which allows Forth source code
8412: and data to be stored in files and read into Gforth (@pxref{Files}).
8413:
8414: Traditionally, Forth has been an important programming language on
8415: systems where it has interfaced directly to the underlying hardware with
8416: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8417: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8418:
8419: A block is a 1024-byte data area, which can be used to hold data or
8420: Forth source code. No structure is imposed on the contents of the
8421: block. A block is identified by its number; blocks are numbered
8422: contiguously from 1 to an implementation-defined maximum.
8423:
8424: A typical system that used blocks but no operating system might use a
8425: single floppy-disk drive for mass storage, with the disks formatted to
8426: provide 256-byte sectors. Blocks would be implemented by assigning the
8427: first four sectors of the disk to block 1, the second four sectors to
8428: block 2 and so on, up to the limit of the capacity of the disk. The disk
8429: would not contain any file system information, just the set of blocks.
8430:
1.29 crook 8431: @cindex blocks file
1.28 crook 8432: On systems that do provide file services, blocks are typically
1.29 crook 8433: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8434: file}. The size of the blocks file will be an exact multiple of 1024
8435: bytes, corresponding to the number of blocks it contains. This is the
8436: mechanism that Gforth uses.
8437:
1.29 crook 8438: @cindex @file{blocks.fb}
1.75 anton 8439: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8440: having specified a blocks file, Gforth defaults to the blocks file
8441: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8442: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8443:
1.29 crook 8444: @cindex block buffers
1.28 crook 8445: When you read and write blocks under program control, Gforth uses a
1.29 crook 8446: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8447: not used when you use @code{load} to interpret the contents of a block.
8448:
1.75 anton 8449: The behaviour of the block buffers is analagous to that of a cache.
8450: Each block buffer has three states:
1.28 crook 8451:
8452: @itemize @bullet
8453: @item
8454: Unassigned
8455: @item
8456: Assigned-clean
8457: @item
8458: Assigned-dirty
8459: @end itemize
8460:
1.29 crook 8461: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8462: block, the block (specified by its block number) must be assigned to a
8463: block buffer.
8464:
8465: The assignment of a block to a block buffer is performed by @code{block}
8466: or @code{buffer}. Use @code{block} when you wish to modify the existing
8467: contents of a block. Use @code{buffer} when you don't care about the
8468: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8469: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8470: with the particular block is already stored in a block buffer due to an
8471: earlier @code{block} command, @code{buffer} will return that block
8472: buffer and the existing contents of the block will be
8473: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8474: block buffer for the block.}.
1.28 crook 8475:
1.47 crook 8476: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8477: @code{buffer}, that block buffer becomes the @i{current block
8478: buffer}. Data may only be manipulated (read or written) within the
8479: current block buffer.
1.47 crook 8480:
8481: When the contents of the current block buffer has been modified it is
1.48 anton 8482: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8483: either abandon the changes (by doing nothing) or mark the block as
8484: changed (assigned-dirty), using @code{update}. Using @code{update} does
8485: not change the blocks file; it simply changes a block buffer's state to
8486: @i{assigned-dirty}. The block will be written implicitly when it's
8487: buffer is needed for another block, or explicitly by @code{flush} or
8488: @code{save-buffers}.
8489:
8490: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8491: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8492: @code{flush}.
1.28 crook 8493:
1.29 crook 8494: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8495: algorithm to assign a block buffer to a block. That means that any
8496: particular block can only be assigned to one specific block buffer,
1.29 crook 8497: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8498: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8499: the new block immediately. If it is @i{assigned-dirty} its current
8500: contents are written back to the blocks file on disk before it is
1.28 crook 8501: allocated to the new block.
8502:
8503: Although no structure is imposed on the contents of a block, it is
8504: traditional to display the contents as 16 lines each of 64 characters. A
8505: block provides a single, continuous stream of input (for example, it
8506: acts as a single parse area) -- there are no end-of-line characters
8507: within a block, and no end-of-file character at the end of a
8508: block. There are two consequences of this:
1.26 crook 8509:
1.28 crook 8510: @itemize @bullet
8511: @item
8512: The last character of one line wraps straight into the first character
8513: of the following line
8514: @item
8515: The word @code{\} -- comment to end of line -- requires special
8516: treatment; in the context of a block it causes all characters until the
8517: end of the current 64-character ``line'' to be ignored.
8518: @end itemize
8519:
8520: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8521: the current blocks file will be extended to the appropriate size and the
1.28 crook 8522: block buffer will be initialised with spaces.
8523:
1.47 crook 8524: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8525: for details) but doesn't encourage the use of blocks; the mechanism is
8526: only provided for backward compatibility -- ANS Forth requires blocks to
8527: be available when files are.
1.28 crook 8528:
8529: Common techniques that are used when working with blocks include:
8530:
8531: @itemize @bullet
8532: @item
8533: A screen editor that allows you to edit blocks without leaving the Forth
8534: environment.
8535: @item
8536: Shadow screens; where every code block has an associated block
8537: containing comments (for example: code in odd block numbers, comments in
8538: even block numbers). Typically, the block editor provides a convenient
8539: mechanism to toggle between code and comments.
8540: @item
8541: Load blocks; a single block (typically block 1) contains a number of
8542: @code{thru} commands which @code{load} the whole of the application.
8543: @end itemize
1.26 crook 8544:
1.29 crook 8545: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8546: integrated into a Forth programming environment.
1.26 crook 8547:
8548: @comment TODO what about errors on open-blocks?
1.44 crook 8549:
1.26 crook 8550: doc-open-blocks
8551: doc-use
1.75 anton 8552: doc-block-offset
1.26 crook 8553: doc-get-block-fid
8554: doc-block-position
1.28 crook 8555:
1.75 anton 8556: doc-list
1.28 crook 8557: doc-scr
8558:
1.45 crook 8559: doc---gforthman-block
1.28 crook 8560: doc-buffer
8561:
1.75 anton 8562: doc-empty-buffers
8563: doc-empty-buffer
1.26 crook 8564: doc-update
1.28 crook 8565: doc-updated?
1.26 crook 8566: doc-save-buffers
1.75 anton 8567: doc-save-buffer
1.26 crook 8568: doc-flush
1.28 crook 8569:
1.26 crook 8570: doc-load
8571: doc-thru
8572: doc-+load
8573: doc-+thru
1.45 crook 8574: doc---gforthman--->
1.26 crook 8575: doc-block-included
8576:
1.44 crook 8577:
1.26 crook 8578: @c -------------------------------------------------------------
1.126 pazsan 8579: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8580: @section Other I/O
1.28 crook 8581: @cindex I/O - keyboard and display
1.26 crook 8582:
8583: @menu
8584: * Simple numeric output:: Predefined formats
8585: * Formatted numeric output:: Formatted (pictured) output
8586: * String Formats:: How Forth stores strings in memory
1.67 anton 8587: * Displaying characters and strings:: Other stuff
1.26 crook 8588: * Input:: Input
1.112 anton 8589: * Pipes:: How to create your own pipes
1.149 ! pazsan 8590: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 8591: @end menu
8592:
8593: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8594: @subsection Simple numeric output
1.28 crook 8595: @cindex numeric output - simple/free-format
1.5 anton 8596:
1.26 crook 8597: The simplest output functions are those that display numbers from the
8598: data or floating-point stacks. Floating-point output is always displayed
8599: using base 10. Numbers displayed from the data stack use the value stored
8600: in @code{base}.
1.5 anton 8601:
1.44 crook 8602:
1.26 crook 8603: doc-.
8604: doc-dec.
8605: doc-hex.
8606: doc-u.
8607: doc-.r
8608: doc-u.r
8609: doc-d.
8610: doc-ud.
8611: doc-d.r
8612: doc-ud.r
8613: doc-f.
8614: doc-fe.
8615: doc-fs.
1.111 anton 8616: doc-f.rdp
1.44 crook 8617:
1.26 crook 8618: Examples of printing the number 1234.5678E23 in the different floating-point output
8619: formats are shown below:
1.5 anton 8620:
8621: @example
1.26 crook 8622: f. 123456779999999000000000000.
8623: fe. 123.456779999999E24
8624: fs. 1.23456779999999E26
1.5 anton 8625: @end example
8626:
8627:
1.26 crook 8628: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8629: @subsection Formatted numeric output
1.28 crook 8630: @cindex formatted numeric output
1.26 crook 8631: @cindex pictured numeric output
1.28 crook 8632: @cindex numeric output - formatted
1.26 crook 8633:
1.29 crook 8634: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8635: output} for formatted printing of integers. In this technique, digits
8636: are extracted from the number (using the current output radix defined by
8637: @code{base}), converted to ASCII codes and appended to a string that is
8638: built in a scratch-pad area of memory (@pxref{core-idef,
8639: Implementation-defined options, Implementation-defined
8640: options}). Arbitrary characters can be appended to the string during the
8641: extraction process. The completed string is specified by an address
8642: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8643: under program control.
1.5 anton 8644:
1.75 anton 8645: All of the integer output words described in the previous section
8646: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8647: numeric output.
1.5 anton 8648:
1.47 crook 8649: Three important things to remember about pictured numeric output:
1.5 anton 8650:
1.26 crook 8651: @itemize @bullet
8652: @item
1.28 crook 8653: It always operates on double-precision numbers; to display a
1.49 anton 8654: single-precision number, convert it first (for ways of doing this
8655: @pxref{Double precision}).
1.26 crook 8656: @item
1.28 crook 8657: It always treats the double-precision number as though it were
8658: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8659: @item
8660: The string is built up from right to left; least significant digit first.
8661: @end itemize
1.5 anton 8662:
1.44 crook 8663:
1.26 crook 8664: doc-<#
1.47 crook 8665: doc-<<#
1.26 crook 8666: doc-#
8667: doc-#s
8668: doc-hold
8669: doc-sign
8670: doc-#>
1.47 crook 8671: doc-#>>
1.5 anton 8672:
1.26 crook 8673: doc-represent
1.111 anton 8674: doc-f>str-rdp
8675: doc-f>buf-rdp
1.5 anton 8676:
1.44 crook 8677:
8678: @noindent
1.26 crook 8679: Here are some examples of using pictured numeric output:
1.5 anton 8680:
8681: @example
1.26 crook 8682: : my-u. ( u -- )
8683: \ Simplest use of pns.. behaves like Standard u.
8684: 0 \ convert to unsigned double
1.75 anton 8685: <<# \ start conversion
1.26 crook 8686: #s \ convert all digits
8687: #> \ complete conversion
1.75 anton 8688: TYPE SPACE \ display, with trailing space
8689: #>> ; \ release hold area
1.5 anton 8690:
1.26 crook 8691: : cents-only ( u -- )
8692: 0 \ convert to unsigned double
1.75 anton 8693: <<# \ start conversion
1.26 crook 8694: # # \ convert two least-significant digits
8695: #> \ complete conversion, discard other digits
1.75 anton 8696: TYPE SPACE \ display, with trailing space
8697: #>> ; \ release hold area
1.5 anton 8698:
1.26 crook 8699: : dollars-and-cents ( u -- )
8700: 0 \ convert to unsigned double
1.75 anton 8701: <<# \ start conversion
1.26 crook 8702: # # \ convert two least-significant digits
8703: [char] . hold \ insert decimal point
8704: #s \ convert remaining digits
8705: [char] $ hold \ append currency symbol
8706: #> \ complete conversion
1.75 anton 8707: TYPE SPACE \ display, with trailing space
8708: #>> ; \ release hold area
1.5 anton 8709:
1.26 crook 8710: : my-. ( n -- )
8711: \ handling negatives.. behaves like Standard .
8712: s>d \ convert to signed double
8713: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8714: <<# \ start conversion
1.26 crook 8715: #s \ convert all digits
8716: rot sign \ get at sign byte, append "-" if needed
8717: #> \ complete conversion
1.75 anton 8718: TYPE SPACE \ display, with trailing space
8719: #>> ; \ release hold area
1.5 anton 8720:
1.26 crook 8721: : account. ( n -- )
1.75 anton 8722: \ accountants don't like minus signs, they use parentheses
1.26 crook 8723: \ for negative numbers
8724: s>d \ convert to signed double
8725: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8726: <<# \ start conversion
1.26 crook 8727: 2 pick \ get copy of sign byte
8728: 0< IF [char] ) hold THEN \ right-most character of output
8729: #s \ convert all digits
8730: rot \ get at sign byte
8731: 0< IF [char] ( hold THEN
8732: #> \ complete conversion
1.75 anton 8733: TYPE SPACE \ display, with trailing space
8734: #>> ; \ release hold area
8735:
1.5 anton 8736: @end example
8737:
1.26 crook 8738: Here are some examples of using these words:
1.5 anton 8739:
8740: @example
1.26 crook 8741: 1 my-u. 1
8742: hex -1 my-u. decimal FFFFFFFF
8743: 1 cents-only 01
8744: 1234 cents-only 34
8745: 2 dollars-and-cents $0.02
8746: 1234 dollars-and-cents $12.34
8747: 123 my-. 123
8748: -123 my. -123
8749: 123 account. 123
8750: -456 account. (456)
1.5 anton 8751: @end example
8752:
8753:
1.26 crook 8754: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8755: @subsection String Formats
1.27 crook 8756: @cindex strings - see character strings
8757: @cindex character strings - formats
1.28 crook 8758: @cindex I/O - see character strings
1.75 anton 8759: @cindex counted strings
8760:
8761: @c anton: this does not really belong here; maybe the memory section,
8762: @c or the principles chapter
1.26 crook 8763:
1.27 crook 8764: Forth commonly uses two different methods for representing character
8765: strings:
1.26 crook 8766:
8767: @itemize @bullet
8768: @item
8769: @cindex address of counted string
1.45 crook 8770: @cindex counted string
1.29 crook 8771: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8772: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8773: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8774: memory.
8775: @item
1.29 crook 8776: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8777: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8778: first byte of the string.
8779: @end itemize
8780:
8781: ANS Forth encourages the use of the second format when representing
1.75 anton 8782: strings.
1.26 crook 8783:
1.44 crook 8784:
1.26 crook 8785: doc-count
8786:
1.44 crook 8787:
1.49 anton 8788: For words that move, copy and search for strings see @ref{Memory
8789: Blocks}. For words that display characters and strings see
8790: @ref{Displaying characters and strings}.
1.26 crook 8791:
8792: @node Displaying characters and strings, Input, String Formats, Other I/O
8793: @subsection Displaying characters and strings
1.27 crook 8794: @cindex characters - compiling and displaying
8795: @cindex character strings - compiling and displaying
1.26 crook 8796:
8797: This section starts with a glossary of Forth words and ends with a set
8798: of examples.
8799:
1.44 crook 8800:
1.26 crook 8801: doc-bl
8802: doc-space
8803: doc-spaces
8804: doc-emit
8805: doc-toupper
8806: doc-."
8807: doc-.(
1.98 anton 8808: doc-.\"
1.26 crook 8809: doc-type
1.44 crook 8810: doc-typewhite
1.26 crook 8811: doc-cr
1.27 crook 8812: @cindex cursor control
1.26 crook 8813: doc-at-xy
8814: doc-page
8815: doc-s"
1.98 anton 8816: doc-s\"
1.26 crook 8817: doc-c"
8818: doc-char
8819: doc-[char]
8820:
1.44 crook 8821:
8822: @noindent
1.26 crook 8823: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8824:
8825: @example
1.26 crook 8826: .( text-1)
8827: : my-word
8828: ." text-2" cr
8829: .( text-3)
8830: ;
8831:
8832: ." text-4"
8833:
8834: : my-char
8835: [char] ALPHABET emit
8836: char emit
8837: ;
1.5 anton 8838: @end example
8839:
1.26 crook 8840: When you load this code into Gforth, the following output is generated:
1.5 anton 8841:
1.26 crook 8842: @example
1.30 anton 8843: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8844: @end example
1.5 anton 8845:
1.26 crook 8846: @itemize @bullet
8847: @item
8848: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8849: is an immediate word; it behaves in the same way whether it is used inside
8850: or outside a colon definition.
8851: @item
8852: Message @code{text-4} is displayed because of Gforth's added interpretation
8853: semantics for @code{."}.
8854: @item
1.29 crook 8855: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8856: performs the compilation semantics for @code{."} within the definition of
8857: @code{my-word}.
8858: @end itemize
1.5 anton 8859:
1.26 crook 8860: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8861:
1.26 crook 8862: @example
1.30 anton 8863: @kbd{my-word @key{RET}} text-2
1.26 crook 8864: ok
1.30 anton 8865: @kbd{my-char fred @key{RET}} Af ok
8866: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 8867: @end example
1.5 anton 8868:
8869: @itemize @bullet
8870: @item
1.26 crook 8871: Message @code{text-2} is displayed because of the run-time behaviour of
8872: @code{."}.
8873: @item
8874: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8875: on the stack at run-time. @code{emit} always displays the character
8876: when @code{my-char} is executed.
8877: @item
8878: @code{char} parses a string at run-time and the second @code{emit} displays
8879: the first character of the string.
1.5 anton 8880: @item
1.26 crook 8881: If you type @code{see my-char} you can see that @code{[char]} discarded
8882: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8883: definition of @code{my-char}.
1.5 anton 8884: @end itemize
8885:
8886:
8887:
1.112 anton 8888: @node Input, Pipes, Displaying characters and strings, Other I/O
1.26 crook 8889: @subsection Input
8890: @cindex input
1.28 crook 8891: @cindex I/O - see input
8892: @cindex parsing a string
1.5 anton 8893:
1.49 anton 8894: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 8895:
1.27 crook 8896: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 8897: @comment then index them
1.27 crook 8898:
1.44 crook 8899:
1.27 crook 8900: doc-key
8901: doc-key?
1.45 crook 8902: doc-ekey
1.141 anton 8903: doc-ekey>char
1.45 crook 8904: doc-ekey?
1.141 anton 8905:
8906: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
8907: you need the ANSI.SYS driver to get that behaviour). These are the
8908: keyboard events produced by various common keys:
8909:
8910: doc-k-left
8911: doc-k-right
8912: doc-k-up
8913: doc-k-down
8914: doc-k-home
8915: doc-k-end
8916: doc-k-prior
8917: doc-k-next
8918: doc-k-insert
8919: doc-k-delete
8920:
8921: The function keys (aka keypad keys) are:
8922:
8923: doc-k1
8924: doc-k2
8925: doc-k3
8926: doc-k4
8927: doc-k5
8928: doc-k6
8929: doc-k7
8930: doc-k8
8931: doc-k9
8932: doc-k10
8933: doc-k11
8934: doc-k12
8935:
8936: Note that K11 and K12 are not as widely available. The shifted
8937: function keys are also not very widely available:
8938:
8939: doc-s-k8
8940: doc-s-k1
8941: doc-s-k2
8942: doc-s-k3
8943: doc-s-k4
8944: doc-s-k5
8945: doc-s-k6
8946: doc-s-k7
8947: doc-s-k8
8948: doc-s-k9
8949: doc-s-k10
8950: doc-s-k11
8951: doc-s-k12
8952:
8953: Words for inputting one line from the keyboard:
8954:
8955: doc-accept
8956: doc-edit-line
8957:
8958: Conversion words:
8959:
1.143 anton 8960: doc-s>number?
8961: doc-s>unumber?
1.26 crook 8962: doc->number
8963: doc->float
1.143 anton 8964:
1.141 anton 8965:
1.27 crook 8966: @comment obsolescent words..
1.141 anton 8967: Obsolescent input and conversion words:
8968:
1.27 crook 8969: doc-convert
1.26 crook 8970: doc-expect
1.27 crook 8971: doc-span
1.5 anton 8972:
8973:
1.149 ! pazsan 8974: @node Pipes, Xchars and Unicode, Input, Other I/O
1.112 anton 8975: @subsection Pipes
8976: @cindex pipes, creating your own
8977:
8978: In addition to using Gforth in pipes created by other processes
8979: (@pxref{Gforth in pipes}), you can create your own pipe with
8980: @code{open-pipe}, and read from or write to it.
8981:
8982: doc-open-pipe
8983: doc-close-pipe
8984:
8985: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
8986: you don't catch this exception, Gforth will catch it and exit, usually
8987: silently (@pxref{Gforth in pipes}). Since you probably do not want
8988: this, you should wrap a @code{catch} or @code{try} block around the code
8989: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
8990: problem yourself, and then return to regular processing.
8991:
8992: doc-broken-pipe-error
8993:
1.149 ! pazsan 8994: @node Xchars and Unicode, , Pipes, Other I/O
! 8995:
! 8996: This chapter needs completion
1.112 anton 8997:
1.121 anton 8998: @node OS command line arguments, Locals, Other I/O, Words
8999: @section OS command line arguments
9000: @cindex OS command line arguments
9001: @cindex command line arguments, OS
9002: @cindex arguments, OS command line
9003:
9004: The usual way to pass arguments to Gforth programs on the command line
9005: is via the @option{-e} option, e.g.
9006:
9007: @example
9008: gforth -e "123 456" foo.fs -e bye
9009: @end example
9010:
9011: However, you may want to interpret the command-line arguments directly.
9012: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9013: through @code{next-arg}:
1.121 anton 9014:
1.123 anton 9015: doc-next-arg
1.121 anton 9016:
1.123 anton 9017: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9018:
9019: @example
9020: : echo ( -- )
1.122 anton 9021: begin
1.123 anton 9022: next-arg 2dup 0 0 d<> while
9023: type space
9024: repeat
9025: 2drop ;
1.121 anton 9026:
9027: echo cr bye
9028: @end example
9029:
9030: This can be invoked with
9031:
9032: @example
9033: gforth echo.fs hello world
9034: @end example
1.123 anton 9035:
9036: and it will print
9037:
9038: @example
9039: hello world
9040: @end example
9041:
9042: The next lower level of dealing with the OS command line are the
9043: following words:
9044:
9045: doc-arg
9046: doc-shift-args
9047:
9048: Finally, at the lowest level Gforth provides the following words:
9049:
9050: doc-argc
9051: doc-argv
1.121 anton 9052:
1.78 anton 9053: @c -------------------------------------------------------------
1.126 pazsan 9054: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9055: @section Locals
9056: @cindex locals
9057:
9058: Local variables can make Forth programming more enjoyable and Forth
9059: programs easier to read. Unfortunately, the locals of ANS Forth are
9060: laden with restrictions. Therefore, we provide not only the ANS Forth
9061: locals wordset, but also our own, more powerful locals wordset (we
9062: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9063:
1.78 anton 9064: The ideas in this section have also been published in M. Anton Ertl,
9065: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9066: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9067:
9068: @menu
1.78 anton 9069: * Gforth locals::
9070: * ANS Forth locals::
1.5 anton 9071: @end menu
9072:
1.78 anton 9073: @node Gforth locals, ANS Forth locals, Locals, Locals
9074: @subsection Gforth locals
9075: @cindex Gforth locals
9076: @cindex locals, Gforth style
1.5 anton 9077:
1.78 anton 9078: Locals can be defined with
1.44 crook 9079:
1.78 anton 9080: @example
9081: @{ local1 local2 ... -- comment @}
9082: @end example
9083: or
9084: @example
9085: @{ local1 local2 ... @}
9086: @end example
1.5 anton 9087:
1.78 anton 9088: E.g.,
9089: @example
9090: : max @{ n1 n2 -- n3 @}
9091: n1 n2 > if
9092: n1
9093: else
9094: n2
9095: endif ;
9096: @end example
1.44 crook 9097:
1.78 anton 9098: The similarity of locals definitions with stack comments is intended. A
9099: locals definition often replaces the stack comment of a word. The order
9100: of the locals corresponds to the order in a stack comment and everything
9101: after the @code{--} is really a comment.
1.77 anton 9102:
1.78 anton 9103: This similarity has one disadvantage: It is too easy to confuse locals
9104: declarations with stack comments, causing bugs and making them hard to
9105: find. However, this problem can be avoided by appropriate coding
9106: conventions: Do not use both notations in the same program. If you do,
9107: they should be distinguished using additional means, e.g. by position.
1.77 anton 9108:
1.78 anton 9109: @cindex types of locals
9110: @cindex locals types
9111: The name of the local may be preceded by a type specifier, e.g.,
9112: @code{F:} for a floating point value:
1.5 anton 9113:
1.78 anton 9114: @example
9115: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9116: \ complex multiplication
9117: Ar Br f* Ai Bi f* f-
9118: Ar Bi f* Ai Br f* f+ ;
9119: @end example
1.44 crook 9120:
1.78 anton 9121: @cindex flavours of locals
9122: @cindex locals flavours
9123: @cindex value-flavoured locals
9124: @cindex variable-flavoured locals
9125: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9126: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9127: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9128: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9129: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9130: produces its address (which becomes invalid when the variable's scope is
9131: left). E.g., the standard word @code{emit} can be defined in terms of
9132: @code{type} like this:
1.5 anton 9133:
1.78 anton 9134: @example
9135: : emit @{ C^ char* -- @}
9136: char* 1 type ;
9137: @end example
1.5 anton 9138:
1.78 anton 9139: @cindex default type of locals
9140: @cindex locals, default type
9141: A local without type specifier is a @code{W:} local. Both flavours of
9142: locals are initialized with values from the data or FP stack.
1.44 crook 9143:
1.78 anton 9144: Currently there is no way to define locals with user-defined data
9145: structures, but we are working on it.
1.5 anton 9146:
1.78 anton 9147: Gforth allows defining locals everywhere in a colon definition. This
9148: poses the following questions:
1.5 anton 9149:
1.78 anton 9150: @menu
9151: * Where are locals visible by name?::
9152: * How long do locals live?::
9153: * Locals programming style::
9154: * Locals implementation::
9155: @end menu
1.44 crook 9156:
1.78 anton 9157: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9158: @subsubsection Where are locals visible by name?
9159: @cindex locals visibility
9160: @cindex visibility of locals
9161: @cindex scope of locals
1.5 anton 9162:
1.78 anton 9163: Basically, the answer is that locals are visible where you would expect
9164: it in block-structured languages, and sometimes a little longer. If you
9165: want to restrict the scope of a local, enclose its definition in
9166: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9167:
9168:
1.78 anton 9169: doc-scope
9170: doc-endscope
1.5 anton 9171:
9172:
1.78 anton 9173: These words behave like control structure words, so you can use them
9174: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9175: arbitrary ways.
1.77 anton 9176:
1.78 anton 9177: If you want a more exact answer to the visibility question, here's the
9178: basic principle: A local is visible in all places that can only be
9179: reached through the definition of the local@footnote{In compiler
9180: construction terminology, all places dominated by the definition of the
9181: local.}. In other words, it is not visible in places that can be reached
9182: without going through the definition of the local. E.g., locals defined
9183: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9184: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9185: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9186:
1.78 anton 9187: The reasoning behind this solution is: We want to have the locals
9188: visible as long as it is meaningful. The user can always make the
9189: visibility shorter by using explicit scoping. In a place that can
9190: only be reached through the definition of a local, the meaning of a
9191: local name is clear. In other places it is not: How is the local
9192: initialized at the control flow path that does not contain the
9193: definition? Which local is meant, if the same name is defined twice in
9194: two independent control flow paths?
1.77 anton 9195:
1.78 anton 9196: This should be enough detail for nearly all users, so you can skip the
9197: rest of this section. If you really must know all the gory details and
9198: options, read on.
1.77 anton 9199:
1.78 anton 9200: In order to implement this rule, the compiler has to know which places
9201: are unreachable. It knows this automatically after @code{AHEAD},
9202: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9203: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9204: compiler that the control flow never reaches that place. If
9205: @code{UNREACHABLE} is not used where it could, the only consequence is
9206: that the visibility of some locals is more limited than the rule above
9207: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9208: lie to the compiler), buggy code will be produced.
1.77 anton 9209:
1.5 anton 9210:
1.78 anton 9211: doc-unreachable
1.5 anton 9212:
1.23 crook 9213:
1.78 anton 9214: Another problem with this rule is that at @code{BEGIN}, the compiler
9215: does not know which locals will be visible on the incoming
9216: back-edge. All problems discussed in the following are due to this
9217: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9218: loops as examples; the discussion also applies to @code{?DO} and other
9219: loops). Perhaps the most insidious example is:
1.26 crook 9220: @example
1.78 anton 9221: AHEAD
9222: BEGIN
9223: x
9224: [ 1 CS-ROLL ] THEN
9225: @{ x @}
9226: ...
9227: UNTIL
1.26 crook 9228: @end example
1.23 crook 9229:
1.78 anton 9230: This should be legal according to the visibility rule. The use of
9231: @code{x} can only be reached through the definition; but that appears
9232: textually below the use.
9233:
9234: From this example it is clear that the visibility rules cannot be fully
9235: implemented without major headaches. Our implementation treats common
9236: cases as advertised and the exceptions are treated in a safe way: The
9237: compiler makes a reasonable guess about the locals visible after a
9238: @code{BEGIN}; if it is too pessimistic, the
9239: user will get a spurious error about the local not being defined; if the
9240: compiler is too optimistic, it will notice this later and issue a
9241: warning. In the case above the compiler would complain about @code{x}
9242: being undefined at its use. You can see from the obscure examples in
9243: this section that it takes quite unusual control structures to get the
9244: compiler into trouble, and even then it will often do fine.
1.23 crook 9245:
1.78 anton 9246: If the @code{BEGIN} is reachable from above, the most optimistic guess
9247: is that all locals visible before the @code{BEGIN} will also be
9248: visible after the @code{BEGIN}. This guess is valid for all loops that
9249: are entered only through the @code{BEGIN}, in particular, for normal
9250: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9251: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9252: compiler. When the branch to the @code{BEGIN} is finally generated by
9253: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9254: warns the user if it was too optimistic:
1.26 crook 9255: @example
1.78 anton 9256: IF
9257: @{ x @}
9258: BEGIN
9259: \ x ?
9260: [ 1 cs-roll ] THEN
9261: ...
9262: UNTIL
1.26 crook 9263: @end example
1.23 crook 9264:
1.78 anton 9265: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9266: optimistically assumes that it lives until the @code{THEN}. It notices
9267: this difference when it compiles the @code{UNTIL} and issues a
9268: warning. The user can avoid the warning, and make sure that @code{x}
9269: is not used in the wrong area by using explicit scoping:
9270: @example
9271: IF
9272: SCOPE
9273: @{ x @}
9274: ENDSCOPE
9275: BEGIN
9276: [ 1 cs-roll ] THEN
9277: ...
9278: UNTIL
9279: @end example
1.23 crook 9280:
1.78 anton 9281: Since the guess is optimistic, there will be no spurious error messages
9282: about undefined locals.
1.44 crook 9283:
1.78 anton 9284: If the @code{BEGIN} is not reachable from above (e.g., after
9285: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9286: optimistic guess, as the locals visible after the @code{BEGIN} may be
9287: defined later. Therefore, the compiler assumes that no locals are
9288: visible after the @code{BEGIN}. However, the user can use
9289: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9290: visible at the BEGIN as at the point where the top control-flow stack
9291: item was created.
1.23 crook 9292:
1.44 crook 9293:
1.78 anton 9294: doc-assume-live
1.26 crook 9295:
1.23 crook 9296:
1.78 anton 9297: @noindent
9298: E.g.,
9299: @example
9300: @{ x @}
9301: AHEAD
9302: ASSUME-LIVE
9303: BEGIN
9304: x
9305: [ 1 CS-ROLL ] THEN
9306: ...
9307: UNTIL
9308: @end example
1.44 crook 9309:
1.78 anton 9310: Other cases where the locals are defined before the @code{BEGIN} can be
9311: handled by inserting an appropriate @code{CS-ROLL} before the
9312: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9313: behind the @code{ASSUME-LIVE}).
1.23 crook 9314:
1.78 anton 9315: Cases where locals are defined after the @code{BEGIN} (but should be
9316: visible immediately after the @code{BEGIN}) can only be handled by
9317: rearranging the loop. E.g., the ``most insidious'' example above can be
9318: arranged into:
9319: @example
9320: BEGIN
9321: @{ x @}
9322: ... 0=
9323: WHILE
9324: x
9325: REPEAT
9326: @end example
1.44 crook 9327:
1.78 anton 9328: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9329: @subsubsection How long do locals live?
9330: @cindex locals lifetime
9331: @cindex lifetime of locals
1.23 crook 9332:
1.78 anton 9333: The right answer for the lifetime question would be: A local lives at
9334: least as long as it can be accessed. For a value-flavoured local this
9335: means: until the end of its visibility. However, a variable-flavoured
9336: local could be accessed through its address far beyond its visibility
9337: scope. Ultimately, this would mean that such locals would have to be
9338: garbage collected. Since this entails un-Forth-like implementation
9339: complexities, I adopted the same cowardly solution as some other
9340: languages (e.g., C): The local lives only as long as it is visible;
9341: afterwards its address is invalid (and programs that access it
9342: afterwards are erroneous).
1.23 crook 9343:
1.78 anton 9344: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9345: @subsubsection Locals programming style
9346: @cindex locals programming style
9347: @cindex programming style, locals
1.23 crook 9348:
1.78 anton 9349: The freedom to define locals anywhere has the potential to change
9350: programming styles dramatically. In particular, the need to use the
9351: return stack for intermediate storage vanishes. Moreover, all stack
9352: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9353: determined arguments) can be eliminated: If the stack items are in the
9354: wrong order, just write a locals definition for all of them; then
9355: write the items in the order you want.
1.23 crook 9356:
1.78 anton 9357: This seems a little far-fetched and eliminating stack manipulations is
9358: unlikely to become a conscious programming objective. Still, the number
9359: of stack manipulations will be reduced dramatically if local variables
9360: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9361: a traditional implementation of @code{max}).
1.23 crook 9362:
1.78 anton 9363: This shows one potential benefit of locals: making Forth programs more
9364: readable. Of course, this benefit will only be realized if the
9365: programmers continue to honour the principle of factoring instead of
9366: using the added latitude to make the words longer.
1.23 crook 9367:
1.78 anton 9368: @cindex single-assignment style for locals
9369: Using @code{TO} can and should be avoided. Without @code{TO},
9370: every value-flavoured local has only a single assignment and many
9371: advantages of functional languages apply to Forth. I.e., programs are
9372: easier to analyse, to optimize and to read: It is clear from the
9373: definition what the local stands for, it does not turn into something
9374: different later.
1.23 crook 9375:
1.78 anton 9376: E.g., a definition using @code{TO} might look like this:
9377: @example
9378: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9379: u1 u2 min 0
9380: ?do
9381: addr1 c@@ addr2 c@@ -
9382: ?dup-if
9383: unloop exit
9384: then
9385: addr1 char+ TO addr1
9386: addr2 char+ TO addr2
9387: loop
9388: u1 u2 - ;
1.26 crook 9389: @end example
1.78 anton 9390: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9391: every loop iteration. @code{strcmp} is a typical example of the
9392: readability problems of using @code{TO}. When you start reading
9393: @code{strcmp}, you think that @code{addr1} refers to the start of the
9394: string. Only near the end of the loop you realize that it is something
9395: else.
1.23 crook 9396:
1.78 anton 9397: This can be avoided by defining two locals at the start of the loop that
9398: are initialized with the right value for the current iteration.
9399: @example
9400: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9401: addr1 addr2
9402: u1 u2 min 0
9403: ?do @{ s1 s2 @}
9404: s1 c@@ s2 c@@ -
9405: ?dup-if
9406: unloop exit
9407: then
9408: s1 char+ s2 char+
9409: loop
9410: 2drop
9411: u1 u2 - ;
9412: @end example
9413: Here it is clear from the start that @code{s1} has a different value
9414: in every loop iteration.
1.23 crook 9415:
1.78 anton 9416: @node Locals implementation, , Locals programming style, Gforth locals
9417: @subsubsection Locals implementation
9418: @cindex locals implementation
9419: @cindex implementation of locals
1.23 crook 9420:
1.78 anton 9421: @cindex locals stack
9422: Gforth uses an extra locals stack. The most compelling reason for
9423: this is that the return stack is not float-aligned; using an extra stack
9424: also eliminates the problems and restrictions of using the return stack
9425: as locals stack. Like the other stacks, the locals stack grows toward
9426: lower addresses. A few primitives allow an efficient implementation:
9427:
9428:
9429: doc-@local#
9430: doc-f@local#
9431: doc-laddr#
9432: doc-lp+!#
9433: doc-lp!
9434: doc->l
9435: doc-f>l
9436:
9437:
9438: In addition to these primitives, some specializations of these
9439: primitives for commonly occurring inline arguments are provided for
9440: efficiency reasons, e.g., @code{@@local0} as specialization of
9441: @code{@@local#} for the inline argument 0. The following compiling words
9442: compile the right specialized version, or the general version, as
9443: appropriate:
1.23 crook 9444:
1.5 anton 9445:
1.107 dvdkhlng 9446: @c doc-compile-@local
9447: @c doc-compile-f@local
1.78 anton 9448: doc-compile-lp+!
1.5 anton 9449:
9450:
1.78 anton 9451: Combinations of conditional branches and @code{lp+!#} like
9452: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9453: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9454:
1.78 anton 9455: A special area in the dictionary space is reserved for keeping the
9456: local variable names. @code{@{} switches the dictionary pointer to this
9457: area and @code{@}} switches it back and generates the locals
9458: initializing code. @code{W:} etc.@ are normal defining words. This
9459: special area is cleared at the start of every colon definition.
1.5 anton 9460:
1.78 anton 9461: @cindex word list for defining locals
9462: A special feature of Gforth's dictionary is used to implement the
9463: definition of locals without type specifiers: every word list (aka
9464: vocabulary) has its own methods for searching
9465: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9466: with a special search method: When it is searched for a word, it
9467: actually creates that word using @code{W:}. @code{@{} changes the search
9468: order to first search the word list containing @code{@}}, @code{W:} etc.,
9469: and then the word list for defining locals without type specifiers.
1.5 anton 9470:
1.78 anton 9471: The lifetime rules support a stack discipline within a colon
9472: definition: The lifetime of a local is either nested with other locals
9473: lifetimes or it does not overlap them.
1.23 crook 9474:
1.78 anton 9475: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9476: pointer manipulation is generated. Between control structure words
9477: locals definitions can push locals onto the locals stack. @code{AGAIN}
9478: is the simplest of the other three control flow words. It has to
9479: restore the locals stack depth of the corresponding @code{BEGIN}
9480: before branching. The code looks like this:
9481: @format
9482: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9483: @code{branch} <begin>
9484: @end format
1.26 crook 9485:
1.78 anton 9486: @code{UNTIL} is a little more complicated: If it branches back, it
9487: must adjust the stack just like @code{AGAIN}. But if it falls through,
9488: the locals stack must not be changed. The compiler generates the
9489: following code:
9490: @format
9491: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9492: @end format
9493: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9494:
1.78 anton 9495: @code{THEN} can produce somewhat inefficient code:
9496: @format
9497: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9498: <orig target>:
9499: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9500: @end format
9501: The second @code{lp+!#} adjusts the locals stack pointer from the
9502: level at the @i{orig} point to the level after the @code{THEN}. The
9503: first @code{lp+!#} adjusts the locals stack pointer from the current
9504: level to the level at the orig point, so the complete effect is an
9505: adjustment from the current level to the right level after the
9506: @code{THEN}.
1.26 crook 9507:
1.78 anton 9508: @cindex locals information on the control-flow stack
9509: @cindex control-flow stack items, locals information
9510: In a conventional Forth implementation a dest control-flow stack entry
9511: is just the target address and an orig entry is just the address to be
9512: patched. Our locals implementation adds a word list to every orig or dest
9513: item. It is the list of locals visible (or assumed visible) at the point
9514: described by the entry. Our implementation also adds a tag to identify
9515: the kind of entry, in particular to differentiate between live and dead
9516: (reachable and unreachable) orig entries.
1.26 crook 9517:
1.78 anton 9518: A few unusual operations have to be performed on locals word lists:
1.44 crook 9519:
1.5 anton 9520:
1.78 anton 9521: doc-common-list
9522: doc-sub-list?
9523: doc-list-size
1.52 anton 9524:
9525:
1.78 anton 9526: Several features of our locals word list implementation make these
9527: operations easy to implement: The locals word lists are organised as
9528: linked lists; the tails of these lists are shared, if the lists
9529: contain some of the same locals; and the address of a name is greater
9530: than the address of the names behind it in the list.
1.5 anton 9531:
1.78 anton 9532: Another important implementation detail is the variable
9533: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9534: determine if they can be reached directly or only through the branch
9535: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9536: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9537: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9538:
1.78 anton 9539: Counted loops are similar to other loops in most respects, but
9540: @code{LEAVE} requires special attention: It performs basically the same
9541: service as @code{AHEAD}, but it does not create a control-flow stack
9542: entry. Therefore the information has to be stored elsewhere;
9543: traditionally, the information was stored in the target fields of the
9544: branches created by the @code{LEAVE}s, by organizing these fields into a
9545: linked list. Unfortunately, this clever trick does not provide enough
9546: space for storing our extended control flow information. Therefore, we
9547: introduce another stack, the leave stack. It contains the control-flow
9548: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9549:
1.78 anton 9550: Local names are kept until the end of the colon definition, even if
9551: they are no longer visible in any control-flow path. In a few cases
9552: this may lead to increased space needs for the locals name area, but
9553: usually less than reclaiming this space would cost in code size.
1.5 anton 9554:
1.44 crook 9555:
1.78 anton 9556: @node ANS Forth locals, , Gforth locals, Locals
9557: @subsection ANS Forth locals
9558: @cindex locals, ANS Forth style
1.5 anton 9559:
1.78 anton 9560: The ANS Forth locals wordset does not define a syntax for locals, but
9561: words that make it possible to define various syntaxes. One of the
9562: possible syntaxes is a subset of the syntax we used in the Gforth locals
9563: wordset, i.e.:
1.29 crook 9564:
9565: @example
1.78 anton 9566: @{ local1 local2 ... -- comment @}
9567: @end example
9568: @noindent
9569: or
9570: @example
9571: @{ local1 local2 ... @}
1.29 crook 9572: @end example
9573:
1.78 anton 9574: The order of the locals corresponds to the order in a stack comment. The
9575: restrictions are:
1.5 anton 9576:
1.78 anton 9577: @itemize @bullet
9578: @item
9579: Locals can only be cell-sized values (no type specifiers are allowed).
9580: @item
9581: Locals can be defined only outside control structures.
9582: @item
9583: Locals can interfere with explicit usage of the return stack. For the
9584: exact (and long) rules, see the standard. If you don't use return stack
9585: accessing words in a definition using locals, you will be all right. The
9586: purpose of this rule is to make locals implementation on the return
9587: stack easier.
9588: @item
9589: The whole definition must be in one line.
9590: @end itemize
1.5 anton 9591:
1.78 anton 9592: Locals defined in ANS Forth behave like @code{VALUE}s
9593: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9594: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9595:
1.78 anton 9596: Since the syntax above is supported by Gforth directly, you need not do
9597: anything to use it. If you want to port a program using this syntax to
9598: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9599: syntax on the other system.
1.5 anton 9600:
1.78 anton 9601: Note that a syntax shown in the standard, section A.13 looks
9602: similar, but is quite different in having the order of locals
9603: reversed. Beware!
1.5 anton 9604:
1.78 anton 9605: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9606:
1.78 anton 9607: doc-(local)
1.5 anton 9608:
1.78 anton 9609: The ANS Forth locals extension wordset defines a syntax using
9610: @code{locals|}, but it is so awful that we strongly recommend not to use
9611: it. We have implemented this syntax to make porting to Gforth easy, but
9612: do not document it here. The problem with this syntax is that the locals
9613: are defined in an order reversed with respect to the standard stack
9614: comment notation, making programs harder to read, and easier to misread
9615: and miswrite. The only merit of this syntax is that it is easy to
9616: implement using the ANS Forth locals wordset.
1.53 anton 9617:
9618:
1.78 anton 9619: @c ----------------------------------------------------------
9620: @node Structures, Object-oriented Forth, Locals, Words
9621: @section Structures
9622: @cindex structures
9623: @cindex records
1.53 anton 9624:
1.78 anton 9625: This section presents the structure package that comes with Gforth. A
9626: version of the package implemented in ANS Forth is available in
9627: @file{compat/struct.fs}. This package was inspired by a posting on
9628: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9629: possibly John Hayes). A version of this section has been published in
9630: M. Anton Ertl,
9631: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9632: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9633: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9634:
1.78 anton 9635: @menu
9636: * Why explicit structure support?::
9637: * Structure Usage::
9638: * Structure Naming Convention::
9639: * Structure Implementation::
9640: * Structure Glossary::
9641: @end menu
1.55 anton 9642:
1.78 anton 9643: @node Why explicit structure support?, Structure Usage, Structures, Structures
9644: @subsection Why explicit structure support?
1.53 anton 9645:
1.78 anton 9646: @cindex address arithmetic for structures
9647: @cindex structures using address arithmetic
9648: If we want to use a structure containing several fields, we could simply
9649: reserve memory for it, and access the fields using address arithmetic
9650: (@pxref{Address arithmetic}). As an example, consider a structure with
9651: the following fields
1.57 anton 9652:
1.78 anton 9653: @table @code
9654: @item a
9655: is a float
9656: @item b
9657: is a cell
9658: @item c
9659: is a float
9660: @end table
1.57 anton 9661:
1.78 anton 9662: Given the (float-aligned) base address of the structure we get the
9663: address of the field
1.52 anton 9664:
1.78 anton 9665: @table @code
9666: @item a
9667: without doing anything further.
9668: @item b
9669: with @code{float+}
9670: @item c
9671: with @code{float+ cell+ faligned}
9672: @end table
1.52 anton 9673:
1.78 anton 9674: It is easy to see that this can become quite tiring.
1.52 anton 9675:
1.78 anton 9676: Moreover, it is not very readable, because seeing a
9677: @code{cell+} tells us neither which kind of structure is
9678: accessed nor what field is accessed; we have to somehow infer the kind
9679: of structure, and then look up in the documentation, which field of
9680: that structure corresponds to that offset.
1.53 anton 9681:
1.78 anton 9682: Finally, this kind of address arithmetic also causes maintenance
9683: troubles: If you add or delete a field somewhere in the middle of the
9684: structure, you have to find and change all computations for the fields
9685: afterwards.
1.52 anton 9686:
1.78 anton 9687: So, instead of using @code{cell+} and friends directly, how
9688: about storing the offsets in constants:
1.52 anton 9689:
1.78 anton 9690: @example
9691: 0 constant a-offset
9692: 0 float+ constant b-offset
9693: 0 float+ cell+ faligned c-offset
9694: @end example
1.64 pazsan 9695:
1.78 anton 9696: Now we can get the address of field @code{x} with @code{x-offset
9697: +}. This is much better in all respects. Of course, you still
9698: have to change all later offset definitions if you add a field. You can
9699: fix this by declaring the offsets in the following way:
1.57 anton 9700:
1.78 anton 9701: @example
9702: 0 constant a-offset
9703: a-offset float+ constant b-offset
9704: b-offset cell+ faligned constant c-offset
9705: @end example
1.57 anton 9706:
1.78 anton 9707: Since we always use the offsets with @code{+}, we could use a defining
9708: word @code{cfield} that includes the @code{+} in the action of the
9709: defined word:
1.64 pazsan 9710:
1.78 anton 9711: @example
9712: : cfield ( n "name" -- )
9713: create ,
9714: does> ( name execution: addr1 -- addr2 )
9715: @@ + ;
1.64 pazsan 9716:
1.78 anton 9717: 0 cfield a
9718: 0 a float+ cfield b
9719: 0 b cell+ faligned cfield c
9720: @end example
1.64 pazsan 9721:
1.78 anton 9722: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9723:
1.78 anton 9724: The structure field words now can be used quite nicely. However,
9725: their definition is still a bit cumbersome: We have to repeat the
9726: name, the information about size and alignment is distributed before
9727: and after the field definitions etc. The structure package presented
9728: here addresses these problems.
1.64 pazsan 9729:
1.78 anton 9730: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9731: @subsection Structure Usage
9732: @cindex structure usage
1.57 anton 9733:
1.78 anton 9734: @cindex @code{field} usage
9735: @cindex @code{struct} usage
9736: @cindex @code{end-struct} usage
9737: You can define a structure for a (data-less) linked list with:
1.57 anton 9738: @example
1.78 anton 9739: struct
9740: cell% field list-next
9741: end-struct list%
1.57 anton 9742: @end example
9743:
1.78 anton 9744: With the address of the list node on the stack, you can compute the
9745: address of the field that contains the address of the next node with
9746: @code{list-next}. E.g., you can determine the length of a list
9747: with:
1.57 anton 9748:
9749: @example
1.78 anton 9750: : list-length ( list -- n )
9751: \ "list" is a pointer to the first element of a linked list
9752: \ "n" is the length of the list
9753: 0 BEGIN ( list1 n1 )
9754: over
9755: WHILE ( list1 n1 )
9756: 1+ swap list-next @@ swap
9757: REPEAT
9758: nip ;
1.57 anton 9759: @end example
9760:
1.78 anton 9761: You can reserve memory for a list node in the dictionary with
9762: @code{list% %allot}, which leaves the address of the list node on the
9763: stack. For the equivalent allocation on the heap you can use @code{list%
9764: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9765: use @code{list% %allocate}). You can get the the size of a list
9766: node with @code{list% %size} and its alignment with @code{list%
9767: %alignment}.
9768:
9769: Note that in ANS Forth the body of a @code{create}d word is
9770: @code{aligned} but not necessarily @code{faligned};
9771: therefore, if you do a:
1.57 anton 9772:
9773: @example
1.78 anton 9774: create @emph{name} foo% %allot drop
1.57 anton 9775: @end example
9776:
1.78 anton 9777: @noindent
9778: then the memory alloted for @code{foo%} is guaranteed to start at the
9779: body of @code{@emph{name}} only if @code{foo%} contains only character,
9780: cell and double fields. Therefore, if your structure contains floats,
9781: better use
1.57 anton 9782:
9783: @example
1.78 anton 9784: foo% %allot constant @emph{name}
1.57 anton 9785: @end example
9786:
1.78 anton 9787: @cindex structures containing structures
9788: You can include a structure @code{foo%} as a field of
9789: another structure, like this:
1.65 anton 9790: @example
1.78 anton 9791: struct
9792: ...
9793: foo% field ...
9794: ...
9795: end-struct ...
1.65 anton 9796: @end example
1.52 anton 9797:
1.78 anton 9798: @cindex structure extension
9799: @cindex extended records
9800: Instead of starting with an empty structure, you can extend an
9801: existing structure. E.g., a plain linked list without data, as defined
9802: above, is hardly useful; You can extend it to a linked list of integers,
9803: like this:@footnote{This feature is also known as @emph{extended
9804: records}. It is the main innovation in the Oberon language; in other
9805: words, adding this feature to Modula-2 led Wirth to create a new
9806: language, write a new compiler etc. Adding this feature to Forth just
9807: required a few lines of code.}
1.52 anton 9808:
1.78 anton 9809: @example
9810: list%
9811: cell% field intlist-int
9812: end-struct intlist%
9813: @end example
1.55 anton 9814:
1.78 anton 9815: @code{intlist%} is a structure with two fields:
9816: @code{list-next} and @code{intlist-int}.
1.55 anton 9817:
1.78 anton 9818: @cindex structures containing arrays
9819: You can specify an array type containing @emph{n} elements of
9820: type @code{foo%} like this:
1.55 anton 9821:
9822: @example
1.78 anton 9823: foo% @emph{n} *
1.56 anton 9824: @end example
1.55 anton 9825:
1.78 anton 9826: You can use this array type in any place where you can use a normal
9827: type, e.g., when defining a @code{field}, or with
9828: @code{%allot}.
9829:
9830: @cindex first field optimization
9831: The first field is at the base address of a structure and the word for
9832: this field (e.g., @code{list-next}) actually does not change the address
9833: on the stack. You may be tempted to leave it away in the interest of
9834: run-time and space efficiency. This is not necessary, because the
9835: structure package optimizes this case: If you compile a first-field
9836: words, no code is generated. So, in the interest of readability and
9837: maintainability you should include the word for the field when accessing
9838: the field.
1.52 anton 9839:
9840:
1.78 anton 9841: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9842: @subsection Structure Naming Convention
9843: @cindex structure naming convention
1.52 anton 9844:
1.78 anton 9845: The field names that come to (my) mind are often quite generic, and,
9846: if used, would cause frequent name clashes. E.g., many structures
9847: probably contain a @code{counter} field. The structure names
9848: that come to (my) mind are often also the logical choice for the names
9849: of words that create such a structure.
1.52 anton 9850:
1.78 anton 9851: Therefore, I have adopted the following naming conventions:
1.52 anton 9852:
1.78 anton 9853: @itemize @bullet
9854: @cindex field naming convention
9855: @item
9856: The names of fields are of the form
9857: @code{@emph{struct}-@emph{field}}, where
9858: @code{@emph{struct}} is the basic name of the structure, and
9859: @code{@emph{field}} is the basic name of the field. You can
9860: think of field words as converting the (address of the)
9861: structure into the (address of the) field.
1.52 anton 9862:
1.78 anton 9863: @cindex structure naming convention
9864: @item
9865: The names of structures are of the form
9866: @code{@emph{struct}%}, where
9867: @code{@emph{struct}} is the basic name of the structure.
9868: @end itemize
1.52 anton 9869:
1.78 anton 9870: This naming convention does not work that well for fields of extended
9871: structures; e.g., the integer list structure has a field
9872: @code{intlist-int}, but has @code{list-next}, not
9873: @code{intlist-next}.
1.53 anton 9874:
1.78 anton 9875: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9876: @subsection Structure Implementation
9877: @cindex structure implementation
9878: @cindex implementation of structures
1.52 anton 9879:
1.78 anton 9880: The central idea in the implementation is to pass the data about the
9881: structure being built on the stack, not in some global
9882: variable. Everything else falls into place naturally once this design
9883: decision is made.
1.53 anton 9884:
1.78 anton 9885: The type description on the stack is of the form @emph{align
9886: size}. Keeping the size on the top-of-stack makes dealing with arrays
9887: very simple.
1.53 anton 9888:
1.78 anton 9889: @code{field} is a defining word that uses @code{Create}
9890: and @code{DOES>}. The body of the field contains the offset
9891: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 9892:
9893: @example
1.78 anton 9894: @@ +
1.53 anton 9895: @end example
9896:
1.78 anton 9897: @noindent
9898: i.e., add the offset to the address, giving the stack effect
9899: @i{addr1 -- addr2} for a field.
9900:
9901: @cindex first field optimization, implementation
9902: This simple structure is slightly complicated by the optimization
9903: for fields with offset 0, which requires a different
9904: @code{DOES>}-part (because we cannot rely on there being
9905: something on the stack if such a field is invoked during
9906: compilation). Therefore, we put the different @code{DOES>}-parts
9907: in separate words, and decide which one to invoke based on the
9908: offset. For a zero offset, the field is basically a noop; it is
9909: immediate, and therefore no code is generated when it is compiled.
1.53 anton 9910:
1.78 anton 9911: @node Structure Glossary, , Structure Implementation, Structures
9912: @subsection Structure Glossary
9913: @cindex structure glossary
1.53 anton 9914:
1.5 anton 9915:
1.78 anton 9916: doc-%align
9917: doc-%alignment
9918: doc-%alloc
9919: doc-%allocate
9920: doc-%allot
9921: doc-cell%
9922: doc-char%
9923: doc-dfloat%
9924: doc-double%
9925: doc-end-struct
9926: doc-field
9927: doc-float%
9928: doc-naligned
9929: doc-sfloat%
9930: doc-%size
9931: doc-struct
1.54 anton 9932:
9933:
1.26 crook 9934: @c -------------------------------------------------------------
1.78 anton 9935: @node Object-oriented Forth, Programming Tools, Structures, Words
9936: @section Object-oriented Forth
9937:
9938: Gforth comes with three packages for object-oriented programming:
9939: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9940: is preloaded, so you have to @code{include} them before use. The most
9941: important differences between these packages (and others) are discussed
9942: in @ref{Comparison with other object models}. All packages are written
9943: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 9944:
1.78 anton 9945: @menu
9946: * Why object-oriented programming?::
9947: * Object-Oriented Terminology::
9948: * Objects::
9949: * OOF::
9950: * Mini-OOF::
9951: * Comparison with other object models::
9952: @end menu
1.5 anton 9953:
1.78 anton 9954: @c ----------------------------------------------------------------
9955: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9956: @subsection Why object-oriented programming?
9957: @cindex object-oriented programming motivation
9958: @cindex motivation for object-oriented programming
1.44 crook 9959:
1.78 anton 9960: Often we have to deal with several data structures (@emph{objects}),
9961: that have to be treated similarly in some respects, but differently in
9962: others. Graphical objects are the textbook example: circles, triangles,
9963: dinosaurs, icons, and others, and we may want to add more during program
9964: development. We want to apply some operations to any graphical object,
9965: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9966: has to do something different for every kind of object.
9967: @comment TODO add some other operations eg perimeter, area
9968: @comment and tie in to concrete examples later..
1.5 anton 9969:
1.78 anton 9970: We could implement @code{draw} as a big @code{CASE}
9971: control structure that executes the appropriate code depending on the
9972: kind of object to be drawn. This would be not be very elegant, and,
9973: moreover, we would have to change @code{draw} every time we add
9974: a new kind of graphical object (say, a spaceship).
1.44 crook 9975:
1.78 anton 9976: What we would rather do is: When defining spaceships, we would tell
9977: the system: ``Here's how you @code{draw} a spaceship; you figure
9978: out the rest''.
1.5 anton 9979:
1.78 anton 9980: This is the problem that all systems solve that (rightfully) call
9981: themselves object-oriented; the object-oriented packages presented here
9982: solve this problem (and not much else).
9983: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 9984:
1.78 anton 9985: @c ------------------------------------------------------------------------
9986: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
9987: @subsection Object-Oriented Terminology
9988: @cindex object-oriented terminology
9989: @cindex terminology for object-oriented programming
1.5 anton 9990:
1.78 anton 9991: This section is mainly for reference, so you don't have to understand
9992: all of it right away. The terminology is mainly Smalltalk-inspired. In
9993: short:
1.44 crook 9994:
1.78 anton 9995: @table @emph
9996: @cindex class
9997: @item class
9998: a data structure definition with some extras.
1.5 anton 9999:
1.78 anton 10000: @cindex object
10001: @item object
10002: an instance of the data structure described by the class definition.
1.5 anton 10003:
1.78 anton 10004: @cindex instance variables
10005: @item instance variables
10006: fields of the data structure.
1.5 anton 10007:
1.78 anton 10008: @cindex selector
10009: @cindex method selector
10010: @cindex virtual function
10011: @item selector
10012: (or @emph{method selector}) a word (e.g.,
10013: @code{draw}) that performs an operation on a variety of data
10014: structures (classes). A selector describes @emph{what} operation to
10015: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10016:
1.78 anton 10017: @cindex method
10018: @item method
10019: the concrete definition that performs the operation
10020: described by the selector for a specific class. A method specifies
10021: @emph{how} the operation is performed for a specific class.
1.5 anton 10022:
1.78 anton 10023: @cindex selector invocation
10024: @cindex message send
10025: @cindex invoking a selector
10026: @item selector invocation
10027: a call of a selector. One argument of the call (the TOS (top-of-stack))
10028: is used for determining which method is used. In Smalltalk terminology:
10029: a message (consisting of the selector and the other arguments) is sent
10030: to the object.
1.5 anton 10031:
1.78 anton 10032: @cindex receiving object
10033: @item receiving object
10034: the object used for determining the method executed by a selector
10035: invocation. In the @file{objects.fs} model, it is the object that is on
10036: the TOS when the selector is invoked. (@emph{Receiving} comes from
10037: the Smalltalk @emph{message} terminology.)
1.5 anton 10038:
1.78 anton 10039: @cindex child class
10040: @cindex parent class
10041: @cindex inheritance
10042: @item child class
10043: a class that has (@emph{inherits}) all properties (instance variables,
10044: selectors, methods) from a @emph{parent class}. In Smalltalk
10045: terminology: The subclass inherits from the superclass. In C++
10046: terminology: The derived class inherits from the base class.
1.5 anton 10047:
1.78 anton 10048: @end table
1.5 anton 10049:
1.78 anton 10050: @c If you wonder about the message sending terminology, it comes from
10051: @c a time when each object had it's own task and objects communicated via
10052: @c message passing; eventually the Smalltalk developers realized that
10053: @c they can do most things through simple (indirect) calls. They kept the
10054: @c terminology.
1.5 anton 10055:
1.78 anton 10056: @c --------------------------------------------------------------
10057: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10058: @subsection The @file{objects.fs} model
10059: @cindex objects
10060: @cindex object-oriented programming
1.26 crook 10061:
1.78 anton 10062: @cindex @file{objects.fs}
10063: @cindex @file{oof.fs}
1.26 crook 10064:
1.78 anton 10065: This section describes the @file{objects.fs} package. This material also
10066: has been published in M. Anton Ertl,
10067: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10068: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10069: 37--43.
10070: @c McKewan's and Zsoter's packages
1.26 crook 10071:
1.78 anton 10072: This section assumes that you have read @ref{Structures}.
1.5 anton 10073:
1.78 anton 10074: The techniques on which this model is based have been used to implement
10075: the parser generator, Gray, and have also been used in Gforth for
10076: implementing the various flavours of word lists (hashed or not,
10077: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10078:
10079:
1.26 crook 10080: @menu
1.78 anton 10081: * Properties of the Objects model::
10082: * Basic Objects Usage::
10083: * The Objects base class::
10084: * Creating objects::
10085: * Object-Oriented Programming Style::
10086: * Class Binding::
10087: * Method conveniences::
10088: * Classes and Scoping::
10089: * Dividing classes::
10090: * Object Interfaces::
10091: * Objects Implementation::
10092: * Objects Glossary::
1.26 crook 10093: @end menu
1.5 anton 10094:
1.78 anton 10095: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10096:
1.78 anton 10097: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10098: @subsubsection Properties of the @file{objects.fs} model
10099: @cindex @file{objects.fs} properties
1.5 anton 10100:
1.78 anton 10101: @itemize @bullet
10102: @item
10103: It is straightforward to pass objects on the stack. Passing
10104: selectors on the stack is a little less convenient, but possible.
1.44 crook 10105:
1.78 anton 10106: @item
10107: Objects are just data structures in memory, and are referenced by their
10108: address. You can create words for objects with normal defining words
10109: like @code{constant}. Likewise, there is no difference between instance
10110: variables that contain objects and those that contain other data.
1.5 anton 10111:
1.78 anton 10112: @item
10113: Late binding is efficient and easy to use.
1.44 crook 10114:
1.78 anton 10115: @item
10116: It avoids parsing, and thus avoids problems with state-smartness
10117: and reduced extensibility; for convenience there are a few parsing
10118: words, but they have non-parsing counterparts. There are also a few
10119: defining words that parse. This is hard to avoid, because all standard
10120: defining words parse (except @code{:noname}); however, such
10121: words are not as bad as many other parsing words, because they are not
10122: state-smart.
1.5 anton 10123:
1.78 anton 10124: @item
10125: It does not try to incorporate everything. It does a few things and does
10126: them well (IMO). In particular, this model was not designed to support
10127: information hiding (although it has features that may help); you can use
10128: a separate package for achieving this.
1.5 anton 10129:
1.78 anton 10130: @item
10131: It is layered; you don't have to learn and use all features to use this
10132: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10133: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10134: are optional and independent of each other.
1.5 anton 10135:
1.78 anton 10136: @item
10137: An implementation in ANS Forth is available.
1.5 anton 10138:
1.78 anton 10139: @end itemize
1.5 anton 10140:
1.44 crook 10141:
1.78 anton 10142: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10143: @subsubsection Basic @file{objects.fs} Usage
10144: @cindex basic objects usage
10145: @cindex objects, basic usage
1.5 anton 10146:
1.78 anton 10147: You can define a class for graphical objects like this:
1.44 crook 10148:
1.78 anton 10149: @cindex @code{class} usage
10150: @cindex @code{end-class} usage
10151: @cindex @code{selector} usage
1.5 anton 10152: @example
1.78 anton 10153: object class \ "object" is the parent class
10154: selector draw ( x y graphical -- )
10155: end-class graphical
10156: @end example
10157:
10158: This code defines a class @code{graphical} with an
10159: operation @code{draw}. We can perform the operation
10160: @code{draw} on any @code{graphical} object, e.g.:
10161:
10162: @example
10163: 100 100 t-rex draw
1.26 crook 10164: @end example
1.5 anton 10165:
1.78 anton 10166: @noindent
10167: where @code{t-rex} is a word (say, a constant) that produces a
10168: graphical object.
10169:
10170: @comment TODO add a 2nd operation eg perimeter.. and use for
10171: @comment a concrete example
1.5 anton 10172:
1.78 anton 10173: @cindex abstract class
10174: How do we create a graphical object? With the present definitions,
10175: we cannot create a useful graphical object. The class
10176: @code{graphical} describes graphical objects in general, but not
10177: any concrete graphical object type (C++ users would call it an
10178: @emph{abstract class}); e.g., there is no method for the selector
10179: @code{draw} in the class @code{graphical}.
1.5 anton 10180:
1.78 anton 10181: For concrete graphical objects, we define child classes of the
10182: class @code{graphical}, e.g.:
1.5 anton 10183:
1.78 anton 10184: @cindex @code{overrides} usage
10185: @cindex @code{field} usage in class definition
1.26 crook 10186: @example
1.78 anton 10187: graphical class \ "graphical" is the parent class
10188: cell% field circle-radius
1.5 anton 10189:
1.78 anton 10190: :noname ( x y circle -- )
10191: circle-radius @@ draw-circle ;
10192: overrides draw
1.5 anton 10193:
1.78 anton 10194: :noname ( n-radius circle -- )
10195: circle-radius ! ;
10196: overrides construct
1.5 anton 10197:
1.78 anton 10198: end-class circle
10199: @end example
1.44 crook 10200:
1.78 anton 10201: Here we define a class @code{circle} as a child of @code{graphical},
10202: with field @code{circle-radius} (which behaves just like a field
10203: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10204: for the selectors @code{draw} and @code{construct} (@code{construct} is
10205: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10206:
1.78 anton 10207: Now we can create a circle on the heap (i.e.,
10208: @code{allocate}d memory) with:
1.44 crook 10209:
1.78 anton 10210: @cindex @code{heap-new} usage
1.5 anton 10211: @example
1.78 anton 10212: 50 circle heap-new constant my-circle
1.5 anton 10213: @end example
10214:
1.78 anton 10215: @noindent
10216: @code{heap-new} invokes @code{construct}, thus
10217: initializing the field @code{circle-radius} with 50. We can draw
10218: this new circle at (100,100) with:
1.5 anton 10219:
10220: @example
1.78 anton 10221: 100 100 my-circle draw
1.5 anton 10222: @end example
10223:
1.78 anton 10224: @cindex selector invocation, restrictions
10225: @cindex class definition, restrictions
10226: Note: You can only invoke a selector if the object on the TOS
10227: (the receiving object) belongs to the class where the selector was
10228: defined or one of its descendents; e.g., you can invoke
10229: @code{draw} only for objects belonging to @code{graphical}
10230: or its descendents (e.g., @code{circle}). Immediately before
10231: @code{end-class}, the search order has to be the same as
10232: immediately after @code{class}.
10233:
10234: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10235: @subsubsection The @file{object.fs} base class
10236: @cindex @code{object} class
10237:
10238: When you define a class, you have to specify a parent class. So how do
10239: you start defining classes? There is one class available from the start:
10240: @code{object}. It is ancestor for all classes and so is the
10241: only class that has no parent. It has two selectors: @code{construct}
10242: and @code{print}.
10243:
10244: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10245: @subsubsection Creating objects
10246: @cindex creating objects
10247: @cindex object creation
10248: @cindex object allocation options
10249:
10250: @cindex @code{heap-new} discussion
10251: @cindex @code{dict-new} discussion
10252: @cindex @code{construct} discussion
10253: You can create and initialize an object of a class on the heap with
10254: @code{heap-new} ( ... class -- object ) and in the dictionary
10255: (allocation with @code{allot}) with @code{dict-new} (
10256: ... class -- object ). Both words invoke @code{construct}, which
10257: consumes the stack items indicated by "..." above.
10258:
10259: @cindex @code{init-object} discussion
10260: @cindex @code{class-inst-size} discussion
10261: If you want to allocate memory for an object yourself, you can get its
10262: alignment and size with @code{class-inst-size 2@@} ( class --
10263: align size ). Once you have memory for an object, you can initialize
10264: it with @code{init-object} ( ... class object -- );
10265: @code{construct} does only a part of the necessary work.
10266:
10267: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10268: @subsubsection Object-Oriented Programming Style
10269: @cindex object-oriented programming style
10270: @cindex programming style, object-oriented
1.5 anton 10271:
1.78 anton 10272: This section is not exhaustive.
1.5 anton 10273:
1.78 anton 10274: @cindex stack effects of selectors
10275: @cindex selectors and stack effects
10276: In general, it is a good idea to ensure that all methods for the
10277: same selector have the same stack effect: when you invoke a selector,
10278: you often have no idea which method will be invoked, so, unless all
10279: methods have the same stack effect, you will not know the stack effect
10280: of the selector invocation.
1.5 anton 10281:
1.78 anton 10282: One exception to this rule is methods for the selector
10283: @code{construct}. We know which method is invoked, because we
10284: specify the class to be constructed at the same place. Actually, I
10285: defined @code{construct} as a selector only to give the users a
10286: convenient way to specify initialization. The way it is used, a
10287: mechanism different from selector invocation would be more natural
10288: (but probably would take more code and more space to explain).
1.5 anton 10289:
1.78 anton 10290: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10291: @subsubsection Class Binding
10292: @cindex class binding
10293: @cindex early binding
1.5 anton 10294:
1.78 anton 10295: @cindex late binding
10296: Normal selector invocations determine the method at run-time depending
10297: on the class of the receiving object. This run-time selection is called
10298: @i{late binding}.
1.5 anton 10299:
1.78 anton 10300: Sometimes it's preferable to invoke a different method. For example,
10301: you might want to use the simple method for @code{print}ing
10302: @code{object}s instead of the possibly long-winded @code{print} method
10303: of the receiver class. You can achieve this by replacing the invocation
10304: of @code{print} with:
1.5 anton 10305:
1.78 anton 10306: @cindex @code{[bind]} usage
1.5 anton 10307: @example
1.78 anton 10308: [bind] object print
1.5 anton 10309: @end example
10310:
1.78 anton 10311: @noindent
10312: in compiled code or:
10313:
10314: @cindex @code{bind} usage
1.5 anton 10315: @example
1.78 anton 10316: bind object print
1.5 anton 10317: @end example
10318:
1.78 anton 10319: @cindex class binding, alternative to
10320: @noindent
10321: in interpreted code. Alternatively, you can define the method with a
10322: name (e.g., @code{print-object}), and then invoke it through the
10323: name. Class binding is just a (often more convenient) way to achieve
10324: the same effect; it avoids name clutter and allows you to invoke
10325: methods directly without naming them first.
1.5 anton 10326:
1.78 anton 10327: @cindex superclass binding
10328: @cindex parent class binding
10329: A frequent use of class binding is this: When we define a method
10330: for a selector, we often want the method to do what the selector does
10331: in the parent class, and a little more. There is a special word for
10332: this purpose: @code{[parent]}; @code{[parent]
10333: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10334: selector}}, where @code{@emph{parent}} is the parent
10335: class of the current class. E.g., a method definition might look like:
1.44 crook 10336:
1.78 anton 10337: @cindex @code{[parent]} usage
10338: @example
10339: :noname
10340: dup [parent] foo \ do parent's foo on the receiving object
10341: ... \ do some more
10342: ; overrides foo
10343: @end example
1.6 pazsan 10344:
1.78 anton 10345: @cindex class binding as optimization
10346: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10347: March 1997), Andrew McKewan presents class binding as an optimization
10348: technique. I recommend not using it for this purpose unless you are in
10349: an emergency. Late binding is pretty fast with this model anyway, so the
10350: benefit of using class binding is small; the cost of using class binding
10351: where it is not appropriate is reduced maintainability.
1.44 crook 10352:
1.78 anton 10353: While we are at programming style questions: You should bind
10354: selectors only to ancestor classes of the receiving object. E.g., say,
10355: you know that the receiving object is of class @code{foo} or its
10356: descendents; then you should bind only to @code{foo} and its
10357: ancestors.
1.12 anton 10358:
1.78 anton 10359: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10360: @subsubsection Method conveniences
10361: @cindex method conveniences
1.44 crook 10362:
1.78 anton 10363: In a method you usually access the receiving object pretty often. If
10364: you define the method as a plain colon definition (e.g., with
10365: @code{:noname}), you may have to do a lot of stack
10366: gymnastics. To avoid this, you can define the method with @code{m:
10367: ... ;m}. E.g., you could define the method for
10368: @code{draw}ing a @code{circle} with
1.6 pazsan 10369:
1.78 anton 10370: @cindex @code{this} usage
10371: @cindex @code{m:} usage
10372: @cindex @code{;m} usage
10373: @example
10374: m: ( x y circle -- )
10375: ( x y ) this circle-radius @@ draw-circle ;m
10376: @end example
1.6 pazsan 10377:
1.78 anton 10378: @cindex @code{exit} in @code{m: ... ;m}
10379: @cindex @code{exitm} discussion
10380: @cindex @code{catch} in @code{m: ... ;m}
10381: When this method is executed, the receiver object is removed from the
10382: stack; you can access it with @code{this} (admittedly, in this
10383: example the use of @code{m: ... ;m} offers no advantage). Note
10384: that I specify the stack effect for the whole method (i.e. including
10385: the receiver object), not just for the code between @code{m:}
10386: and @code{;m}. You cannot use @code{exit} in
10387: @code{m:...;m}; instead, use
10388: @code{exitm}.@footnote{Moreover, for any word that calls
10389: @code{catch} and was defined before loading
10390: @code{objects.fs}, you have to redefine it like I redefined
10391: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10392:
1.78 anton 10393: @cindex @code{inst-var} usage
10394: You will frequently use sequences of the form @code{this
10395: @emph{field}} (in the example above: @code{this
10396: circle-radius}). If you use the field only in this way, you can
10397: define it with @code{inst-var} and eliminate the
10398: @code{this} before the field name. E.g., the @code{circle}
10399: class above could also be defined with:
1.6 pazsan 10400:
1.78 anton 10401: @example
10402: graphical class
10403: cell% inst-var radius
1.6 pazsan 10404:
1.78 anton 10405: m: ( x y circle -- )
10406: radius @@ draw-circle ;m
10407: overrides draw
1.6 pazsan 10408:
1.78 anton 10409: m: ( n-radius circle -- )
10410: radius ! ;m
10411: overrides construct
1.6 pazsan 10412:
1.78 anton 10413: end-class circle
10414: @end example
1.6 pazsan 10415:
1.78 anton 10416: @code{radius} can only be used in @code{circle} and its
10417: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10418:
1.78 anton 10419: @cindex @code{inst-value} usage
10420: You can also define fields with @code{inst-value}, which is
10421: to @code{inst-var} what @code{value} is to
10422: @code{variable}. You can change the value of such a field with
10423: @code{[to-inst]}. E.g., we could also define the class
10424: @code{circle} like this:
1.44 crook 10425:
1.78 anton 10426: @example
10427: graphical class
10428: inst-value radius
1.6 pazsan 10429:
1.78 anton 10430: m: ( x y circle -- )
10431: radius draw-circle ;m
10432: overrides draw
1.44 crook 10433:
1.78 anton 10434: m: ( n-radius circle -- )
10435: [to-inst] radius ;m
10436: overrides construct
1.6 pazsan 10437:
1.78 anton 10438: end-class circle
10439: @end example
1.6 pazsan 10440:
1.78 anton 10441: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10442:
1.78 anton 10443: @c Finally, you can define named methods with @code{:m}. One use of this
10444: @c feature is the definition of words that occur only in one class and are
10445: @c not intended to be overridden, but which still need method context
10446: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10447: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10448:
10449:
1.78 anton 10450: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10451: @subsubsection Classes and Scoping
10452: @cindex classes and scoping
10453: @cindex scoping and classes
1.6 pazsan 10454:
1.78 anton 10455: Inheritance is frequent, unlike structure extension. This exacerbates
10456: the problem with the field name convention (@pxref{Structure Naming
10457: Convention}): One always has to remember in which class the field was
10458: originally defined; changing a part of the class structure would require
10459: changes for renaming in otherwise unaffected code.
1.6 pazsan 10460:
1.78 anton 10461: @cindex @code{inst-var} visibility
10462: @cindex @code{inst-value} visibility
10463: To solve this problem, I added a scoping mechanism (which was not in my
10464: original charter): A field defined with @code{inst-var} (or
10465: @code{inst-value}) is visible only in the class where it is defined and in
10466: the descendent classes of this class. Using such fields only makes
10467: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10468:
1.78 anton 10469: This scoping mechanism allows us to use the unadorned field name,
10470: because name clashes with unrelated words become much less likely.
1.6 pazsan 10471:
1.78 anton 10472: @cindex @code{protected} discussion
10473: @cindex @code{private} discussion
10474: Once we have this mechanism, we can also use it for controlling the
10475: visibility of other words: All words defined after
10476: @code{protected} are visible only in the current class and its
10477: descendents. @code{public} restores the compilation
10478: (i.e. @code{current}) word list that was in effect before. If you
10479: have several @code{protected}s without an intervening
10480: @code{public} or @code{set-current}, @code{public}
10481: will restore the compilation word list in effect before the first of
10482: these @code{protected}s.
1.6 pazsan 10483:
1.78 anton 10484: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10485: @subsubsection Dividing classes
10486: @cindex Dividing classes
10487: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10488:
1.78 anton 10489: You may want to do the definition of methods separate from the
10490: definition of the class, its selectors, fields, and instance variables,
10491: i.e., separate the implementation from the definition. You can do this
10492: in the following way:
1.6 pazsan 10493:
1.78 anton 10494: @example
10495: graphical class
10496: inst-value radius
10497: end-class circle
1.6 pazsan 10498:
1.78 anton 10499: ... \ do some other stuff
1.6 pazsan 10500:
1.78 anton 10501: circle methods \ now we are ready
1.44 crook 10502:
1.78 anton 10503: m: ( x y circle -- )
10504: radius draw-circle ;m
10505: overrides draw
1.6 pazsan 10506:
1.78 anton 10507: m: ( n-radius circle -- )
10508: [to-inst] radius ;m
10509: overrides construct
1.44 crook 10510:
1.78 anton 10511: end-methods
10512: @end example
1.7 pazsan 10513:
1.78 anton 10514: You can use several @code{methods}...@code{end-methods} sections. The
10515: only things you can do to the class in these sections are: defining
10516: methods, and overriding the class's selectors. You must not define new
10517: selectors or fields.
1.7 pazsan 10518:
1.78 anton 10519: Note that you often have to override a selector before using it. In
10520: particular, you usually have to override @code{construct} with a new
10521: method before you can invoke @code{heap-new} and friends. E.g., you
10522: must not create a circle before the @code{overrides construct} sequence
10523: in the example above.
1.7 pazsan 10524:
1.78 anton 10525: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10526: @subsubsection Object Interfaces
10527: @cindex object interfaces
10528: @cindex interfaces for objects
1.7 pazsan 10529:
1.78 anton 10530: In this model you can only call selectors defined in the class of the
10531: receiving objects or in one of its ancestors. If you call a selector
10532: with a receiving object that is not in one of these classes, the
10533: result is undefined; if you are lucky, the program crashes
10534: immediately.
1.7 pazsan 10535:
1.78 anton 10536: @cindex selectors common to hardly-related classes
10537: Now consider the case when you want to have a selector (or several)
10538: available in two classes: You would have to add the selector to a
10539: common ancestor class, in the worst case to @code{object}. You
10540: may not want to do this, e.g., because someone else is responsible for
10541: this ancestor class.
1.7 pazsan 10542:
1.78 anton 10543: The solution for this problem is interfaces. An interface is a
10544: collection of selectors. If a class implements an interface, the
10545: selectors become available to the class and its descendents. A class
10546: can implement an unlimited number of interfaces. For the problem
10547: discussed above, we would define an interface for the selector(s), and
10548: both classes would implement the interface.
1.7 pazsan 10549:
1.78 anton 10550: As an example, consider an interface @code{storage} for
10551: writing objects to disk and getting them back, and a class
10552: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10553:
1.78 anton 10554: @cindex @code{interface} usage
10555: @cindex @code{end-interface} usage
10556: @cindex @code{implementation} usage
10557: @example
10558: interface
10559: selector write ( file object -- )
10560: selector read1 ( file object -- )
10561: end-interface storage
1.13 pazsan 10562:
1.78 anton 10563: bar class
10564: storage implementation
1.13 pazsan 10565:
1.78 anton 10566: ... overrides write
10567: ... overrides read1
10568: ...
10569: end-class foo
10570: @end example
1.13 pazsan 10571:
1.78 anton 10572: @noindent
10573: (I would add a word @code{read} @i{( file -- object )} that uses
10574: @code{read1} internally, but that's beyond the point illustrated
10575: here.)
1.13 pazsan 10576:
1.78 anton 10577: Note that you cannot use @code{protected} in an interface; and
10578: of course you cannot define fields.
1.13 pazsan 10579:
1.78 anton 10580: In the Neon model, all selectors are available for all classes;
10581: therefore it does not need interfaces. The price you pay in this model
10582: is slower late binding, and therefore, added complexity to avoid late
10583: binding.
1.13 pazsan 10584:
1.78 anton 10585: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10586: @subsubsection @file{objects.fs} Implementation
10587: @cindex @file{objects.fs} implementation
1.13 pazsan 10588:
1.78 anton 10589: @cindex @code{object-map} discussion
10590: An object is a piece of memory, like one of the data structures
10591: described with @code{struct...end-struct}. It has a field
10592: @code{object-map} that points to the method map for the object's
10593: class.
1.13 pazsan 10594:
1.78 anton 10595: @cindex method map
10596: @cindex virtual function table
10597: The @emph{method map}@footnote{This is Self terminology; in C++
10598: terminology: virtual function table.} is an array that contains the
10599: execution tokens (@i{xt}s) of the methods for the object's class. Each
10600: selector contains an offset into a method map.
1.13 pazsan 10601:
1.78 anton 10602: @cindex @code{selector} implementation, class
10603: @code{selector} is a defining word that uses
10604: @code{CREATE} and @code{DOES>}. The body of the
10605: selector contains the offset; the @code{DOES>} action for a
10606: class selector is, basically:
1.8 pazsan 10607:
10608: @example
1.78 anton 10609: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10610: @end example
10611:
1.78 anton 10612: Since @code{object-map} is the first field of the object, it
10613: does not generate any code. As you can see, calling a selector has a
10614: small, constant cost.
1.26 crook 10615:
1.78 anton 10616: @cindex @code{current-interface} discussion
10617: @cindex class implementation and representation
10618: A class is basically a @code{struct} combined with a method
10619: map. During the class definition the alignment and size of the class
10620: are passed on the stack, just as with @code{struct}s, so
10621: @code{field} can also be used for defining class
10622: fields. However, passing more items on the stack would be
10623: inconvenient, so @code{class} builds a data structure in memory,
10624: which is accessed through the variable
10625: @code{current-interface}. After its definition is complete, the
10626: class is represented on the stack by a pointer (e.g., as parameter for
10627: a child class definition).
1.26 crook 10628:
1.78 anton 10629: A new class starts off with the alignment and size of its parent,
10630: and a copy of the parent's method map. Defining new fields extends the
10631: size and alignment; likewise, defining new selectors extends the
10632: method map. @code{overrides} just stores a new @i{xt} in the method
10633: map at the offset given by the selector.
1.13 pazsan 10634:
1.78 anton 10635: @cindex class binding, implementation
10636: Class binding just gets the @i{xt} at the offset given by the selector
10637: from the class's method map and @code{compile,}s (in the case of
10638: @code{[bind]}) it.
1.13 pazsan 10639:
1.78 anton 10640: @cindex @code{this} implementation
10641: @cindex @code{catch} and @code{this}
10642: @cindex @code{this} and @code{catch}
10643: I implemented @code{this} as a @code{value}. At the
10644: start of an @code{m:...;m} method the old @code{this} is
10645: stored to the return stack and restored at the end; and the object on
10646: the TOS is stored @code{TO this}. This technique has one
10647: disadvantage: If the user does not leave the method via
10648: @code{;m}, but via @code{throw} or @code{exit},
10649: @code{this} is not restored (and @code{exit} may
10650: crash). To deal with the @code{throw} problem, I have redefined
10651: @code{catch} to save and restore @code{this}; the same
10652: should be done with any word that can catch an exception. As for
10653: @code{exit}, I simply forbid it (as a replacement, there is
10654: @code{exitm}).
1.13 pazsan 10655:
1.78 anton 10656: @cindex @code{inst-var} implementation
10657: @code{inst-var} is just the same as @code{field}, with
10658: a different @code{DOES>} action:
1.13 pazsan 10659: @example
1.78 anton 10660: @@ this +
1.8 pazsan 10661: @end example
1.78 anton 10662: Similar for @code{inst-value}.
1.8 pazsan 10663:
1.78 anton 10664: @cindex class scoping implementation
10665: Each class also has a word list that contains the words defined with
10666: @code{inst-var} and @code{inst-value}, and its protected
10667: words. It also has a pointer to its parent. @code{class} pushes
10668: the word lists of the class and all its ancestors onto the search order stack,
10669: and @code{end-class} drops them.
1.20 pazsan 10670:
1.78 anton 10671: @cindex interface implementation
10672: An interface is like a class without fields, parent and protected
10673: words; i.e., it just has a method map. If a class implements an
10674: interface, its method map contains a pointer to the method map of the
10675: interface. The positive offsets in the map are reserved for class
10676: methods, therefore interface map pointers have negative
10677: offsets. Interfaces have offsets that are unique throughout the
10678: system, unlike class selectors, whose offsets are only unique for the
10679: classes where the selector is available (invokable).
1.20 pazsan 10680:
1.78 anton 10681: This structure means that interface selectors have to perform one
10682: indirection more than class selectors to find their method. Their body
10683: contains the interface map pointer offset in the class method map, and
10684: the method offset in the interface method map. The
10685: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10686:
10687: @example
1.78 anton 10688: ( object selector-body )
10689: 2dup selector-interface @@ ( object selector-body object interface-offset )
10690: swap object-map @@ + @@ ( object selector-body map )
10691: swap selector-offset @@ + @@ execute
1.20 pazsan 10692: @end example
10693:
1.78 anton 10694: where @code{object-map} and @code{selector-offset} are
10695: first fields and generate no code.
1.20 pazsan 10696:
1.78 anton 10697: As a concrete example, consider the following code:
1.20 pazsan 10698:
10699: @example
1.78 anton 10700: interface
10701: selector if1sel1
10702: selector if1sel2
10703: end-interface if1
1.20 pazsan 10704:
1.78 anton 10705: object class
10706: if1 implementation
10707: selector cl1sel1
10708: cell% inst-var cl1iv1
1.20 pazsan 10709:
1.78 anton 10710: ' m1 overrides construct
10711: ' m2 overrides if1sel1
10712: ' m3 overrides if1sel2
10713: ' m4 overrides cl1sel2
10714: end-class cl1
1.20 pazsan 10715:
1.78 anton 10716: create obj1 object dict-new drop
10717: create obj2 cl1 dict-new drop
10718: @end example
1.20 pazsan 10719:
1.78 anton 10720: The data structure created by this code (including the data structure
10721: for @code{object}) is shown in the
10722: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10723: @comment TODO add this diagram..
1.20 pazsan 10724:
1.78 anton 10725: @node Objects Glossary, , Objects Implementation, Objects
10726: @subsubsection @file{objects.fs} Glossary
10727: @cindex @file{objects.fs} Glossary
1.20 pazsan 10728:
10729:
1.78 anton 10730: doc---objects-bind
10731: doc---objects-<bind>
10732: doc---objects-bind'
10733: doc---objects-[bind]
10734: doc---objects-class
10735: doc---objects-class->map
10736: doc---objects-class-inst-size
10737: doc---objects-class-override!
1.79 anton 10738: doc---objects-class-previous
10739: doc---objects-class>order
1.78 anton 10740: doc---objects-construct
10741: doc---objects-current'
10742: doc---objects-[current]
10743: doc---objects-current-interface
10744: doc---objects-dict-new
10745: doc---objects-end-class
10746: doc---objects-end-class-noname
10747: doc---objects-end-interface
10748: doc---objects-end-interface-noname
10749: doc---objects-end-methods
10750: doc---objects-exitm
10751: doc---objects-heap-new
10752: doc---objects-implementation
10753: doc---objects-init-object
10754: doc---objects-inst-value
10755: doc---objects-inst-var
10756: doc---objects-interface
10757: doc---objects-m:
10758: doc---objects-:m
10759: doc---objects-;m
10760: doc---objects-method
10761: doc---objects-methods
10762: doc---objects-object
10763: doc---objects-overrides
10764: doc---objects-[parent]
10765: doc---objects-print
10766: doc---objects-protected
10767: doc---objects-public
10768: doc---objects-selector
10769: doc---objects-this
10770: doc---objects-<to-inst>
10771: doc---objects-[to-inst]
10772: doc---objects-to-this
10773: doc---objects-xt-new
1.20 pazsan 10774:
10775:
1.78 anton 10776: @c -------------------------------------------------------------
10777: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10778: @subsection The @file{oof.fs} model
10779: @cindex oof
10780: @cindex object-oriented programming
1.20 pazsan 10781:
1.78 anton 10782: @cindex @file{objects.fs}
10783: @cindex @file{oof.fs}
1.20 pazsan 10784:
1.78 anton 10785: This section describes the @file{oof.fs} package.
1.20 pazsan 10786:
1.78 anton 10787: The package described in this section has been used in bigFORTH since 1991, and
10788: used for two large applications: a chromatographic system used to
10789: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10790:
1.78 anton 10791: You can find a description (in German) of @file{oof.fs} in @cite{Object
10792: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10793: 10(2), 1994.
1.20 pazsan 10794:
1.78 anton 10795: @menu
10796: * Properties of the OOF model::
10797: * Basic OOF Usage::
10798: * The OOF base class::
10799: * Class Declaration::
10800: * Class Implementation::
10801: @end menu
1.20 pazsan 10802:
1.78 anton 10803: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10804: @subsubsection Properties of the @file{oof.fs} model
10805: @cindex @file{oof.fs} properties
1.20 pazsan 10806:
1.78 anton 10807: @itemize @bullet
10808: @item
10809: This model combines object oriented programming with information
10810: hiding. It helps you writing large application, where scoping is
10811: necessary, because it provides class-oriented scoping.
1.20 pazsan 10812:
1.78 anton 10813: @item
10814: Named objects, object pointers, and object arrays can be created,
10815: selector invocation uses the ``object selector'' syntax. Selector invocation
10816: to objects and/or selectors on the stack is a bit less convenient, but
10817: possible.
1.44 crook 10818:
1.78 anton 10819: @item
10820: Selector invocation and instance variable usage of the active object is
10821: straightforward, since both make use of the active object.
1.44 crook 10822:
1.78 anton 10823: @item
10824: Late binding is efficient and easy to use.
1.20 pazsan 10825:
1.78 anton 10826: @item
10827: State-smart objects parse selectors. However, extensibility is provided
10828: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10829:
1.78 anton 10830: @item
10831: An implementation in ANS Forth is available.
1.20 pazsan 10832:
1.78 anton 10833: @end itemize
1.23 crook 10834:
10835:
1.78 anton 10836: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10837: @subsubsection Basic @file{oof.fs} Usage
10838: @cindex @file{oof.fs} usage
1.23 crook 10839:
1.78 anton 10840: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 10841:
1.78 anton 10842: You can define a class for graphical objects like this:
1.23 crook 10843:
1.78 anton 10844: @cindex @code{class} usage
10845: @cindex @code{class;} usage
10846: @cindex @code{method} usage
10847: @example
10848: object class graphical \ "object" is the parent class
1.139 pazsan 10849: method draw ( x y -- )
1.78 anton 10850: class;
10851: @end example
1.23 crook 10852:
1.78 anton 10853: This code defines a class @code{graphical} with an
10854: operation @code{draw}. We can perform the operation
10855: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 10856:
1.78 anton 10857: @example
10858: 100 100 t-rex draw
10859: @end example
1.23 crook 10860:
1.78 anton 10861: @noindent
10862: where @code{t-rex} is an object or object pointer, created with e.g.
10863: @code{graphical : t-rex}.
1.23 crook 10864:
1.78 anton 10865: @cindex abstract class
10866: How do we create a graphical object? With the present definitions,
10867: we cannot create a useful graphical object. The class
10868: @code{graphical} describes graphical objects in general, but not
10869: any concrete graphical object type (C++ users would call it an
10870: @emph{abstract class}); e.g., there is no method for the selector
10871: @code{draw} in the class @code{graphical}.
1.23 crook 10872:
1.78 anton 10873: For concrete graphical objects, we define child classes of the
10874: class @code{graphical}, e.g.:
1.23 crook 10875:
1.78 anton 10876: @example
10877: graphical class circle \ "graphical" is the parent class
10878: cell var circle-radius
10879: how:
10880: : draw ( x y -- )
10881: circle-radius @@ draw-circle ;
1.23 crook 10882:
1.139 pazsan 10883: : init ( n-radius -- )
1.78 anton 10884: circle-radius ! ;
10885: class;
10886: @end example
1.1 anton 10887:
1.78 anton 10888: Here we define a class @code{circle} as a child of @code{graphical},
10889: with a field @code{circle-radius}; it defines new methods for the
10890: selectors @code{draw} and @code{init} (@code{init} is defined in
10891: @code{object}, the parent class of @code{graphical}).
1.1 anton 10892:
1.78 anton 10893: Now we can create a circle in the dictionary with:
1.1 anton 10894:
1.78 anton 10895: @example
10896: 50 circle : my-circle
10897: @end example
1.21 crook 10898:
1.78 anton 10899: @noindent
10900: @code{:} invokes @code{init}, thus initializing the field
10901: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10902: with:
1.1 anton 10903:
1.78 anton 10904: @example
10905: 100 100 my-circle draw
10906: @end example
1.1 anton 10907:
1.78 anton 10908: @cindex selector invocation, restrictions
10909: @cindex class definition, restrictions
10910: Note: You can only invoke a selector if the receiving object belongs to
10911: the class where the selector was defined or one of its descendents;
10912: e.g., you can invoke @code{draw} only for objects belonging to
10913: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10914: mechanism will check if you try to invoke a selector that is not
10915: defined in this class hierarchy, so you'll get an error at compilation
10916: time.
1.1 anton 10917:
10918:
1.78 anton 10919: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10920: @subsubsection The @file{oof.fs} base class
10921: @cindex @file{oof.fs} base class
1.1 anton 10922:
1.78 anton 10923: When you define a class, you have to specify a parent class. So how do
10924: you start defining classes? There is one class available from the start:
10925: @code{object}. You have to use it as ancestor for all classes. It is the
10926: only class that has no parent. Classes are also objects, except that
10927: they don't have instance variables; class manipulation such as
10928: inheritance or changing definitions of a class is handled through
10929: selectors of the class @code{object}.
1.1 anton 10930:
1.78 anton 10931: @code{object} provides a number of selectors:
1.1 anton 10932:
1.78 anton 10933: @itemize @bullet
10934: @item
10935: @code{class} for subclassing, @code{definitions} to add definitions
10936: later on, and @code{class?} to get type informations (is the class a
10937: subclass of the class passed on the stack?).
1.1 anton 10938:
1.78 anton 10939: doc---object-class
10940: doc---object-definitions
10941: doc---object-class?
1.1 anton 10942:
10943:
1.26 crook 10944: @item
1.78 anton 10945: @code{init} and @code{dispose} as constructor and destructor of the
10946: object. @code{init} is invocated after the object's memory is allocated,
10947: while @code{dispose} also handles deallocation. Thus if you redefine
10948: @code{dispose}, you have to call the parent's dispose with @code{super
10949: dispose}, too.
10950:
10951: doc---object-init
10952: doc---object-dispose
10953:
1.1 anton 10954:
1.26 crook 10955: @item
1.78 anton 10956: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10957: @code{[]} to create named and unnamed objects and object arrays or
10958: object pointers.
10959:
10960: doc---object-new
10961: doc---object-new[]
10962: doc---object-:
10963: doc---object-ptr
10964: doc---object-asptr
10965: doc---object-[]
10966:
1.1 anton 10967:
1.26 crook 10968: @item
1.78 anton 10969: @code{::} and @code{super} for explicit scoping. You should use explicit
10970: scoping only for super classes or classes with the same set of instance
10971: variables. Explicitly-scoped selectors use early binding.
1.21 crook 10972:
1.78 anton 10973: doc---object-::
10974: doc---object-super
1.21 crook 10975:
10976:
1.26 crook 10977: @item
1.78 anton 10978: @code{self} to get the address of the object
1.21 crook 10979:
1.78 anton 10980: doc---object-self
1.21 crook 10981:
10982:
1.78 anton 10983: @item
10984: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10985: pointers and instance defers.
1.21 crook 10986:
1.78 anton 10987: doc---object-bind
10988: doc---object-bound
10989: doc---object-link
10990: doc---object-is
1.21 crook 10991:
10992:
1.78 anton 10993: @item
10994: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10995: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 10996:
1.78 anton 10997: doc---object-'
10998: doc---object-postpone
1.21 crook 10999:
11000:
1.78 anton 11001: @item
11002: @code{with} and @code{endwith} to select the active object from the
11003: stack, and enable its scope. Using @code{with} and @code{endwith}
11004: also allows you to create code using selector @code{postpone} without being
11005: trapped by the state-smart objects.
1.21 crook 11006:
1.78 anton 11007: doc---object-with
11008: doc---object-endwith
1.21 crook 11009:
11010:
1.78 anton 11011: @end itemize
1.21 crook 11012:
1.78 anton 11013: @node Class Declaration, Class Implementation, The OOF base class, OOF
11014: @subsubsection Class Declaration
11015: @cindex class declaration
1.21 crook 11016:
1.78 anton 11017: @itemize @bullet
11018: @item
11019: Instance variables
1.21 crook 11020:
1.78 anton 11021: doc---oof-var
1.21 crook 11022:
11023:
1.78 anton 11024: @item
11025: Object pointers
1.21 crook 11026:
1.78 anton 11027: doc---oof-ptr
11028: doc---oof-asptr
1.21 crook 11029:
11030:
1.78 anton 11031: @item
11032: Instance defers
1.21 crook 11033:
1.78 anton 11034: doc---oof-defer
1.21 crook 11035:
11036:
1.78 anton 11037: @item
11038: Method selectors
1.21 crook 11039:
1.78 anton 11040: doc---oof-early
11041: doc---oof-method
1.21 crook 11042:
11043:
1.78 anton 11044: @item
11045: Class-wide variables
1.21 crook 11046:
1.78 anton 11047: doc---oof-static
1.21 crook 11048:
11049:
1.78 anton 11050: @item
11051: End declaration
1.1 anton 11052:
1.78 anton 11053: doc---oof-how:
11054: doc---oof-class;
1.21 crook 11055:
11056:
1.78 anton 11057: @end itemize
1.21 crook 11058:
1.78 anton 11059: @c -------------------------------------------------------------
11060: @node Class Implementation, , Class Declaration, OOF
11061: @subsubsection Class Implementation
11062: @cindex class implementation
1.21 crook 11063:
1.78 anton 11064: @c -------------------------------------------------------------
11065: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11066: @subsection The @file{mini-oof.fs} model
11067: @cindex mini-oof
1.21 crook 11068:
1.78 anton 11069: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11070: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11071: and reduces to the bare minimum of features. This is based on a posting
11072: of Bernd Paysan in comp.lang.forth.
1.21 crook 11073:
1.78 anton 11074: @menu
11075: * Basic Mini-OOF Usage::
11076: * Mini-OOF Example::
11077: * Mini-OOF Implementation::
11078: @end menu
1.21 crook 11079:
1.78 anton 11080: @c -------------------------------------------------------------
11081: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11082: @subsubsection Basic @file{mini-oof.fs} Usage
11083: @cindex mini-oof usage
1.21 crook 11084:
1.78 anton 11085: There is a base class (@code{class}, which allocates one cell for the
11086: object pointer) plus seven other words: to define a method, a variable,
11087: a class; to end a class, to resolve binding, to allocate an object and
11088: to compile a class method.
11089: @comment TODO better description of the last one
1.26 crook 11090:
1.21 crook 11091:
1.78 anton 11092: doc-object
11093: doc-method
11094: doc-var
11095: doc-class
11096: doc-end-class
11097: doc-defines
11098: doc-new
11099: doc-::
1.21 crook 11100:
11101:
11102:
1.78 anton 11103: @c -------------------------------------------------------------
11104: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11105: @subsubsection Mini-OOF Example
11106: @cindex mini-oof example
1.1 anton 11107:
1.78 anton 11108: A short example shows how to use this package. This example, in slightly
11109: extended form, is supplied as @file{moof-exm.fs}
11110: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11111:
1.26 crook 11112: @example
1.78 anton 11113: object class
11114: method init
11115: method draw
11116: end-class graphical
1.26 crook 11117: @end example
1.20 pazsan 11118:
1.78 anton 11119: This code defines a class @code{graphical} with an
11120: operation @code{draw}. We can perform the operation
11121: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11122:
1.26 crook 11123: @example
1.78 anton 11124: 100 100 t-rex draw
1.26 crook 11125: @end example
1.12 anton 11126:
1.78 anton 11127: where @code{t-rex} is an object or object pointer, created with e.g.
11128: @code{graphical new Constant t-rex}.
1.12 anton 11129:
1.78 anton 11130: For concrete graphical objects, we define child classes of the
11131: class @code{graphical}, e.g.:
1.12 anton 11132:
1.26 crook 11133: @example
11134: graphical class
1.78 anton 11135: cell var circle-radius
11136: end-class circle \ "graphical" is the parent class
1.12 anton 11137:
1.78 anton 11138: :noname ( x y -- )
11139: circle-radius @@ draw-circle ; circle defines draw
11140: :noname ( r -- )
11141: circle-radius ! ; circle defines init
11142: @end example
1.12 anton 11143:
1.78 anton 11144: There is no implicit init method, so we have to define one. The creation
11145: code of the object now has to call init explicitely.
1.21 crook 11146:
1.78 anton 11147: @example
11148: circle new Constant my-circle
11149: 50 my-circle init
1.12 anton 11150: @end example
11151:
1.78 anton 11152: It is also possible to add a function to create named objects with
11153: automatic call of @code{init}, given that all objects have @code{init}
11154: on the same place:
1.38 anton 11155:
1.78 anton 11156: @example
11157: : new: ( .. o "name" -- )
11158: new dup Constant init ;
11159: 80 circle new: large-circle
11160: @end example
1.12 anton 11161:
1.78 anton 11162: We can draw this new circle at (100,100) with:
1.12 anton 11163:
1.78 anton 11164: @example
11165: 100 100 my-circle draw
11166: @end example
1.12 anton 11167:
1.78 anton 11168: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11169: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11170:
1.78 anton 11171: Object-oriented systems with late binding typically use a
11172: ``vtable''-approach: the first variable in each object is a pointer to a
11173: table, which contains the methods as function pointers. The vtable
11174: may also contain other information.
1.12 anton 11175:
1.79 anton 11176: So first, let's declare selectors:
1.37 anton 11177:
11178: @example
1.79 anton 11179: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11180: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11181: @end example
1.37 anton 11182:
1.79 anton 11183: During selector declaration, the number of selectors and instance
11184: variables is on the stack (in address units). @code{method} creates one
11185: selector and increments the selector number. To execute a selector, it
1.78 anton 11186: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11187: executes the method @i{xt} stored there. Each selector takes the object
11188: it is invoked with as top of stack parameter; it passes the parameters
11189: (including the object) unchanged to the appropriate method which should
1.78 anton 11190: consume that object.
1.37 anton 11191:
1.78 anton 11192: Now, we also have to declare instance variables
1.37 anton 11193:
1.78 anton 11194: @example
1.79 anton 11195: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11196: DOES> ( o -- addr ) @@ + ;
1.37 anton 11197: @end example
11198:
1.78 anton 11199: As before, a word is created with the current offset. Instance
11200: variables can have different sizes (cells, floats, doubles, chars), so
11201: all we do is take the size and add it to the offset. If your machine
11202: has alignment restrictions, put the proper @code{aligned} or
11203: @code{faligned} before the variable, to adjust the variable
11204: offset. That's why it is on the top of stack.
1.37 anton 11205:
1.78 anton 11206: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11207:
1.78 anton 11208: @example
11209: Create object 1 cells , 2 cells ,
1.79 anton 11210: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11211: @end example
1.12 anton 11212:
1.78 anton 11213: For inheritance, the vtable of the parent object has to be
11214: copied when a new, derived class is declared. This gives all the
11215: methods of the parent class, which can be overridden, though.
1.12 anton 11216:
1.78 anton 11217: @example
1.79 anton 11218: : end-class ( class selectors vars "name" -- )
1.78 anton 11219: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11220: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11221: @end example
1.12 anton 11222:
1.78 anton 11223: The first line creates the vtable, initialized with
11224: @code{noop}s. The second line is the inheritance mechanism, it
11225: copies the xts from the parent vtable.
1.12 anton 11226:
1.78 anton 11227: We still have no way to define new methods, let's do that now:
1.12 anton 11228:
1.26 crook 11229: @example
1.79 anton 11230: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11231: @end example
1.12 anton 11232:
1.78 anton 11233: To allocate a new object, we need a word, too:
1.12 anton 11234:
1.78 anton 11235: @example
11236: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11237: @end example
11238:
1.78 anton 11239: Sometimes derived classes want to access the method of the
11240: parent object. There are two ways to achieve this with Mini-OOF:
11241: first, you could use named words, and second, you could look up the
11242: vtable of the parent object.
1.12 anton 11243:
1.78 anton 11244: @example
11245: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11246: @end example
1.12 anton 11247:
11248:
1.78 anton 11249: Nothing can be more confusing than a good example, so here is
11250: one. First let's declare a text object (called
11251: @code{button}), that stores text and position:
1.12 anton 11252:
1.78 anton 11253: @example
11254: object class
11255: cell var text
11256: cell var len
11257: cell var x
11258: cell var y
11259: method init
11260: method draw
11261: end-class button
11262: @end example
1.12 anton 11263:
1.78 anton 11264: @noindent
11265: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11266:
1.26 crook 11267: @example
1.78 anton 11268: :noname ( o -- )
11269: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11270: button defines draw
11271: :noname ( addr u o -- )
11272: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11273: button defines init
1.26 crook 11274: @end example
1.12 anton 11275:
1.78 anton 11276: @noindent
11277: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11278: new data and no new selectors:
1.78 anton 11279:
11280: @example
11281: button class
11282: end-class bold-button
1.12 anton 11283:
1.78 anton 11284: : bold 27 emit ." [1m" ;
11285: : normal 27 emit ." [0m" ;
11286: @end example
1.1 anton 11287:
1.78 anton 11288: @noindent
11289: The class @code{bold-button} has a different draw method to
11290: @code{button}, but the new method is defined in terms of the draw method
11291: for @code{button}:
1.20 pazsan 11292:
1.78 anton 11293: @example
11294: :noname bold [ button :: draw ] normal ; bold-button defines draw
11295: @end example
1.21 crook 11296:
1.78 anton 11297: @noindent
1.79 anton 11298: Finally, create two objects and apply selectors:
1.21 crook 11299:
1.26 crook 11300: @example
1.78 anton 11301: button new Constant foo
11302: s" thin foo" foo init
11303: page
11304: foo draw
11305: bold-button new Constant bar
11306: s" fat bar" bar init
11307: 1 bar y !
11308: bar draw
1.26 crook 11309: @end example
1.21 crook 11310:
11311:
1.78 anton 11312: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11313: @subsection Comparison with other object models
11314: @cindex comparison of object models
11315: @cindex object models, comparison
11316:
11317: Many object-oriented Forth extensions have been proposed (@cite{A survey
11318: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11319: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11320: relation of the object models described here to two well-known and two
11321: closely-related (by the use of method maps) models. Andras Zsoter
11322: helped us with this section.
11323:
11324: @cindex Neon model
11325: The most popular model currently seems to be the Neon model (see
11326: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11327: 1997) by Andrew McKewan) but this model has a number of limitations
11328: @footnote{A longer version of this critique can be
11329: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11330: Dimensions, May 1997) by Anton Ertl.}:
11331:
11332: @itemize @bullet
11333: @item
11334: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11335: to pass objects on the stack.
1.21 crook 11336:
1.78 anton 11337: @item
11338: It requires that the selector parses the input stream (at
1.79 anton 11339: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11340: hard to find.
1.21 crook 11341:
1.78 anton 11342: @item
1.79 anton 11343: It allows using every selector on every object; this eliminates the
11344: need for interfaces, but makes it harder to create efficient
11345: implementations.
1.78 anton 11346: @end itemize
1.21 crook 11347:
1.78 anton 11348: @cindex Pountain's object-oriented model
11349: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11350: Press, London, 1987) by Dick Pountain. However, it is not really about
11351: object-oriented programming, because it hardly deals with late
11352: binding. Instead, it focuses on features like information hiding and
11353: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11354:
1.78 anton 11355: @cindex Zsoter's object-oriented model
1.79 anton 11356: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11357: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11358: describes a model that makes heavy use of an active object (like
11359: @code{this} in @file{objects.fs}): The active object is not only used
11360: for accessing all fields, but also specifies the receiving object of
11361: every selector invocation; you have to change the active object
11362: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11363: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11364: the method entry point is unnecessary with Zsoter's model, because the
11365: receiving object is the active object already. On the other hand, the
11366: explicit change is absolutely necessary in that model, because otherwise
11367: no one could ever change the active object. An ANS Forth implementation
11368: of this model is available through
11369: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11370:
1.78 anton 11371: @cindex @file{oof.fs}, differences to other models
11372: The @file{oof.fs} model combines information hiding and overloading
11373: resolution (by keeping names in various word lists) with object-oriented
11374: programming. It sets the active object implicitly on method entry, but
11375: also allows explicit changing (with @code{>o...o>} or with
11376: @code{with...endwith}). It uses parsing and state-smart objects and
11377: classes for resolving overloading and for early binding: the object or
11378: class parses the selector and determines the method from this. If the
11379: selector is not parsed by an object or class, it performs a call to the
11380: selector for the active object (late binding), like Zsoter's model.
11381: Fields are always accessed through the active object. The big
11382: disadvantage of this model is the parsing and the state-smartness, which
11383: reduces extensibility and increases the opportunities for subtle bugs;
11384: essentially, you are only safe if you never tick or @code{postpone} an
11385: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11386:
1.78 anton 11387: @cindex @file{mini-oof.fs}, differences to other models
11388: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11389: version of the @file{objects.fs} model, but syntactically it is a
11390: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11391:
11392:
1.78 anton 11393: @c -------------------------------------------------------------
11394: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11395: @section Programming Tools
11396: @cindex programming tools
1.21 crook 11397:
1.78 anton 11398: @c !! move this and assembler down below OO stuff.
1.21 crook 11399:
1.78 anton 11400: @menu
11401: * Examining::
11402: * Forgetting words::
11403: * Debugging:: Simple and quick.
11404: * Assertions:: Making your programs self-checking.
11405: * Singlestep Debugger:: Executing your program word by word.
11406: @end menu
1.21 crook 11407:
1.78 anton 11408: @node Examining, Forgetting words, Programming Tools, Programming Tools
11409: @subsection Examining data and code
11410: @cindex examining data and code
11411: @cindex data examination
11412: @cindex code examination
1.44 crook 11413:
1.78 anton 11414: The following words inspect the stack non-destructively:
1.21 crook 11415:
1.78 anton 11416: doc-.s
11417: doc-f.s
1.44 crook 11418:
1.78 anton 11419: There is a word @code{.r} but it does @i{not} display the return stack!
11420: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11421:
1.78 anton 11422: doc-depth
11423: doc-fdepth
11424: doc-clearstack
1.124 anton 11425: doc-clearstacks
1.21 crook 11426:
1.78 anton 11427: The following words inspect memory.
1.21 crook 11428:
1.78 anton 11429: doc-?
11430: doc-dump
1.21 crook 11431:
1.78 anton 11432: And finally, @code{see} allows to inspect code:
1.21 crook 11433:
1.78 anton 11434: doc-see
11435: doc-xt-see
1.111 anton 11436: doc-simple-see
11437: doc-simple-see-range
1.21 crook 11438:
1.78 anton 11439: @node Forgetting words, Debugging, Examining, Programming Tools
11440: @subsection Forgetting words
11441: @cindex words, forgetting
11442: @cindex forgeting words
1.21 crook 11443:
1.78 anton 11444: @c anton: other, maybe better places for this subsection: Defining Words;
11445: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11446:
1.78 anton 11447: Forth allows you to forget words (and everything that was alloted in the
11448: dictonary after them) in a LIFO manner.
1.21 crook 11449:
1.78 anton 11450: doc-marker
1.21 crook 11451:
1.78 anton 11452: The most common use of this feature is during progam development: when
11453: you change a source file, forget all the words it defined and load it
11454: again (since you also forget everything defined after the source file
11455: was loaded, you have to reload that, too). Note that effects like
11456: storing to variables and destroyed system words are not undone when you
11457: forget words. With a system like Gforth, that is fast enough at
11458: starting up and compiling, I find it more convenient to exit and restart
11459: Gforth, as this gives me a clean slate.
1.21 crook 11460:
1.78 anton 11461: Here's an example of using @code{marker} at the start of a source file
11462: that you are debugging; it ensures that you only ever have one copy of
11463: the file's definitions compiled at any time:
1.21 crook 11464:
1.78 anton 11465: @example
11466: [IFDEF] my-code
11467: my-code
11468: [ENDIF]
1.26 crook 11469:
1.78 anton 11470: marker my-code
11471: init-included-files
1.21 crook 11472:
1.78 anton 11473: \ .. definitions start here
11474: \ .
11475: \ .
11476: \ end
11477: @end example
1.21 crook 11478:
1.26 crook 11479:
1.78 anton 11480: @node Debugging, Assertions, Forgetting words, Programming Tools
11481: @subsection Debugging
11482: @cindex debugging
1.21 crook 11483:
1.78 anton 11484: Languages with a slow edit/compile/link/test development loop tend to
11485: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11486:
1.78 anton 11487: A much better (faster) way in fast-compiling languages is to add
11488: printing code at well-selected places, let the program run, look at
11489: the output, see where things went wrong, add more printing code, etc.,
11490: until the bug is found.
1.21 crook 11491:
1.78 anton 11492: The simple debugging aids provided in @file{debugs.fs}
11493: are meant to support this style of debugging.
1.21 crook 11494:
1.78 anton 11495: The word @code{~~} prints debugging information (by default the source
11496: location and the stack contents). It is easy to insert. If you use Emacs
11497: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11498: query-replace them with nothing). The deferred words
1.101 anton 11499: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11500: @code{~~}. The default source location output format works well with
11501: Emacs' compilation mode, so you can step through the program at the
11502: source level using @kbd{C-x `} (the advantage over a stepping debugger
11503: is that you can step in any direction and you know where the crash has
11504: happened or where the strange data has occurred).
1.21 crook 11505:
1.78 anton 11506: doc-~~
11507: doc-printdebugdata
1.101 anton 11508: doc-.debugline
1.21 crook 11509:
1.106 anton 11510: @cindex filenames in @code{~~} output
11511: @code{~~} (and assertions) will usually print the wrong file name if a
11512: marker is executed in the same file after their occurance. They will
11513: print @samp{*somewhere*} as file name if a marker is executed in the
11514: same file before their occurance.
11515:
11516:
1.78 anton 11517: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11518: @subsection Assertions
11519: @cindex assertions
1.21 crook 11520:
1.78 anton 11521: It is a good idea to make your programs self-checking, especially if you
11522: make an assumption that may become invalid during maintenance (for
11523: example, that a certain field of a data structure is never zero). Gforth
11524: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11525:
11526: @example
1.78 anton 11527: assert( @i{flag} )
1.26 crook 11528: @end example
11529:
1.78 anton 11530: The code between @code{assert(} and @code{)} should compute a flag, that
11531: should be true if everything is alright and false otherwise. It should
11532: not change anything else on the stack. The overall stack effect of the
11533: assertion is @code{( -- )}. E.g.
1.21 crook 11534:
1.26 crook 11535: @example
1.78 anton 11536: assert( 1 1 + 2 = ) \ what we learn in school
11537: assert( dup 0<> ) \ assert that the top of stack is not zero
11538: assert( false ) \ this code should not be reached
1.21 crook 11539: @end example
11540:
1.78 anton 11541: The need for assertions is different at different times. During
11542: debugging, we want more checking, in production we sometimes care more
11543: for speed. Therefore, assertions can be turned off, i.e., the assertion
11544: becomes a comment. Depending on the importance of an assertion and the
11545: time it takes to check it, you may want to turn off some assertions and
11546: keep others turned on. Gforth provides several levels of assertions for
11547: this purpose:
11548:
11549:
11550: doc-assert0(
11551: doc-assert1(
11552: doc-assert2(
11553: doc-assert3(
11554: doc-assert(
11555: doc-)
1.21 crook 11556:
11557:
1.78 anton 11558: The variable @code{assert-level} specifies the highest assertions that
11559: are turned on. I.e., at the default @code{assert-level} of one,
11560: @code{assert0(} and @code{assert1(} assertions perform checking, while
11561: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11562:
1.78 anton 11563: The value of @code{assert-level} is evaluated at compile-time, not at
11564: run-time. Therefore you cannot turn assertions on or off at run-time;
11565: you have to set the @code{assert-level} appropriately before compiling a
11566: piece of code. You can compile different pieces of code at different
11567: @code{assert-level}s (e.g., a trusted library at level 1 and
11568: newly-written code at level 3).
1.26 crook 11569:
11570:
1.78 anton 11571: doc-assert-level
1.26 crook 11572:
11573:
1.78 anton 11574: If an assertion fails, a message compatible with Emacs' compilation mode
11575: is produced and the execution is aborted (currently with @code{ABORT"}.
11576: If there is interest, we will introduce a special throw code. But if you
11577: intend to @code{catch} a specific condition, using @code{throw} is
11578: probably more appropriate than an assertion).
1.106 anton 11579:
11580: @cindex filenames in assertion output
11581: Assertions (and @code{~~}) will usually print the wrong file name if a
11582: marker is executed in the same file after their occurance. They will
11583: print @samp{*somewhere*} as file name if a marker is executed in the
11584: same file before their occurance.
1.44 crook 11585:
1.78 anton 11586: Definitions in ANS Forth for these assertion words are provided
11587: in @file{compat/assert.fs}.
1.26 crook 11588:
1.44 crook 11589:
1.78 anton 11590: @node Singlestep Debugger, , Assertions, Programming Tools
11591: @subsection Singlestep Debugger
11592: @cindex singlestep Debugger
11593: @cindex debugging Singlestep
1.44 crook 11594:
1.112 anton 11595: The singlestep debugger does not work in this release.
11596:
1.78 anton 11597: When you create a new word there's often the need to check whether it
11598: behaves correctly or not. You can do this by typing @code{dbg
11599: badword}. A debug session might look like this:
1.26 crook 11600:
1.78 anton 11601: @example
11602: : badword 0 DO i . LOOP ; ok
11603: 2 dbg badword
11604: : badword
11605: Scanning code...
1.44 crook 11606:
1.78 anton 11607: Nesting debugger ready!
1.44 crook 11608:
1.78 anton 11609: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11610: 400D4740 8049F68 DO -> [ 0 ]
11611: 400D4744 804A0C8 i -> [ 1 ] 00000
11612: 400D4748 400C5E60 . -> 0 [ 0 ]
11613: 400D474C 8049D0C LOOP -> [ 0 ]
11614: 400D4744 804A0C8 i -> [ 1 ] 00001
11615: 400D4748 400C5E60 . -> 1 [ 0 ]
11616: 400D474C 8049D0C LOOP -> [ 0 ]
11617: 400D4758 804B384 ; -> ok
11618: @end example
1.21 crook 11619:
1.78 anton 11620: Each line displayed is one step. You always have to hit return to
11621: execute the next word that is displayed. If you don't want to execute
11622: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11623: an overview what keys are available:
1.44 crook 11624:
1.78 anton 11625: @table @i
1.44 crook 11626:
1.78 anton 11627: @item @key{RET}
11628: Next; Execute the next word.
1.21 crook 11629:
1.78 anton 11630: @item n
11631: Nest; Single step through next word.
1.44 crook 11632:
1.78 anton 11633: @item u
11634: Unnest; Stop debugging and execute rest of word. If we got to this word
11635: with nest, continue debugging with the calling word.
1.44 crook 11636:
1.78 anton 11637: @item d
11638: Done; Stop debugging and execute rest.
1.21 crook 11639:
1.78 anton 11640: @item s
11641: Stop; Abort immediately.
1.44 crook 11642:
1.78 anton 11643: @end table
1.44 crook 11644:
1.78 anton 11645: Debugging large application with this mechanism is very difficult, because
11646: you have to nest very deeply into the program before the interesting part
11647: begins. This takes a lot of time.
1.26 crook 11648:
1.78 anton 11649: To do it more directly put a @code{BREAK:} command into your source code.
11650: When program execution reaches @code{BREAK:} the single step debugger is
11651: invoked and you have all the features described above.
1.44 crook 11652:
1.78 anton 11653: If you have more than one part to debug it is useful to know where the
11654: program has stopped at the moment. You can do this by the
11655: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11656: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11657:
1.26 crook 11658:
1.78 anton 11659: doc-dbg
11660: doc-break:
11661: doc-break"
1.44 crook 11662:
11663:
1.26 crook 11664:
1.78 anton 11665: @c -------------------------------------------------------------
11666: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11667: @section Assembler and Code Words
11668: @cindex assembler
11669: @cindex code words
1.44 crook 11670:
1.78 anton 11671: @menu
11672: * Code and ;code::
11673: * Common Assembler:: Assembler Syntax
11674: * Common Disassembler::
11675: * 386 Assembler:: Deviations and special cases
11676: * Alpha Assembler:: Deviations and special cases
11677: * MIPS assembler:: Deviations and special cases
11678: * Other assemblers:: How to write them
11679: @end menu
1.21 crook 11680:
1.78 anton 11681: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11682: @subsection @code{Code} and @code{;code}
1.26 crook 11683:
1.78 anton 11684: Gforth provides some words for defining primitives (words written in
11685: machine code), and for defining the machine-code equivalent of
11686: @code{DOES>}-based defining words. However, the machine-independent
11687: nature of Gforth poses a few problems: First of all, Gforth runs on
11688: several architectures, so it can provide no standard assembler. What's
11689: worse is that the register allocation not only depends on the processor,
11690: but also on the @code{gcc} version and options used.
1.44 crook 11691:
1.78 anton 11692: The words that Gforth offers encapsulate some system dependences (e.g.,
11693: the header structure), so a system-independent assembler may be used in
11694: Gforth. If you do not have an assembler, you can compile machine code
11695: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11696: because these words emit stuff in @i{data} space; it works because
11697: Gforth has unified code/data spaces. Assembler isn't likely to be
11698: portable anyway.}.
1.21 crook 11699:
1.44 crook 11700:
1.78 anton 11701: doc-assembler
11702: doc-init-asm
11703: doc-code
11704: doc-end-code
11705: doc-;code
11706: doc-flush-icache
1.44 crook 11707:
1.21 crook 11708:
1.78 anton 11709: If @code{flush-icache} does not work correctly, @code{code} words
11710: etc. will not work (reliably), either.
1.44 crook 11711:
1.78 anton 11712: The typical usage of these @code{code} words can be shown most easily by
11713: analogy to the equivalent high-level defining words:
1.44 crook 11714:
1.78 anton 11715: @example
11716: : foo code foo
11717: <high-level Forth words> <assembler>
11718: ; end-code
11719:
11720: : bar : bar
11721: <high-level Forth words> <high-level Forth words>
11722: CREATE CREATE
11723: <high-level Forth words> <high-level Forth words>
11724: DOES> ;code
11725: <high-level Forth words> <assembler>
11726: ; end-code
11727: @end example
1.21 crook 11728:
1.78 anton 11729: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 11730:
1.78 anton 11731: @cindex registers of the inner interpreter
11732: In the assembly code you will want to refer to the inner interpreter's
11733: registers (e.g., the data stack pointer) and you may want to use other
11734: registers for temporary storage. Unfortunately, the register allocation
11735: is installation-dependent.
1.44 crook 11736:
1.78 anton 11737: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 11738: (return stack pointer) may be in different places in @code{gforth} and
11739: @code{gforth-fast}, or different installations. This means that you
11740: cannot write a @code{NEXT} routine that works reliably on both versions
11741: or different installations; so for doing @code{NEXT}, I recommend
11742: jumping to @code{' noop >code-address}, which contains nothing but a
11743: @code{NEXT}.
1.21 crook 11744:
1.78 anton 11745: For general accesses to the inner interpreter's registers, the easiest
11746: solution is to use explicit register declarations (@pxref{Explicit Reg
11747: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11748: all of the inner interpreter's registers: You have to compile Gforth
11749: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11750: the appropriate declarations must be present in the @code{machine.h}
11751: file (see @code{mips.h} for an example; you can find a full list of all
11752: declarable register symbols with @code{grep register engine.c}). If you
11753: give explicit registers to all variables that are declared at the
11754: beginning of @code{engine()}, you should be able to use the other
11755: caller-saved registers for temporary storage. Alternatively, you can use
11756: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11757: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11758: reserve a register (however, this restriction on register allocation may
11759: slow Gforth significantly).
1.44 crook 11760:
1.78 anton 11761: If this solution is not viable (e.g., because @code{gcc} does not allow
11762: you to explicitly declare all the registers you need), you have to find
11763: out by looking at the code where the inner interpreter's registers
11764: reside and which registers can be used for temporary storage. You can
11765: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 11766:
1.78 anton 11767: In any case, it is good practice to abstract your assembly code from the
11768: actual register allocation. E.g., if the data stack pointer resides in
11769: register @code{$17}, create an alias for this register called @code{sp},
11770: and use that in your assembly code.
1.21 crook 11771:
1.78 anton 11772: @cindex code words, portable
11773: Another option for implementing normal and defining words efficiently
11774: is to add the desired functionality to the source of Gforth. For normal
11775: words you just have to edit @file{primitives} (@pxref{Automatic
11776: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11777: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11778: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 11779:
1.78 anton 11780: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11781: @subsection Common Assembler
1.44 crook 11782:
1.78 anton 11783: The assemblers in Gforth generally use a postfix syntax, i.e., the
11784: instruction name follows the operands.
1.21 crook 11785:
1.78 anton 11786: The operands are passed in the usual order (the same that is used in the
11787: manual of the architecture). Since they all are Forth words, they have
11788: to be separated by spaces; you can also use Forth words to compute the
11789: operands.
1.44 crook 11790:
1.78 anton 11791: The instruction names usually end with a @code{,}. This makes it easier
11792: to visually separate instructions if you put several of them on one
11793: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 11794:
1.78 anton 11795: Registers are usually specified by number; e.g., (decimal) @code{11}
11796: specifies registers R11 and F11 on the Alpha architecture (which one,
11797: depends on the instruction). The usual names are also available, e.g.,
11798: @code{s2} for R11 on Alpha.
1.21 crook 11799:
1.78 anton 11800: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11801: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11802: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11803: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
11804: conditions are specified in a way specific to each assembler.
1.1 anton 11805:
1.78 anton 11806: Note that the register assignments of the Gforth engine can change
11807: between Gforth versions, or even between different compilations of the
11808: same Gforth version (e.g., if you use a different GCC version). So if
11809: you want to refer to Gforth's registers (e.g., the stack pointer or
11810: TOS), I recommend defining your own words for refering to these
11811: registers, and using them later on; then you can easily adapt to a
11812: changed register assignment. The stability of the register assignment
11813: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 11814:
1.100 anton 11815: The most common use of these registers is to dispatch to the next word
11816: (the @code{next} routine). A portable way to do this is to jump to
11817: @code{' noop >code-address} (of course, this is less efficient than
11818: integrating the @code{next} code and scheduling it well).
1.1 anton 11819:
1.96 anton 11820: Another difference between Gforth version is that the top of stack is
11821: kept in memory in @code{gforth} and, on most platforms, in a register in
11822: @code{gforth-fast}.
11823:
1.78 anton 11824: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11825: @subsection Common Disassembler
1.127 anton 11826: @cindex disassembler, general
11827: @cindex gdb disassembler
1.1 anton 11828:
1.78 anton 11829: You can disassemble a @code{code} word with @code{see}
11830: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 11831:
1.127 anton 11832: doc-discode
1.44 crook 11833:
1.127 anton 11834: There are two kinds of disassembler for Gforth: The Forth disassembler
11835: (available on some CPUs) and the gdb disassembler (available on
11836: platforms with @command{gdb} and @command{mktemp}). If both are
11837: available, the Forth disassembler is used by default. If you prefer
11838: the gdb disassembler, say
11839:
11840: @example
11841: ' disasm-gdb is discode
11842: @end example
11843:
11844: If neither is available, @code{discode} performs @code{dump}.
11845:
11846: The Forth disassembler generally produces output that can be fed into the
1.78 anton 11847: assembler (i.e., same syntax, etc.). It also includes additional
11848: information in comments. In particular, the address of the instruction
11849: is given in a comment before the instruction.
1.1 anton 11850:
1.127 anton 11851: The gdb disassembler produces output in the same format as the gdb
11852: @code{disassemble} command (@pxref{Machine Code,,Source and machine
11853: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
11854: the 386 and AMD64 architectures).
11855:
1.78 anton 11856: @code{See} may display more or less than the actual code of the word,
11857: because the recognition of the end of the code is unreliable. You can
1.127 anton 11858: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 11859: the code word is not immediately followed by a named word. If you have
1.116 anton 11860: something else there, you can follow the word with @code{align latest ,}
1.78 anton 11861: to ensure that the end is recognized.
1.21 crook 11862:
1.78 anton 11863: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11864: @subsection 386 Assembler
1.44 crook 11865:
1.78 anton 11866: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11867: available under GPL, and originally part of bigFORTH.
1.21 crook 11868:
1.78 anton 11869: The 386 disassembler included in Gforth was written by Andrew McKewan
11870: and is in the public domain.
1.21 crook 11871:
1.91 anton 11872: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 11873:
1.78 anton 11874: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 11875:
1.78 anton 11876: The assembler includes all instruction of the Athlon, i.e. 486 core
11877: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11878: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11879: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 11880:
1.78 anton 11881: There are several prefixes to switch between different operation sizes,
11882: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11883: double-word accesses. Addressing modes can be switched with @code{.wa}
11884: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11885: need a prefix for byte register names (@code{AL} et al).
1.1 anton 11886:
1.78 anton 11887: For floating point operations, the prefixes are @code{.fs} (IEEE
11888: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11889: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 11890:
1.78 anton 11891: The MMX opcodes don't have size prefixes, they are spelled out like in
11892: the Intel assembler. Instead of move from and to memory, there are
11893: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 11894:
1.78 anton 11895: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11896: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 11897: e.g., @code{3 #}. Here are some examples of addressing modes in various
11898: syntaxes:
1.21 crook 11899:
1.26 crook 11900: @example
1.91 anton 11901: Gforth Intel (NASM) AT&T (gas) Name
11902: .w ax ax %ax register (16 bit)
11903: ax eax %eax register (32 bit)
11904: 3 # offset 3 $3 immediate
11905: 1000 #) byte ptr 1000 1000 displacement
11906: bx ) [ebx] (%ebx) base
11907: 100 di d) 100[edi] 100(%edi) base+displacement
11908: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
11909: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
11910: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
11911: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
11912: @end example
11913:
11914: You can use @code{L)} and @code{LI)} instead of @code{D)} and
11915: @code{DI)} to enforce 32-bit displacement fields (useful for
11916: later patching).
1.21 crook 11917:
1.78 anton 11918: Some example of instructions are:
1.1 anton 11919:
11920: @example
1.78 anton 11921: ax bx mov \ move ebx,eax
11922: 3 # ax mov \ mov eax,3
1.137 pazsan 11923: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 11924: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
11925: .w ax bx mov \ mov bx,ax
1.1 anton 11926: @end example
11927:
1.78 anton 11928: The following forms are supported for binary instructions:
1.1 anton 11929:
11930: @example
1.78 anton 11931: <reg> <reg> <inst>
11932: <n> # <reg> <inst>
11933: <mem> <reg> <inst>
11934: <reg> <mem> <inst>
1.136 pazsan 11935: <n> # <mem> <inst>
1.1 anton 11936: @end example
11937:
1.136 pazsan 11938: The shift/rotate syntax is:
1.1 anton 11939:
1.26 crook 11940: @example
1.78 anton 11941: <reg/mem> 1 # shl \ shortens to shift without immediate
11942: <reg/mem> 4 # shl
11943: <reg/mem> cl shl
1.26 crook 11944: @end example
1.1 anton 11945:
1.78 anton 11946: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11947: the byte version.
1.1 anton 11948:
1.78 anton 11949: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11950: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11951: pc < >= <= >}. (Note that most of these words shadow some Forth words
11952: when @code{assembler} is in front of @code{forth} in the search path,
11953: e.g., in @code{code} words). Currently the control structure words use
11954: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11955: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 11956:
1.78 anton 11957: Here is an example of a @code{code} word (assumes that the stack pointer
11958: is in esi and the TOS is in ebx):
1.21 crook 11959:
1.26 crook 11960: @example
1.78 anton 11961: code my+ ( n1 n2 -- n )
11962: 4 si D) bx add
11963: 4 # si add
11964: Next
11965: end-code
1.26 crook 11966: @end example
1.21 crook 11967:
1.78 anton 11968: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11969: @subsection Alpha Assembler
1.21 crook 11970:
1.78 anton 11971: The Alpha assembler and disassembler were originally written by Bernd
11972: Thallner.
1.26 crook 11973:
1.78 anton 11974: The register names @code{a0}--@code{a5} are not available to avoid
11975: shadowing hex numbers.
1.2 jwilke 11976:
1.78 anton 11977: Immediate forms of arithmetic instructions are distinguished by a
11978: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11979: does not count as arithmetic instruction).
1.2 jwilke 11980:
1.78 anton 11981: You have to specify all operands to an instruction, even those that
11982: other assemblers consider optional, e.g., the destination register for
11983: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 11984:
1.78 anton 11985: You can specify conditions for @code{if,} by removing the first @code{b}
11986: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 11987:
1.26 crook 11988: @example
1.78 anton 11989: 11 fgt if, \ if F11>0e
11990: ...
11991: endif,
1.26 crook 11992: @end example
1.2 jwilke 11993:
1.78 anton 11994: @code{fbgt,} gives @code{fgt}.
11995:
11996: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11997: @subsection MIPS assembler
1.2 jwilke 11998:
1.78 anton 11999: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12000:
1.78 anton 12001: Currently the assembler and disassembler only cover the MIPS-I
12002: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12003:
1.78 anton 12004: The register names @code{$a0}--@code{$a3} are not available to avoid
12005: shadowing hex numbers.
1.2 jwilke 12006:
1.78 anton 12007: Because there is no way to distinguish registers from immediate values,
12008: you have to explicitly use the immediate forms of instructions, i.e.,
12009: @code{addiu,}, not just @code{addu,} (@command{as} does this
12010: implicitly).
1.2 jwilke 12011:
1.78 anton 12012: If the architecture manual specifies several formats for the instruction
12013: (e.g., for @code{jalr,}), you usually have to use the one with more
12014: arguments (i.e., two for @code{jalr,}). When in doubt, see
12015: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12016:
1.78 anton 12017: Branches and jumps in the MIPS architecture have a delay slot. You have
12018: to fill it yourself (the simplest way is to use @code{nop,}), the
12019: assembler does not do it for you (unlike @command{as}). Even
12020: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12021: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12022: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12023:
1.78 anton 12024: Note that you must not put branches, jumps, or @code{li,} into the delay
12025: slot: @code{li,} may expand to several instructions, and control flow
12026: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12027:
1.78 anton 12028: For branches the argument specifying the target is a relative address;
12029: You have to add the address of the delay slot to get the absolute
12030: address.
1.1 anton 12031:
1.78 anton 12032: The MIPS architecture also has load delay slots and restrictions on
12033: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12034: yourself to satisfy these restrictions, the assembler does not do it for
12035: you.
1.1 anton 12036:
1.78 anton 12037: You can specify the conditions for @code{if,} etc. by taking a
12038: conditional branch and leaving away the @code{b} at the start and the
12039: @code{,} at the end. E.g.,
1.1 anton 12040:
1.26 crook 12041: @example
1.78 anton 12042: 4 5 eq if,
12043: ... \ do something if $4 equals $5
12044: then,
1.26 crook 12045: @end example
1.1 anton 12046:
1.78 anton 12047: @node Other assemblers, , MIPS assembler, Assembler and Code Words
12048: @subsection Other assemblers
12049:
12050: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12051: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12052: an assembler already. If you are writing them from scratch, please use
12053: a similar syntax style as the one we use (i.e., postfix, commas at the
12054: end of the instruction names, @pxref{Common Assembler}); make the output
12055: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12056: similar to the style we used.
12057:
12058: Hints on implementation: The most important part is to have a good test
12059: suite that contains all instructions. Once you have that, the rest is
12060: easy. For actual coding you can take a look at
12061: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12062: the assembler and disassembler, avoiding redundancy and some potential
12063: bugs. You can also look at that file (and @pxref{Advanced does> usage
12064: example}) to get ideas how to factor a disassembler.
12065:
12066: Start with the disassembler, because it's easier to reuse data from the
12067: disassembler for the assembler than the other way round.
1.1 anton 12068:
1.78 anton 12069: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12070: how simple it can be.
1.1 anton 12071:
1.78 anton 12072: @c -------------------------------------------------------------
12073: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12074: @section Threading Words
12075: @cindex threading words
1.1 anton 12076:
1.78 anton 12077: @cindex code address
12078: These words provide access to code addresses and other threading stuff
12079: in Gforth (and, possibly, other interpretive Forths). It more or less
12080: abstracts away the differences between direct and indirect threading
12081: (and, for direct threading, the machine dependences). However, at
12082: present this wordset is still incomplete. It is also pretty low-level;
12083: some day it will hopefully be made unnecessary by an internals wordset
12084: that abstracts implementation details away completely.
1.1 anton 12085:
1.78 anton 12086: The terminology used here stems from indirect threaded Forth systems; in
12087: such a system, the XT of a word is represented by the CFA (code field
12088: address) of a word; the CFA points to a cell that contains the code
12089: address. The code address is the address of some machine code that
12090: performs the run-time action of invoking the word (e.g., the
12091: @code{dovar:} routine pushes the address of the body of the word (a
12092: variable) on the stack
12093: ).
1.1 anton 12094:
1.78 anton 12095: @cindex code address
12096: @cindex code field address
12097: In an indirect threaded Forth, you can get the code address of @i{name}
12098: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12099: >code-address}, independent of the threading method.
1.1 anton 12100:
1.78 anton 12101: doc-threading-method
12102: doc->code-address
12103: doc-code-address!
1.1 anton 12104:
1.78 anton 12105: @cindex @code{does>}-handler
12106: @cindex @code{does>}-code
12107: For a word defined with @code{DOES>}, the code address usually points to
12108: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12109: routine (in Gforth on some platforms, it can also point to the dodoes
12110: routine itself). What you are typically interested in, though, is
12111: whether a word is a @code{DOES>}-defined word, and what Forth code it
12112: executes; @code{>does-code} tells you that.
1.1 anton 12113:
1.78 anton 12114: doc->does-code
1.1 anton 12115:
1.78 anton 12116: To create a @code{DOES>}-defined word with the following basic words,
12117: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12118: @code{/does-handler} aus behind you have to place your executable Forth
12119: code. Finally you have to create a word and modify its behaviour with
12120: @code{does-handler!}.
1.1 anton 12121:
1.78 anton 12122: doc-does-code!
12123: doc-does-handler!
12124: doc-/does-handler
1.1 anton 12125:
1.78 anton 12126: The code addresses produced by various defining words are produced by
12127: the following words:
1.1 anton 12128:
1.78 anton 12129: doc-docol:
12130: doc-docon:
12131: doc-dovar:
12132: doc-douser:
12133: doc-dodefer:
12134: doc-dofield:
1.1 anton 12135:
1.99 anton 12136: @cindex definer
12137: The following two words generalize @code{>code-address},
12138: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12139:
12140: doc->definer
12141: doc-definer!
12142:
1.26 crook 12143: @c -------------------------------------------------------------
1.78 anton 12144: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12145: @section Passing Commands to the Operating System
12146: @cindex operating system - passing commands
12147: @cindex shell commands
12148:
12149: Gforth allows you to pass an arbitrary string to the host operating
12150: system shell (if such a thing exists) for execution.
12151:
12152: doc-sh
12153: doc-system
12154: doc-$?
1.23 crook 12155: doc-getenv
1.44 crook 12156:
1.26 crook 12157: @c -------------------------------------------------------------
1.47 crook 12158: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12159: @section Keeping track of Time
12160: @cindex time-related words
12161:
12162: doc-ms
12163: doc-time&date
1.79 anton 12164: doc-utime
12165: doc-cputime
1.47 crook 12166:
12167:
12168: @c -------------------------------------------------------------
12169: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12170: @section Miscellaneous Words
12171: @cindex miscellaneous words
12172:
1.29 crook 12173: @comment TODO find homes for these
12174:
1.26 crook 12175: These section lists the ANS Forth words that are not documented
1.21 crook 12176: elsewhere in this manual. Ultimately, they all need proper homes.
12177:
1.68 anton 12178: doc-quit
1.44 crook 12179:
1.26 crook 12180: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12181: (@pxref{ANS conformance}):
1.21 crook 12182:
12183: @code{EDITOR}
12184: @code{EMIT?}
12185: @code{FORGET}
12186:
1.24 anton 12187: @c ******************************************************************
12188: @node Error messages, Tools, Words, Top
12189: @chapter Error messages
12190: @cindex error messages
12191: @cindex backtrace
12192:
12193: A typical Gforth error message looks like this:
12194:
12195: @example
1.86 anton 12196: in file included from \evaluated string/:-1
1.24 anton 12197: in file included from ./yyy.fs:1
12198: ./xxx.fs:4: Invalid memory address
1.134 anton 12199: >>>bar<<<
1.79 anton 12200: Backtrace:
1.25 anton 12201: $400E664C @@
12202: $400E6664 foo
1.24 anton 12203: @end example
12204:
12205: The message identifying the error is @code{Invalid memory address}. The
12206: error happened when text-interpreting line 4 of the file
12207: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12208: word on the line where the error happened, is pointed out (with
1.134 anton 12209: @code{>>>} and @code{<<<}).
1.24 anton 12210:
12211: The file containing the error was included in line 1 of @file{./yyy.fs},
12212: and @file{yyy.fs} was included from a non-file (in this case, by giving
12213: @file{yyy.fs} as command-line parameter to Gforth).
12214:
12215: At the end of the error message you find a return stack dump that can be
12216: interpreted as a backtrace (possibly empty). On top you find the top of
12217: the return stack when the @code{throw} happened, and at the bottom you
12218: find the return stack entry just above the return stack of the topmost
12219: text interpreter.
12220:
12221: To the right of most return stack entries you see a guess for the word
12222: that pushed that return stack entry as its return address. This gives a
12223: backtrace. In our case we see that @code{bar} called @code{foo}, and
12224: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12225: address} exception).
12226:
12227: Note that the backtrace is not perfect: We don't know which return stack
12228: entries are return addresses (so we may get false positives); and in
12229: some cases (e.g., for @code{abort"}) we cannot determine from the return
12230: address the word that pushed the return address, so for some return
12231: addresses you see no names in the return stack dump.
1.25 anton 12232:
12233: @cindex @code{catch} and backtraces
12234: The return stack dump represents the return stack at the time when a
12235: specific @code{throw} was executed. In programs that make use of
12236: @code{catch}, it is not necessarily clear which @code{throw} should be
12237: used for the return stack dump (e.g., consider one @code{throw} that
12238: indicates an error, which is caught, and during recovery another error
1.42 anton 12239: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 12240: presents the return stack dump for the first @code{throw} after the last
12241: executed (not returned-to) @code{catch}; this works well in the usual
12242: case.
12243:
12244: @cindex @code{gforth-fast} and backtraces
12245: @cindex @code{gforth-fast}, difference from @code{gforth}
12246: @cindex backtraces with @code{gforth-fast}
12247: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12248: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12249: from primitives (e.g., invalid memory address, stack empty etc.);
12250: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12251: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12252: exception caused by a primitive in @code{gforth-fast}, you will
12253: typically see no return stack dump at all; however, if the exception is
12254: caught by @code{catch} (e.g., for restoring some state), and then
12255: @code{throw}n again, the return stack dump will be for the first such
12256: @code{throw}.
1.2 jwilke 12257:
1.5 anton 12258: @c ******************************************************************
1.24 anton 12259: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12260: @chapter Tools
12261:
12262: @menu
12263: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 12264: * Stack depth changes:: Where does this stack item come from?
1.1 anton 12265: @end menu
12266:
12267: See also @ref{Emacs and Gforth}.
12268:
1.126 pazsan 12269: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 12270: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12271: @cindex @file{ans-report.fs}
12272: @cindex report the words used in your program
12273: @cindex words used in your program
12274:
12275: If you want to label a Forth program as ANS Forth Program, you must
12276: document which wordsets the program uses; for extension wordsets, it is
12277: helpful to list the words the program requires from these wordsets
12278: (because Forth systems are allowed to provide only some words of them).
12279:
12280: The @file{ans-report.fs} tool makes it easy for you to determine which
12281: words from which wordset and which non-ANS words your application
12282: uses. You simply have to include @file{ans-report.fs} before loading the
12283: program you want to check. After loading your program, you can get the
12284: report with @code{print-ans-report}. A typical use is to run this as
12285: batch job like this:
12286: @example
12287: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12288: @end example
12289:
12290: The output looks like this (for @file{compat/control.fs}):
12291: @example
12292: The program uses the following words
12293: from CORE :
12294: : POSTPONE THEN ; immediate ?dup IF 0=
12295: from BLOCK-EXT :
12296: \
12297: from FILE :
12298: (
12299: @end example
12300:
12301: @subsection Caveats
12302:
12303: Note that @file{ans-report.fs} just checks which words are used, not whether
12304: they are used in an ANS Forth conforming way!
12305:
12306: Some words are defined in several wordsets in the
12307: standard. @file{ans-report.fs} reports them for only one of the
12308: wordsets, and not necessarily the one you expect. It depends on usage
12309: which wordset is the right one to specify. E.g., if you only use the
12310: compilation semantics of @code{S"}, it is a Core word; if you also use
12311: its interpretation semantics, it is a File word.
1.124 anton 12312:
12313:
1.127 anton 12314: @node Stack depth changes, , ANS Report, Tools
1.124 anton 12315: @section Stack depth changes during interpretation
12316: @cindex @file{depth-changes.fs}
12317: @cindex depth changes during interpretation
12318: @cindex stack depth changes during interpretation
12319: @cindex items on the stack after interpretation
12320:
12321: Sometimes you notice that, after loading a file, there are items left
12322: on the stack. The tool @file{depth-changes.fs} helps you find out
12323: quickly where in the file these stack items are coming from.
12324:
12325: The simplest way of using @file{depth-changes.fs} is to include it
12326: before the file(s) you want to check, e.g.:
12327:
12328: @example
12329: gforth depth-changes.fs my-file.fs
12330: @end example
12331:
12332: This will compare the stack depths of the data and FP stack at every
12333: empty line (in interpretation state) against these depths at the last
12334: empty line (in interpretation state). If the depths are not equal,
12335: the position in the file and the stack contents are printed with
12336: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
12337: change has occured in the paragraph of non-empty lines before the
12338: indicated line. It is a good idea to leave an empty line at the end
12339: of the file, so the last paragraph is checked, too.
12340:
12341: Checking only at empty lines usually works well, but sometimes you
12342: have big blocks of non-empty lines (e.g., when building a big table),
12343: and you want to know where in this block the stack depth changed. You
12344: can check all interpreted lines with
12345:
12346: @example
12347: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12348: @end example
12349:
12350: This checks the stack depth at every end-of-line. So the depth change
12351: occured in the line reported by the @code{~~} (not in the line
12352: before).
12353:
12354: Note that, while this offers better accuracy in indicating where the
12355: stack depth changes, it will often report many intentional stack depth
12356: changes (e.g., when an interpreted computation stretches across
12357: several lines). You can suppress the checking of some lines by
12358: putting backslashes at the end of these lines (not followed by white
12359: space), and using
12360:
12361: @example
12362: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12363: @end example
1.1 anton 12364:
12365: @c ******************************************************************
1.65 anton 12366: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12367: @chapter ANS conformance
12368: @cindex ANS conformance of Gforth
12369:
12370: To the best of our knowledge, Gforth is an
12371:
12372: ANS Forth System
12373: @itemize @bullet
12374: @item providing the Core Extensions word set
12375: @item providing the Block word set
12376: @item providing the Block Extensions word set
12377: @item providing the Double-Number word set
12378: @item providing the Double-Number Extensions word set
12379: @item providing the Exception word set
12380: @item providing the Exception Extensions word set
12381: @item providing the Facility word set
1.40 anton 12382: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12383: @item providing the File Access word set
12384: @item providing the File Access Extensions word set
12385: @item providing the Floating-Point word set
12386: @item providing the Floating-Point Extensions word set
12387: @item providing the Locals word set
12388: @item providing the Locals Extensions word set
12389: @item providing the Memory-Allocation word set
12390: @item providing the Memory-Allocation Extensions word set (that one's easy)
12391: @item providing the Programming-Tools word set
12392: @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
12393: @item providing the Search-Order word set
12394: @item providing the Search-Order Extensions word set
12395: @item providing the String word set
12396: @item providing the String Extensions word set (another easy one)
12397: @end itemize
12398:
1.118 anton 12399: Gforth has the following environmental restrictions:
12400:
12401: @cindex environmental restrictions
12402: @itemize @bullet
12403: @item
12404: While processing the OS command line, if an exception is not caught,
12405: Gforth exits with a non-zero exit code instyead of performing QUIT.
12406:
12407: @item
12408: When an @code{throw} is performed after a @code{query}, Gforth does not
12409: allways restore the input source specification in effect at the
12410: corresponding catch.
12411:
12412: @end itemize
12413:
12414:
1.1 anton 12415: @cindex system documentation
12416: In addition, ANS Forth systems are required to document certain
12417: implementation choices. This chapter tries to meet these
12418: requirements. In many cases it gives a way to ask the system for the
12419: information instead of providing the information directly, in
12420: particular, if the information depends on the processor, the operating
12421: system or the installation options chosen, or if they are likely to
12422: change during the maintenance of Gforth.
12423:
12424: @comment The framework for the rest has been taken from pfe.
12425:
12426: @menu
12427: * The Core Words::
12428: * The optional Block word set::
12429: * The optional Double Number word set::
12430: * The optional Exception word set::
12431: * The optional Facility word set::
12432: * The optional File-Access word set::
12433: * The optional Floating-Point word set::
12434: * The optional Locals word set::
12435: * The optional Memory-Allocation word set::
12436: * The optional Programming-Tools word set::
12437: * The optional Search-Order word set::
12438: @end menu
12439:
12440:
12441: @c =====================================================================
12442: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12443: @comment node-name, next, previous, up
12444: @section The Core Words
12445: @c =====================================================================
12446: @cindex core words, system documentation
12447: @cindex system documentation, core words
12448:
12449: @menu
12450: * core-idef:: Implementation Defined Options
12451: * core-ambcond:: Ambiguous Conditions
12452: * core-other:: Other System Documentation
12453: @end menu
12454:
12455: @c ---------------------------------------------------------------------
12456: @node core-idef, core-ambcond, The Core Words, The Core Words
12457: @subsection Implementation Defined Options
12458: @c ---------------------------------------------------------------------
12459: @cindex core words, implementation-defined options
12460: @cindex implementation-defined options, core words
12461:
12462:
12463: @table @i
12464: @item (Cell) aligned addresses:
12465: @cindex cell-aligned addresses
12466: @cindex aligned addresses
12467: processor-dependent. Gforth's alignment words perform natural alignment
12468: (e.g., an address aligned for a datum of size 8 is divisible by
12469: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12470:
12471: @item @code{EMIT} and non-graphic characters:
12472: @cindex @code{EMIT} and non-graphic characters
12473: @cindex non-graphic characters and @code{EMIT}
12474: The character is output using the C library function (actually, macro)
12475: @code{putc}.
12476:
12477: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12478: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12479: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12480: @cindex @code{ACCEPT}, editing
12481: @cindex @code{EXPECT}, editing
12482: This is modeled on the GNU readline library (@pxref{Readline
12483: Interaction, , Command Line Editing, readline, The GNU Readline
12484: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12485: producing a full word completion every time you type it (instead of
1.28 crook 12486: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12487:
12488: @item character set:
12489: @cindex character set
12490: The character set of your computer and display device. Gforth is
12491: 8-bit-clean (but some other component in your system may make trouble).
12492:
12493: @item Character-aligned address requirements:
12494: @cindex character-aligned address requirements
12495: installation-dependent. Currently a character is represented by a C
12496: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12497: (Comments on that requested).
12498:
12499: @item character-set extensions and matching of names:
12500: @cindex character-set extensions and matching of names
1.26 crook 12501: @cindex case-sensitivity for name lookup
12502: @cindex name lookup, case-sensitivity
12503: @cindex locale and case-sensitivity
1.21 crook 12504: Any character except the ASCII NUL character can be used in a
1.1 anton 12505: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12506: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12507: function is probably influenced by the locale. E.g., the @code{C} locale
12508: does not know about accents and umlauts, so they are matched
12509: case-sensitively in that locale. For portability reasons it is best to
12510: write programs such that they work in the @code{C} locale. Then one can
12511: use libraries written by a Polish programmer (who might use words
12512: containing ISO Latin-2 encoded characters) and by a French programmer
12513: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12514: funny results for some of the words (which ones, depends on the font you
12515: are using)). Also, the locale you prefer may not be available in other
12516: operating systems. Hopefully, Unicode will solve these problems one day.
12517:
12518: @item conditions under which control characters match a space delimiter:
12519: @cindex space delimiters
12520: @cindex control characters as delimiters
1.117 anton 12521: If @code{word} is called with the space character as a delimiter, all
1.1 anton 12522: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 12523: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 12524: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 12525: interpreter (aka text interpreter) by default, treats all white-space
12526: characters as delimiters.
12527:
1.26 crook 12528: @item format of the control-flow stack:
12529: @cindex control-flow stack, format
12530: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12531: stack item in cells is given by the constant @code{cs-item-size}. At the
12532: time of this writing, an item consists of a (pointer to a) locals list
12533: (third), an address in the code (second), and a tag for identifying the
12534: item (TOS). The following tags are used: @code{defstart},
12535: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12536: @code{scopestart}.
12537:
12538: @item conversion of digits > 35
12539: @cindex digits > 35
12540: The characters @code{[\]^_'} are the digits with the decimal value
12541: 36@minus{}41. There is no way to input many of the larger digits.
12542:
12543: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12544: @cindex @code{EXPECT}, display after end of input
12545: @cindex @code{ACCEPT}, display after end of input
12546: The cursor is moved to the end of the entered string. If the input is
12547: terminated using the @kbd{Return} key, a space is typed.
12548:
12549: @item exception abort sequence of @code{ABORT"}:
12550: @cindex exception abort sequence of @code{ABORT"}
12551: @cindex @code{ABORT"}, exception abort sequence
12552: The error string is stored into the variable @code{"error} and a
12553: @code{-2 throw} is performed.
12554:
12555: @item input line terminator:
12556: @cindex input line terminator
12557: @cindex line terminator on input
1.26 crook 12558: @cindex newline character on input
1.1 anton 12559: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12560: lines. One of these characters is typically produced when you type the
12561: @kbd{Enter} or @kbd{Return} key.
12562:
12563: @item maximum size of a counted string:
12564: @cindex maximum size of a counted string
12565: @cindex counted string, maximum size
12566: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 12567: on all platforms, but this may change.
1.1 anton 12568:
12569: @item maximum size of a parsed string:
12570: @cindex maximum size of a parsed string
12571: @cindex parsed string, maximum size
12572: Given by the constant @code{/line}. Currently 255 characters.
12573:
12574: @item maximum size of a definition name, in characters:
12575: @cindex maximum size of a definition name, in characters
12576: @cindex name, maximum length
1.113 anton 12577: MAXU/8
1.1 anton 12578:
12579: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12580: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12581: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 12582: MAXU/8
1.1 anton 12583:
12584: @item method of selecting the user input device:
12585: @cindex user input device, method of selecting
12586: The user input device is the standard input. There is currently no way to
12587: change it from within Gforth. However, the input can typically be
12588: redirected in the command line that starts Gforth.
12589:
12590: @item method of selecting the user output device:
12591: @cindex user output device, method of selecting
12592: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12593: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12594: output when the user output device is a terminal, otherwise the output
12595: is buffered.
1.1 anton 12596:
12597: @item methods of dictionary compilation:
12598: What are we expected to document here?
12599:
12600: @item number of bits in one address unit:
12601: @cindex number of bits in one address unit
12602: @cindex address unit, size in bits
12603: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 12604: platforms.
1.1 anton 12605:
12606: @item number representation and arithmetic:
12607: @cindex number representation and arithmetic
1.79 anton 12608: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 12609:
12610: @item ranges for integer types:
12611: @cindex ranges for integer types
12612: @cindex integer types, ranges
12613: Installation-dependent. Make environmental queries for @code{MAX-N},
12614: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12615: unsigned (and positive) types is 0. The lower bound for signed types on
12616: two's complement and one's complement machines machines can be computed
12617: by adding 1 to the upper bound.
12618:
12619: @item read-only data space regions:
12620: @cindex read-only data space regions
12621: @cindex data-space, read-only regions
12622: The whole Forth data space is writable.
12623:
12624: @item size of buffer at @code{WORD}:
12625: @cindex size of buffer at @code{WORD}
12626: @cindex @code{WORD} buffer size
12627: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12628: shared with the pictured numeric output string. If overwriting
12629: @code{PAD} is acceptable, it is as large as the remaining dictionary
12630: space, although only as much can be sensibly used as fits in a counted
12631: string.
12632:
12633: @item size of one cell in address units:
12634: @cindex cell size
12635: @code{1 cells .}.
12636:
12637: @item size of one character in address units:
12638: @cindex char size
1.79 anton 12639: @code{1 chars .}. 1 on all current platforms.
1.1 anton 12640:
12641: @item size of the keyboard terminal buffer:
12642: @cindex size of the keyboard terminal buffer
12643: @cindex terminal buffer, size
12644: Varies. You can determine the size at a specific time using @code{lp@@
12645: tib - .}. It is shared with the locals stack and TIBs of files that
12646: include the current file. You can change the amount of space for TIBs
12647: and locals stack at Gforth startup with the command line option
12648: @code{-l}.
12649:
12650: @item size of the pictured numeric output buffer:
12651: @cindex size of the pictured numeric output buffer
12652: @cindex pictured numeric output buffer, size
12653: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12654: shared with @code{WORD}.
12655:
12656: @item size of the scratch area returned by @code{PAD}:
12657: @cindex size of the scratch area returned by @code{PAD}
12658: @cindex @code{PAD} size
12659: The remainder of dictionary space. @code{unused pad here - - .}.
12660:
12661: @item system case-sensitivity characteristics:
12662: @cindex case-sensitivity characteristics
1.26 crook 12663: Dictionary searches are case-insensitive (except in
1.1 anton 12664: @code{TABLE}s). However, as explained above under @i{character-set
12665: extensions}, the matching for non-ASCII characters is determined by the
12666: locale you are using. In the default @code{C} locale all non-ASCII
12667: characters are matched case-sensitively.
12668:
12669: @item system prompt:
12670: @cindex system prompt
12671: @cindex prompt
12672: @code{ ok} in interpret state, @code{ compiled} in compile state.
12673:
12674: @item division rounding:
12675: @cindex division rounding
12676: installation dependent. @code{s" floored" environment? drop .}. We leave
12677: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12678: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12679:
12680: @item values of @code{STATE} when true:
12681: @cindex @code{STATE} values
12682: -1.
12683:
12684: @item values returned after arithmetic overflow:
12685: On two's complement machines, arithmetic is performed modulo
12686: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12687: arithmetic (with appropriate mapping for signed types). Division by zero
12688: typically results in a @code{-55 throw} (Floating-point unidentified
1.80 anton 12689: fault) or @code{-10 throw} (divide by zero).
1.1 anton 12690:
12691: @item whether the current definition can be found after @t{DOES>}:
12692: @cindex @t{DOES>}, visibility of current definition
12693: No.
12694:
12695: @end table
12696:
12697: @c ---------------------------------------------------------------------
12698: @node core-ambcond, core-other, core-idef, The Core Words
12699: @subsection Ambiguous conditions
12700: @c ---------------------------------------------------------------------
12701: @cindex core words, ambiguous conditions
12702: @cindex ambiguous conditions, core words
12703:
12704: @table @i
12705:
12706: @item a name is neither a word nor a number:
12707: @cindex name not found
1.26 crook 12708: @cindex undefined word
1.80 anton 12709: @code{-13 throw} (Undefined word).
1.1 anton 12710:
12711: @item a definition name exceeds the maximum length allowed:
1.26 crook 12712: @cindex word name too long
1.1 anton 12713: @code{-19 throw} (Word name too long)
12714:
12715: @item addressing a region not inside the various data spaces of the forth system:
12716: @cindex Invalid memory address
1.32 anton 12717: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12718: typically readable. Accessing other addresses gives results dependent on
12719: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12720: address).
12721:
12722: @item argument type incompatible with parameter:
1.26 crook 12723: @cindex argument type mismatch
1.1 anton 12724: This is usually not caught. Some words perform checks, e.g., the control
12725: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12726: mismatch).
12727:
12728: @item attempting to obtain the execution token of a word with undefined execution semantics:
12729: @cindex Interpreting a compile-only word, for @code{'} etc.
12730: @cindex execution token of words with undefined execution semantics
12731: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12732: get an execution token for @code{compile-only-error} (which performs a
12733: @code{-14 throw} when executed).
12734:
12735: @item dividing by zero:
12736: @cindex dividing by zero
12737: @cindex floating point unidentified fault, integer division
1.80 anton 12738: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 12739: zero); on other systems, this typically results in a @code{-55 throw}
12740: (Floating-point unidentified fault).
1.1 anton 12741:
12742: @item insufficient data stack or return stack space:
12743: @cindex insufficient data stack or return stack space
12744: @cindex stack overflow
1.26 crook 12745: @cindex address alignment exception, stack overflow
1.1 anton 12746: @cindex Invalid memory address, stack overflow
12747: Depending on the operating system, the installation, and the invocation
12748: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12749: it is not checked. If it is checked, you typically get a @code{-3 throw}
12750: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12751: throw} (Invalid memory address) (depending on the platform and how you
12752: achieved the overflow) as soon as the overflow happens. If it is not
12753: checked, overflows typically result in mysterious illegal memory
12754: accesses, producing @code{-9 throw} (Invalid memory address) or
12755: @code{-23 throw} (Address alignment exception); they might also destroy
12756: the internal data structure of @code{ALLOCATE} and friends, resulting in
12757: various errors in these words.
1.1 anton 12758:
12759: @item insufficient space for loop control parameters:
12760: @cindex insufficient space for loop control parameters
1.80 anton 12761: Like other return stack overflows.
1.1 anton 12762:
12763: @item insufficient space in the dictionary:
12764: @cindex insufficient space in the dictionary
12765: @cindex dictionary overflow
1.12 anton 12766: If you try to allot (either directly with @code{allot}, or indirectly
12767: with @code{,}, @code{create} etc.) more memory than available in the
12768: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12769: to access memory beyond the end of the dictionary, the results are
12770: similar to stack overflows.
1.1 anton 12771:
12772: @item interpreting a word with undefined interpretation semantics:
12773: @cindex interpreting a word with undefined interpretation semantics
12774: @cindex Interpreting a compile-only word
12775: For some words, we have defined interpretation semantics. For the
12776: others: @code{-14 throw} (Interpreting a compile-only word).
12777:
12778: @item modifying the contents of the input buffer or a string literal:
12779: @cindex modifying the contents of the input buffer or a string literal
12780: These are located in writable memory and can be modified.
12781:
12782: @item overflow of the pictured numeric output string:
12783: @cindex overflow of the pictured numeric output string
12784: @cindex pictured numeric output string, overflow
1.24 anton 12785: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 12786:
12787: @item parsed string overflow:
12788: @cindex parsed string overflow
12789: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12790:
12791: @item producing a result out of range:
12792: @cindex result out of range
12793: On two's complement machines, arithmetic is performed modulo
12794: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12795: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12796: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12797: throw} (floating point unidentified fault). @code{convert} and
12798: @code{>number} currently overflow silently.
1.1 anton 12799:
12800: @item reading from an empty data or return stack:
12801: @cindex stack empty
12802: @cindex stack underflow
1.24 anton 12803: @cindex return stack underflow
1.1 anton 12804: The data stack is checked by the outer (aka text) interpreter after
12805: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12806: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 12807: depending on operating system, installation, and invocation. If they are
12808: caught by a check, they typically result in @code{-4 throw} (Stack
12809: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12810: (Invalid memory address), depending on the platform and which stack
12811: underflows and by how much. Note that even if the system uses checking
12812: (through the MMU), your program may have to underflow by a significant
12813: number of stack items to trigger the reaction (the reason for this is
12814: that the MMU, and therefore the checking, works with a page-size
12815: granularity). If there is no checking, the symptoms resulting from an
12816: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 12817: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 12818: (Invalid memory address) and Illegal Instruction (typically @code{-260
12819: throw}).
1.1 anton 12820:
12821: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12822: @cindex unexpected end of the input buffer
12823: @cindex zero-length string as a name
12824: @cindex Attempt to use zero-length string as a name
12825: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12826: use zero-length string as a name). Words like @code{'} probably will not
12827: find what they search. Note that it is possible to create zero-length
12828: names with @code{nextname} (should it not?).
12829:
12830: @item @code{>IN} greater than input buffer:
12831: @cindex @code{>IN} greater than input buffer
12832: The next invocation of a parsing word returns a string with length 0.
12833:
12834: @item @code{RECURSE} appears after @code{DOES>}:
12835: @cindex @code{RECURSE} appears after @code{DOES>}
12836: Compiles a recursive call to the defining word, not to the defined word.
12837:
12838: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12839: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 12840: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 12841: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12842: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12843: the end of the file was reached), its source-id may be
12844: reused. Therefore, restoring an input source specification referencing a
12845: closed file may lead to unpredictable results instead of a @code{-12
12846: THROW}.
12847:
12848: In the future, Gforth may be able to restore input source specifications
12849: from other than the current input source.
12850:
12851: @item data space containing definitions gets de-allocated:
12852: @cindex data space containing definitions gets de-allocated
12853: Deallocation with @code{allot} is not checked. This typically results in
12854: memory access faults or execution of illegal instructions.
12855:
12856: @item data space read/write with incorrect alignment:
12857: @cindex data space read/write with incorrect alignment
12858: @cindex alignment faults
1.26 crook 12859: @cindex address alignment exception
1.1 anton 12860: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 12861: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 12862: alignment turned on, incorrect alignment results in a @code{-9 throw}
12863: (Invalid memory address). There are reportedly some processors with
1.12 anton 12864: alignment restrictions that do not report violations.
1.1 anton 12865:
12866: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12867: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12868: Like other alignment errors.
12869:
12870: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12871: Like other stack underflows.
12872:
12873: @item loop control parameters not available:
12874: @cindex loop control parameters not available
12875: Not checked. The counted loop words simply assume that the top of return
12876: stack items are loop control parameters and behave accordingly.
12877:
12878: @item most recent definition does not have a name (@code{IMMEDIATE}):
12879: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12880: @cindex last word was headerless
12881: @code{abort" last word was headerless"}.
12882:
12883: @item name not defined by @code{VALUE} used by @code{TO}:
12884: @cindex name not defined by @code{VALUE} used by @code{TO}
12885: @cindex @code{TO} on non-@code{VALUE}s
12886: @cindex Invalid name argument, @code{TO}
12887: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12888: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12889:
12890: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12891: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 12892: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 12893: @code{-13 throw} (Undefined word)
12894:
12895: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12896: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12897: Gforth behaves as if they were of the same type. I.e., you can predict
12898: the behaviour by interpreting all parameters as, e.g., signed.
12899:
12900: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12901: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12902: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12903: compilation semantics of @code{TO}.
12904:
12905: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 12906: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 12907: @cindex @code{WORD}, string overflow
12908: Not checked. The string will be ok, but the count will, of course,
12909: contain only the least significant bits of the length.
12910:
12911: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12912: @cindex @code{LSHIFT}, large shift counts
12913: @cindex @code{RSHIFT}, large shift counts
12914: Processor-dependent. Typical behaviours are returning 0 and using only
12915: the low bits of the shift count.
12916:
12917: @item word not defined via @code{CREATE}:
12918: @cindex @code{>BODY} of non-@code{CREATE}d words
12919: @code{>BODY} produces the PFA of the word no matter how it was defined.
12920:
12921: @cindex @code{DOES>} of non-@code{CREATE}d words
12922: @code{DOES>} changes the execution semantics of the last defined word no
12923: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12924: @code{CREATE , DOES>}.
12925:
12926: @item words improperly used outside @code{<#} and @code{#>}:
12927: Not checked. As usual, you can expect memory faults.
12928:
12929: @end table
12930:
12931:
12932: @c ---------------------------------------------------------------------
12933: @node core-other, , core-ambcond, The Core Words
12934: @subsection Other system documentation
12935: @c ---------------------------------------------------------------------
12936: @cindex other system documentation, core words
12937: @cindex core words, other system documentation
12938:
12939: @table @i
12940: @item nonstandard words using @code{PAD}:
12941: @cindex @code{PAD} use by nonstandard words
12942: None.
12943:
12944: @item operator's terminal facilities available:
12945: @cindex operator's terminal facilities available
1.80 anton 12946: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 12947: and you can give commands to Gforth interactively. The actual facilities
12948: available depend on how you invoke Gforth.
12949:
12950: @item program data space available:
12951: @cindex program data space available
12952: @cindex data space available
12953: @code{UNUSED .} gives the remaining dictionary space. The total
12954: dictionary space can be specified with the @code{-m} switch
12955: (@pxref{Invoking Gforth}) when Gforth starts up.
12956:
12957: @item return stack space available:
12958: @cindex return stack space available
12959: You can compute the total return stack space in cells with
12960: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12961: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12962:
12963: @item stack space available:
12964: @cindex stack space available
12965: You can compute the total data stack space in cells with
12966: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12967: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12968:
12969: @item system dictionary space required, in address units:
12970: @cindex system dictionary space required, in address units
12971: Type @code{here forthstart - .} after startup. At the time of this
12972: writing, this gives 80080 (bytes) on a 32-bit system.
12973: @end table
12974:
12975:
12976: @c =====================================================================
12977: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12978: @section The optional Block word set
12979: @c =====================================================================
12980: @cindex system documentation, block words
12981: @cindex block words, system documentation
12982:
12983: @menu
12984: * block-idef:: Implementation Defined Options
12985: * block-ambcond:: Ambiguous Conditions
12986: * block-other:: Other System Documentation
12987: @end menu
12988:
12989:
12990: @c ---------------------------------------------------------------------
12991: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12992: @subsection Implementation Defined Options
12993: @c ---------------------------------------------------------------------
12994: @cindex implementation-defined options, block words
12995: @cindex block words, implementation-defined options
12996:
12997: @table @i
12998: @item the format for display by @code{LIST}:
12999: @cindex @code{LIST} display format
13000: First the screen number is displayed, then 16 lines of 64 characters,
13001: each line preceded by the line number.
13002:
13003: @item the length of a line affected by @code{\}:
13004: @cindex length of a line affected by @code{\}
13005: @cindex @code{\}, line length in blocks
13006: 64 characters.
13007: @end table
13008:
13009:
13010: @c ---------------------------------------------------------------------
13011: @node block-ambcond, block-other, block-idef, The optional Block word set
13012: @subsection Ambiguous conditions
13013: @c ---------------------------------------------------------------------
13014: @cindex block words, ambiguous conditions
13015: @cindex ambiguous conditions, block words
13016:
13017: @table @i
13018: @item correct block read was not possible:
13019: @cindex block read not possible
13020: Typically results in a @code{throw} of some OS-derived value (between
13021: -512 and -2048). If the blocks file was just not long enough, blanks are
13022: supplied for the missing portion.
13023:
13024: @item I/O exception in block transfer:
13025: @cindex I/O exception in block transfer
13026: @cindex block transfer, I/O exception
13027: Typically results in a @code{throw} of some OS-derived value (between
13028: -512 and -2048).
13029:
13030: @item invalid block number:
13031: @cindex invalid block number
13032: @cindex block number invalid
13033: @code{-35 throw} (Invalid block number)
13034:
13035: @item a program directly alters the contents of @code{BLK}:
13036: @cindex @code{BLK}, altering @code{BLK}
13037: The input stream is switched to that other block, at the same
13038: position. If the storing to @code{BLK} happens when interpreting
13039: non-block input, the system will get quite confused when the block ends.
13040:
13041: @item no current block buffer for @code{UPDATE}:
13042: @cindex @code{UPDATE}, no current block buffer
13043: @code{UPDATE} has no effect.
13044:
13045: @end table
13046:
13047: @c ---------------------------------------------------------------------
13048: @node block-other, , block-ambcond, The optional Block word set
13049: @subsection Other system documentation
13050: @c ---------------------------------------------------------------------
13051: @cindex other system documentation, block words
13052: @cindex block words, other system documentation
13053:
13054: @table @i
13055: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13056: No restrictions (yet).
13057:
13058: @item the number of blocks available for source and data:
13059: depends on your disk space.
13060:
13061: @end table
13062:
13063:
13064: @c =====================================================================
13065: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13066: @section The optional Double Number word set
13067: @c =====================================================================
13068: @cindex system documentation, double words
13069: @cindex double words, system documentation
13070:
13071: @menu
13072: * double-ambcond:: Ambiguous Conditions
13073: @end menu
13074:
13075:
13076: @c ---------------------------------------------------------------------
13077: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13078: @subsection Ambiguous conditions
13079: @c ---------------------------------------------------------------------
13080: @cindex double words, ambiguous conditions
13081: @cindex ambiguous conditions, double words
13082:
13083: @table @i
1.29 crook 13084: @item @i{d} outside of range of @i{n} in @code{D>S}:
13085: @cindex @code{D>S}, @i{d} out of range of @i{n}
13086: The least significant cell of @i{d} is produced.
1.1 anton 13087:
13088: @end table
13089:
13090:
13091: @c =====================================================================
13092: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13093: @section The optional Exception word set
13094: @c =====================================================================
13095: @cindex system documentation, exception words
13096: @cindex exception words, system documentation
13097:
13098: @menu
13099: * exception-idef:: Implementation Defined Options
13100: @end menu
13101:
13102:
13103: @c ---------------------------------------------------------------------
13104: @node exception-idef, , The optional Exception word set, The optional Exception word set
13105: @subsection Implementation Defined Options
13106: @c ---------------------------------------------------------------------
13107: @cindex implementation-defined options, exception words
13108: @cindex exception words, implementation-defined options
13109:
13110: @table @i
13111: @item @code{THROW}-codes used in the system:
13112: @cindex @code{THROW}-codes used in the system
13113: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13114: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13115: codes -512@minus{}-2047 are used for OS errors (for file and memory
13116: allocation operations). The mapping from OS error numbers to throw codes
13117: is -512@minus{}@code{errno}. One side effect of this mapping is that
13118: undefined OS errors produce a message with a strange number; e.g.,
13119: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13120: @end table
13121:
13122: @c =====================================================================
13123: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13124: @section The optional Facility word set
13125: @c =====================================================================
13126: @cindex system documentation, facility words
13127: @cindex facility words, system documentation
13128:
13129: @menu
13130: * facility-idef:: Implementation Defined Options
13131: * facility-ambcond:: Ambiguous Conditions
13132: @end menu
13133:
13134:
13135: @c ---------------------------------------------------------------------
13136: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13137: @subsection Implementation Defined Options
13138: @c ---------------------------------------------------------------------
13139: @cindex implementation-defined options, facility words
13140: @cindex facility words, implementation-defined options
13141:
13142: @table @i
13143: @item encoding of keyboard events (@code{EKEY}):
13144: @cindex keyboard events, encoding in @code{EKEY}
13145: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13146: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13147: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13148: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13149: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13150: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13151:
1.1 anton 13152:
13153: @item duration of a system clock tick:
13154: @cindex duration of a system clock tick
13155: @cindex clock tick duration
13156: System dependent. With respect to @code{MS}, the time is specified in
13157: microseconds. How well the OS and the hardware implement this, is
13158: another question.
13159:
13160: @item repeatability to be expected from the execution of @code{MS}:
13161: @cindex repeatability to be expected from the execution of @code{MS}
13162: @cindex @code{MS}, repeatability to be expected
13163: System dependent. On Unix, a lot depends on load. If the system is
13164: lightly loaded, and the delay is short enough that Gforth does not get
13165: swapped out, the performance should be acceptable. Under MS-DOS and
13166: other single-tasking systems, it should be good.
13167:
13168: @end table
13169:
13170:
13171: @c ---------------------------------------------------------------------
13172: @node facility-ambcond, , facility-idef, The optional Facility word set
13173: @subsection Ambiguous conditions
13174: @c ---------------------------------------------------------------------
13175: @cindex facility words, ambiguous conditions
13176: @cindex ambiguous conditions, facility words
13177:
13178: @table @i
13179: @item @code{AT-XY} can't be performed on user output device:
13180: @cindex @code{AT-XY} can't be performed on user output device
13181: Largely terminal dependent. No range checks are done on the arguments.
13182: No errors are reported. You may see some garbage appearing, you may see
13183: simply nothing happen.
13184:
13185: @end table
13186:
13187:
13188: @c =====================================================================
13189: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13190: @section The optional File-Access word set
13191: @c =====================================================================
13192: @cindex system documentation, file words
13193: @cindex file words, system documentation
13194:
13195: @menu
13196: * file-idef:: Implementation Defined Options
13197: * file-ambcond:: Ambiguous Conditions
13198: @end menu
13199:
13200: @c ---------------------------------------------------------------------
13201: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13202: @subsection Implementation Defined Options
13203: @c ---------------------------------------------------------------------
13204: @cindex implementation-defined options, file words
13205: @cindex file words, implementation-defined options
13206:
13207: @table @i
13208: @item file access methods used:
13209: @cindex file access methods used
13210: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13211: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13212: @code{wb}): The file is cleared, if it exists, and created, if it does
13213: not (with both @code{open-file} and @code{create-file}). Under Unix
13214: @code{create-file} creates a file with 666 permissions modified by your
13215: umask.
13216:
13217: @item file exceptions:
13218: @cindex file exceptions
13219: The file words do not raise exceptions (except, perhaps, memory access
13220: faults when you pass illegal addresses or file-ids).
13221:
13222: @item file line terminator:
13223: @cindex file line terminator
13224: System-dependent. Gforth uses C's newline character as line
13225: terminator. What the actual character code(s) of this are is
13226: system-dependent.
13227:
13228: @item file name format:
13229: @cindex file name format
13230: System dependent. Gforth just uses the file name format of your OS.
13231:
13232: @item information returned by @code{FILE-STATUS}:
13233: @cindex @code{FILE-STATUS}, returned information
13234: @code{FILE-STATUS} returns the most powerful file access mode allowed
13235: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13236: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13237: along with the returned mode.
13238:
13239: @item input file state after an exception when including source:
13240: @cindex exception when including source
13241: All files that are left via the exception are closed.
13242:
1.29 crook 13243: @item @i{ior} values and meaning:
13244: @cindex @i{ior} values and meaning
1.68 anton 13245: @cindex @i{wior} values and meaning
1.29 crook 13246: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13247: intended as throw codes. They typically are in the range
13248: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13249: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13250:
13251: @item maximum depth of file input nesting:
13252: @cindex maximum depth of file input nesting
13253: @cindex file input nesting, maximum depth
13254: limited by the amount of return stack, locals/TIB stack, and the number
13255: of open files available. This should not give you troubles.
13256:
13257: @item maximum size of input line:
13258: @cindex maximum size of input line
13259: @cindex input line size, maximum
13260: @code{/line}. Currently 255.
13261:
13262: @item methods of mapping block ranges to files:
13263: @cindex mapping block ranges to files
13264: @cindex files containing blocks
13265: @cindex blocks in files
13266: By default, blocks are accessed in the file @file{blocks.fb} in the
13267: current working directory. The file can be switched with @code{USE}.
13268:
13269: @item number of string buffers provided by @code{S"}:
13270: @cindex @code{S"}, number of string buffers
13271: 1
13272:
13273: @item size of string buffer used by @code{S"}:
13274: @cindex @code{S"}, size of string buffer
13275: @code{/line}. currently 255.
13276:
13277: @end table
13278:
13279: @c ---------------------------------------------------------------------
13280: @node file-ambcond, , file-idef, The optional File-Access word set
13281: @subsection Ambiguous conditions
13282: @c ---------------------------------------------------------------------
13283: @cindex file words, ambiguous conditions
13284: @cindex ambiguous conditions, file words
13285:
13286: @table @i
13287: @item attempting to position a file outside its boundaries:
13288: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13289: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13290: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13291:
13292: @item attempting to read from file positions not yet written:
13293: @cindex reading from file positions not yet written
13294: End-of-file, i.e., zero characters are read and no error is reported.
13295:
1.29 crook 13296: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13297: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13298: An appropriate exception may be thrown, but a memory fault or other
13299: problem is more probable.
13300:
1.29 crook 13301: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13302: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13303: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13304: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13305: thrown.
13306:
13307: @item named file cannot be opened (@code{INCLUDED}):
13308: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13309: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13310:
13311: @item requesting an unmapped block number:
13312: @cindex unmapped block numbers
13313: There are no unmapped legal block numbers. On some operating systems,
13314: writing a block with a large number may overflow the file system and
13315: have an error message as consequence.
13316:
13317: @item using @code{source-id} when @code{blk} is non-zero:
13318: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13319: @code{source-id} performs its function. Typically it will give the id of
13320: the source which loaded the block. (Better ideas?)
13321:
13322: @end table
13323:
13324:
13325: @c =====================================================================
13326: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13327: @section The optional Floating-Point word set
13328: @c =====================================================================
13329: @cindex system documentation, floating-point words
13330: @cindex floating-point words, system documentation
13331:
13332: @menu
13333: * floating-idef:: Implementation Defined Options
13334: * floating-ambcond:: Ambiguous Conditions
13335: @end menu
13336:
13337:
13338: @c ---------------------------------------------------------------------
13339: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13340: @subsection Implementation Defined Options
13341: @c ---------------------------------------------------------------------
13342: @cindex implementation-defined options, floating-point words
13343: @cindex floating-point words, implementation-defined options
13344:
13345: @table @i
13346: @item format and range of floating point numbers:
13347: @cindex format and range of floating point numbers
13348: @cindex floating point numbers, format and range
13349: System-dependent; the @code{double} type of C.
13350:
1.29 crook 13351: @item results of @code{REPRESENT} when @i{float} is out of range:
13352: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13353: System dependent; @code{REPRESENT} is implemented using the C library
13354: function @code{ecvt()} and inherits its behaviour in this respect.
13355:
13356: @item rounding or truncation of floating-point numbers:
13357: @cindex rounding of floating-point numbers
13358: @cindex truncation of floating-point numbers
13359: @cindex floating-point numbers, rounding or truncation
13360: System dependent; the rounding behaviour is inherited from the hosting C
13361: compiler. IEEE-FP-based (i.e., most) systems by default round to
13362: nearest, and break ties by rounding to even (i.e., such that the last
13363: bit of the mantissa is 0).
13364:
13365: @item size of floating-point stack:
13366: @cindex floating-point stack size
13367: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13368: the floating-point stack (in floats). You can specify this on startup
13369: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13370:
13371: @item width of floating-point stack:
13372: @cindex floating-point stack width
13373: @code{1 floats}.
13374:
13375: @end table
13376:
13377:
13378: @c ---------------------------------------------------------------------
13379: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13380: @subsection Ambiguous conditions
13381: @c ---------------------------------------------------------------------
13382: @cindex floating-point words, ambiguous conditions
13383: @cindex ambiguous conditions, floating-point words
13384:
13385: @table @i
13386: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13387: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13388: System-dependent. Typically results in a @code{-23 THROW} like other
13389: alignment violations.
13390:
13391: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13392: @cindex @code{f@@} used with an address that is not float aligned
13393: @cindex @code{f!} used with an address that is not float aligned
13394: System-dependent. Typically results in a @code{-23 THROW} like other
13395: alignment violations.
13396:
13397: @item floating-point result out of range:
13398: @cindex floating-point result out of range
1.80 anton 13399: System-dependent. Can result in a @code{-43 throw} (floating point
13400: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13401: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13402: unidentified fault), or can produce a special value representing, e.g.,
13403: Infinity.
13404:
13405: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13406: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13407: System-dependent. Typically results in an alignment fault like other
13408: alignment violations.
13409:
1.35 anton 13410: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13411: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13412: The floating-point number is converted into decimal nonetheless.
13413:
13414: @item Both arguments are equal to zero (@code{FATAN2}):
13415: @cindex @code{FATAN2}, both arguments are equal to zero
13416: System-dependent. @code{FATAN2} is implemented using the C library
13417: function @code{atan2()}.
13418:
1.29 crook 13419: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13420: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13421: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13422: because of small errors and the tan will be a very large (or very small)
13423: but finite number.
13424:
1.29 crook 13425: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13426: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13427: The result is rounded to the nearest float.
13428:
13429: @item dividing by zero:
13430: @cindex dividing by zero, floating-point
13431: @cindex floating-point dividing by zero
13432: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13433: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13434: (floating point divide by zero) or @code{-55 throw} (Floating-point
13435: unidentified fault).
1.1 anton 13436:
13437: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13438: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13439: System dependent. On IEEE-FP based systems the number is converted into
13440: an infinity.
13441:
1.29 crook 13442: @item @i{float}<1 (@code{FACOSH}):
13443: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13444: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13445: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13446:
1.29 crook 13447: @item @i{float}=<-1 (@code{FLNP1}):
13448: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13449: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13450: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13451: negative infinity for @i{float}=-1).
1.1 anton 13452:
1.29 crook 13453: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13454: @cindex @code{FLN}, @i{float}=<0
13455: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13456: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13457: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13458: negative infinity for @i{float}=0).
1.1 anton 13459:
1.29 crook 13460: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13461: @cindex @code{FASINH}, @i{float}<0
13462: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13463: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13464: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13465: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13466: C library?).
1.1 anton 13467:
1.29 crook 13468: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13469: @cindex @code{FACOS}, |@i{float}|>1
13470: @cindex @code{FASIN}, |@i{float}|>1
13471: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13472: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13473: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13474:
1.29 crook 13475: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13476: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13477: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13478: Platform-dependent; typically, some double number is produced and no
13479: error is reported.
1.1 anton 13480:
13481: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13482: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13483: @code{Precision} characters of the numeric output area are used. If
13484: @code{precision} is too high, these words will smash the data or code
13485: close to @code{here}.
1.1 anton 13486: @end table
13487:
13488: @c =====================================================================
13489: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13490: @section The optional Locals word set
13491: @c =====================================================================
13492: @cindex system documentation, locals words
13493: @cindex locals words, system documentation
13494:
13495: @menu
13496: * locals-idef:: Implementation Defined Options
13497: * locals-ambcond:: Ambiguous Conditions
13498: @end menu
13499:
13500:
13501: @c ---------------------------------------------------------------------
13502: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13503: @subsection Implementation Defined Options
13504: @c ---------------------------------------------------------------------
13505: @cindex implementation-defined options, locals words
13506: @cindex locals words, implementation-defined options
13507:
13508: @table @i
13509: @item maximum number of locals in a definition:
13510: @cindex maximum number of locals in a definition
13511: @cindex locals, maximum number in a definition
13512: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13513: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13514: characters. The number of locals in a definition is bounded by the size
13515: of locals-buffer, which contains the names of the locals.
13516:
13517: @end table
13518:
13519:
13520: @c ---------------------------------------------------------------------
13521: @node locals-ambcond, , locals-idef, The optional Locals word set
13522: @subsection Ambiguous conditions
13523: @c ---------------------------------------------------------------------
13524: @cindex locals words, ambiguous conditions
13525: @cindex ambiguous conditions, locals words
13526:
13527: @table @i
13528: @item executing a named local in interpretation state:
13529: @cindex local in interpretation state
13530: @cindex Interpreting a compile-only word, for a local
13531: Locals have no interpretation semantics. If you try to perform the
13532: interpretation semantics, you will get a @code{-14 throw} somewhere
13533: (Interpreting a compile-only word). If you perform the compilation
13534: semantics, the locals access will be compiled (irrespective of state).
13535:
1.29 crook 13536: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13537: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13538: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13539: @cindex Invalid name argument, @code{TO}
13540: @code{-32 throw} (Invalid name argument)
13541:
13542: @end table
13543:
13544:
13545: @c =====================================================================
13546: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13547: @section The optional Memory-Allocation word set
13548: @c =====================================================================
13549: @cindex system documentation, memory-allocation words
13550: @cindex memory-allocation words, system documentation
13551:
13552: @menu
13553: * memory-idef:: Implementation Defined Options
13554: @end menu
13555:
13556:
13557: @c ---------------------------------------------------------------------
13558: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13559: @subsection Implementation Defined Options
13560: @c ---------------------------------------------------------------------
13561: @cindex implementation-defined options, memory-allocation words
13562: @cindex memory-allocation words, implementation-defined options
13563:
13564: @table @i
1.29 crook 13565: @item values and meaning of @i{ior}:
13566: @cindex @i{ior} values and meaning
13567: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13568: intended as throw codes. They typically are in the range
13569: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13570: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13571:
13572: @end table
13573:
13574: @c =====================================================================
13575: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13576: @section The optional Programming-Tools word set
13577: @c =====================================================================
13578: @cindex system documentation, programming-tools words
13579: @cindex programming-tools words, system documentation
13580:
13581: @menu
13582: * programming-idef:: Implementation Defined Options
13583: * programming-ambcond:: Ambiguous Conditions
13584: @end menu
13585:
13586:
13587: @c ---------------------------------------------------------------------
13588: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13589: @subsection Implementation Defined Options
13590: @c ---------------------------------------------------------------------
13591: @cindex implementation-defined options, programming-tools words
13592: @cindex programming-tools words, implementation-defined options
13593:
13594: @table @i
13595: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13596: @cindex @code{;CODE} ending sequence
13597: @cindex @code{CODE} ending sequence
13598: @code{END-CODE}
13599:
13600: @item manner of processing input following @code{;CODE} and @code{CODE}:
13601: @cindex @code{;CODE}, processing input
13602: @cindex @code{CODE}, processing input
13603: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13604: the input is processed by the text interpreter, (starting) in interpret
13605: state.
13606:
13607: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13608: @cindex @code{ASSEMBLER}, search order capability
13609: The ANS Forth search order word set.
13610:
13611: @item source and format of display by @code{SEE}:
13612: @cindex @code{SEE}, source and format of output
1.80 anton 13613: The source for @code{see} is the executable code used by the inner
1.1 anton 13614: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 13615: (and on some platforms, assembly code for primitives) as well as
13616: possible.
1.1 anton 13617:
13618: @end table
13619:
13620: @c ---------------------------------------------------------------------
13621: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13622: @subsection Ambiguous conditions
13623: @c ---------------------------------------------------------------------
13624: @cindex programming-tools words, ambiguous conditions
13625: @cindex ambiguous conditions, programming-tools words
13626:
13627: @table @i
13628:
1.21 crook 13629: @item deleting the compilation word list (@code{FORGET}):
13630: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13631: Not implemented (yet).
13632:
1.29 crook 13633: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13634: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13635: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13636: @cindex control-flow stack underflow
13637: This typically results in an @code{abort"} with a descriptive error
13638: message (may change into a @code{-22 throw} (Control structure mismatch)
13639: in the future). You may also get a memory access error. If you are
13640: unlucky, this ambiguous condition is not caught.
13641:
1.29 crook 13642: @item @i{name} can't be found (@code{FORGET}):
13643: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13644: Not implemented (yet).
13645:
1.29 crook 13646: @item @i{name} not defined via @code{CREATE}:
13647: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13648: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13649: the execution semantics of the last defined word no matter how it was
13650: defined.
13651:
13652: @item @code{POSTPONE} applied to @code{[IF]}:
13653: @cindex @code{POSTPONE} applied to @code{[IF]}
13654: @cindex @code{[IF]} and @code{POSTPONE}
13655: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13656: equivalent to @code{[IF]}.
13657:
13658: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13659: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13660: Continue in the same state of conditional compilation in the next outer
13661: input source. Currently there is no warning to the user about this.
13662:
13663: @item removing a needed definition (@code{FORGET}):
13664: @cindex @code{FORGET}, removing a needed definition
13665: Not implemented (yet).
13666:
13667: @end table
13668:
13669:
13670: @c =====================================================================
13671: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13672: @section The optional Search-Order word set
13673: @c =====================================================================
13674: @cindex system documentation, search-order words
13675: @cindex search-order words, system documentation
13676:
13677: @menu
13678: * search-idef:: Implementation Defined Options
13679: * search-ambcond:: Ambiguous Conditions
13680: @end menu
13681:
13682:
13683: @c ---------------------------------------------------------------------
13684: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13685: @subsection Implementation Defined Options
13686: @c ---------------------------------------------------------------------
13687: @cindex implementation-defined options, search-order words
13688: @cindex search-order words, implementation-defined options
13689:
13690: @table @i
13691: @item maximum number of word lists in search order:
13692: @cindex maximum number of word lists in search order
13693: @cindex search order, maximum depth
13694: @code{s" wordlists" environment? drop .}. Currently 16.
13695:
13696: @item minimum search order:
13697: @cindex minimum search order
13698: @cindex search order, minimum
13699: @code{root root}.
13700:
13701: @end table
13702:
13703: @c ---------------------------------------------------------------------
13704: @node search-ambcond, , search-idef, The optional Search-Order word set
13705: @subsection Ambiguous conditions
13706: @c ---------------------------------------------------------------------
13707: @cindex search-order words, ambiguous conditions
13708: @cindex ambiguous conditions, search-order words
13709:
13710: @table @i
1.21 crook 13711: @item changing the compilation word list (during compilation):
13712: @cindex changing the compilation word list (during compilation)
13713: @cindex compilation word list, change before definition ends
13714: The word is entered into the word list that was the compilation word list
1.1 anton 13715: at the start of the definition. Any changes to the name field (e.g.,
13716: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 13717: are applied to the latest defined word (as reported by @code{latest} or
13718: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 13719:
13720: @item search order empty (@code{previous}):
13721: @cindex @code{previous}, search order empty
1.26 crook 13722: @cindex vocstack empty, @code{previous}
1.1 anton 13723: @code{abort" Vocstack empty"}.
13724:
13725: @item too many word lists in search order (@code{also}):
13726: @cindex @code{also}, too many word lists in search order
1.26 crook 13727: @cindex vocstack full, @code{also}
1.1 anton 13728: @code{abort" Vocstack full"}.
13729:
13730: @end table
13731:
13732: @c ***************************************************************
1.65 anton 13733: @node Standard vs Extensions, Model, ANS conformance, Top
13734: @chapter Should I use Gforth extensions?
13735: @cindex Gforth extensions
13736:
13737: As you read through the rest of this manual, you will see documentation
13738: for @i{Standard} words, and documentation for some appealing Gforth
13739: @i{extensions}. You might ask yourself the question: @i{``Should I
13740: restrict myself to the standard, or should I use the extensions?''}
13741:
13742: The answer depends on the goals you have for the program you are working
13743: on:
13744:
13745: @itemize @bullet
13746:
13747: @item Is it just for yourself or do you want to share it with others?
13748:
13749: @item
13750: If you want to share it, do the others all use Gforth?
13751:
13752: @item
13753: If it is just for yourself, do you want to restrict yourself to Gforth?
13754:
13755: @end itemize
13756:
13757: If restricting the program to Gforth is ok, then there is no reason not
13758: to use extensions. It is still a good idea to keep to the standard
13759: where it is easy, in case you want to reuse these parts in another
13760: program that you want to be portable.
13761:
13762: If you want to be able to port the program to other Forth systems, there
13763: are the following points to consider:
13764:
13765: @itemize @bullet
13766:
13767: @item
13768: Most Forth systems that are being maintained support the ANS Forth
13769: standard. So if your program complies with the standard, it will be
13770: portable among many systems.
13771:
13772: @item
13773: A number of the Gforth extensions can be implemented in ANS Forth using
13774: public-domain files provided in the @file{compat/} directory. These are
13775: mentioned in the text in passing. There is no reason not to use these
13776: extensions, your program will still be ANS Forth compliant; just include
13777: the appropriate compat files with your program.
13778:
13779: @item
13780: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13781: analyse your program and determine what non-Standard words it relies
13782: upon. However, it does not check whether you use standard words in a
13783: non-standard way.
13784:
13785: @item
13786: Some techniques are not standardized by ANS Forth, and are hard or
13787: impossible to implement in a standard way, but can be implemented in
13788: most Forth systems easily, and usually in similar ways (e.g., accessing
13789: word headers). Forth has a rich historical precedent for programmers
13790: taking advantage of implementation-dependent features of their tools
13791: (for example, relying on a knowledge of the dictionary
13792: structure). Sometimes these techniques are necessary to extract every
13793: last bit of performance from the hardware, sometimes they are just a
13794: programming shorthand.
13795:
13796: @item
13797: Does using a Gforth extension save more work than the porting this part
13798: to other Forth systems (if any) will cost?
13799:
13800: @item
13801: Is the additional functionality worth the reduction in portability and
13802: the additional porting problems?
13803:
13804: @end itemize
13805:
13806: In order to perform these consideratios, you need to know what's
13807: standard and what's not. This manual generally states if something is
1.81 anton 13808: non-standard, but the authoritative source is the
13809: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 13810: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13811: into the thought processes of the technical committee.
13812:
13813: Note also that portability between Forth systems is not the only
13814: portability issue; there is also the issue of portability between
13815: different platforms (processor/OS combinations).
13816:
13817: @c ***************************************************************
13818: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 13819: @chapter Model
13820:
13821: This chapter has yet to be written. It will contain information, on
13822: which internal structures you can rely.
13823:
13824: @c ***************************************************************
13825: @node Integrating Gforth, Emacs and Gforth, Model, Top
13826: @chapter Integrating Gforth into C programs
13827:
13828: This is not yet implemented.
13829:
13830: Several people like to use Forth as scripting language for applications
13831: that are otherwise written in C, C++, or some other language.
13832:
13833: The Forth system ATLAST provides facilities for embedding it into
13834: applications; unfortunately it has several disadvantages: most
13835: importantly, it is not based on ANS Forth, and it is apparently dead
13836: (i.e., not developed further and not supported). The facilities
1.21 crook 13837: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 13838: making the switch should not be hard.
13839:
13840: We also tried to design the interface such that it can easily be
13841: implemented by other Forth systems, so that we may one day arrive at a
13842: standardized interface. Such a standard interface would allow you to
13843: replace the Forth system without having to rewrite C code.
13844:
13845: You embed the Gforth interpreter by linking with the library
13846: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13847: global symbols in this library that belong to the interface, have the
13848: prefix @code{forth_}. (Global symbols that are used internally have the
13849: prefix @code{gforth_}).
13850:
13851: You can include the declarations of Forth types and the functions and
13852: variables of the interface with @code{#include <forth.h>}.
13853:
13854: Types.
13855:
13856: Variables.
13857:
13858: Data and FP Stack pointer. Area sizes.
13859:
13860: functions.
13861:
13862: forth_init(imagefile)
13863: forth_evaluate(string) exceptions?
13864: forth_goto(address) (or forth_execute(xt)?)
13865: forth_continue() (a corountining mechanism)
13866:
13867: Adding primitives.
13868:
13869: No checking.
13870:
13871: Signals?
13872:
13873: Accessing the Stacks
13874:
1.26 crook 13875: @c ******************************************************************
1.1 anton 13876: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13877: @chapter Emacs and Gforth
13878: @cindex Emacs and Gforth
13879:
13880: @cindex @file{gforth.el}
13881: @cindex @file{forth.el}
13882: @cindex Rydqvist, Goran
1.107 dvdkhlng 13883: @cindex Kuehling, David
1.1 anton 13884: @cindex comment editing commands
13885: @cindex @code{\}, editing with Emacs
13886: @cindex debug tracer editing commands
13887: @cindex @code{~~}, removal with Emacs
13888: @cindex Forth mode in Emacs
1.107 dvdkhlng 13889:
1.1 anton 13890: Gforth comes with @file{gforth.el}, an improved version of
13891: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 13892: improvements are:
13893:
13894: @itemize @bullet
13895: @item
1.107 dvdkhlng 13896: A better handling of indentation.
13897: @item
13898: A custom hilighting engine for Forth-code.
1.26 crook 13899: @item
13900: Comment paragraph filling (@kbd{M-q})
13901: @item
13902: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13903: @item
13904: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 13905: @item
13906: Support of the @code{info-lookup} feature for looking up the
13907: documentation of a word.
1.107 dvdkhlng 13908: @item
13909: Support for reading and writing blocks files.
1.26 crook 13910: @end itemize
13911:
1.107 dvdkhlng 13912: To get a basic description of these features, enter Forth mode and
13913: type @kbd{C-h m}.
1.1 anton 13914:
13915: @cindex source location of error or debugging output in Emacs
13916: @cindex error output, finding the source location in Emacs
13917: @cindex debugging output, finding the source location in Emacs
13918: In addition, Gforth supports Emacs quite well: The source code locations
13919: given in error messages, debugging output (from @code{~~}) and failed
13920: assertion messages are in the right format for Emacs' compilation mode
13921: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13922: Manual}) so the source location corresponding to an error or other
13923: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13924: @kbd{C-c C-c} for the error under the cursor).
13925:
1.107 dvdkhlng 13926: @cindex viewing the documentation of a word in Emacs
13927: @cindex context-sensitive help
13928: Moreover, for words documented in this manual, you can look up the
13929: glossary entry quickly by using @kbd{C-h TAB}
13930: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13931: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
13932: later and does not work for words containing @code{:}.
13933:
13934: @menu
13935: * Installing gforth.el:: Making Emacs aware of Forth.
13936: * Emacs Tags:: Viewing the source of a word in Emacs.
13937: * Hilighting:: Making Forth code look prettier.
13938: * Auto-Indentation:: Customizing auto-indentation.
13939: * Blocks Files:: Reading and writing blocks files.
13940: @end menu
13941:
13942: @c ----------------------------------
1.109 anton 13943: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 13944: @section Installing gforth.el
13945: @cindex @file{.emacs}
13946: @cindex @file{gforth.el}, installation
13947: To make the features from @file{gforth.el} available in Emacs, add
13948: the following lines to your @file{.emacs} file:
13949:
13950: @example
13951: (autoload 'forth-mode "gforth.el")
13952: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
13953: auto-mode-alist))
13954: (autoload 'forth-block-mode "gforth.el")
13955: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
13956: auto-mode-alist))
13957: (add-hook 'forth-mode-hook (function (lambda ()
13958: ;; customize variables here:
13959: (setq forth-indent-level 4)
13960: (setq forth-minor-indent-level 2)
13961: (setq forth-hilight-level 3)
13962: ;;; ...
13963: )))
13964: @end example
13965:
13966: @c ----------------------------------
13967: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
13968: @section Emacs Tags
1.1 anton 13969: @cindex @file{TAGS} file
13970: @cindex @file{etags.fs}
13971: @cindex viewing the source of a word in Emacs
1.43 anton 13972: @cindex @code{require}, placement in files
13973: @cindex @code{include}, placement in files
1.107 dvdkhlng 13974: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
13975: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 13976: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 13977: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 13978: several tags files at the same time (e.g., one for the Gforth sources
13979: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13980: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13981: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 13982: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
13983: with @file{etags.fs}, you should avoid putting definitions both before
13984: and after @code{require} etc., otherwise you will see the same file
13985: visited several times by commands like @code{tags-search}.
1.1 anton 13986:
1.107 dvdkhlng 13987: @c ----------------------------------
13988: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
13989: @section Hilighting
13990: @cindex hilighting Forth code in Emacs
13991: @cindex highlighting Forth code in Emacs
13992: @file{gforth.el} comes with a custom source hilighting engine. When
13993: you open a file in @code{forth-mode}, it will be completely parsed,
13994: assigning faces to keywords, comments, strings etc. While you edit
13995: the file, modified regions get parsed and updated on-the-fly.
13996:
13997: Use the variable `forth-hilight-level' to change the level of
13998: decoration from 0 (no hilighting at all) to 3 (the default). Even if
13999: you set the hilighting level to 0, the parser will still work in the
14000: background, collecting information about whether regions of text are
14001: ``compiled'' or ``interpreted''. Those information are required for
14002: auto-indentation to work properly. Set `forth-disable-parser' to
14003: non-nil if your computer is too slow to handle parsing. This will
14004: have an impact on the smartness of the auto-indentation engine,
14005: though.
14006:
14007: Sometimes Forth sources define new features that should be hilighted,
14008: new control structures, defining-words etc. You can use the variable
14009: `forth-custom-words' to make @code{forth-mode} hilight additional
14010: words and constructs. See the docstring of `forth-words' for details
14011: (in Emacs, type @kbd{C-h v forth-words}).
14012:
14013: `forth-custom-words' is meant to be customized in your
14014: @file{.emacs} file. To customize hilighing in a file-specific manner,
14015: set `forth-local-words' in a local-variables section at the end of
14016: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14017:
14018: Example:
14019: @example
14020: 0 [IF]
14021: Local Variables:
14022: forth-local-words:
14023: ((("t:") definition-starter (font-lock-keyword-face . 1)
14024: "[ \t\n]" t name (font-lock-function-name-face . 3))
14025: ((";t") definition-ender (font-lock-keyword-face . 1)))
14026: End:
14027: [THEN]
14028: @end example
14029:
14030: @c ----------------------------------
14031: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14032: @section Auto-Indentation
14033: @cindex auto-indentation of Forth code in Emacs
14034: @cindex indentation of Forth code in Emacs
14035: @code{forth-mode} automatically tries to indent lines in a smart way,
14036: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14037:
14038: Simple customization can be achieved by setting
14039: `forth-indent-level' and `forth-minor-indent-level' in your
14040: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14041: per default by multiples of 4 columns. To use the more traditional
14042: 3-column indentation, add the following lines to your @file{.emacs}:
14043:
14044: @example
14045: (add-hook 'forth-mode-hook (function (lambda ()
14046: ;; customize variables here:
14047: (setq forth-indent-level 3)
14048: (setq forth-minor-indent-level 1)
14049: )))
14050: @end example
14051:
14052: If you want indentation to recognize non-default words, customize it
14053: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14054: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14055: v forth-indent-words}).
14056:
14057: To customize indentation in a file-specific manner, set
14058: `forth-local-indent-words' in a local-variables section at the end of
14059: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14060: Emacs Manual}).
14061:
14062: Example:
14063: @example
14064: 0 [IF]
14065: Local Variables:
14066: forth-local-indent-words:
14067: ((("t:") (0 . 2) (0 . 2))
14068: ((";t") (-2 . 0) (0 . -2)))
14069: End:
14070: [THEN]
14071: @end example
14072:
14073: @c ----------------------------------
1.109 anton 14074: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14075: @section Blocks Files
14076: @cindex blocks files, use with Emacs
14077: @code{forth-mode} Autodetects blocks files by checking whether the
14078: length of the first line exceeds 1023 characters. It then tries to
14079: convert the file into normal text format. When you save the file, it
14080: will be written to disk as normal stream-source file.
14081:
14082: If you want to write blocks files, use @code{forth-blocks-mode}. It
14083: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 14084:
1.107 dvdkhlng 14085: @itemize @bullet
14086: @item
14087: Files are written to disk in blocks file format.
14088: @item
14089: Screen numbers are displayed in the mode line (enumerated beginning
14090: with the value of `forth-block-base')
14091: @item
14092: Warnings are displayed when lines exceed 64 characters.
14093: @item
14094: The beginning of the currently edited block is marked with an
14095: overlay-arrow.
14096: @end itemize
1.41 anton 14097:
1.107 dvdkhlng 14098: There are some restrictions you should be aware of. When you open a
14099: blocks file that contains tabulator or newline characters, these
14100: characters will be translated into spaces when the file is written
14101: back to disk. If tabs or newlines are encountered during blocks file
14102: reading, an error is output to the echo area. So have a look at the
14103: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14104:
1.107 dvdkhlng 14105: Please consult the docstring of @code{forth-blocks-mode} for more
14106: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14107:
1.26 crook 14108: @c ******************************************************************
1.1 anton 14109: @node Image Files, Engine, Emacs and Gforth, Top
14110: @chapter Image Files
1.26 crook 14111: @cindex image file
14112: @cindex @file{.fi} files
1.1 anton 14113: @cindex precompiled Forth code
14114: @cindex dictionary in persistent form
14115: @cindex persistent form of dictionary
14116:
14117: An image file is a file containing an image of the Forth dictionary,
14118: i.e., compiled Forth code and data residing in the dictionary. By
14119: convention, we use the extension @code{.fi} for image files.
14120:
14121: @menu
1.18 anton 14122: * Image Licensing Issues:: Distribution terms for images.
14123: * Image File Background:: Why have image files?
1.67 anton 14124: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14125: * Data-Relocatable Image Files:: are better.
1.67 anton 14126: * Fully Relocatable Image Files:: better yet.
1.18 anton 14127: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14128: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14129: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14130: @end menu
14131:
1.18 anton 14132: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14133: @section Image Licensing Issues
14134: @cindex license for images
14135: @cindex image license
14136:
14137: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14138: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14139: original image; i.e., according to copyright law it is a derived work of
14140: the original image.
14141:
14142: Since Gforth is distributed under the GNU GPL, the newly created image
14143: falls under the GNU GPL, too. In particular, this means that if you
14144: distribute the image, you have to make all of the sources for the image
1.113 anton 14145: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 14146: GNU General Public License (Section 3)}.
14147:
14148: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14149: contains only code compiled from the sources you gave it; if none of
14150: these sources is under the GPL, the terms discussed above do not apply
14151: to the image. However, if your image needs an engine (a gforth binary)
14152: that is under the GPL, you should make sure that you distribute both in
14153: a way that is at most a @emph{mere aggregation}, if you don't want the
14154: terms of the GPL to apply to the image.
14155:
14156: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14157: @section Image File Background
14158: @cindex image file background
14159:
1.80 anton 14160: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14161: definitions written in Forth. Since the Forth compiler itself belongs to
14162: those definitions, it is not possible to start the system with the
1.80 anton 14163: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14164: code as an image file in nearly executable form. When Gforth starts up,
14165: a C routine loads the image file into memory, optionally relocates the
14166: addresses, then sets up the memory (stacks etc.) according to
14167: information in the image file, and (finally) starts executing Forth
14168: code.
1.1 anton 14169:
14170: The image file variants represent different compromises between the
14171: goals of making it easy to generate image files and making them
14172: portable.
14173:
14174: @cindex relocation at run-time
1.26 crook 14175: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 14176: run-time. This avoids many of the complications discussed below (image
14177: files are data relocatable without further ado), but costs performance
14178: (one addition per memory access).
14179:
14180: @cindex relocation at load-time
1.26 crook 14181: By contrast, the Gforth loader performs relocation at image load time. The
14182: loader also has to replace tokens that represent primitive calls with the
1.1 anton 14183: appropriate code-field addresses (or code addresses in the case of
14184: direct threading).
14185:
14186: There are three kinds of image files, with different degrees of
14187: relocatability: non-relocatable, data-relocatable, and fully relocatable
14188: image files.
14189:
14190: @cindex image file loader
14191: @cindex relocating loader
14192: @cindex loader for image files
14193: These image file variants have several restrictions in common; they are
14194: caused by the design of the image file loader:
14195:
14196: @itemize @bullet
14197: @item
14198: There is only one segment; in particular, this means, that an image file
14199: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 14200: them). The contents of the stacks are not represented, either.
1.1 anton 14201:
14202: @item
14203: The only kinds of relocation supported are: adding the same offset to
14204: all cells that represent data addresses; and replacing special tokens
14205: with code addresses or with pieces of machine code.
14206:
14207: If any complex computations involving addresses are performed, the
14208: results cannot be represented in the image file. Several applications that
14209: use such computations come to mind:
14210: @itemize @minus
14211: @item
14212: Hashing addresses (or data structures which contain addresses) for table
14213: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14214: purpose, you will have no problem, because the hash tables are
14215: recomputed automatically when the system is started. If you use your own
14216: hash tables, you will have to do something similar.
14217:
14218: @item
14219: There's a cute implementation of doubly-linked lists that uses
14220: @code{XOR}ed addresses. You could represent such lists as singly-linked
14221: in the image file, and restore the doubly-linked representation on
14222: startup.@footnote{In my opinion, though, you should think thrice before
14223: using a doubly-linked list (whatever implementation).}
14224:
14225: @item
14226: The code addresses of run-time routines like @code{docol:} cannot be
14227: represented in the image file (because their tokens would be replaced by
14228: machine code in direct threaded implementations). As a workaround,
14229: compute these addresses at run-time with @code{>code-address} from the
14230: executions tokens of appropriate words (see the definitions of
1.80 anton 14231: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 14232:
14233: @item
14234: On many architectures addresses are represented in machine code in some
14235: shifted or mangled form. You cannot put @code{CODE} words that contain
14236: absolute addresses in this form in a relocatable image file. Workarounds
14237: are representing the address in some relative form (e.g., relative to
14238: the CFA, which is present in some register), or loading the address from
14239: a place where it is stored in a non-mangled form.
14240: @end itemize
14241: @end itemize
14242:
14243: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14244: @section Non-Relocatable Image Files
14245: @cindex non-relocatable image files
1.26 crook 14246: @cindex image file, non-relocatable
1.1 anton 14247:
14248: These files are simple memory dumps of the dictionary. They are specific
14249: to the executable (i.e., @file{gforth} file) they were created
14250: with. What's worse, they are specific to the place on which the
14251: dictionary resided when the image was created. Now, there is no
14252: guarantee that the dictionary will reside at the same place the next
14253: time you start Gforth, so there's no guarantee that a non-relocatable
14254: image will work the next time (Gforth will complain instead of crashing,
14255: though).
14256:
14257: You can create a non-relocatable image file with
14258:
1.44 crook 14259:
1.1 anton 14260: doc-savesystem
14261:
1.44 crook 14262:
1.1 anton 14263: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14264: @section Data-Relocatable Image Files
14265: @cindex data-relocatable image files
1.26 crook 14266: @cindex image file, data-relocatable
1.1 anton 14267:
14268: These files contain relocatable data addresses, but fixed code addresses
14269: (instead of tokens). They are specific to the executable (i.e.,
14270: @file{gforth} file) they were created with. For direct threading on some
14271: architectures (e.g., the i386), data-relocatable images do not work. You
14272: get a data-relocatable image, if you use @file{gforthmi} with a
14273: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14274: Relocatable Image Files}).
14275:
14276: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14277: @section Fully Relocatable Image Files
14278: @cindex fully relocatable image files
1.26 crook 14279: @cindex image file, fully relocatable
1.1 anton 14280:
14281: @cindex @file{kern*.fi}, relocatability
14282: @cindex @file{gforth.fi}, relocatability
14283: These image files have relocatable data addresses, and tokens for code
14284: addresses. They can be used with different binaries (e.g., with and
14285: without debugging) on the same machine, and even across machines with
14286: the same data formats (byte order, cell size, floating point
14287: format). However, they are usually specific to the version of Gforth
14288: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14289: are fully relocatable.
14290:
14291: There are two ways to create a fully relocatable image file:
14292:
14293: @menu
1.29 crook 14294: * gforthmi:: The normal way
1.1 anton 14295: * cross.fs:: The hard way
14296: @end menu
14297:
14298: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14299: @subsection @file{gforthmi}
14300: @cindex @file{comp-i.fs}
14301: @cindex @file{gforthmi}
14302:
14303: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 14304: image @i{file} that contains everything you would load by invoking
14305: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 14306: @example
1.29 crook 14307: gforthmi @i{file} @i{options}
1.1 anton 14308: @end example
14309:
14310: E.g., if you want to create an image @file{asm.fi} that has the file
14311: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14312: like this:
14313:
14314: @example
14315: gforthmi asm.fi asm.fs
14316: @end example
14317:
1.27 crook 14318: @file{gforthmi} is implemented as a sh script and works like this: It
14319: produces two non-relocatable images for different addresses and then
14320: compares them. Its output reflects this: first you see the output (if
1.62 crook 14321: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14322: files, then you see the output of the comparing program: It displays the
14323: offset used for data addresses and the offset used for code addresses;
1.1 anton 14324: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14325: image files, it displays a line like this:
1.1 anton 14326:
14327: @example
14328: 78DC BFFFFA50 BFFFFA40
14329: @end example
14330:
14331: This means that at offset $78dc from @code{forthstart}, one input image
14332: contains $bffffa50, and the other contains $bffffa40. Since these cells
14333: cannot be represented correctly in the output image, you should examine
14334: these places in the dictionary and verify that these cells are dead
14335: (i.e., not read before they are written).
1.39 anton 14336:
14337: @cindex --application, @code{gforthmi} option
14338: If you insert the option @code{--application} in front of the image file
14339: name, you will get an image that uses the @code{--appl-image} option
14340: instead of the @code{--image-file} option (@pxref{Invoking
14341: Gforth}). When you execute such an image on Unix (by typing the image
14342: name as command), the Gforth engine will pass all options to the image
14343: instead of trying to interpret them as engine options.
1.1 anton 14344:
1.27 crook 14345: If you type @file{gforthmi} with no arguments, it prints some usage
14346: instructions.
14347:
1.1 anton 14348: @cindex @code{savesystem} during @file{gforthmi}
14349: @cindex @code{bye} during @file{gforthmi}
14350: @cindex doubly indirect threaded code
1.44 crook 14351: @cindex environment variables
14352: @cindex @code{GFORTHD} -- environment variable
14353: @cindex @code{GFORTH} -- environment variable
1.1 anton 14354: @cindex @code{gforth-ditc}
1.29 crook 14355: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14356: words @code{savesystem} and @code{bye} must be visible. A special doubly
14357: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14358: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14359: this executable through the environment variable @code{GFORTHD}
14360: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14361: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14362: data-relocatable image (because there is no code address offset). The
14363: normal @file{gforth} executable is used for creating the relocatable
14364: image; you can pass the exact filename of this executable through the
14365: environment variable @code{GFORTH}.
1.1 anton 14366:
14367: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14368: @subsection @file{cross.fs}
14369: @cindex @file{cross.fs}
14370: @cindex cross-compiler
14371: @cindex metacompiler
1.47 crook 14372: @cindex target compiler
1.1 anton 14373:
14374: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14375: programming language (@pxref{Cross Compiler}).
1.1 anton 14376:
1.47 crook 14377: @code{cross} allows you to create image files for machines with
1.1 anton 14378: different data sizes and data formats than the one used for generating
14379: the image file. You can also use it to create an application image that
14380: does not contain a Forth compiler. These features are bought with
14381: restrictions and inconveniences in programming. E.g., addresses have to
14382: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14383: order to make the code relocatable.
14384:
14385:
14386: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14387: @section Stack and Dictionary Sizes
14388: @cindex image file, stack and dictionary sizes
14389: @cindex dictionary size default
14390: @cindex stack size default
14391:
14392: If you invoke Gforth with a command line flag for the size
14393: (@pxref{Invoking Gforth}), the size you specify is stored in the
14394: dictionary. If you save the dictionary with @code{savesystem} or create
14395: an image with @file{gforthmi}, this size will become the default
14396: for the resulting image file. E.g., the following will create a
1.21 crook 14397: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14398:
14399: @example
14400: gforthmi gforth.fi -m 1M
14401: @end example
14402:
14403: In other words, if you want to set the default size for the dictionary
14404: and the stacks of an image, just invoke @file{gforthmi} with the
14405: appropriate options when creating the image.
14406:
14407: @cindex stack size, cache-friendly
14408: Note: For cache-friendly behaviour (i.e., good performance), you should
14409: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14410: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14411: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14412:
14413: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14414: @section Running Image Files
14415: @cindex running image files
14416: @cindex invoking image files
14417: @cindex image file invocation
14418:
14419: @cindex -i, invoke image file
14420: @cindex --image file, invoke image file
1.29 crook 14421: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14422: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14423: @example
1.29 crook 14424: gforth -i @i{image}
1.1 anton 14425: @end example
14426:
14427: @cindex executable image file
1.26 crook 14428: @cindex image file, executable
1.1 anton 14429: If your operating system supports starting scripts with a line of the
14430: form @code{#! ...}, you just have to type the image file name to start
14431: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14432: just a convention). I.e., to run Gforth with the image file @i{image},
14433: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14434: This works because every @code{.fi} file starts with a line of this
14435: format:
14436:
14437: @example
14438: #! /usr/local/bin/gforth-0.4.0 -i
14439: @end example
14440:
14441: The file and pathname for the Gforth engine specified on this line is
14442: the specific Gforth executable that it was built against; i.e. the value
14443: of the environment variable @code{GFORTH} at the time that
14444: @file{gforthmi} was executed.
1.1 anton 14445:
1.27 crook 14446: You can make use of the same shell capability to make a Forth source
14447: file into an executable. For example, if you place this text in a file:
1.26 crook 14448:
14449: @example
14450: #! /usr/local/bin/gforth
14451:
14452: ." Hello, world" CR
14453: bye
14454: @end example
14455:
14456: @noindent
1.27 crook 14457: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14458: directly from the command line. The sequence @code{#!} is used in two
14459: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14460: system@footnote{The Unix kernel actually recognises two types of files:
14461: executable files and files of data, where the data is processed by an
14462: interpreter that is specified on the ``interpreter line'' -- the first
14463: line of the file, starting with the sequence #!. There may be a small
14464: limit (e.g., 32) on the number of characters that may be specified on
14465: the interpreter line.} secondly it is treated as a comment character by
14466: Gforth. Because of the second usage, a space is required between
1.80 anton 14467: @code{#!} and the path to the executable (moreover, some Unixes
14468: require the sequence @code{#! /}).
1.27 crook 14469:
14470: The disadvantage of this latter technique, compared with using
1.80 anton 14471: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14472: compiled on-the-fly, each time the program is invoked.
1.26 crook 14473:
1.1 anton 14474: doc-#!
14475:
1.44 crook 14476:
1.1 anton 14477: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14478: @section Modifying the Startup Sequence
14479: @cindex startup sequence for image file
14480: @cindex image file initialization sequence
14481: @cindex initialization sequence of image file
14482:
1.120 anton 14483: You can add your own initialization to the startup sequence of an image
14484: through the deferred word @code{'cold}. @code{'cold} is invoked just
14485: before the image-specific command line processing (i.e., loading files
14486: and evaluating (@code{-e}) strings) starts.
1.1 anton 14487:
14488: A sequence for adding your initialization usually looks like this:
14489:
14490: @example
14491: :noname
14492: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14493: ... \ your stuff
14494: ; IS 'cold
14495: @end example
14496:
14497: @cindex turnkey image files
1.26 crook 14498: @cindex image file, turnkey applications
1.1 anton 14499: You can make a turnkey image by letting @code{'cold} execute a word
14500: (your turnkey application) that never returns; instead, it exits Gforth
14501: via @code{bye} or @code{throw}.
14502:
1.121 anton 14503: You can access the (image-specific) command-line arguments through
14504: @code{argc}, @code{argv} and @code{arg} (@pxref{OS command line
14505: arguments}).
1.1 anton 14506:
1.26 crook 14507: If @code{'cold} exits normally, Gforth processes the command-line
14508: arguments as files to be loaded and strings to be evaluated. Therefore,
14509: @code{'cold} should remove the arguments it has used in this case.
14510:
14511: doc-'cold
1.44 crook 14512:
1.1 anton 14513: @c ******************************************************************
1.113 anton 14514: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 14515: @chapter Engine
14516: @cindex engine
14517: @cindex virtual machine
14518:
1.26 crook 14519: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14520: may be helpful for finding your way in the Gforth sources.
14521:
1.109 anton 14522: The ideas in this section have also been published in the following
14523: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14524: Forth-Tagung '93; M. Anton Ertl,
14525: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14526: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14527: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14528: Threaded code variations and optimizations (extended version)}},
14529: Forth-Tagung '02.
1.1 anton 14530:
14531: @menu
14532: * Portability::
14533: * Threading::
14534: * Primitives::
14535: * Performance::
14536: @end menu
14537:
14538: @node Portability, Threading, Engine, Engine
14539: @section Portability
14540: @cindex engine portability
14541:
1.26 crook 14542: An important goal of the Gforth Project is availability across a wide
14543: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14544: achieved this goal by manually coding the engine in assembly language
14545: for several then-popular processors. This approach is very
14546: labor-intensive and the results are short-lived due to progress in
14547: computer architecture.
1.1 anton 14548:
14549: @cindex C, using C for the engine
14550: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14551: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14552: particularly popular for UNIX-based Forths due to the large variety of
14553: architectures of UNIX machines. Unfortunately an implementation in C
14554: does not mix well with the goals of efficiency and with using
14555: traditional techniques: Indirect or direct threading cannot be expressed
14556: in C, and switch threading, the fastest technique available in C, is
14557: significantly slower. Another problem with C is that it is very
14558: cumbersome to express double integer arithmetic.
14559:
14560: @cindex GNU C for the engine
14561: @cindex long long
14562: Fortunately, there is a portable language that does not have these
14563: limitations: GNU C, the version of C processed by the GNU C compiler
14564: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14565: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14566: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14567: threading possible, its @code{long long} type (@pxref{Long Long, ,
14568: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 14569: double numbers on many systems. GNU C is freely available on all
1.1 anton 14570: important (and many unimportant) UNIX machines, VMS, 80386s running
14571: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14572: on all these machines.
14573:
14574: Writing in a portable language has the reputation of producing code that
14575: is slower than assembly. For our Forth engine we repeatedly looked at
14576: the code produced by the compiler and eliminated most compiler-induced
14577: inefficiencies by appropriate changes in the source code.
14578:
14579: @cindex explicit register declarations
14580: @cindex --enable-force-reg, configuration flag
14581: @cindex -DFORCE_REG
14582: However, register allocation cannot be portably influenced by the
14583: programmer, leading to some inefficiencies on register-starved
14584: machines. We use explicit register declarations (@pxref{Explicit Reg
14585: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14586: improve the speed on some machines. They are turned on by using the
14587: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14588: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14589: machine, but also on the compiler version: On some machines some
14590: compiler versions produce incorrect code when certain explicit register
14591: declarations are used. So by default @code{-DFORCE_REG} is not used.
14592:
14593: @node Threading, Primitives, Portability, Engine
14594: @section Threading
14595: @cindex inner interpreter implementation
14596: @cindex threaded code implementation
14597:
14598: @cindex labels as values
14599: GNU C's labels as values extension (available since @code{gcc-2.0},
14600: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 14601: makes it possible to take the address of @i{label} by writing
14602: @code{&&@i{label}}. This address can then be used in a statement like
14603: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 14604: @code{goto x}.
14605:
1.26 crook 14606: @cindex @code{NEXT}, indirect threaded
1.1 anton 14607: @cindex indirect threaded inner interpreter
14608: @cindex inner interpreter, indirect threaded
1.26 crook 14609: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 14610: @example
14611: cfa = *ip++;
14612: ca = *cfa;
14613: goto *ca;
14614: @end example
14615: @cindex instruction pointer
14616: For those unfamiliar with the names: @code{ip} is the Forth instruction
14617: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14618: execution token and points to the code field of the next word to be
14619: executed; The @code{ca} (code address) fetched from there points to some
14620: executable code, e.g., a primitive or the colon definition handler
14621: @code{docol}.
14622:
1.26 crook 14623: @cindex @code{NEXT}, direct threaded
1.1 anton 14624: @cindex direct threaded inner interpreter
14625: @cindex inner interpreter, direct threaded
14626: Direct threading is even simpler:
14627: @example
14628: ca = *ip++;
14629: goto *ca;
14630: @end example
14631:
14632: Of course we have packaged the whole thing neatly in macros called
1.26 crook 14633: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 14634:
14635: @menu
14636: * Scheduling::
14637: * Direct or Indirect Threaded?::
1.109 anton 14638: * Dynamic Superinstructions::
1.1 anton 14639: * DOES>::
14640: @end menu
14641:
14642: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14643: @subsection Scheduling
14644: @cindex inner interpreter optimization
14645:
14646: There is a little complication: Pipelined and superscalar processors,
14647: i.e., RISC and some modern CISC machines can process independent
14648: instructions while waiting for the results of an instruction. The
14649: compiler usually reorders (schedules) the instructions in a way that
14650: achieves good usage of these delay slots. However, on our first tries
14651: the compiler did not do well on scheduling primitives. E.g., for
14652: @code{+} implemented as
14653: @example
14654: n=sp[0]+sp[1];
14655: sp++;
14656: sp[0]=n;
14657: NEXT;
14658: @end example
1.81 anton 14659: the @code{NEXT} comes strictly after the other code, i.e., there is
14660: nearly no scheduling. After a little thought the problem becomes clear:
14661: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 14662: addresses (and the version of @code{gcc} we used would not know it even
14663: if it was possible), so it could not move the load of the cfa above the
14664: store to the TOS. Indeed the pointers could be the same, if code on or
14665: very near the top of stack were executed. In the interest of speed we
14666: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 14667: in scheduling: @code{NEXT} is divided into several parts:
14668: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14669: like:
1.1 anton 14670: @example
1.81 anton 14671: NEXT_P0;
1.1 anton 14672: n=sp[0]+sp[1];
14673: sp++;
14674: NEXT_P1;
14675: sp[0]=n;
14676: NEXT_P2;
14677: @end example
14678:
1.81 anton 14679: There are various schemes that distribute the different operations of
14680: NEXT between these parts in several ways; in general, different schemes
14681: perform best on different processors. We use a scheme for most
14682: architectures that performs well for most processors of this
1.109 anton 14683: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 14684: the scheme on installation time.
14685:
1.1 anton 14686:
1.109 anton 14687: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 14688: @subsection Direct or Indirect Threaded?
14689: @cindex threading, direct or indirect?
14690:
1.109 anton 14691: Threaded forth code consists of references to primitives (simple machine
14692: code routines like @code{+}) and to non-primitives (e.g., colon
14693: definitions, variables, constants); for a specific class of
14694: non-primitives (e.g., variables) there is one code routine (e.g.,
14695: @code{dovar}), but each variable needs a separate reference to its data.
14696:
14697: Traditionally Forth has been implemented as indirect threaded code,
14698: because this allows to use only one cell to reference a non-primitive
14699: (basically you point to the data, and find the code address there).
14700:
14701: @cindex primitive-centric threaded code
14702: However, threaded code in Gforth (since 0.6.0) uses two cells for
14703: non-primitives, one for the code address, and one for the data address;
14704: the data pointer is an immediate argument for the virtual machine
14705: instruction represented by the code address. We call this
14706: @emph{primitive-centric} threaded code, because all code addresses point
14707: to simple primitives. E.g., for a variable, the code address is for
14708: @code{lit} (also used for integer literals like @code{99}).
14709:
14710: Primitive-centric threaded code allows us to use (faster) direct
14711: threading as dispatch method, completely portably (direct threaded code
14712: in Gforth before 0.6.0 required architecture-specific code). It also
14713: eliminates the performance problems related to I-cache consistency that
14714: 386 implementations have with direct threaded code, and allows
14715: additional optimizations.
14716:
14717: @cindex hybrid direct/indirect threaded code
14718: There is a catch, however: the @var{xt} parameter of @code{execute} can
14719: occupy only one cell, so how do we pass non-primitives with their code
14720: @emph{and} data addresses to them? Our answer is to use indirect
14721: threaded dispatch for @code{execute} and other words that use a
14722: single-cell xt. So, normal threaded code in colon definitions uses
14723: direct threading, and @code{execute} and similar words, which dispatch
14724: to xts on the data stack, use indirect threaded code. We call this
14725: @emph{hybrid direct/indirect} threaded code.
14726:
14727: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14728: @cindex gforth engine
14729: @cindex gforth-fast engine
14730: The engines @command{gforth} and @command{gforth-fast} use hybrid
14731: direct/indirect threaded code. This means that with these engines you
14732: cannot use @code{,} to compile an xt. Instead, you have to use
14733: @code{compile,}.
14734:
14735: @cindex gforth-itc engine
1.115 anton 14736: If you want to compile xts with @code{,}, use @command{gforth-itc}.
14737: This engine uses plain old indirect threaded code. It still compiles in
14738: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 14739: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 14740: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 14741: and execute @code{' , is compile,}. Your program can check if it is
14742: running on a hybrid direct/indirect threaded engine or a pure indirect
14743: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14744:
14745:
14746: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14747: @subsection Dynamic Superinstructions
14748: @cindex Dynamic superinstructions with replication
14749: @cindex Superinstructions
14750: @cindex Replication
14751:
14752: The engines @command{gforth} and @command{gforth-fast} use another
14753: optimization: Dynamic superinstructions with replication. As an
14754: example, consider the following colon definition:
14755:
14756: @example
14757: : squared ( n1 -- n2 )
14758: dup * ;
14759: @end example
14760:
14761: Gforth compiles this into the threaded code sequence
14762:
14763: @example
14764: dup
14765: *
14766: ;s
14767: @end example
14768:
14769: In normal direct threaded code there is a code address occupying one
14770: cell for each of these primitives. Each code address points to a
14771: machine code routine, and the interpreter jumps to this machine code in
14772: order to execute the primitive. The routines for these three
14773: primitives are (in @command{gforth-fast} on the 386):
14774:
14775: @example
14776: Code dup
14777: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
14778: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
14779: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14780: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14781: end-code
14782: Code *
14783: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14784: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
14785: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
14786: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
14787: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14788: end-code
14789: Code ;s
14790: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
14791: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
14792: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14793: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14794: end-code
14795: @end example
14796:
14797: With dynamic superinstructions and replication the compiler does not
14798: just lay down the threaded code, but also copies the machine code
14799: fragments, usually without the jump at the end.
14800:
14801: @example
14802: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
14803: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
14804: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14805: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14806: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
14807: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
14808: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
14809: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
14810: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
14811: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14812: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14813: @end example
14814:
14815: Only when a threaded-code control-flow change happens (e.g., in
14816: @code{;s}), the jump is appended. This optimization eliminates many of
14817: these jumps and makes the rest much more predictable. The speedup
14818: depends on the processor and the application; on the Athlon and Pentium
14819: III this optimization typically produces a speedup by a factor of 2.
14820:
14821: The code addresses in the direct-threaded code are set to point to the
14822: appropriate points in the copied machine code, in this example like
14823: this:
1.1 anton 14824:
1.109 anton 14825: @example
14826: primitive code address
14827: dup $4057D27D
14828: * $4057D286
14829: ;s $4057D292
14830: @end example
14831:
14832: Thus there can be threaded-code jumps to any place in this piece of
14833: code. This also simplifies decompilation quite a bit.
14834:
14835: @cindex --no-dynamic command-line option
14836: @cindex --no-super command-line option
14837: You can disable this optimization with @option{--no-dynamic}. You can
14838: use the copying without eliminating the jumps (i.e., dynamic
14839: replication, but without superinstructions) with @option{--no-super};
14840: this gives the branch prediction benefit alone; the effect on
1.110 anton 14841: performance depends on the CPU; on the Athlon and Pentium III the
14842: speedup is a little less than for dynamic superinstructions with
14843: replication.
14844:
14845: @cindex patching threaded code
14846: One use of these options is if you want to patch the threaded code.
14847: With superinstructions, many of the dispatch jumps are eliminated, so
14848: patching often has no effect. These options preserve all the dispatch
14849: jumps.
1.109 anton 14850:
14851: @cindex --dynamic command-line option
1.110 anton 14852: On some machines dynamic superinstructions are disabled by default,
14853: because it is unsafe on these machines. However, if you feel
14854: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 14855:
14856: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 14857: @subsection DOES>
14858: @cindex @code{DOES>} implementation
14859:
1.26 crook 14860: @cindex @code{dodoes} routine
14861: @cindex @code{DOES>}-code
1.1 anton 14862: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14863: the chunk of code executed by every word defined by a
1.109 anton 14864: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
14865: this is only needed if the xt of the word is @code{execute}d. The main
14866: problem here is: How to find the Forth code to be executed, i.e. the
14867: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
14868: solutions:
1.1 anton 14869:
1.21 crook 14870: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 14871: @code{DOES>}-code address is stored in the cell after the code address
14872: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
14873: illegal in the Forth-79 and all later standards, because in fig-Forth
14874: this address lies in the body (which is illegal in these
14875: standards). However, by making the code field larger for all words this
14876: solution becomes legal again. We use this approach. Leaving a cell
14877: unused in most words is a bit wasteful, but on the machines we are
14878: targeting this is hardly a problem.
14879:
1.1 anton 14880:
14881: @node Primitives, Performance, Threading, Engine
14882: @section Primitives
14883: @cindex primitives, implementation
14884: @cindex virtual machine instructions, implementation
14885:
14886: @menu
14887: * Automatic Generation::
14888: * TOS Optimization::
14889: * Produced code::
14890: @end menu
14891:
14892: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14893: @subsection Automatic Generation
14894: @cindex primitives, automatic generation
14895:
14896: @cindex @file{prims2x.fs}
1.109 anton 14897:
1.1 anton 14898: Since the primitives are implemented in a portable language, there is no
14899: longer any need to minimize the number of primitives. On the contrary,
14900: having many primitives has an advantage: speed. In order to reduce the
14901: number of errors in primitives and to make programming them easier, we
1.109 anton 14902: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
14903: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
14904: generates most (and sometimes all) of the C code for a primitive from
14905: the stack effect notation. The source for a primitive has the following
14906: form:
1.1 anton 14907:
14908: @cindex primitive source format
14909: @format
1.58 anton 14910: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 14911: [@code{""}@i{glossary entry}@code{""}]
14912: @i{C code}
1.1 anton 14913: [@code{:}
1.29 crook 14914: @i{Forth code}]
1.1 anton 14915: @end format
14916:
14917: The items in brackets are optional. The category and glossary fields
14918: are there for generating the documentation, the Forth code is there
14919: for manual implementations on machines without GNU C. E.g., the source
14920: for the primitive @code{+} is:
14921: @example
1.58 anton 14922: + ( n1 n2 -- n ) core plus
1.1 anton 14923: n = n1+n2;
14924: @end example
14925:
14926: This looks like a specification, but in fact @code{n = n1+n2} is C
14927: code. Our primitive generation tool extracts a lot of information from
14928: the stack effect notations@footnote{We use a one-stack notation, even
14929: though we have separate data and floating-point stacks; The separate
14930: notation can be generated easily from the unified notation.}: The number
14931: of items popped from and pushed on the stack, their type, and by what
14932: name they are referred to in the C code. It then generates a C code
14933: prelude and postlude for each primitive. The final C code for @code{+}
14934: looks like this:
14935:
14936: @example
1.46 pazsan 14937: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 14938: /* */ /* documentation */
1.81 anton 14939: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 14940: @{
14941: DEF_CA /* definition of variable ca (indirect threading) */
14942: Cell n1; /* definitions of variables */
14943: Cell n2;
14944: Cell n;
1.81 anton 14945: NEXT_P0; /* NEXT part 0 */
1.1 anton 14946: n1 = (Cell) sp[1]; /* input */
14947: n2 = (Cell) TOS;
14948: sp += 1; /* stack adjustment */
14949: @{
14950: n = n1+n2; /* C code taken from the source */
14951: @}
14952: NEXT_P1; /* NEXT part 1 */
14953: TOS = (Cell)n; /* output */
14954: NEXT_P2; /* NEXT part 2 */
14955: @}
14956: @end example
14957:
14958: This looks long and inefficient, but the GNU C compiler optimizes quite
14959: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14960: HP RISC machines: Defining the @code{n}s does not produce any code, and
14961: using them as intermediate storage also adds no cost.
14962:
1.26 crook 14963: There are also other optimizations that are not illustrated by this
14964: example: assignments between simple variables are usually for free (copy
1.1 anton 14965: propagation). If one of the stack items is not used by the primitive
14966: (e.g. in @code{drop}), the compiler eliminates the load from the stack
14967: (dead code elimination). On the other hand, there are some things that
14968: the compiler does not do, therefore they are performed by
14969: @file{prims2x.fs}: The compiler does not optimize code away that stores
14970: a stack item to the place where it just came from (e.g., @code{over}).
14971:
14972: While programming a primitive is usually easy, there are a few cases
14973: where the programmer has to take the actions of the generator into
14974: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 14975: fall through to @code{NEXT}.
1.109 anton 14976:
14977: For more information
1.1 anton 14978:
14979: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14980: @subsection TOS Optimization
14981: @cindex TOS optimization for primitives
14982: @cindex primitives, keeping the TOS in a register
14983:
14984: An important optimization for stack machine emulators, e.g., Forth
14985: engines, is keeping one or more of the top stack items in
1.29 crook 14986: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
14987: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 14988: @itemize @bullet
14989: @item
1.29 crook 14990: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 14991: due to fewer loads from and stores to the stack.
1.29 crook 14992: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14993: @i{y<n}, due to additional moves between registers.
1.1 anton 14994: @end itemize
14995:
14996: @cindex -DUSE_TOS
14997: @cindex -DUSE_NO_TOS
14998: In particular, keeping one item in a register is never a disadvantage,
14999: if there are enough registers. Keeping two items in registers is a
15000: disadvantage for frequent words like @code{?branch}, constants,
15001: variables, literals and @code{i}. Therefore our generator only produces
15002: code that keeps zero or one items in registers. The generated C code
15003: covers both cases; the selection between these alternatives is made at
15004: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15005: code for @code{+} is just a simple variable name in the one-item case,
15006: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15007: GNU C compiler tries to keep simple variables like @code{TOS} in
15008: registers, and it usually succeeds, if there are enough registers.
15009:
15010: @cindex -DUSE_FTOS
15011: @cindex -DUSE_NO_FTOS
15012: The primitive generator performs the TOS optimization for the
15013: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15014: operations the benefit of this optimization is even larger:
15015: floating-point operations take quite long on most processors, but can be
15016: performed in parallel with other operations as long as their results are
15017: not used. If the FP-TOS is kept in a register, this works. If
15018: it is kept on the stack, i.e., in memory, the store into memory has to
15019: wait for the result of the floating-point operation, lengthening the
15020: execution time of the primitive considerably.
15021:
15022: The TOS optimization makes the automatic generation of primitives a
15023: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15024: @code{TOS} is not sufficient. There are some special cases to
15025: consider:
15026: @itemize @bullet
15027: @item In the case of @code{dup ( w -- w w )} the generator must not
15028: eliminate the store to the original location of the item on the stack,
15029: if the TOS optimization is turned on.
15030: @item Primitives with stack effects of the form @code{--}
1.29 crook 15031: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15032: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 15033: must load the TOS from the stack at the end. But for the null stack
15034: effect @code{--} no stores or loads should be generated.
15035: @end itemize
15036:
15037: @node Produced code, , TOS Optimization, Primitives
15038: @subsection Produced code
15039: @cindex primitives, assembly code listing
15040:
15041: @cindex @file{engine.s}
15042: To see what assembly code is produced for the primitives on your machine
15043: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15044: look at the resulting file @file{engine.s}. Alternatively, you can also
15045: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15046:
15047: @node Performance, , Primitives, Engine
15048: @section Performance
15049: @cindex performance of some Forth interpreters
15050: @cindex engine performance
15051: @cindex benchmarking Forth systems
15052: @cindex Gforth performance
15053:
15054: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 15055: impossible to write a significantly faster threaded-code engine.
1.1 anton 15056:
15057: On register-starved machines like the 386 architecture processors
15058: improvements are possible, because @code{gcc} does not utilize the
15059: registers as well as a human, even with explicit register declarations;
15060: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15061: and hand-tuned it for the 486; this system is 1.19 times faster on the
15062: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15063: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15064: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15065: registers fit in real registers (and we can even afford to use the TOS
15066: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 15067: earlier results. And dynamic superinstructions provide another speedup
15068: (but only around a factor 1.2 on the 486).
1.1 anton 15069:
15070: @cindex Win32Forth performance
15071: @cindex NT Forth performance
15072: @cindex eforth performance
15073: @cindex ThisForth performance
15074: @cindex PFE performance
15075: @cindex TILE performance
1.81 anton 15076: The potential advantage of assembly language implementations is not
1.112 anton 15077: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 15078: (direct threaded, compiled with @code{gcc-2.95.1} and
15079: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15080: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15081: (with and without peephole (aka pinhole) optimization of the threaded
15082: code); all these systems were written in assembly language. We also
15083: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15084: with @code{gcc-2.6.3} with the default configuration for Linux:
15085: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15086: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15087: employs peephole optimization of the threaded code) and TILE (compiled
15088: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15089: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15090: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15091: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15092: then extended it to run the benchmarks, added the peephole optimizer,
15093: ran the benchmarks and reported the results.
1.40 anton 15094:
1.1 anton 15095: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15096: matrix multiplication come from the Stanford integer benchmarks and have
15097: been translated into Forth by Martin Fraeman; we used the versions
15098: included in the TILE Forth package, but with bigger data set sizes; and
15099: a recursive Fibonacci number computation for benchmarking calling
15100: performance. The following table shows the time taken for the benchmarks
15101: scaled by the time taken by Gforth (in other words, it shows the speedup
15102: factor that Gforth achieved over the other systems).
15103:
15104: @example
1.112 anton 15105: relative Win32- NT eforth This-
15106: time Gforth Forth Forth eforth +opt PFE Forth TILE
15107: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15108: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15109: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15110: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15111: @end example
15112:
1.26 crook 15113: You may be quite surprised by the good performance of Gforth when
15114: compared with systems written in assembly language. One important reason
15115: for the disappointing performance of these other systems is probably
15116: that they are not written optimally for the 486 (e.g., they use the
15117: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15118: but costly method for relocating the Forth image: like @code{cforth}, it
15119: computes the actual addresses at run time, resulting in two address
15120: computations per @code{NEXT} (@pxref{Image File Background}).
15121:
1.1 anton 15122: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15123: explained with the self-imposed restriction of the latter systems to
15124: standard C, which makes efficient threading impossible (however, the
1.4 anton 15125: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15126: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15127: Moreover, current C compilers have a hard time optimizing other aspects
15128: of the ThisForth and the TILE source.
15129:
1.26 crook 15130: The performance of Gforth on 386 architecture processors varies widely
15131: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15132: allocate any of the virtual machine registers into real machine
15133: registers by itself and would not work correctly with explicit register
1.112 anton 15134: declarations, giving a significantly slower engine (on a 486DX2/66
15135: running the Sieve) than the one measured above.
1.1 anton 15136:
1.26 crook 15137: Note that there have been several releases of Win32Forth since the
15138: release presented here, so the results presented above may have little
1.40 anton 15139: predictive value for the performance of Win32Forth today (results for
15140: the current release on an i486DX2/66 are welcome).
1.1 anton 15141:
15142: @cindex @file{Benchres}
1.66 anton 15143: In
15144: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15145: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15146: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15147: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15148: several native code systems; that version of Gforth is slower on a 486
1.112 anton 15149: than the version used here. You can find a newer version of these
15150: measurements at
1.47 crook 15151: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15152: find numbers for Gforth on various machines in @file{Benchres}.
15153:
1.26 crook 15154: @c ******************************************************************
1.113 anton 15155: @c @node Binding to System Library, Cross Compiler, Engine, Top
15156: @c @chapter Binding to System Library
1.13 pazsan 15157:
1.113 anton 15158: @c ****************************************************************
15159: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 15160: @chapter Cross Compiler
1.47 crook 15161: @cindex @file{cross.fs}
15162: @cindex cross-compiler
15163: @cindex metacompiler
15164: @cindex target compiler
1.13 pazsan 15165:
1.46 pazsan 15166: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15167: mostly written in Forth, including crucial parts like the outer
15168: interpreter and compiler, it needs compiled Forth code to get
15169: started. The cross compiler allows to create new images for other
15170: architectures, even running under another Forth system.
1.13 pazsan 15171:
15172: @menu
1.67 anton 15173: * Using the Cross Compiler::
15174: * How the Cross Compiler Works::
1.13 pazsan 15175: @end menu
15176:
1.21 crook 15177: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 15178: @section Using the Cross Compiler
1.46 pazsan 15179:
15180: The cross compiler uses a language that resembles Forth, but isn't. The
15181: main difference is that you can execute Forth code after definition,
15182: while you usually can't execute the code compiled by cross, because the
15183: code you are compiling is typically for a different computer than the
15184: one you are compiling on.
15185:
1.81 anton 15186: @c anton: This chapter is somewhat different from waht I would expect: I
15187: @c would expect an explanation of the cross language and how to create an
15188: @c application image with it. The section explains some aspects of
15189: @c creating a Gforth kernel.
15190:
1.46 pazsan 15191: The Makefile is already set up to allow you to create kernels for new
15192: architectures with a simple make command. The generic kernels using the
15193: GCC compiled virtual machine are created in the normal build process
15194: with @code{make}. To create a embedded Gforth executable for e.g. the
15195: 8086 processor (running on a DOS machine), type
15196:
15197: @example
15198: make kernl-8086.fi
15199: @end example
15200:
15201: This will use the machine description from the @file{arch/8086}
15202: directory to create a new kernel. A machine file may look like that:
15203:
15204: @example
15205: \ Parameter for target systems 06oct92py
15206:
15207: 4 Constant cell \ cell size in bytes
15208: 2 Constant cell<< \ cell shift to bytes
15209: 5 Constant cell>bit \ cell shift to bits
15210: 8 Constant bits/char \ bits per character
15211: 8 Constant bits/byte \ bits per byte [default: 8]
15212: 8 Constant float \ bytes per float
15213: 8 Constant /maxalign \ maximum alignment in bytes
15214: false Constant bigendian \ byte order
15215: ( true=big, false=little )
15216:
15217: include machpc.fs \ feature list
15218: @end example
15219:
15220: This part is obligatory for the cross compiler itself, the feature list
15221: is used by the kernel to conditionally compile some features in and out,
15222: depending on whether the target supports these features.
15223:
15224: There are some optional features, if you define your own primitives,
15225: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 15226: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 15227: @code{prims-include} includes primitives, and @code{>boot} prepares for
15228: booting.
15229:
15230: @example
15231: : asm-include ." Include assembler" cr
15232: s" arch/8086/asm.fs" included ;
15233:
15234: : prims-include ." Include primitives" cr
15235: s" arch/8086/prim.fs" included ;
15236:
15237: : >boot ." Prepare booting" cr
15238: s" ' boot >body into-forth 1+ !" evaluate ;
15239: @end example
15240:
15241: These words are used as sort of macro during the cross compilation in
1.81 anton 15242: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 15243: be possible --- but more complicated --- to write a new kernel project
15244: file, too.
15245:
15246: @file{kernel/main.fs} expects the machine description file name on the
15247: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15248: @code{mach-file} leaves a counted string on the stack, or
15249: @code{machine-file} leaves an address, count pair of the filename on the
15250: stack.
15251:
15252: The feature list is typically controlled using @code{SetValue}, generic
15253: files that are used by several projects can use @code{DefaultValue}
15254: instead. Both functions work like @code{Value}, when the value isn't
15255: defined, but @code{SetValue} works like @code{to} if the value is
15256: defined, and @code{DefaultValue} doesn't set anything, if the value is
15257: defined.
15258:
15259: @example
15260: \ generic mach file for pc gforth 03sep97jaw
15261:
15262: true DefaultValue NIL \ relocating
15263:
15264: >ENVIRON
15265:
15266: true DefaultValue file \ controls the presence of the
15267: \ file access wordset
15268: true DefaultValue OS \ flag to indicate a operating system
15269:
15270: true DefaultValue prims \ true: primitives are c-code
15271:
15272: true DefaultValue floating \ floating point wordset is present
15273:
15274: true DefaultValue glocals \ gforth locals are present
15275: \ will be loaded
15276: true DefaultValue dcomps \ double number comparisons
15277:
15278: true DefaultValue hash \ hashing primitives are loaded/present
15279:
15280: true DefaultValue xconds \ used together with glocals,
15281: \ special conditionals supporting gforths'
15282: \ local variables
15283: true DefaultValue header \ save a header information
15284:
15285: true DefaultValue backtrace \ enables backtrace code
15286:
15287: false DefaultValue ec
15288: false DefaultValue crlf
15289:
15290: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15291:
15292: &16 KB DefaultValue stack-size
15293: &15 KB &512 + DefaultValue fstack-size
15294: &15 KB DefaultValue rstack-size
15295: &14 KB &512 + DefaultValue lstack-size
15296: @end example
1.13 pazsan 15297:
1.48 anton 15298: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 15299: @section How the Cross Compiler Works
1.13 pazsan 15300:
15301: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 15302: @appendix Bugs
1.1 anton 15303: @cindex bug reporting
15304:
1.21 crook 15305: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 15306:
1.103 anton 15307: If you find a bug, please submit a bug report through
15308: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 15309:
15310: @itemize @bullet
15311: @item
1.81 anton 15312: A program (or a sequence of keyboard commands) that reproduces the bug.
15313: @item
15314: A description of what you think constitutes the buggy behaviour.
15315: @item
1.21 crook 15316: The Gforth version used (it is announced at the start of an
15317: interactive Gforth session).
15318: @item
15319: The machine and operating system (on Unix
15320: systems @code{uname -a} will report this information).
15321: @item
1.81 anton 15322: The installation options (you can find the configure options at the
15323: start of @file{config.status}) and configuration (@code{configure}
15324: output or @file{config.cache}).
1.21 crook 15325: @item
15326: A complete list of changes (if any) you (or your installer) have made to the
15327: Gforth sources.
15328: @end itemize
1.1 anton 15329:
15330: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15331: to Report Bugs, gcc.info, GNU C Manual}.
15332:
15333:
1.21 crook 15334: @node Origin, Forth-related information, Bugs, Top
15335: @appendix Authors and Ancestors of Gforth
1.1 anton 15336:
15337: @section Authors and Contributors
15338: @cindex authors of Gforth
15339: @cindex contributors to Gforth
15340:
15341: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15342: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15343: lot to the manual. Assemblers and disassemblers were contributed by
15344: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
15345: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15346: inspired us with their continuous feedback. Lennart Benshop contributed
1.1 anton 15347: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15348: support for calling C libraries. Helpful comments also came from Paul
15349: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.113 anton 15350: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert
15351: Epprecht, Dennis Ruffer and David N. Williams. Since the release of
15352: Gforth-0.2.1 there were also helpful comments from many others; thank
15353: you all, sorry for not listing you here (but digging through my mailbox
15354: to extract your names is on my to-do list).
1.1 anton 15355:
15356: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15357: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 15358: was developed across the Internet, and its authors did not meet
1.20 pazsan 15359: physically for the first 4 years of development.
1.1 anton 15360:
15361: @section Pedigree
1.26 crook 15362: @cindex pedigree of Gforth
1.1 anton 15363:
1.81 anton 15364: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15365: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 15366:
1.20 pazsan 15367: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 15368: 32 bit native code version of VolksForth for the Atari ST, written
15369: mostly by Dietrich Weineck.
15370:
1.81 anton 15371: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15372: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 15373: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 15374:
1.147 anton 15375: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15376: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 15377:
15378: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15379: 1979. Robert Selzer and Bill Ragsdale developed the original
15380: implementation of fig-Forth for the 6502 based on microForth.
15381:
15382: The principal architect of microForth was Dean Sanderson. microForth was
15383: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15384: the 1802, and subsequently implemented on the 8080, the 6800 and the
15385: Z80.
15386:
15387: All earlier Forth systems were custom-made, usually by Charles Moore,
15388: who discovered (as he puts it) Forth during the late 60s. The first full
15389: Forth existed in 1971.
15390:
1.81 anton 15391: A part of the information in this section comes from
15392: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15393: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 15394: Charles H. Moore, presented at the HOPL-II conference and preprinted
15395: in SIGPLAN Notices 28(3), 1993. You can find more historical and
15396: genealogical information about Forth there. For a more general (and
15397: graphical) Forth family tree look see
15398: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
15399: Forth Family Tree and Timeline}.
1.1 anton 15400:
1.81 anton 15401: @c ------------------------------------------------------------------
1.113 anton 15402: @node Forth-related information, Licenses, Origin, Top
1.21 crook 15403: @appendix Other Forth-related information
15404: @cindex Forth-related information
15405:
1.81 anton 15406: @c anton: I threw most of this stuff out, because it can be found through
15407: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 15408:
15409: @cindex comp.lang.forth
15410: @cindex frequently asked questions
1.81 anton 15411: There is an active news group (comp.lang.forth) discussing Forth
15412: (including Gforth) and Forth-related issues. Its
15413: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15414: (frequently asked questions and their answers) contains a lot of
15415: information on Forth. You should read it before posting to
15416: comp.lang.forth.
1.21 crook 15417:
1.81 anton 15418: The ANS Forth standard is most usable in its
15419: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15420:
1.113 anton 15421: @c ---------------------------------------------------
15422: @node Licenses, Word Index, Forth-related information, Top
15423: @appendix Licenses
15424:
15425: @menu
15426: * GNU Free Documentation License:: License for copying this manual.
15427: * Copying:: GPL (for copying this software).
15428: @end menu
15429:
15430: @include fdl.texi
15431:
15432: @include gpl.texi
15433:
15434:
15435:
1.81 anton 15436: @c ------------------------------------------------------------------
1.113 anton 15437: @node Word Index, Concept Index, Licenses, Top
1.1 anton 15438: @unnumbered Word Index
15439:
1.26 crook 15440: This index is a list of Forth words that have ``glossary'' entries
15441: within this manual. Each word is listed with its stack effect and
15442: wordset.
1.1 anton 15443:
15444: @printindex fn
15445:
1.81 anton 15446: @c anton: the name index seems superfluous given the word and concept indices.
15447:
15448: @c @node Name Index, Concept Index, Word Index, Top
15449: @c @unnumbered Name Index
1.41 anton 15450:
1.81 anton 15451: @c This index is a list of Forth words that have ``glossary'' entries
15452: @c within this manual.
1.41 anton 15453:
1.81 anton 15454: @c @printindex ky
1.41 anton 15455:
1.113 anton 15456: @c -------------------------------------------------------
1.81 anton 15457: @node Concept Index, , Word Index, Top
1.1 anton 15458: @unnumbered Concept and Word Index
15459:
1.26 crook 15460: Not all entries listed in this index are present verbatim in the
15461: text. This index also duplicates, in abbreviated form, all of the words
15462: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15463:
15464: @printindex cp
15465:
15466: @bye
1.81 anton 15467:
15468:
1.1 anton 15469:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>